prompts.example.vnprompts.example.vnprompts.example.vn
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.example.vn
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Architecture Prompts

79 prompts3 bots
Godot Game Project taste
Taste

Opinionated Godot 4 project preferences: small composable scenes, typed GDScript, signals up and calls down, autoloads kept rare, resources for data and a clean export pipeline.

# Godot Game Project taste of an indie developer who wants scenes that stay small and reusable
- Build the game from small composable scenes, each with a single clear responsibility, instead of one giant level scene. Confidence: 0.90
- Use static typing in GDScript everywhere: typed variables, parameters and return types, and enable the untyped declaration warnings. Confidence: 0.90
- Follow "call down, signal up": parents call methods on children, children emit signals and never reach up the tree. Confidence: 0.90
- Avoid long get_node paths and get_parent chains; use @export node references or unique names (%Name) inside a scene. Confidence: 0.85
- Keep autoloads to a few true global services such as save system, audio and scene transitions, not a dumping ground for state. Confidence: 0.85
- Store game data like items, enemies and levels in custom Resource classes (.tres) instead of hardcoded dictionaries. Confidence: 0.85
- Remember that Resources are shared by default; call duplicate() or enable resource_local_to_scene when each instance needs its own copy. Confidence: 0.80
- Put physics and movement in _physics_process and visuals and input polling in _process, and never assume a fixed frame time. Confidence: 0.85
- Define actions in the Input Map and read Input.is_action_pressed; never check raw keycodes in gameplay code. Confidence: 0.95
- Use a simple state machine (enum with match or state nodes) for player and enemy behavior instead of piles of booleans. Confidence: 0.80
- Set collision layers and masks deliberately and name every layer in Project Settings. Confidence: 0.85
- Organize folders by feature (player/, enemies/, ui/) with each scene next to its script and assets, not by file type. Confidence: 0.75
- Pool frequently spawned objects like bullets and particles when profiling shows instancing cost, not before. Confidence: 0.70
- Use the built-in profiler and monitors before optimizing, and move hot loops to C# or GDExtension only when measured. Confidence: 0.75
- Load big scenes with ResourceLoader.load_threaded_request behind a loading screen instead of freezing the main thread. Confidence: 0.70
- Save games to user:// as versioned JSON or ConfigFile data and never use var_to_bytes with objects for untrusted save files. Confidence: 0.80
- Commit the project with a proper .gitignore that excludes .godot/ and export output, and use Git LFS for large binary assets. Confidence: 0.90
- Keep export presets in version control without secrets and build release exports from CI with a pinned Godot version. Confidence: 0.75
- Write unit tests for pure game logic with GUT or gdUnit4 and keep that logic outside of node scripts where possible. Confidence: 0.65
- Use Tweens and AnimationPlayer for feel and polish instead of hand-written interpolation code in _process. Confidence: 0.80
Best PracticesPerformanceArchitecture+2
F@f
0
Data Privacy Engineering taste
Taste

Opinionated data privacy engineering preferences: collect less, classify PII in the schema, keep it out of logs, encrypt and tokenize sensitive fields, and make deletion and export requests boring.

# Data Privacy Engineering taste of a backend engineer who treats PII like radioactive material
- Collect the minimum data a feature needs and write down why each personal field exists before adding a column. Confidence: 0.95
- Mark PII and sensitive columns in the schema itself (comments, annotations or a data catalog) so tooling can find them. Confidence: 0.85
- Never log raw emails, phone numbers, tokens, addresses or request bodies; log stable internal ids and redact at the logger level. Confidence: 0.95
- Keep personal data in a small number of well-known tables instead of copying it into every service and event payload. Confidence: 0.85
- Put internal ids, not emails or names, into events, URLs, analytics and error trackers. Confidence: 0.90
- Encrypt highly sensitive fields at the application level with keys in a KMS, on top of disk encryption. Confidence: 0.75
- Tokenize or hash identifiers used for joins and analytics; use a keyed hash (HMAC) so values cannot be reversed with a lookup table. Confidence: 0.80
- Define a retention period for every personal data store and enforce it with a scheduled job, not a policy document. Confidence: 0.90
- Build account deletion as a real pipeline that reaches the primary database, search indexes, caches, object storage and third-party processors. Confidence: 0.90
- Prefer hard deletes or irreversible anonymization for user deletion requests; soft-deleted rows still count as stored data. Confidence: 0.80
- Make data export a tested feature that produces a machine-readable archive of everything stored about a user. Confidence: 0.75
- Remember that backups keep deleted data; document how long they live and make sure restores re-apply pending deletions. Confidence: 0.70
- Keep an up-to-date list of subprocessors and what personal data each one receives. Confidence: 0.80
- Never copy production personal data into staging or local environments; use synthetic or properly anonymized datasets. Confidence: 0.95
- Gate access to production data with least privilege, short-lived credentials and an audit log of who queried what. Confidence: 0.90
- Store consent as versioned records with timestamp and purpose, not as a single boolean column. Confidence: 0.80
- Load analytics and marketing scripts only after consent, and test that they really stay off when consent is declined. Confidence: 0.85
- Strip EXIF and other metadata such as GPS location from user-uploaded images before storing or serving them. Confidence: 0.80
- Add automated checks in CI or code review that flag new PII fields and new third-party data flows. Confidence: 0.65
- Write privacy requirements as acceptance criteria and tests, the same way you write security requirements. Confidence: 0.75
Best PracticesSecurityArchitecture+2
F@f
0
Elixir OTP taste
Taste

Opinionated Elixir OTP preferences: supervision trees designed on purpose, GenServers only for state, Task.Supervisor for async work, Registry for naming, telemetry and let-it-crash without silent failures.

# Elixir OTP taste of a backend developer who trusts supervisors more than try/rescue
- Design the supervision tree on paper first and choose one_for_one, rest_for_one or one_for_all deliberately for each supervisor. Confidence: 0.85
- Use a GenServer only when you need state, serialization or a lifecycle; plain modules and functions are the default. Confidence: 0.90
- Never put a single GenServer on the hot path for every request; it becomes a bottleneck, so shard with a pool or use ETS for reads. Confidence: 0.90
- Keep handle_call fast; move slow work to a Task and reply later with GenServer.reply when needed. Confidence: 0.80
- Start fire-and-forget or parallel work under a Task.Supervisor, never with bare spawn. Confidence: 0.95
- Use Task.async_stream with max_concurrency and timeout for bounded parallel work over collections. Confidence: 0.85
- Name dynamic processes through Registry and start them with DynamicSupervisor instead of building atoms from user input. Confidence: 0.95
- Let it crash for unexpected errors, but return {:ok, _} and {:error, _} tuples for expected failures the caller can handle. Confidence: 0.90
- Use with blocks for happy-path pipelines over tagged tuples instead of nested case statements. Confidence: 0.80
- Set explicit max_restarts and max_seconds when the defaults would hide a crash loop or take down the whole app too eagerly. Confidence: 0.65
- Avoid storing large binaries or long-lived lists in process state; watch mailbox length and memory per process. Confidence: 0.80
- Use ETS (or persistent_term for rarely changing config) for shared read-heavy data instead of a GenServer that answers lookups. Confidence: 0.80
- Put configuration that depends on the environment in config/runtime.exs and read it at startup, not with compile-time Application.get_env in module attributes. Confidence: 0.90
- Emit :telemetry events for important operations and attach handlers for metrics and logs instead of logging inside every function. Confidence: 0.80
- Use Oban (or another persistent queue) for jobs that must survive restarts; in-memory processes are not a job queue. Confidence: 0.85
- Write tests with start_supervised! so processes are cleaned up between tests, and use async: true whenever state is not global. Confidence: 0.85
- Run Credo and Dialyzer (or the built-in type checker) in CI and keep typespecs on public functions. Confidence: 0.70
- Use mix release for deployment and connect nodes with libcluster only when you truly need distribution. Confidence: 0.75
- Prefer Phoenix.PubSub over hand-rolled process messaging for broadcasting across nodes. Confidence: 0.75
- Use Logger metadata like request_id and user_id rather than string-concatenating context into messages. Confidence: 0.80
Best PracticesPerformanceArchitecture+1
F@f
0
Kotlin Multiplatform taste
Taste

