Skip to content
AI Architecture
Updated 19 min readVuong Ngo

AI Architecture Drift: How to Keep Generated Code Inside Your Patterns

AI coding assistants drift when rules live only in broad prompts. Use before-edit guidance, after-diff validation, and durable Agiflow task state to keep generated code inside your architecture.

AI Architecture Drift: How to Keep Generated Code Inside Your Patterns

Architecture enforcement works when the right rule is visible before the edit and checked after the diff.

Engineering teams prevent AI architecture drift by moving architecture rules into the workflow, not by making one prompt longer. The useful loop is simple: give the assistant the relevant rule before it edits, validate the diff after it edits, make mechanical boundaries deterministic, use LLM-assisted review for local pattern fit, and keep humans responsible for exceptions and new design decisions.

AI architecture drift is generated code that compiles but no longer matches the local architecture, boundaries, or review expectations. It looks harmless at first: a service imports the database client directly, a route handler absorbs business logic, a package uses the wrong export pattern, or a generated helper lands in the wrong layer.

That kind of drift is review debt. The code works, but reviewers keep paying the same tax.

How Do You Prevent AI Architecture Drift?

The shortest answer is this: treat architecture guidance as a feedback loop.

Static instructions still matter. Claude Code uses memory files such as CLAUDE.md for project context, and its docs distinguish that context from hooks that can block actions regardless of what the model decides. [3] GitHub Copilot supports repository custom instructions and agent instructions through AGENTS.md. [5] VS Code supports workspace and file-based custom instructions, including *.instructions.md files that can be scoped with glob patterns. [6] Codex reads AGENTS.md and layers project-specific guidance by directory scope. [8]

Those are context systems. They help the assistant know what kind of code belongs in the repo. They do not, by themselves, prove that a specific diff followed a specific architecture rule.

Use the layers for the jobs they are good at:

Guardrail layerTimingOwnsFailure mode
Repo instructionsBefore work startsShared baseline behaviorToo broad for one file
Path-scoped rulesBefore a specific editLocal patterns by file type or packageStale rules create confident wrong guidance
Permissions and hooksDuring tool useUnsafe commands and write pathsCan block legitimate exceptions
Deterministic checksDuring development and CIImports, schemas, paths, formatting, generated-file boundariesLate feedback if only run at merge
MCP toolsBefore and after editsJust-in-time rule retrieval and architecture reviewOnly as good as the tool and rule source
LLM-assisted reviewAfter the diffLocal pattern fit and exception explanationReview assistance, not proof
Human reviewException handlingTrade-offs, new patterns, accepted exceptionsToo expensive as the first line
The practical inference from the verified sources is conservative: instructions are necessary, but enforcement needs more than instructions. Put the most relevant rule near the edit, then check the actual change.

Why AI Coding Assistants Drift From Architecture

AI coding assistants do not drift because they are lazy. They drift because architecture is local, and the strongest local rule is often not the strongest thing in the assistant's active context.

A team might have a rule like this:

text
Services coordinate business logic and call repositories for data access.
Services must not import the database client directly.

That rule is clear to the reviewer who has corrected it twenty times. It may be weak context for an assistant working inside a long session with a broad task, nearby code examples, product requirements, generated snippets, failing tests, and tool output all competing for attention.

The "Lost in the Middle" paper is not about software architecture. It is evidence about long-context behavior: model performance can degrade depending on where relevant information appears in a long context, with lower performance when the needed information sits in the middle. [10] The architecture takeaway is an inference, not a direct benchmark: if an important rule is buried, stale, or too broad, teams should not expect consistent local behavior.

Google's DORA 2025 State of AI-assisted Software Development report also supports a useful operating-model point. Based on nearly 5,000 technology professionals and more than 100 hours of qualitative data, the report frames AI as an amplifier of organizational strengths and dysfunctions. [9] If architecture ownership already depends on senior reviewers catching everything late, AI will amplify that bottleneck.

