This prompt is designed for architects, tech leads, and platform engineers who need to systematically detect when a codebase's implementation has diverged from its intended architecture. The core job-to-be-done is comparing a formal or semi-formal architecture specification—such as Architecture Decision Records (ADRs), dependency rule documents, or module boundary definitions—against the current state of the code, including its import graph, package structure, and module map. The ideal user has access to both the documented architecture and tooling that can extract a dependency graph from the codebase (e.g., madge, dependency-cruiser, or a build graph). The output is a structured drift report that doesn't just flag violations but distinguishes between unintentional erosion and intentional, accepted exceptions.
Prompt
Architecture Drift Detection Prompt

When to Use This Prompt
Defines the precise conditions, required inputs, and user profile for the Architecture Drift Detection Prompt, and explicitly warns when it should not be used.
To use this prompt effectively, you must provide two concrete inputs: a machine-readable or clearly structured representation of the intended architecture rules, and a current dependency graph or module map from the codebase. The architecture rules should specify allowed and disallowed dependencies between modules, layers, or bounded contexts. For example, a rule might state 'domain layer must not import infrastructure layer' or 'feature modules must not depend on each other.' The dependency graph should be a list of source-to-target import relationships. Without both inputs, the model cannot perform a meaningful comparison and will either hallucinate a reference architecture or produce a generic, unactionable report. The prompt is not a substitute for a static analysis tool; it is a reasoning layer that interprets the delta between specification and reality.
Do not use this prompt when no architecture documentation exists. If your team operates without ADRs, dependency diagrams, or explicit module contracts, the model will fabricate a plausible but fictional reference architecture, leading to a drift report that is actively misleading. In such cases, start with a prompt for architecture discovery or module coupling audit to first document the as-is state. Similarly, avoid this prompt for small, single-module projects where the concept of architecture drift is not meaningful. The prompt is also unsuitable for runtime behavioral drift (e.g., performance degradation or API response changes) unless that drift is reflected in static code structure. Finally, the output of this prompt is a diagnostic report, not an automated refactoring script. Human review is required to validate each finding, confirm that flagged exceptions are truly intentional, and decide on remediation actions.
Use Case Fit
Where the Architecture Drift Detection Prompt works, where it fails, and what you must have in place before running it.
Good Fit: Documented Architecture Exists
Use when: you have Architecture Decision Records (ADRs), dependency diagrams, or explicit module boundary rules. The prompt compares declared intent against code reality. Avoid when: architecture exists only in tribal knowledge or informal conversations. Without a written reference, the model hallucinates what the architecture 'should' be.
Bad Fit: Greenfield or Rapid Prototyping
Avoid when: the codebase is in early exploration with intentionally fluid boundaries. Drift detection assumes a stable target architecture. Risk: the prompt flags intentional experimentation as violations, generating noise that desensitizes the team to real drift. Use lightweight convention checks instead.
Required Input: Machine-Readable Architecture Spec
Guardrail: the prompt needs structured input—module allowlists, layer rules, dependency direction constraints, or an ADR corpus. Risk: feeding only natural-language docs produces inconsistent drift detection because the model interprets prose differently across runs. Provide a JSON or YAML spec of allowed and forbidden dependencies.
Required Input: Current Import Graph
Guardrail: the prompt must receive a pre-computed dependency graph (e.g., from madge, dependency-cruiser, or a build tool). Risk: asking the model to infer imports from file contents is unreliable at scale and misses dynamic imports, barrel files, and path aliases. Compute the graph outside the prompt and pass it as structured data.
Operational Risk: False Positives on Intentional Exceptions
Risk: every codebase has justified rule violations—performance shortcuts, legacy integration points, or pragmatic coupling. The prompt flags these as drift. Guardrail: maintain an exceptions registry file that the prompt reads before classifying violations. Any flagged dependency present in the registry is automatically labeled as 'acknowledged exception' rather than 'drift.'
Operational Risk: Stale Architecture Specs
Risk: the architecture spec drifts from reality while the code is correct. The prompt then reports 'drift' that is actually the spec being outdated. Guardrail: version the architecture spec alongside the code and include a last_reviewed timestamp. The prompt should warn when the spec is older than a configured threshold and recommend a spec review before acting on findings.
Copy-Ready Prompt Template
A copy-ready prompt for detecting architecture drift between documented design decisions and the current codebase.
This prompt template is designed to be pasted directly into your AI coding agent or LLM workflow. It instructs the model to compare your documented architecture decisions against the actual codebase structure, import graphs, and module boundaries. The goal is to produce a structured drift report that distinguishes intentional exceptions from genuine erosion, giving you an actionable list of violations to investigate.
codeYou are an architecture conformance auditor. Your task is to compare the documented architecture decisions for a software system against the current codebase structure and produce a drift report. ## INPUTS - Architecture Decision Records (ADRs) or design docs: [ARCHITECTURE_DOCS] - Current codebase structure (file tree, import graph, module boundaries): [CODEBASE_STRUCTURE] - Known intentional exceptions (if any): [KNOWN_EXCEPTIONS] ## OUTPUT SCHEMA Return a JSON object with the following structure: { "summary": "string summarizing overall drift severity and top findings", "findings": [ { "id": "string (unique identifier)", "rule_violated": "string (reference to the specific architecture rule or ADR)", "severity": "CRITICAL | HIGH | MEDIUM | LOW", "location": "string (file path, module, or import statement)", "evidence": "string (specific code or import that violates the rule)", "impact": "string (consequence of this drift)", "recommendation": "string (suggested remediation)", "is_intentional_exception": false } ], "intentional_exceptions_confirmed": ["list of exception IDs that match known exceptions"], "unexpected_dependencies": ["list of module pairs with unexpected coupling"], "missing_enforced_boundaries": ["list of boundaries that should exist but don't"] } ## CONSTRAINTS - Only flag violations where the code clearly contradicts a documented rule. - If a violation matches a known intentional exception, mark `is_intentional_exception` as true and include it in `intentional_exceptions_confirmed`. - Do not invent architecture rules. Only use rules explicitly stated in [ARCHITECTURE_DOCS]. - For each finding, provide specific file paths and import statements as evidence. - If no drift is detected, return an empty findings array with a summary stating conformance. - Distinguish between missing enforcement (a boundary that should exist but doesn't) and direct violations (code that crosses a boundary it shouldn't). ## RISK LEVEL: [RISK_LEVEL] - If RISK_LEVEL is HIGH, flag even minor deviations and require explicit justification for any finding marked as intentional. - If RISK_LEVEL is MEDIUM, focus on CRITICAL and HIGH severity findings. - If RISK_LEVEL is LOW, only flag CRITICAL violations.
To adapt this template, replace the square-bracket placeholders with your specific inputs. [ARCHITECTURE_DOCS] should contain your ADRs, design docs, or a structured list of architecture rules. [CODEBASE_STRUCTURE] should include a file tree, module dependency graph, or import analysis output—tools like madge, dependency-cruiser, or eslint import rules can generate this. [KNOWN_EXCEPTIONS] is a list of violations your team has already accepted with rationale. Set [RISK_LEVEL] based on your tolerance: use HIGH for regulated systems or critical infrastructure, MEDIUM for most production systems, and LOW for early-stage projects where architecture is still evolving. After running the prompt, validate the output against your known exceptions list to ensure the model correctly identified them. For high-risk systems, always have a senior engineer review findings before filing remediation tickets.
Prompt Variables
Placeholders required by the Architecture Drift Detection Prompt. Each variable must be populated before the prompt is assembled and sent. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ARCHITECTURE_DOCS] | Reference architecture decisions, ADRs, or design docs defining the intended system structure | ADR-003: Payment Service owns all transaction state; ADR-007: No direct imports from shared/utils into domain modules | Must contain at least one explicit module boundary rule or dependency constraint. Reject empty or purely aspirational documents. Parse for rule statements before prompt assembly. |
[CODEBASE_MAP] | Current codebase structure including file tree, import graph, and module boundaries | src/domain/payments/ -> imports from src/infra/db/, src/shared/logging/; src/api/ -> imports from src/domain/payments/, src/domain/users/ | Must be generated from actual codebase analysis, not hand-written. Validate that import edges match source files. Reject stale maps older than the last commit being analyzed. |
[IMPORT_GRAPH] | Directed graph of module-level imports extracted from the current codebase | Nodes: domain/payments, domain/users, infra/db, api/handlers. Edges: api/handlers -> domain/payments, domain/payments -> infra/db | Must be machine-generated from static analysis. Validate node count matches module count in [CODEBASE_MAP]. Reject if edge count is zero or graph is disconnected without documented justification. |
[MODULE_BOUNDARIES] | Declared module boundaries with allowed and forbidden dependency directions | domain/payments: allowed imports from shared/types, infra/db; forbidden imports from api/*, domain/users | Must include at least one forbidden dependency rule per module. Validate that each boundary declaration references real modules present in [CODEBASE_MAP]. Flag rules that reference non-existent modules. |
[EXCEPTIONS_LIST] | Known intentional deviations from architecture with documented rationale and approval | domain/users imports from domain/payments for UserBillingInfo aggregate - approved per ADR-012, ticket ARCH-451 | Each exception must include a reference to an ADR, ticket, or approval record. Reject exceptions without traceable justification. Cross-reference against [ARCHITECTURE_DOCS] to confirm exception is documented, not assumed. |
[CHANGE_WINDOW] | Time range of commits to analyze for drift introduction | commits between 2025-01-01 and 2025-03-15 on main branch | Must be a valid date range with start before end. Validate that commits exist in the range. Reject windows spanning more than 6 months without explicit justification to keep analysis focused. |
[DRIFT_SEVERITY_RULES] | Team-specific severity classification rules for drift findings | CRITICAL: circular dependency or forbidden import across domain boundaries; HIGH: new dependency violating layer rules; MEDIUM: undocumented import in allowed direction; LOW: deprecated pattern without active erosion | Must define at least 3 severity levels with concrete criteria per level. Validate that each rule references observable code properties, not subjective judgments. Reject rules that cannot be mechanically checked against [IMPORT_GRAPH]. |
[OUTPUT_SCHEMA] | Expected structure for the drift report output | JSON schema with fields: finding_id, severity, rule_violated, file_locations, introduced_in_commit, exception_match, recommendation | Must be a valid JSON Schema or TypeScript interface. Validate that required fields cover traceability (commit, file, rule) and actionability (severity, recommendation). Reject schemas missing exception_match field for triage workflow. |
Implementation Harness Notes
How to wire the Architecture Drift Detection Prompt into an automated CI/CD pipeline or a scheduled audit workflow.
This prompt is designed to be run as a scheduled job or a CI/CD gate, not as a one-off chat. The core workflow involves a three-stage pipeline: context assembly, model inference, and output validation. In the context assembly stage, you must gather the canonical architecture decision records (ADRs), the current dependency graph (from dep-tree or a similar tool), and a list of module boundary rules. The prompt's [ARCHITECTURE_SPEC] placeholder expects a structured markdown document, not a file path. The [CODEBASE_CONTEXT] placeholder should be populated with a pre-computed import graph and a list of public API surfaces, not raw source code, to stay within context limits.
For the inference stage, use a model with a large context window and strong reasoning capabilities, such as claude-sonnet-4-20250514 or gpt-4o. The output is a structured JSON report, so you must enforce the [OUTPUT_SCHEMA] strictly. Implement a retry loop with a maximum of 3 attempts. If the initial response fails JSON schema validation, feed the raw output and the validation error back into the model with a repair prompt: 'The previous output failed JSON schema validation with the following errors: [ERRORS]. Please correct the JSON output to match the schema.' If the repair fails twice, log the failure and escalate for human review. Do not silently accept a malformed drift report.
The most critical part of the harness is the post-inference validation layer. Beyond basic JSON schema checks, implement a finding grounding check. For every drift finding in the report, the validator must verify that the file_path and symbol referenced in the finding actually exist in the current codebase. A finding that points to a non-existent file is a hallucination and must be discarded. Additionally, implement a suppression file mechanism. Known and accepted drifts (intentional exceptions) should be stored in a .drift-suppressions.yaml file. The validator must filter out any finding that matches an active suppression rule before publishing the report. This prevents alert fatigue.
Finally, integrate the validated report into your observability stack. Publish the drift score and the count of new, unresolved findings as metrics to your monitoring system (e.g., Datadog, Prometheus). For each new finding, create a ticket in your issue tracker (Jira, Linear) with the rationale, evidence, and remediation fields from the report. The ticket should be assigned to the team that owns the violating module. To avoid noise, configure the harness to only create tickets for findings with a severity of high or critical. Run the full pipeline on a weekly schedule and on every merge to the main branch that modifies an ADR document or a module boundary configuration.
Expected Output Contract
Each field the Architecture Drift Detection Prompt must return, with its type, requirement status, and a concrete validation rule you can enforce in your harness before the report reaches a reviewer.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
drift_report_id | string (uuid) | Must parse as a valid UUID v4; reject if missing or malformed. | |
generated_at | string (ISO-8601) | Must parse to a UTC timestamp within the last 5 minutes; reject if in the future or older than 1 hour. | |
architecture_decision_references | array of objects | Each object must contain a non-empty 'adr_id' string and a 'source' string that matches a file path or URL pattern; array must not be empty. | |
findings | array of objects | Array length must be >= 1; each object must include 'rule_id', 'status' (one of: 'conformant', 'drift', 'intentional_exception', 'unverifiable'), and 'evidence'. | |
findings[].rule_id | string | Must match the pattern ^ADR-\d{3,4}$ or a provided rule identifier from the input architecture spec. | |
findings[].status | string (enum) | Must be exactly one of: 'conformant', 'drift', 'intentional_exception', 'unverifiable'. Reject any other value. | |
findings[].evidence.file_path | string | Must be a relative path from the repository root; reject absolute paths or paths containing '..' traversal. | |
findings[].evidence.line_range | string or null | If present, must match the pattern ^\d+(-\d+)?$ (e.g., '42' or '42-58'); null is allowed only when status is 'unverifiable'. | |
intentional_exceptions | array of objects | If present, each object must include 'finding_index' (integer referencing a findings[] entry with status 'intentional_exception'), 'justification' (non-empty string), and 'approved_by' (non-empty string). | |
summary | object | Must contain 'total_rules_checked' (integer >= 1), 'conformant_count' (integer), 'drift_count' (integer), 'intentional_exception_count' (integer), and 'unverifiable_count' (integer). Sum of counts must equal total_rules_checked. | |
summary.overall_assessment | string (enum) | Must be one of: 'aligned', 'minor_drift', 'significant_drift', 'critical_drift'. Reject if the assessment contradicts the drift_count proportion (e.g., 'aligned' when drift_count > 20% of total). |
Common Failure Modes
Architecture drift detection fails in predictable ways. These cards cover the most common failure modes and how to guard against them before the report reaches a human reviewer.
False Positives from Intentional Exceptions
What to watch: The prompt flags every deviation from the documented architecture as drift, including intentional exceptions, pragmatic trade-offs, and legacy carve-outs that the team has already accepted. Guardrail: Require the prompt to distinguish between undocumented drift and documented exceptions by cross-referencing architecture decision records (ADRs) and inline suppression comments before classifying a finding as a violation.
Stale Architecture Document Baseline
What to watch: The prompt compares current code against architecture documents that haven't been updated in months, producing a flood of drift findings that actually reflect documentation rot rather than code erosion. Guardrail: Include a document freshness check step that flags architecture docs older than a configurable threshold and downgrades drift severity when the baseline itself is stale.
Import Graph Blindness to Runtime Wiring
What to watch: The prompt relies solely on static import analysis and misses drift introduced through runtime dependency injection, service locators, reflection, or dynamic module loading. Guardrail: Supplement static import graphs with runtime dependency traces or configuration-driven wiring maps. When those aren't available, the prompt must explicitly flag blind spots and downgrade confidence for dynamically wired modules.
Overfitting to a Single Architecture Style
What to watch: The prompt assumes a specific architecture pattern (e.g., clean architecture, hexagonal ports) and misclassifies valid alternative patterns as drift. A layered monolith gets flagged for not looking like microservices. Guardrail: Bind the prompt to the project's actual architecture decision records and style guide. Include a pre-check that identifies the intended architecture style before applying conformance rules.
Noise Overload from Low-Severity Findings
What to watch: The prompt produces hundreds of minor import violations or naming convention deviations that bury the critical boundary violations. Reviewers ignore the entire report. Guardrail: Implement severity tiering with a hard cap on the number of findings per tier. Require the prompt to surface only the top-N highest-severity violations by default, with full detail available on demand.
Missing Remediation Context
What to watch: The prompt identifies that a module boundary has eroded but provides no actionable path back to compliance—no suggested refactoring, no migration steps, no effort estimate. Guardrail: Require each high-severity finding to include a remediation hint: which imports to remove, which interfaces to introduce, or which module to extract. Flag findings without actionable remediation for manual enrichment before the report is shared.
Evaluation Rubric
Use this rubric to test the Architecture Drift Detection Prompt before shipping. Each criterion targets a specific failure mode—run these checks against a sample of 10–20 modules and flag any row that fails more than once.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Module boundary accuracy | Every module listed in the drift report matches a real directory or package boundary defined in the codebase | Report references a module that does not exist or mislabels a subpackage as a top-level module | Parse the report's module list and diff against a ground-truth directory tree extracted from the repository |
Import rule violation precision | At least 90% of flagged import violations correspond to actual cross-boundary imports that violate the documented architecture rules | More than 10% of flagged imports are false positives—imports that are allowed by architecture decision records or intentional exceptions | Sample 20 flagged imports and manually verify each against the architecture decision records and allowlist |
Drift severity classification consistency | Severity labels (critical, high, medium, low) follow a consistent pattern: critical for circular dependencies, high for layer violations, medium for convention breaks, low for style deviations | Two identical violation types receive different severity labels in different parts of the report | Extract all severity assignments, group by violation type, and check for label consistency across groups |
Intentional exception recognition | Report correctly identifies and excludes modules or imports that are documented as intentional exceptions in architecture decision records | Report flags an import that is explicitly listed in an ADR as an accepted exception without noting the exception status | Maintain a test set of 5 known intentional exceptions and verify none appear as unflagged violations |
Evidence grounding per finding | Every drift finding includes a specific file path, line reference, or import statement as evidence | A finding states a violation exists but provides only a module name without a concrete code location | Scan the report output for findings that lack a file path or import statement; count and require below 5% of total findings |
False negative rate on known drift | Report detects at least 80% of pre-seeded drift violations that were intentionally introduced into the test codebase | Report misses more than 20% of known violations, indicating low recall on real drift patterns | Inject 10 known architecture violations into a test repository, run the prompt, and measure recall |
Output schema compliance | Report output matches the expected [OUTPUT_SCHEMA] exactly: all required fields present, no extra top-level keys, arrays properly typed | Output is missing required fields, contains hallucinated fields, or nests objects incorrectly | Validate the full JSON output against the [OUTPUT_SCHEMA] using a schema validator; reject on any schema error |
Remediation suggestion actionability | Each remediation suggestion includes a specific action (rename, move, extract interface, add facade) tied to the violation type | Suggestions are generic ('fix the import' or 'refactor the module') without concrete steps or patterns | Review all remediation suggestions and classify each as actionable or generic; require at least 85% actionable rate |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a single repository. Replace [ARCHITECTURE_DOCS] with a path to one ADR file or a short architecture decision log. Use [CODEBASE_CONTEXT] as a tree output from tree -L 3 plus a dependency graph from madge or dependency-cruiser. Drop the severity classification and remediation sections. Ask for a simple markdown table with three columns: Rule, Status (Conform/Drift/Unknown), Evidence.
Watch for
- The model will flag every deviation as drift without distinguishing intentional exceptions. Add a sentence: "If a deviation appears intentional based on naming conventions or comments, mark it as 'Likely Intentional' and explain why."
- Tree output alone won't show import direction. Include a module dependency graph even in prototype mode.
- Models may hallucinate architecture rules that aren't in your docs. Add: "Only report rules explicitly stated in [ARCHITECTURE_DOCS]. Do not infer rules."

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us