Opinionated Kotlin Multiplatform preferences: share logic not UI by default, thin expect/actual, Ktor and SQLDelight in common code, coroutines and Flow, clean Swift interop and fast CI.

# Kotlin Multiplatform taste of a mobile developer who wants one codebase without fighting either platform
- Share business logic, networking, persistence and validation first; keep native UI per platform unless the team explicitly chooses Compose Multiplatform. Confidence: 0.80
- Start from the official KMP wizard template and keep the module layout boring: shared, androidApp, iosApp. Confidence: 0.75
- Split a growing shared module into feature modules early instead of one giant shared module. Confidence: 0.70
- Keep expect/actual declarations tiny and few; prefer interfaces in common code with platform implementations injected at startup. Confidence: 0.85
- Use Ktor client in commonMain with the platform engines (OkHttp on Android, Darwin on iOS) and kotlinx.serialization for JSON. Confidence: 0.90
- Use SQLDelight or Room for KMP for local storage so schemas and queries live in shared code. Confidence: 0.80
- Use kotlinx-datetime instead of platform date APIs in shared code. Confidence: 0.85
- Expose suspend functions and Flow from shared code and use SKIE or KMP-NativeCoroutines so Swift gets async/await and AsyncSequence. Confidence: 0.80
- Never block the main thread in shared code; inject dispatchers so tests can swap them. Confidence: 0.85
- Keep shared ViewModels or presenters platform-neutral and expose immutable UI state as StateFlow. Confidence: 0.75
- Use Koin or manual constructor injection in common code; avoid DI frameworks that only work on Android. Confidence: 0.70
- Design the Swift-facing API on purpose: avoid generics-heavy, sealed-class-heavy or default-argument APIs that translate badly to Objective-C headers. Confidence: 0.80
- Ship the iOS framework through Swift Package Manager (XCFramework) or direct integration rather than CocoaPods for new projects. Confidence: 0.70
- Manage versions with a Gradle version catalog and keep Kotlin, Compose and AGP versions upgraded together. Confidence: 0.85
- Put build logic in convention plugins instead of copy-pasting Gradle blocks across modules. Confidence: 0.75
- Write most tests in commonTest with kotlin.test and run them on both JVM and iOS simulator targets. Confidence: 0.85
- Use Turbine for testing Flows and fakes over mocking libraries that do not support Kotlin/Native. Confidence: 0.75
- Handle errors with sealed result types at the shared boundary instead of letting Kotlin exceptions crash Swift callers. Confidence: 0.80
- Mark functions that can throw to Swift with @Throws so iOS sees real errors. Confidence: 0.85
- Keep secrets and API keys out of shared code; load them per platform from the build config or a backend. Confidence: 0.85
- Cache Gradle and Kotlin/Native artifacts in CI and run iOS builds only on macOS runners when shared or iOS code changes. Confidence: 0.75
- Let iOS developers review shared module API changes so Kotlin-first decisions do not surprise the Swift side. Confidence: 0.70
Best PracticesArchitectureiOS+2
F@f
0
City in Soft Light: Minimalist Architectural Editorial Poster From Your Photo (JSON Prompt)
TrendingImage
City in Soft Light: Minimalist Architectural Editorial Poster From Your Photo (JSON Prompt)

Upload a photo of any city or landmark and turn it into a quiet editorial art print: a realistic 35mm golden-hour photograph on top, a tiny watercolor miniature of the same place below, generous ivory paper space and the caption "CITY IN SOFT LIGHT."

{
  "aspect_ratio": "3:4",
  "style": "minimalist architectural editorial poster, cinematic photography paired with fine-art print design",
  "reference_instructions": {
    "use_uploaded_image": true,
    "preserve_subject": true,
    "preserve_architecture": true,
    "preserve_recognizable_landmarks": true,
    "preserve_original_composition": false,
    "instruction": "Use the uploaded photograph as the primary reference. Accurately preserve the recognizable buildings, architecture, skyline, structures, and distinctive visual identity of the location while transforming it into a sophisticated minimalist poster composition."
  },
  "composition": {
    "layout": "vertical editorial poster",
    "structure": "two-part visual composition",
    "top_section": {
      "size": "approximately 60 percent of the canvas",
      "content": "a realistic photographic view of the uploaded location",
      "treatment": "warm late-afternoon sunlight, subtle film grain, natural atmospheric perspective, muted cinematic colors",
      "framing": "wide architectural composition with the main landmark clearly visible",
      "photographic_style": "35mm film photography, realistic textures, natural imperfections, soft sunlight and gentle shadows"
    },
    "middle_section": {
      "transition": "large uninterrupted area of warm ivory textured paper",
      "spacing": "generous negative space",
      "divider": "no visible hard border, clean separation between photograph and artwork"
    },
    "bottom_section": {
      "size": "approximately 35 percent of the canvas",
      "content": "a miniature artistic reconstruction of the same cityscape or architecture",
      "placement": "small, centered horizontally and positioned within the lower half",
      "scale": "tiny architectural diorama-like composition surrounded by expansive empty space",
      "style": "soft watercolor, gouache, muted architectural illustration, slightly faded vintage print",
      "details": "retain the recognizable silhouettes and relative positions of the important structures while simplifying minor details"
    }
  },
  "background": {
    "color": "warm cream, ivory, pale beige",
    "texture": "subtle fine-grain handmade paper texture, delicate fibers, vintage print imperfections",
    "appearance": "matte, elegant, tactile, minimal"
  },
  "color_palette": {
    "primary": [
      "warm ivory",
      "sand beige",
      "muted terracotta",
      "dusty blue",
      "soft gray",
      "faded olive"
    ],
    "saturation": "low to moderate",
    "grading": "warm nostalgic film color grading"
  },
  "typography": {
    "text": "CITY IN SOFT LIGHT.",
    "placement": "centered beneath the miniature illustration",
    "font_style": "elegant serif typography",
    "letter_spacing": "wide tracking",
    "font_size": "small and understated",
    "color": "muted dark brown",
    "alignment": "center",
    "additional_text": "none"
  },
  "visual_mood": [
    "quiet",
    "nostalgic",
    "minimalist",
    "architectural",
    "poetic",
    "editorial",
    "museum-quality"
  ],
  "lighting": {
    "photographic_section": "soft golden-hour sunlight",
    "illustration_section": "diffused warm light",
    "shadows": "gentle and natural"
  },
  "rendering": {
    "photorealism": "high in the upper photograph",
    "illustration": "painterly and subtly imperfect in the lower miniature",
    "texture": "visible paper grain throughout",
    "quality": "premium art print, refined visual storytelling, sophisticated design magazine aesthetic"
  },
  "constraints": [
    "Do not invent or replace the main architecture",
    "Do not distort recognizable buildings",
    "Keep the upper photograph realistic",
    "The lower illustration must depict the same location as the photograph",
    "The lower illustration should be significantly smaller than the upper photograph",
    "Maintain large amounts of negative space",
    "Avoid clutter",
    "Avoid excessive decorative elements",
    "Avoid modern graphic design clutter",
    "No borders",
    "No watermark",
    "No extra text",
    "No logos"
  ]
}
ArchitectureJSONImage Generation+2
F@f
0
Architecture Decision Record Builder (JSON)
Text

Capture one important technical decision as an architecture decision record in JSON: neutral context and forces, at least three honestly compared options scored against ranked quality goals, the decision and its trade-offs, first steps, revisit triggers and a ready-to-commit Markdown version.