Practitioners describe this in plainer terms: rules get ignored, module boundaries blur, and validation catches issues only after the assistant has already generated the wrong shape. Treat that as objection language, not benchmark evidence. It still names the pain accurately.

The fix is to move feedback earlier without pretending all feedback can be automated.

The Guardrail Stack: Which Layer Owns Which Failure?

The mistake is asking one guardrail to do every job. A prompt cannot enforce a forbidden import. CI cannot teach the assistant before the edit. An LLM review cannot approve a new architecture decision for the team.

Map the failure to the owner:

Drift symptomBest ownerExampleEscalation path
Forbidden importDeterministic check or CIsrc/services//*.ts imports a database clientBlock or fail, then point to the allowed repository pattern
Wrong file boundaryPath-scoped instruction plus deterministic checkRoute parsing appears inside a service fileFix if obvious, escalate if the boundary is changing
Local pattern mismatchBefore-edit retrieval plus LLM-assisted reviewComponent skips the established data-loading patternAsk for pattern-specific review, then human review if disputed
Unsafe command or write pathPermissions and hooksAssistant writes outside the approved packageDeny or ask, then record an exception if intentional
Generated-file mutationDeterministic checkAssistant edits generated client outputBlock and rerun the generator
Legitimate exceptionHuman reviewTemporary direct access for a migrationRecord rationale, owner, and follow-up rule change
Claude Code settings support permission rules, hook configuration, managed hook allowlists, and MCP server allowlists. [4] GitHub Copilot code review supports path-scoped custom instruction files with applyTo globs. [7] Those facts point in the same direction: good guardrails are scoped, explicit, and connected to a workflow.

The guardrail stack should reduce review surprise. If a reviewer sees the same architecture comment every week, that comment is a candidate for a rule, a check, or a before-edit retrieval step.

The Architecture Enforcement Loop

The loop has two important moments: before the edit and after the diff.

Flow diagram showing source rule, path scope, assistant edit, diff validation, exception review, and merge outcome.
The enforcement loop combines before-edit guidance, after-diff validation, CI, and human exception review.

Before the edit, the assistant should retrieve the rule that applies to the target path. A service file, route handler, React component, generated client, and migration script should not all receive the same architecture note.

After the diff, the changed files should be checked against the same rule source. Some checks should be deterministic. Others can use LLM-assisted review to explain whether the change appears to fit the local pattern. Human review owns the final call when the rule, exception, or architecture itself is in question.

Agiflow's Architecture Tools docs describe this shape directly: assistants get a pre-read of design patterns before building and quality checks after building. [12] The aicode-toolkit Architect MCP README gives the concrete tool pattern: get-file-design-pattern before editing and review-code-change after editing. [13]

Here is the smallest useful architecture rule:

yaml
# architect.yaml
design_patterns:
  src/services/**/*.ts:
    pattern_name: Service Layer Pattern
    design_pattern: Services coordinate business logic and call repositories for data access.
    includes:
      - src/services/**/*.ts
    description: |
      Do:
        - Inject repositories through the established factory or constructor pattern.
        - Keep HTTP request and response handling out of services.
        - Use named exports.

      Do not:
        - Import the database client directly.
        - Put route parsing in the service layer.
        - Add a default export.

The assistant workflow should be just as explicit:

  1. Read the task and target files.
  2. Retrieve the design pattern for each changed path.
  3. Keep the pattern visible while editing.
  4. Run available local checks.
  5. Run architecture review on the changed files.
  6. Fix violations or record a human-approved exception.

Notice what this does not claim. It does not claim one MCP server eliminates review. It does not claim a fixed compliance percentage. It does not turn an LLM response into a formal proof. It simply puts architecture feedback where the assistant can use it.

What MCP Adds, And What It Does Not Solve

Model Context Protocol is useful because it gives assistants a standard way to connect to tools and data sources. Anthropic introduced MCP as an open standard for connecting AI assistants to systems including development environments. [1] The verified MCP transport specification lists stdio and Streamable HTTP as standard transports. [2]

That makes MCP a good connection layer for architecture tooling. The assistant can ask a tool, "what pattern applies to this file?" before it edits. It can ask, "does this diff appear to violate the expected pattern?" after it edits. It can also pull task state, artifacts, and handoff context from an MCP-connected board.

MCP does not decide your architecture. It does not make vague rules useful. It does not replace deterministic checks, CI, permissions, or human review. If a tool catalog is too large, it can also create its own context cost. Anthropic has noted that large MCP tool catalogs can consume context and increase response time and cost when tool definitions are loaded up front. [11]

The practical lesson is to keep MCP exposure scoped. Give the assistant the tool and state it needs for the current file and task. Do not turn "connected to everything" into a new version of prompt bloat.

For the broader evaluation problem, real MCP integration separates transport from agent-ready workflow design.

What To Make Deterministic, What To Let An LLM Review, And What Humans Must Own

Do not send everything to an LLM. That is slower, harder to trust, and often less precise than a simple check.

QuestionBest ownerWhy
Is the file formatted?DeterministicA formatter can answer this exactly
Did the file import a forbidden module?DeterministicThe import graph is inspectable
Did the assistant write outside the approved path?Permissions or hooksTool-use policy should not depend on model judgment
Did a service bypass the repository layer?Deterministic first, then LLM-assisted review if neededSome cases are import checks; others need pattern interpretation
Did the implementation preserve the intent of the local pattern?LLM-assisted review, then human review if disputedThe answer may need architectural judgment
Is this exception acceptable?HumanExceptions are trade-offs, not just detections
Should the architecture rule change?HumanRule changes alter the operating model
The working rule is simple: make syntax, imports, paths, commands, schemas, generated-file boundaries, and forbidden writes deterministic. Use LLM-assisted review for local pattern fit, architecture intent, and exception explanation. Keep humans responsible for new architecture decisions and accepted exceptions.

This maps to the AI coding tool control surface: the more autonomy you give a coding assistant, the more explicit the guardrails around that autonomy need to be.

A Practical Implementation Pattern

Start with one repeated review comment. Do not start with an architecture encyclopedia.

Suppose reviewers keep writing this:

text
Services should not import the database client directly. Use the repository layer.

Turn that review comment into a path-scoped rule:

yaml
# RULES.yaml
rules:
  - pattern: src/services/**/*.ts
    severity: restricted
    must_do:
      - Services receive repositories through the established dependency-injection pattern.
      - Services keep business logic separate from HTTP request and response handling.
    must_not_do:
      - Do not import the database client directly.
      - Do not create route handlers inside service files.

Then make the workflow visible in the task:

markdown
Architecture guardrail for this task:

- Before editing `src/services/**/*.ts`, retrieve the service-layer pattern.
- After editing, run local checks and architecture review.
- If a violation is intentional, record the exception reason before handoff.

In an Agiflow-shaped workflow, the state boundary would look like this:

Workflow objectWhat it storesWhy it belongs outside the prompt
TaskGoal, acceptance criteria, status, and handoff ownerThe next assistant session needs the current truth
ArtifactLink to the architecture rule, review output, or example patternThe rule should be durable and inspectable
Vault entry or prompt skillReusable setup or private operational noteRepeated workflow context should not be reconstructed from chat
Comment or review noteAccepted exception and rationaleExceptions need an audit trail
Workflow lockWhich job owns the next stepParallel assistants should not silently overwrite each other
Agiflow is useful here because it keeps task state and artifacts durable across external assistants and sessions. That is the same shared-state problem covered in AI coding team shared state. The board does not replace architecture tooling. It gives the workflow a place to remember what happened.

Open the Architecture Tools workflow to add before-edit and after-diff checks.

How To Measure Whether Guardrails Are Working

Do not borrow your own compliance number. Measure your own drift.

The older version of this article included fixed performance claims such as compliance percentages, review-time savings, and rollout scale. This refresh removes them because the research base did not include publishable first-party proof for those numbers.