1{
2 "role": "You are a pragmatic staff engineer who has written and reviewed many architecture decision records (ADRs) for small and mid-sized software teams. You help a team capture one important technical decision so that a new teammate can understand it two years from now: the context and forces at the time, the options that were really considered, why one was chosen, what it costs, and when the decision should be revisited. You write short, honest records, not sales documents for the chosen option.",
3 "context": {
4 "team_and_system": "${team:a 7-person product team running a Django monolith on PostgreSQL with a React front end, about 40,000 daily active users}",
5 "decision_to_record": "${decision:how to run background jobs such as email sending, PDF invoice generation and nightly data syncs}",
6 "options_considered": "${options:keep cron jobs on the web server, Celery with Redis, a managed cloud queue with serverless workers, PostgreSQL-based job queue}",
7 "leaning_or_decided": "${status:the team is leaning toward a PostgreSQL-based job queue but has not decided yet}",
8 "forces_and_constraints": "${forces:jobs sometimes run twice or not at all after deploys, one engineer knows the cron setup, no dedicated ops person, cloud budget is tight, jobs must survive deploys}",
9 "quality_goals": "${quality:reliability and observability first, then low operating effort, then cost}",
10 "evidence_available": "${evidence:last quarter 11 failed or duplicated invoice jobs, a 2-day spike test of two options, rough cost estimates}",
...+118 more lines
Best PracticesArchitectureJSON+4
F@f
0
Enterprise SaaS Architect
Text

Designs and builds scalable SaaS platforms with authentication, organizations, subscriptions, dashboards, and enterprise-grade infrastructure.

Act as a Principal SaaS Architect.

Design and implement a complete SaaS platform.

Include:
- Multi-tenant architecture
- Authentication and authorization
- Organization management
- Role-based access control
- Subscription infrastructure
- Billing integration
- Admin dashboard
- REST or GraphQL APIs
- Database migrations
- Audit logging

Implement real functionality.
Ensure tenant data isolation.
Build scalable and maintainable modules.
Add automated tests for critical workflows.

Do not create a static SaaS dashboard.
ArchitectureSaaSEnterprise+1
P@mirm14354
0
RabbitMQ Messaging taste
Taste

Opinionated preferences for reliable RabbitMQ messaging: quorum queues, publisher confirms, manual acks, dead lettering, retries and idempotent consumers.

# RabbitMQ Messaging taste of an engineer who wants every message accounted for
- Declare exchanges, queues and bindings in code or a definitions file at startup, never by hand in the management UI. Confidence: 0.90
- Use quorum queues for anything that matters; keep classic queues only for throwaway, non-critical traffic. Confidence: 0.90
- Make queues durable and publish messages as persistent, and enable publisher confirms on every producer. Confidence: 0.95
- Publish to a named topic exchange, never to the default exchange with a queue name as routing key. Confidence: 0.80
- Use routing keys shaped like domain.entity.event (orders.order.created) so consumers bind with wildcards. Confidence: 0.80
- Give each consuming service its own queue bound to the exchange; services never share a queue. Confidence: 0.90
- Turn off auto-ack and ack only after the work and its side effects are committed. Confidence: 0.95
- Set a prefetch (basic.qos) per consumer, starting around 10 to 50, instead of leaving it unlimited. Confidence: 0.85
- Make every consumer idempotent with a message_id and a processed-ids table, because delivery is at least once. Confidence: 0.95
- Configure a dead letter exchange for every work queue and alert when the dead letter queue is not empty. Confidence: 0.90
- Retry with delay through a TTL retry queue or the delivery-limit setting, with a capped number of attempts, never a hot requeue loop. Confidence: 0.85
- Reject poison messages without requeue after the retry limit so one bad payload cannot block the queue. Confidence: 0.85
- Send JSON with a content_type, a schema version field and a stable message type header. Confidence: 0.80
- Keep messages small (under about 128 KB) and put large payloads in object storage with a link in the message. Confidence: 0.80
- Propagate trace context (traceparent) in message headers so traces cross the broker. Confidence: 0.80
- Use the transactional outbox pattern to publish events that must match a database write. Confidence: 0.85
- Open one long-lived connection per process and separate channels for publishing and consuming. Confidence: 0.80
- Set queue length limits or message TTLs on queues that can grow without bound. Confidence: 0.75
- Do not use RabbitMQ as a long-term event log; reach for streams or Kafka when replay is a requirement. Confidence: 0.75
- Monitor queue depth, consumer count, unacked messages and publish and deliver rates with the Prometheus plugin. Confidence: 0.85
- Run a three-node cluster for production and use a separate vhost and user per application with least privilege. Confidence: 0.80
- Test consumers against a real broker in CI with Testcontainers instead of mocking the client library. Confidence: 0.75
Best PracticesArchitectureInfrastructure+2
F@f
0
Act as a Legacy Codebase Onboarding Guide
Text

Get productive in an unfamiliar legacy codebase safely: orientation questions, a day-one safety checklist, a reading strategy from entry points and git churn, a one-page architecture sketch, a careful plan for your first task, a questions log and a two-week ramp-up plan.

Act as a Legacy Codebase Onboarding Guide. You are a patient senior engineer who has joined many unfamiliar, poorly documented codebases and knows how to become productive in one without breaking things. I have just joined a team (or inherited a project) and need to understand an existing codebase quickly and safely.

My situation:
- Codebase: a 9-year-old monolith web app with a REST API, background jobs and a relational database
- Main languages and frameworks: Python, Django, Celery, PostgreSQL, some jQuery on the frontend
- Size and age: about 250k lines, 40 contributors over the years, 5 still active
- State of docs and tests: an outdated README, a few wiki pages, patchy unit tests, no architecture diagram
- My role and experience: backend developer, 4 years of experience, new to this domain
- My first assignment: fix a bug where invoice emails are sometimes sent twice
- Time I have to ramp up: 2 weeks
- People I can ask: one tech lead with little free time, a product manager, a retired original author reachable by email

Guide me through the onboarding in this order:

1. Orientation questions. Before giving a plan, ask me up to 5 short questions whose answers would change your advice the most (for example how deployments happen, whether there is a staging environment, who is on call). If I say "skip", continue with sensible assumptions and list them.

2. Day 1 safety checklist. What to set up and verify before touching code: getting the app and tests running locally, read-only access to logs and the production database replica, where secrets live and what never to commit, how to run one test, how a change reaches production and how it is rolled back.

3. Build a mental map. Give me a step-by-step reading strategy that does not try to read everything: start from entry points (routes, CLI commands, job schedulers, message consumers), follow one real request end to end, find the core domain models and the 5-10 files that change most often (show git commands such as `git log --format=format: --name-only | sort | uniq -c | sort -rn | head -30`), identify the oldest and scariest areas, and note configuration and feature flags. Tell me what to write down while reading.

4. Architecture sketch. Show me how to draw a one-page map of the system as a text diagram: components, data stores, external services, queues and the direction of calls. Give a template I can fill in and tell me which questions to ask the tech lead to confirm it in 20 minutes.

5. First task plan. For my first assignment, explain how to find the relevant code (search terms, logs, tracing one example), how to reproduce the problem, how to write a characterization test that pins the current behavior before changing it, how to keep the change small, and what to check in review. Point out typical legacy traps: hidden side effects, global state, implicit ordering, timezone and encoding issues, code paths only used by one big customer, and dead code that is not actually dead.

6. Questions log. Give me a format for a running questions log (question, where I looked, answer, who answered, date) and explain how to batch questions so I respect busy colleagues' time.

7. Two-week ramp-up plan. A day-by-day plan for 2 weeks with concrete goals (for example "Day 3: trace the checkout request end to end and draw it"), each with a small output I can show my lead.

8. Leave it better. Suggest 3-5 small, low-risk improvements a newcomer is perfectly placed to make (README setup steps, a glossary of domain terms, a diagram, a missing test, removing a confusing warning) and how to propose them without sounding critical of the people who built the system.

Rules:
- Be practical and specific to my stack; show real commands and file patterns where useful, but never invent facts about my codebase: when something depends on code you have not seen, say what to look for instead.
- Prefer safe, reversible steps; flag anything that could affect production data or customers.
- Keep each section short and scannable, with checklists where they help.
- End with the 3 things I should do first tomorrow morning.
ArchitectureDocumentationDeveloper+5
F@f
0
Multi-Tenant SaaS taste
Taste

Opinionated preferences for tenant isolation, data modeling and operations in a multi-tenant B2B SaaS.

# Multi-Tenant SaaS taste of a backend architect who builds B2B products
- Start with a shared database and a `tenant_id` column on every tenant-owned table; move to schema- or database-per-tenant only for a proven need. Confidence: 0.85
- Make `tenant_id` NOT NULL and part of every composite index and unique constraint on tenant tables. Confidence: 0.90
- Enforce isolation in the database with Postgres row-level security, not only in application code. Confidence: 0.85
- Resolve the tenant once per request from the authenticated session or token, never from a client-supplied header or body field. Confidence: 0.95
- Carry the tenant in a request context and have the data layer scope every query automatically. Confidence: 0.85
- Write a test for each endpoint that proves a user from tenant A gets 404 for tenant B's resources. Confidence: 0.90
- Return 404 instead of 403 for another tenant's resources so ids don't leak existence. Confidence: 0.80
- Use non-guessable ids (UUIDv7 or prefixed random ids) for anything shown in URLs. Confidence: 0.85
- Model users and organizations separately with a membership table, so one user can belong to many tenants. Confidence: 0.90
- Keep roles per membership (owner, admin, member) and check permissions against the membership, not the user. Confidence: 0.85
- Include `tenant_id` in every cache key, queue message, log line and metric label. Confidence: 0.90
- Prefix object storage paths with the tenant id and issue only short-lived signed URLs. Confidence: 0.85
- Apply rate limits and quotas per tenant so one noisy customer can't degrade everyone else. Confidence: 0.85
- Drive plan limits and features from a per-tenant entitlements record, not scattered `if plan == "pro"` checks. Confidence: 0.80
- Run background jobs with an explicit tenant argument; no job ever processes "all tenants" in one unscoped query. Confidence: 0.80
- Run migrations once for the shared schema and keep them backward compatible, since all tenants upgrade together. Confidence: 0.80
- Support tenant-level data export and hard deletion from day one; enterprise customers and GDPR will ask. Confidence: 0.85
- Keep an audit log per tenant of admin actions, logins and permission changes, visible to tenant admins. Confidence: 0.80
- Offer SSO (SAML/OIDC) and SCIM provisioning as tenant settings, not one-off custom code per customer. Confidence: 0.75
- Let support staff impersonate a tenant user only with an explicit, logged, time-limited session. Confidence: 0.85
- Track usage and cost per tenant so pricing decisions are based on real data. Confidence: 0.75
- Avoid per-tenant code branches; express customer differences as configuration. Confidence: 0.80
SecurityArchitectureDatabase+2
F@f
0
Python Import Cycle Detector
Skill

Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.

---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---

# Python Import Cycle Detector

You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.

## Files in this skill

- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError

## Workflow

### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.

### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.

### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.

### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.

### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.

### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.

## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.

FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)

## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.

So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
  `ImportError: cannot import name 'X' from partially initialized module 'a'` or
  `AttributeError: partially initialized module 'a' has no attribute 'X'`.

Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.

## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |

## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |

## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.

## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.

FILE:references/fix-patterns.md
# Fix patterns for circular imports

Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).

## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.

## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.

## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.

## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
    ...
    if on_success:
        on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.

## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.

## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.

## 7. Deferred import (last resort)
```python
def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.

## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.

## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.

FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})

**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}

## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}

## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |

## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |

## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}

## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`

FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order

__all__ = ["Order", "place_order"]

FILE:examples/shop/models.py
from dataclasses import dataclass

from shop.orders import ORDER_STATUSES


@dataclass
class Customer:
    id: int
    email: str
    status: str = ORDER_STATUSES[0]

FILE:examples/shop/orders.py
from dataclasses import dataclass, field

from shop.models import Customer
from shop import payments

ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]


@dataclass
class Order:
    id: int
    customer: Customer
    total_cents: int
    status: str = "new"
    lines: list = field(default_factory=list)


def place_order(order):
    payments.charge(order)
    order.status = "paid"
    return order

FILE:examples/shop/payments.py
from shop.notifications import send_receipt


def charge(order):
    # pretend to call a payment provider here
    send_receipt(order)
    return True

FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from shop.models import Customer


def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deferred import, runs only when called
    return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])


def greet(customer: "Customer"):
    return "Hello " + customer.email

FILE:examples/shop/utils.py
def cents_to_text(cents):
    return "%d.%02d" % divmod(cents, 100)

FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).

Usage:
  python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
  python3 scripts/import_cycles.py --self-test

Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque

SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
             ".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}


def module_name(path, root):
    rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
    if rel.endswith(".__init__"):
        rel = rel[: -len(".__init__")]
    return rel


def find_root(project):
    """Use project/src if it exists (src layout), else the project dir itself."""
    src = os.path.join(project, "src")
    return src if os.path.isdir(src) else project


def collect_files(root):
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
        for f in sorted(filenames):
            if f.endswith(".py"):
                out.append(os.path.join(dirpath, f))
    return out


class ImportVisitor(ast.NodeVisitor):
    """Collect (target, line, kind, names) where kind is top, deferred or type_checking."""

    def __init__(self, modname, is_pkg):
        self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
        self.found = []

    def _kind(self):
        if self.tc:
            return "type_checking"
        return "deferred" if self.depth else "top"

    def visit_FunctionDef(self, node):
        self.depth += 1; self.generic_visit(node); self.depth -= 1
    visit_AsyncFunctionDef = visit_FunctionDef
    visit_Lambda = visit_FunctionDef

    def visit_If(self, node):
        t = node.test
        is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
                (isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
        if is_tc:
            self.tc += 1
            for n in node.body:
                self.visit(n)
            self.tc -= 1
            for n in node.orelse:
                self.visit(n)
        else:
            self.generic_visit(node)

    def visit_Import(self, node):
        for a in node.names:
            self.found.append((a.name, node.lineno, self._kind(), []))

    def visit_ImportFrom(self, node):
        if node.level:
            parts = self.mod.split(".")
            base = parts if self.is_pkg else parts[:-1]
            up = node.level - 1
            if up > len(base):
                return
            base = base[: len(base) - up] if up else base
            target = ".".join(base + ([node.module] if node.module else []))
        else:
            target = node.module or ""
        names = [a.name for a in node.names]
        self.found.append((target, node.lineno, self._kind(), names))


def resolve(target, names, modules):
    """Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
    hits = []
    if names:
        for n in names:
            sub = target + "." + n if target else n
            if sub in modules:
                hits.append(sub)
    if len(hits) < len(names) or not names:
        t = target
        while t and t not in modules:
            t = t.rpartition(".")[0]
        if t:
            hits.append(t)
    return sorted(set(hits))


def build_graph(project, root=None):
    root = root or find_root(project)
    files = collect_files(root)
    if not files:
        raise ValueError("no .py files under " + root)
    modules = {module_name(f, root): f for f in files}
    edges, errors = {}, []
    for mod, path in modules.items():
        try:
            tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
        except (SyntaxError, UnicodeDecodeError) as e:
            errors.append((mod, str(e).splitlines()[0])); continue
        v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
        for target, line, kind, names in v.found:
            for dst in resolve(target, names, modules):
                if dst == mod:
                    continue
                key = (mod, dst)
                rank = {"top": 0, "deferred": 1, "type_checking": 2}
                old = edges.get(key)
                if old is None or rank[kind] < rank[old["kind"]]:
                    edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
    return root, modules, edges, errors


def sccs(nodes, adj):
    """Tarjan's algorithm, iterative."""
    index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
    for start in sorted(nodes):
        if start in index:
            continue
        work = [(start, iter(sorted(adj.get(start, ()))))]
        index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
        while work:
            v, it = work[-1]
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
                    work.append((w, iter(sorted(adj.get(w, ())))))
                    break
                if w in onstack:
                    low[v] = min(low[v], index[w])
            else:
                work.pop()
                if work:
                    low[work[-1][0]] = min(low[work[-1][0]], low[v])
                if low[v] == index[v]:
                    comp = []
                    while True:
                        w = stack.pop(); onstack.discard(w); comp.append(w)
                        if w == v:
                            break
                    if len(comp) > 1:
                        out.append(sorted(comp))
    return out


def shortest_cycle(comp, adj):
    best = None
    cs = set(comp)
    for s in comp:
        prev, q = {s: None}, deque([s])
        while q:
            v = q.popleft()
            for w in sorted(adj.get(v, ())):
                if w not in cs:
                    continue
                if w == s:
                    path = [v]
                    while prev[path[-1]] is not None:
                        path.append(prev[path[-1]])
                    cyc = list(reversed(path)) + [s]
                    if best is None or len(cyc) < len(best):
                        best = cyc
                    q.clear(); break
                if w not in prev:
                    prev[w] = v; q.append(w)
    return best


def analyze(project, root=None, include_tc=False):
    root, modules, edges, errors = build_graph(project, root)
    use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
    top = {k: v for k, v in use.items() if v["kind"] == "top"}
    def adj_of(es):
        a = {}
        for (s, d) in es:
            a.setdefault(s, set()).add(d)
        return a
    adj_all, adj_top = adj_of(use), adj_of(top)
    groups, findings = [], []
    top_sccs = [set(c) for c in sccs(modules, adj_top)]
    for comp in sccs(modules, adj_all):
        cyc = shortest_cycle(comp, adj_all)
        cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
        import_time = any(set(comp) & t for t in top_sccs)
        inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
        # break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
        cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
        brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
        g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
                 import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
        groups.append(g)
        label = " -> ".join(cyc)
        if import_time:
            findings.append(("high", "IC01", "import-time cycle: " + label))
        else:
            findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
        if len(comp) >= 5:
            findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
        for e in cyc_edges:
            if e["file"].endswith("__init__.py") and e["kind"] == "top":
                findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
            if e["kind"] == "top" and e["names"] == ["*"]:
                findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
    tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
    if tc_only and not include_tc:
        findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
    for mod, err in errors:
        findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
    return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
                findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])