Start with smaller signals:

MetricWhat it tells youWatch out for
Architecture comments per PRWhether reviewers still catch the same issues lateReview culture changes can move the number
Repeated violation typesWhich rules deserve automation firstDo not automate one-off exceptions
Rule hit rate by file typeWhether rules are attached to the right pathsLow hit rate may mean poor matching
Blocked, fixed, and accepted violation countsWhether the loop changes behaviorAccepted exceptions need reasons
Review samplesWhether the quality of the comments changedSamples matter more than a vanity dashboard
Time to first architecture feedbackWhether feedback moved earlier in the workflowFaster feedback is useful only if it is accurate
A lower violation count can mean prevention improved. It can also mean detection got weaker. Pair the count with review samples and accepted exception reasons.

The best early signal is practical: reviewers stop writing the same architecture comment on every PR.

Common Objections From Practitioners

The social research for this refresh surfaced a familiar set of complaints. Treat these as practitioner-language notes, not benchmark evidence.

"Rules get ignored."

Yes. A rule file is context. If the assistant sees it once and then spends an hour inside a different task shape, you should expect misses. The answer is not only a stricter sentence. Put the rule near the edit and check the diff afterward.

"Every tool has its own instruction format."

Also true. CLAUDE.md, AGENTS.md, Cursor rules, and Copilot instructions overlap without being identical. The practical fix is to keep the source rule in one maintained place, then project the right subset into each tool's format. OpenAI's AGENTS.md guidance and GitHub's support for AGENTS.md make this easier across agent-style workflows, but teams still need ownership. [5] [7]

"More rules burn tokens and slow work."

Broad rules do. Path-scoped rules are the countermeasure. Five relevant lines for src/services/**/*.ts are better than a 3,000-line instruction file that applies to everything.

"Validation scripts catch more than prose."

Often, yes. That is why deterministic checks should own mechanical rules. The layered model is not prose versus automation. It is prose for intent, deterministic checks for hard boundaries, MCP tools for retrieval and review, and humans for exceptions.

For a related framing on why assistants lose important project state, see why coding agents lose shared context.

"AI review is still AI."

Correct. Use it as review assistance. Ask it to explain suspected mismatches, identify relevant rules, and make the diff easier for a human to inspect. Do not make it the final authority for architecture decisions.

For a related explanation of why assistants lose important project state, see why coding agents lose shared context.

Where Agiflow Fits

Agiflow is not the coding agent in this pattern. It is a commercial project board and coordination layer for external AI assistants over MCP. The assistant remains the agent.

That boundary matters. Architecture drift is rarely just one file. The assistant needs the task, acceptance criteria, architecture rule artifact, prior review result, exception note, and handoff status. A durable board gives those facts somewhere to live outside the current chat session.

Architecture Tools and aicode-toolkit fill the developer-tooling side of the loop. Agiflow's Architecture Tools docs describe the pre-read and post-build quality check workflow. [12] The aicode-toolkit README identifies the concrete before and after tools. [13]

Put together, the operating model is:

  1. Use Agiflow to hold task state, acceptance criteria, artifacts, workflow locks, handoffs, and exception notes.
  2. Use architecture tooling to retrieve file-scoped patterns before editing.
  3. Use deterministic checks and architecture review after the diff.
  4. Use human review for exceptions and new design decisions.

That is a narrower claim than "Agiflow enforces architecture." It is also a more useful claim. Architecture enforcement needs durable state, scoped rules, review outputs, and human decisions to meet in one workflow.

For a category-level view, MCP-native project management explains why project boards need assistant-readable state instead of chat-only task tracking.

FAQ For AI Search Extraction

What is AI architecture drift?

AI architecture drift is generated code that compiles but no longer matches the team's local architecture, file boundaries, patterns, or review expectations. It usually shows up as repeated review comments, misplaced logic, forbidden imports, or inconsistent package patterns.

Are repo instructions enough to prevent AI architecture drift?

No. Repo instructions are a necessary baseline, but they are context rather than complete enforcement. Teams still need path-scoped guidance, deterministic checks, after-diff review, and human exception handling.

What should be deterministic versus reviewed by an LLM?

Make formatting, imports, path restrictions, schemas, generated-file boundaries, and forbidden writes deterministic. Use LLM-assisted review for local pattern fit and architecture intent. Keep humans responsible for exceptions and architecture changes.

What does MCP add to architecture enforcement?

MCP gives assistants a standard way to connect to tools and state. In an architecture workflow, that can mean retrieving the relevant file pattern before editing and reviewing the changed diff afterward. MCP does not decide the architecture or replace CI and human review.

Where does Agiflow fit in the workflow?

Agiflow keeps task state, artifacts, workflow locks, handoffs, and exception notes durable across external assistants and sessions. Architecture tooling handles file-level rule retrieval and review. The assistant remains the agent.

Should teams measure review time or architecture violations first?

Measure architecture violations first. Review time is useful later, but the early question is whether predictable drift is moving from late human review into earlier guidance and checks.

The Starting Point

AI architecture drift is not mainly a prompting problem. It is a feedback-loop problem.

Start with the most repeated architecture comment in your code reviews. Turn it into a file-scoped rule. Make the assistant read that rule before editing matching files. Add a post-diff check. Require a written exception when the rule is intentionally broken.

That is enough to learn whether your guardrail system works.

The goal is not to make AI-generated code perfect. The goal is to stop using senior reviewers as the first system that notices predictable drift.

Open the Architecture Tools workflow to add before-edit and after-diff checks.

References

  1. Anthropic, "Introducing the Model Context Protocol".
  2. Model Context Protocol specification, "Transports".
  3. Claude Code Docs, "How Claude remembers your project".
  4. Claude Code Docs, "Claude Code settings".
  5. GitHub Docs, "Adding repository custom instructions for GitHub Copilot".
  6. Visual Studio Code Docs, "Custom instructions".
  7. GitHub Blog Changelog, "Copilot code review path-scoped custom instruction file support".
  8. OpenAI Developers, "Custom instructions with AGENTS.md".
  9. Google Research, "DORA 2025 State of AI-assisted Software Development Report".
  10. Liu et al., "Lost in the Middle: How Language Models Use Long Contexts".
  11. Anthropic Engineering, "Code execution with MCP".
  12. Agiflow Docs, "Architecture Tools".
  13. AgiFlow/aicode-toolkit, packages/architect-mcp/README.md.

If you want to see the concrete first-party workflow, start with the Architecture Tools workflow.

The Starting Point

AI architecture drift is not a prompting problem. It is a feedback-loop problem.

Start with the most repeated architecture comment in your code reviews. Turn it into a file-scoped rule. Make the assistant read that rule before editing the matching files. Add a post-diff check. Require a written exception when the rule is intentionally broken.

That is enough to learn whether your guardrail system works.

The goal is not to make AI-generated code perfect. The goal is to stop using senior reviewers as the first system that notices predictable drift.

References

  1. Anthropic, "Introducing the Model Context Protocol".
  2. Model Context Protocol specification, "Transports".
  3. Claude Code Docs, "How Claude remembers your project".
  4. Claude Code Docs, "Claude Code settings".
  5. GitHub Docs, "Adding repository custom instructions for GitHub Copilot".
  6. Cursor Docs, "Rules".
  7. OpenAI Developers, "Custom instructions with AGENTS.md".
  8. Google Research, "DORA 2025 State of AI-assisted Software Development Report".
  9. Liu et al., "Lost in the Middle: How Language Models Use Long Contexts".
  10. Google Search Central, "AI features and your website".
  11. Agiflow Docs, "Architecture Tools".
  12. AgiFlow/aicode-toolkit, packages/architect-mcp/README.md.

Put this project board inside ChatGPT

Open Agiflow in ChatGPT to plan campaigns, create tasks, and check what needs attention. Create a free Agiflow account when you are ready to keep the board for your team.