def render(res):
    L = ["# Import cycle report", "",
         "Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
         (res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
    for i, g in enumerate(res["groups"], 1):
        L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
        L.append("Modules: " + ", ".join(g["modules"]))
        L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
        for e in g["cycle_edges"]:
            L.append("  - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
                     (" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
        if g["other_edges"]:
            L.append("Other imports inside this group:")
            for e in g["other_edges"]:
                L.append("  - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
        b = g["break_candidate"]
        L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
        L.append("")
    if not res["groups"]:
        L += ["No import cycles between project modules.", ""]
    L.append("## Findings")
    order = {"high": 0, "medium": 1, "low": 2, "info": 3}
    for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
        L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
    if not res["findings"]:
        L.append("- none")
    return "\n".join(L)


def self_test():
    import tempfile
    ok = [0, 0]
    def check(name, cond):
        ok[0 if cond else 1] += 1
        print(("PASS  " if cond else "FAIL  ") + name)
    def proj(files):
        d = tempfile.mkdtemp()
        for rel, txt in files.items():
            p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
            open(p, "w").write(txt)
        return d
    r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
    check("no cycle in a -> b", not r["groups"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
    check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
    r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
    check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n    import a\n"}))
    check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}))
    check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}), include_tc=True)
    check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
    check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
    r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
    check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
    check("from pkg import submodule maps to the submodule", not r["groups"])
    r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
    check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
    r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
    check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
    files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
    r = analyze(proj(files))
    check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
    r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
    check("stdlib imports ignored", r["edges"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
    check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
    r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
    check("venv folder skipped", r["modules"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    b = r["groups"][0]["break_candidate"]
    check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
    try:
        analyze(proj({"README.md": "x"})); check("empty project rejected", False)
    except ValueError:
        check("empty project rejected", True)
    print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
    return 0 if not ok[1] else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("project", nargs="?")
    ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--include-type-checking", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.project or not os.path.isdir(a.project):
        print("error: give a project directory", file=sys.stderr); return 2
    try:
        res = analyze(a.project, a.root, a.include_type_checking)
    except ValueError as e:
        print("error:", e, file=sys.stderr); return 2
    print(json.dumps(res, indent=2) if a.json else render(res))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
ArchitectureRefactoringEngineering+3
F@f
0
Design a wellness resort
Text

I'm architecture student and I have a project of resort design in my design subject so this is my site and the north is upward side and the location is near Palampur Himachal Pradesh and no I have to design a resort in this site in which I hai to make a service room, reception, gazebo, open seating area 1 meditation hall, 4, 5 treatment room, 4 double cottages and 3 single cottages, 1 cafe and restaurant and also design a good landscape, or garden

I'm architecture student and I have a project of resort design in my design subject so this is my site and the north is upward side and the location is near Palampur Himachal Pradesh and no I have to design a resort in this site in which I hai to make a service room, reception, gazebo, open seating area 1 meditation hall, 4, 5 treatment room, 4 double cottages and 3 single cottages, 1 cafe and restaurant and 
also design a good landscape, or garden
Architecture
A@arch240323010005ayush
0
Renaissance Sgraffito Wall Panel of a Lemon Tree with Swallows
Image
Renaissance Sgraffito Wall Panel of a Lemon Tree with Swallows

Italian Renaissance-style sgraffito plaster panel in cream and charcoal: a lemon tree heavy with fruit in an ornate urn, two swallows in its branches, framed by scrolling acanthus leaves and a lattice border, with crisp scratched lines, cross-hatched shading, trowel texture and gentle weathering.

An authentic Italian Renaissance-style sgraffito wall panel of a lemon tree in an ornate urn, portrait 3:4, photographed straight on. A tall lemon tree rises from a decorated, patterned urn, its branches heavy with round lemons and pointed leaves, with two small swallows perched in the upper branches; the panel is framed by a border of scrolling acanthus leaves and a lattice band. Sgraffito technique details: two layers of lime plaster, a dark charcoal-grey under layer revealed wherever the cream-white top layer has been scratched and scraped away; crisp incised outlines and cross-hatched shading cut with a metal stylus; slightly raised edges and tiny crumbs along the cut lines; flat areas of creamy plaster with subtle trowel texture; gentle weathering, hairline cracks and a few chipped spots at the corners. Two tones only, cream and charcoal grey, with no paint colors. Soft even daylight raking slightly from the left to show the shallow relief of the cuts. Calm, elegant, Mediterranean mood. No text, no signature, no people, no modern objects.
ArchitectureVisualCreative+2
F@f
0
Surrealist Nested-Arch Travel Art: Fill-in Template That Frames Any Landmark Through Infinite Portals (4:5)
Image
Surrealist Nested-Arch Travel Art: Fill-in Template That Frames Any Landmark Through Infinite Portals (4:5)

A reusable collectible travel-art template: name a landmark, city and country and the model frames it inside a monumental arch with a smaller nested arch for infinite depth, adds a dreamlike landscape, a lone traveller with footprints, an oversized sun or crescent moon, a unique colour palette and minimal typography with a tiny poetic tagline.

Create an exceptionally beautiful surrealist architectural travel artwork featuring LANDMARK NAME, CITY, COUNTRY.

1. THE SIGNATURE COMPOSITION

Create a monumental architectural arch or doorway as the dominant foreground frame.
Inside the arch, reveal a breathtaking surreal landscape featuring the iconic landmark.
Add a second, smaller nested arch in the centre, creating an illusion of infinite depth.
Position the landmark naturally within this inner portal, preserving its recognisable architectural details.

2. DREAMLIKE LANDSCAPE

Surround the landmark with abstract rolling landscapes inspired by the destination.
Add a tiny solitary traveller walking towards the inner arch.
Create a delicate trail of footprints leading towards the landmark.
Introduce a crescent moon or oversized sun in the distant sky.
Use beautiful gradients, dramatic shadows and atmospheric lighting.

3. COLOUR IDENTITY

Every destination must have its own distinctive palette. Never repeat colours.

4. ART DIRECTION

Surrealist architectural photography.
Minimalist geometric composition.
Cinematic colour grading.
Monumental arches and nested frames.
Dreamlike scale and perspective.
Rich textures and soft atmospheric gradients.
Deep, sophisticated shadows.

5. TYPOGRAPHY

Add the country and landmark name in elegant minimal typography, with a tiny poetic tagline.

No clutter, no unnecessary decorations, no random buildings. Premium collectible travel-art aesthetic. Vertical 4:5

Keep the nested arches as the signature element in every poster, but change the landscape, lighting, colour palette and architectural details for every destination. That will make the collection instantly recognisable while keeping every artwork unique.
ArchitectureTemplateGPT Image+3
F@f
0
3D Layered Paper-Cut Architectural Travel Poster: Fill-in Template for Any Landmark, City and Country (2:3)
Image
3D Layered Paper-Cut Architectural Travel Poster: Fill-in Template for Any Landmark, City and Country (2:3)

A reusable travel-poster template: fill in [LANDMARK NAME], [CITY] and [COUNTRY] and the model builds the destination as a handcrafted miniature diorama from layered, sculpted coloured paper, with paper-cut hills, rivers and clouds, a destination-specific palette, an organic paper-cut frame and minimal typography with a short poetic tagline.

Create an extraordinarily beautiful 3D layered paper-cut architectural travel poster featuring [LANDMARK NAME], [CITY], [COUNTRY].

Transform the destination into an enchanting miniature architectural world, crafted entirely from intricately layered, sculpted and cut coloured paper.

1. CENTRAL ARCHITECTURAL SCENE

Feature the destination’s most iconic landmark as the main attraction.
Preserve its authentic and recognisable architectural identity.
Recreate buildings using multiple layers of carefully cut paper.
Include distinctive rooftops, windows, arches, towers, domes, bridges or architectural details specific to the destination.
Arrange smaller surrounding buildings to create a charming miniature cityscape.
Make the entire scene resemble a beautifully handcrafted architectural diorama.

2. LAYERED PAPER LANDSCAPE

Build an extraordinary three-dimensional environment.

Flowing paper-cut hills and sculpted mountains.
Layered rivers, lakes, coastlines or ocean waves where appropriate.
Curved bridges, winding pathways and miniature staircases.
Overlapping paper clouds, hills and architectural backgrounds.
Intricate foreground elements framing the composition.
Beautiful irregular paper-cut edges surrounding the scene.

Every layer should have visible depth, delicate edges and realistic cast shadows.

3. UNIQUE DESTINATION DETAILS

Include small architectural and cultural elements that make each destination instantly recognisable.

Select details according to the location rather than repeating the same decorations.

4. DESTINATION-SPECIFIC COLOUR PALETTE

Create a completely original colour identity for every destination.

Use 6–9 harmonious shades inspired by its architecture, culture, landscape and atmosphere.

Combine rich colours, soft pastels, contrasting paper layers and carefully selected neutral tones.

Never repeat the same palette between different destinations.

5. THREE-DIMENSIONAL PAPER ART

Authentic handmade paper-cut aesthetic.
Multiple overlapping cardstock layers.
Sculpted paper architecture.
Delicate folded and curved paper details.
Visible paper thickness.
Soft realistic shadows between layers.
Beautiful tactile textures.
Intricate miniature craftsmanship.
Gentle studio lighting.

The artwork must look like a real handcrafted paper sculpture photographed professionally, not a flat illustration or plastic 3D render.

6. DISTINCTIVE POSTER COMPOSITION

Place the entire architectural scene inside an elegant irregular organic paper-cut frame.

Use a balanced vertical composition with:

Large miniature architectural scene in the centre.
Beautiful layered foreground.
Subtle surrounding negative space.
Soft neutral background.
Realistic depth and dimensional shadows.

7. MINIMAL TYPOGRAPHY

Below the artwork, write:

[CITY / DESTINATION NAME]

[COUNTRY]

Add one short, elegant poetic tagline of approximately 3–6 words inspired by the destination.

Use elegant uppercase modern typography for the destination name and a delicate refined serif font for the tagline.

Keep typography minimal, correctly spelled and beautifully positioned.

8. FINAL ART DIRECTION

A breathtaking fusion of miniature architecture, layered paper sculpture, handcrafted papercraft, whimsical storytelling and premium contemporary travel poster design.

Extremely intricate craftsmanship, sophisticated colour harmony, realistic paper shadows, beautiful depth, exquisite architectural details and museum-quality presentation.

Portrait 2:3 composition. No watermark, no unnecessary text, no photorealistic buildings, no plastic appearance.
ArchitectureTemplatePaper+3
F@f
1
Giant-Letter Landmark Poster: Fill-in Template That Merges Any Landmark Into One Oversized Typographic Letter (4:5)
Image
Giant-Letter Landmark Poster: Fill-in Template That Merges Any Landmark Into One Oversized Typographic Letter (4:5)

A reusable template for collectible architectural art prints: fill in [LANDMARK NAME], [CITY] and [COUNTRY] and the model builds one enormous uppercase letter from the destination's name, fuses the landmark into it as a double exposure, colours it with a palette drawn from the place's culture, and finishes it with editorial Swiss-style typography, coordinates and a tagline on textured ivory paper.

Create an exceptionally sophisticated, contemporary architectural art poster featuring [LANDMARK NAME], [CITY], [COUNTRY].

1. GIANT TYPOGRAPHIC COMPOSITION

Feature one enormous, oversized uppercase letter associated with the destination name as the central graphic element.

The letter should dominate the composition, extending almost across the entire poster.

Use bold, elegant, geometric typography with distinctive curves and negative spaces.

2. LANDMARK INTEGRATION

Seamlessly integrate a highly detailed architectural photograph or realistic architectural illustration of [LANDMARK NAME] into and across the oversized letter.

The landmark should appear to emerge from the typography, partially overlap its boundaries and interact naturally with its shape.

Preserve the landmark’s authentic architectural details, proportions and recognisable silhouette.

Create an artistic double-exposure effect where the architecture and typography become one unified visual composition.

3. DISTINCTIVE COLOUR TREATMENT

Choose a unique colour palette inspired by the destination’s cultural identity, national colours and architectural character.

Use two or three contrasting colours within the oversized typography.

Apply translucent colour overlays across selected sections of the landmark, creating a beautiful combination of architectural photography, coloured light and graphic shapes.

Every new destination must receive a different colour combination. Never repeat palettes.

4. TEXTURE & BACKGROUND

Use a warm ivory, soft white or subtle textured paper background.

Introduce delicate architectural sketch marks, distressed ink textures, faded photographic grain and subtle print imperfections around the central composition.

Keep the surrounding space clean and uncluttered.

5. EDITORIAL TYPOGRAPHY

Include the following information:

[LANDMARK NAME]

[CITY NAME]

[COUNTRY NAME]

Add small vertical typography along one side, geographical coordinates and a subtle destination-inspired tagline.

Use sophisticated editorial typography with carefully balanced spacing.

6. ART DIRECTION

Luxury architectural editorial design, experimental typography, architectural double exposure, contemporary Swiss graphic design, oversized letterforms, cinematic monochromatic photography, translucent colour blocking and minimalist gallery poster aesthetics.

7. FINAL PRESENTATION

Create a visually striking, intellectual and artistic collectible landmark poster.

The architecture must remain recognisable while becoming an integral part of the oversized letter.

Vertical 4:5 composition, premium art-print quality, exceptional visual balance and sophisticated negative space.

Avoid ordinary travel-poster layouts, decorative clutter, excessive colours and generic typography.
ArchitectureDesignImage Generation+3
F@f
1
Video
Luxury Contemporary Mansion FPV Walkthrough: Golden-Hour Rooftop Pool to Double-Height Interior (16:9 Real Estate Video)

A hyper-realistic cinematic architectural walkthrough for luxury real estate videos. It opens on a rooftop infinity pool above a city skyline at golden hour, reveals a multi-level glass-and-dark-frame contemporary mansion, then flies FPV-drone style around the terraces, through the glass into a marble living room and down a hallway to a double-height ceiling as day turns to a warm evening. Includes visual style, 16:9, a 10-15 s duration and an avoid list.

Create a hyper-realistic cinematic architectural walkthrough of an ultra-luxurious contemporary mansion during golden hour, transitioning smoothly into a warm evening atmosphere.

**Opening Scene:** Begin with a breathtaking rooftop infinity swimming pool overlooking a beautiful modern city skyline. Golden sunlight reflects across the water as the camera glides forward.

**Exterior Architecture:** Reveal a spectacular multi-level contemporary mansion featuring floor-to-ceiling glass windows, dark architectural framing, minimalist geometric structures, spacious terraces, landscaped greenery, and premium materials.

**Camera Movement:** Use a smooth, continuous FPV drone-style cinematic movement. Fly around the exterior terrace, glide between the architectural structures, and smoothly enter the house through the glass openings.

**Interior Tour:** Transition into an expansive luxury living room featuring polished marble flooring, designer furniture, elegant cream-colored sofas, warm ambient lighting, modern artwork, a sophisticated open-plan layout, and enormous glass windows overlooking the surroundings.

**Final Scene:** Move through the elegant interior hallway, revealing breathtaking architectural details and a stunning double-height ceiling.

**Visual Style:** Photorealistic luxury real estate commercial, ultra-modern architecture, cinematic golden-hour lighting, realistic reflections, sophisticated neutral color palette, 4K detail, professional architectural cinematography, smooth stabilized camera movement.

**Aspect Ratio:** 16:9  
**Duration:** 10–15 seconds  
**Quality:** Ultra-realistic, cinematic, premium architectural visualization.

**Avoid:** People, distorted architecture, flickering lights, warped windows, unrealistic reflections, camera jitter, text, logos, and watermarks.
ArchitectureTrendingVideo Generation+7
F@f
1
Video
Acropolis at Golden Sunrise: 15-Shot Historical Documentary with 1-Second Hard Cuts (15s Video)

A 15-second photoreal historical documentary of the Acropolis of Athens at golden sunrise, built as exactly 15 one-second shots with clean hard cuts: aerial reveal, drone glide to the Parthenon, column close-ups, an orbit, the Caryatids of the Erechtheion and a final aerial pull-back over the city. Includes visual style, orchestral audio and consistency rules for accurate architecture and sunrise direction. Swap in any other historic landmark to reuse the shot list.

Create an ultra-realistic 15-second cinematic historical documentary of the Acropolis of Athens, Greece, during a spectacular golden sunrise. Exactly 15 rapid shots, 1 second each, with clean hard cuts and smooth visual continuity.

Shot sequence:

1. Aerial establishing shot revealing the entire Acropolis above Athens.
2. Smooth drone glide toward the ancient Parthenon.
3. Wide symmetrical view of the Parthenon glowing in sunrise light.
4. Close-up of massive ancient Greek marble columns.
5. Slow tilt-up revealing the magnificent temple architecture.
6. Cinematic orbit around the Parthenon.
7. Close-up of intricate ancient stone carvings and sculptures.
8. Side-angle tracking shot along the majestic columns.
9. Tracking shot across ancient marble pathways.
10. Low-angle hero shot emphasizing the towering columns.
11. Pan across the Erechtheion and its famous Caryatid statues.
12. Golden sunlight illuminating weathered marble textures.
13. Elevated aerial view showing Athens stretching toward the horizon.
14. Close-up revealing ancient architectural details and stone textures.
15. Spectacular aerial pull-back revealing the entire Acropolis beneath the glowing sunrise sky.

Visual style: Photorealistic 4K HDR, premium historical documentary cinematography, authentic ancient Greek architecture, warm golden-pink sunrise, soft atmospheric haze, realistic marble textures, cinematic drone movements, natural shadows, stable geometry, no flickering or distortion.

Audio: Epic orchestral soundtrack with subtle ancient Greek-inspired instrumental atmosphere.

Consistency: Maintain historically accurate architecture, consistent sunrise direction, realistic geography, and smooth visual continuity across all 15 shots.
ArchitectureVisual SequenceTrending+7
F@f
1
Database Schema Design taste
Taste

Opinionated conventions for designing clear, constraint-driven relational database schemas.

# Database Schema Design taste of a pragmatic relational modeler
- Use surrogate primary keys (`bigint` identity or UUIDv7) on every table and enforce natural keys with separate unique constraints. Confidence: 0.85
- Name tables as plural snake_case nouns and columns as singular snake_case, with foreign keys named `<referenced_table_singular>_id`. Confidence: 0.80
- Declare every foreign key constraint in the database instead of relying on the application to keep references valid. Confidence: 0.95
- Mark columns `NOT NULL` by default and allow nulls only when "unknown" is a genuinely different state from an empty value. Confidence: 0.90
- Store timestamps as `timestamptz` in UTC and add `created_at` and `updated_at` to every mutable table. Confidence: 0.90
- Store money as integer minor units or `numeric` with an explicit currency column, never as floating point. Confidence: 0.95
- Normalize to third normal form first and denormalize only for a measured read path, documenting why the copy exists and how it stays in sync. Confidence: 0.85
- Use `CHECK` constraints for simple invariants such as positive quantities, valid ranges and allowed status values. Confidence: 0.85
- Prefer a lookup table or a check constraint over native enum types when the set of values is likely to change. Confidence: 0.70
- Model many-to-many relationships with an explicit join table that has its own composite unique key and room for attributes like role or created_at. Confidence: 0.85
- Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90
- Add indexes from real query patterns and `EXPLAIN` output, not speculatively on every column. Confidence: 0.85
- Use partial indexes for hot subsets, such as active rows or unprocessed jobs, instead of indexing the whole table. Confidence: 0.75
- Keep soft deletes out of the core schema unless they are a product requirement; when needed, pair `deleted_at` with partial unique indexes. Confidence: 0.70
- Use `jsonb` only for genuinely schemaless or third-party payloads, and promote any field you filter or join on into a real column. Confidence: 0.85
- Avoid polymorphic foreign keys (`owner_type` plus `owner_id`); use separate nullable foreign keys with a check constraint or separate join tables. Confidence: 0.80
- Keep audit history in an append-only table or temporal table rather than overwriting rows and losing the past. Confidence: 0.75
- Choose `ON DELETE` behavior deliberately per relationship: `RESTRICT` by default, `CASCADE` only for owned child rows. Confidence: 0.85
- Never store comma-separated lists in a column; model repeating values as rows. Confidence: 0.95
- Keep multi-tenant data in shared tables with a mandatory `tenant_id` in every key and index, enforced with row-level security where available. Confidence: 0.75
- Review every schema change as a migration in version control together with the code that depends on it. Confidence: 0.90
- Document each table and non-obvious column with `COMMENT ON` so the schema explains itself in any database client. Confidence: 0.65
Best PracticesArchitectureDatabase+2
F@f
0
Kafka Streaming taste
Taste

Opinionated conventions for reliable, schema-governed Kafka event streaming and consumers.

# Kafka Streaming taste of a pragmatic event platform engineer
- Name topics by domain and event, such as `orders.order-placed.v1`, and put the schema version in the name only when a breaking change forces a new topic. Confidence: 0.85
- Register every topic schema in a schema registry (Avro or Protobuf) with backward compatibility enforced; never publish raw untyped JSON to shared topics. Confidence: 0.90
- Choose the partition key from the entity whose ordering matters (order id, account id), and never rely on ordering across partitions. Confidence: 0.95
- Start with enough partitions for expected peak consumer parallelism plus headroom, because increasing partitions later breaks key-to-partition mapping. Confidence: 0.80
- Run producers with `acks=all`, idempotence enabled and `min.insync.replicas=2` on a replication factor of 3 for anything business-critical. Confidence: 0.90
- Treat delivery as at-least-once and make every consumer idempotent with a dedupe key or upsert, instead of chasing end-to-end exactly-once. Confidence: 0.90
- Commit offsets only after the side effect has succeeded; disable auto-commit for consumers that write to databases or call APIs. Confidence: 0.90
- Send messages that fail repeatedly to a dead-letter topic with the original headers, error and attempt count, and alert on its growth. Confidence: 0.85
- Retry transient failures with bounded backoff inside the consumer before dead-lettering; never block a partition forever on one poison message. Confidence: 0.85
- Keep events as facts in past tense that describe what happened, not commands telling another service what to do. Confidence: 0.80
- Keep payloads small and self-contained enough to process without a synchronous call back to the producer, but put large blobs in object storage and send a reference. Confidence: 0.75
- Use the transactional outbox pattern to publish events atomically with database writes instead of dual writes. Confidence: 0.90
- Use log compaction for topics that represent the latest state per key, and time-based retention for pure event streams. Confidence: 0.85
- Monitor consumer lag per group and partition as the primary health signal, alerting on sustained growth rather than single spikes. Confidence: 0.90
- Put a correlation id and the producing service name in message headers so traces can follow an event across services. Confidence: 0.80
- Give every consumer group a stable, descriptive id tied to the service, and never share one group between unrelated applications. Confidence: 0.85
- Reach for Kafka Streams or Flink only when you need stateful joins or windowing; a plain consumer is simpler for stateless transforms. Confidence: 0.75
- Manage topics, partitions, retention and ACLs as code reviewed in pull requests, and disable automatic topic creation in production. Confidence: 0.90
- Lock down clusters with TLS, authenticated clients and per-service ACLs that grant only the topics each service needs. Confidence: 0.85
- Test consumers against a real broker in containers for integration tests, and keep unit tests on pure handler functions. Confidence: 0.80
- Document each topic's owner, schema, key, retention and consumers in a catalog that lives next to the topic definitions. Confidence: 0.70
Best PracticesArchitectureEvent Driven+2
F@f
0
Isometric Cutaway of a Busy Corner Coffee Roastery at Dawn
Image
Isometric Cutaway of a Busy Corner Coffee Roastery at Dawn

Isometric cutaway of a busy two-story corner coffee roastery at dawn: ground-floor drum roaster, burlap sacks, cooling beans and packing counter, upstairs cupping nook, warm sunrise through corner windows, soft clay-like diorama style in terracotta, cream and sage, no readable text or logos.

An isometric cutaway illustration of a busy corner coffee roastery at dawn, landscape 4:3. The two-story brick corner building is sliced open to show a ground-floor roasting room with a large drum roaster, burlap coffee sacks, a cooling tray of glossy brown beans, and a small packing counter, while upstairs a tiny tasting nook has a cupping table and shelves of sample jars. Warm early sunlight enters through tall corner windows; a bicycle leans outside by the door; steam rises from a cup on the counter. Soft clay-like 3D diorama style, neat tiny details, pastel morning palette with terracotta, cream, and sage, clean edges, lively but orderly mood. No readable text, no logos, no watermarks, no brand names on bags or signs.
ArchitectureVisualDesign+3
F@f
1
Cutaway Illustration of a Cozy Three-Level Treehouse Library at Dusk
Image
Cutaway Illustration of a Cozy Three-Level Treehouse Library at Dusk

Detailed storybook cutaway of a giant oak at dusk with three lamp-lit library rooms inside: a red armchair reading nook at the bottom, curved bookshelves with a ladder in the middle, and an attic with a brass telescope under a shingled roof, plus a spiral staircase, a lantern-lit rope bridge, falling orange autumn leaves, and a sunset sky.

A detailed cutaway illustration of a cozy three-level treehouse library built inside the trunk of a giant oak tree at dusk, landscape 4:3. The trunk is cut open to show three warm, lamp-lit rooms. The bottom level has a red velvet armchair with a patterned cushion and a knitted throw, a round braided rug, a lantern on a small side table, low bookshelves, a small round window, and ivy around the opening. The middle level has curved floor-to-ceiling bookshelves packed with books, a round window, a wooden ladder leading up, a hanging lantern, a glowing desk lamp, and a potted plant on the left. The top level is an attic under a shingled gable roof with a round window, a brass telescope on a tripod, and a desk covered with books. Outside, a wooden spiral staircase winds up the right side of the trunk, and a rope bridge hung with glowing lanterns stretches off to the right. Orange autumn leaves cling to the branches and drift through the air over a forest, under a deep blue dusk sky fading to an orange sunset on the right. Storybook style, fine ink lines, warm painted colors. No people, no text, no logos.
ArchitectureVisualCreative+3
F@f
0
Phoenix App taste
Taste

Opinionated conventions for building maintainable, real-time web apps with Elixir, Phoenix and LiveView.

# Phoenix App taste of a pragmatic Elixir engineer
- Start new projects on the latest stable Elixir and Phoenix releases, and pin Erlang/OTP and Elixir versions in .tool-versions. Confidence: 0.85
- Group business logic into Phoenix contexts with small public APIs, and never call Repo directly from controllers or LiveViews. Confidence: 0.90
- Keep contexts from reaching into each other's schemas, and talk across boundaries through public context functions. Confidence: 0.80
- Use LiveView for interactive pages by default and add JavaScript hooks only for things the browser must do itself. Confidence: 0.80
- Build UI from function components with declared attrs and slots instead of large shared templates. Confidence: 0.85
- Validate all input with Ecto changesets and keep separate changesets for different actions like registration and profile updates. Confidence: 0.90
- Lean on database constraints with unique_constraint and foreign_key_constraint instead of check-then-insert code. Confidence: 0.95
- Preload associations explicitly in context functions, and never let a template trigger an N+1 query. Confidence: 0.85
- Use Ecto.Multi or Repo.transaction for multi-step writes so partial failures roll back cleanly. Confidence: 0.85
- Write reversible migrations, and split long-running data backfills into separate tasks rather than schema migrations. Confidence: 0.85
- Read runtime settings and secrets in config/runtime.exs from environment variables, never in compile-time config. Confidence: 0.95
- Run background work with Oban backed by Postgres, with unique jobs and retries, instead of bare Task.start calls. Confidence: 0.85
- Put long-lived processes under a supervisor with a clear restart strategy and let them crash instead of rescuing every error. Confidence: 0.90
- Avoid GenServers as a place to hold data the database already owns; use them for real concurrency or coordination. Confidence: 0.80
- Return tagged tuples like {:ok, value} and {:error, reason} from context functions and handle them with with blocks. Confidence: 0.90
- Use PubSub for live updates between LiveViews and keep the broadcast topic names defined in one module. Confidence: 0.75
- Generate auth with phx.gen.auth and extend it, rather than building login and session handling from scratch. Confidence: 0.80
- Format code with mix format and run Credo and Dialyzer in CI so style and type issues fail the build. Confidence: 0.80
- Test contexts with DataCase and the SQL sandbox, and test LiveViews with Phoenix.LiveViewTest instead of a browser. Confidence: 0.85
- Emit metrics through Telemetry and watch them in LiveDashboard and an external metrics backend in production. Confidence: 0.75
- Ship releases built with mix release inside a small Docker image, and run migrations from a release command. Confidence: 0.80
- Cluster nodes with dns_cluster or libcluster only when the app really needs distributed PubSub or presence. Confidence: 0.70
Best PracticesArchitectureBackend+1
F@f
0
gRPC Service taste
Taste

Opinionated conventions for designing, evolving and running reliable gRPC services with Protocol Buffers.

# gRPC Service taste of a pragmatic distributed systems engineer
- Keep all .proto files in one shared schema repo or directory with a single owner per package, and generate code from it in CI. Confidence: 0.85
- Lint and check every proto change for breaking changes with buf lint and buf breaking before it can merge. Confidence: 0.90
- Version packages in the name, such as billing.v1, and add a new v2 package instead of changing the meaning of existing fields. Confidence: 0.90
- Never reuse or renumber a field tag, and mark removed fields and names as reserved. Confidence: 0.95
- Give every RPC its own request and response message, even when it starts empty, so fields can be added later. Confidence: 0.90
- Follow the resource-oriented method style of Get, List, Create, Update and Delete instead of ad hoc verbs where it fits. Confidence: 0.75
- Use field masks for partial updates rather than treating unset fields as a request to clear them. Confidence: 0.80
- Paginate every List call with page_size and an opaque page_token, and cap the page size on the server. Confidence: 0.90
- Use well-known types like google.protobuf.Timestamp and Duration instead of raw integers for time values. Confidence: 0.85
- Return the canonical status codes correctly, such as NOT_FOUND, INVALID_ARGUMENT and UNAVAILABLE, and never wrap every failure in UNKNOWN. Confidence: 0.90
- Attach structured error details with the richer error model for validation failures instead of packing them into the message string. Confidence: 0.75
- Require a deadline on every client call and propagate the remaining deadline to downstream calls. Confidence: 0.95
- Retry only idempotent methods, with backoff and a retry budget configured in the service config, not in hand-written loops. Confidence: 0.85
- Pass request IDs, auth tokens and tracing context in metadata, and keep business data in the message body. Confidence: 0.85
- Put logging, auth, metrics and tracing in interceptors instead of repeating them inside each handler. Confidence: 0.90
- Use mutual TLS between internal services and verify per-call credentials on the server for anything sensitive. Confidence: 0.85
- Implement the standard gRPC health checking service and enable server reflection only outside production. Confidence: 0.80
- Prefer unary calls, and use streaming only when the data is truly incremental or long-lived. Confidence: 0.80
- Apply flow control and backpressure on streams, and send keepalive pings within limits the load balancer allows. Confidence: 0.70
- Balance load per request with an L7 proxy or client-side balancing, because HTTP/2 connections pin traffic to one backend. Confidence: 0.85
- Expose a REST or JSON gateway generated from the same protos for browsers and partners instead of maintaining a second API by hand. Confidence: 0.70
- Test handlers with an in-process server and real generated clients rather than mocking the generated stubs. Confidence: 0.80
- Document each service, method and field with comments in the proto file, since that is where readers look first. Confidence: 0.85
Best PracticesArchitectureAPI+1
F@f
0
1 / 4Next