Six-Layer Architecture and Context Governance for AI Coding Agents

    Many developers treat AI coding agents as chatbots and respond to problems by piling on more instructions—yet longer conversations get messier, more tools make output worse, and longer rule files get followed less. This article argues that the real issue is usually not the model's intelligence but wrong context, or output that can neither be judged nor rolled back. It reframes the agent as a looping system built from six layers—rules, tools, skills, control, isolation, and verification—then adds a five-surface model for diagnosing failures and practical guidance on context governance, skills versus hooks, subagents, prompt caching, and writing rule files. Readers gain a systematic way to design and govern a coding agent layer by layer.

    Introduction: Why “The Prompts Just Aren’t Good Enough” Is Often a Misdiagnosis

    In practice, many people initially treat an AI coding agent as a conversational chatbot: whenever a problem comes up, they keep appending instructions, hoping the model will “behave a little better.” Before long, a few familiar symptoms show up—the longer the conversation runs, the messier the context becomes; the more tools you plug in, the worse the output quality gets; and the longer the rule document grows, the less the model actually follows it.

    After some observation and teardown, a counterintuitive conclusion tends to surface: in most moments where things get stuck, the problem isn’t that the model isn’t smart enough. It’s that you’ve handed it the wrong context, or that what it produces can’t be judged for correctness and can’t be rolled back.

    Put differently, treating an AI coding tool as a black-box chat is no way to use it well. The approach that actually works is to understand it as a multi-layer collaborative agent system, and to design and govern each layer on its own terms. This article takes a general-purpose AI coding agent as its subject and lays out both this systematic way of understanding it and the engineering practice around it.

    1. The Core Operating Model: An Agent Doesn’t “Answer,” It “Loops”

    To understand these tools, you first need to drop the “one question, one answer” intuition. At its core, the agent isn’t producing an answer—it runs a repeatedly iterated agent loop:

    1. Collect context → Take action → Verify result → [Done? Yes → Stop / No → back to Collect]
    2. ↑ │
    3. └────────────────────────────────────────┘

    Within this loop, a few key elements are always present:

    • Rules and memory: provide long-term context and define what the agent “is” and which rules it must keep.
    • Action capabilities (tools / external tool protocols): define what the agent “can do,” such as reading and writing files, running commands, and retrieving information.
    • Skills: on-demand methodologies that tell the agent “how to approach this kind of task.”
    • Hooks: force certain behaviors to trigger, without relying on the model’s own judgment.
    • Subagents and permission sandboxes: isolate context and constrain the boundaries of actions.
    • Verifiers: close the loop, making output verifiable, rollbackable, and auditable.

    Once you understand this loop, a lot of the “mysterious” problems acquire a direction for troubleshooting: unstable model output may be context pollution; chaotic tool selection may be action-surface overload; out-of-control behavior may be a missing control surface.

    2. The Six-Layer Architecture: Design by Layer, Govern Layer by Layer

    A healthy coding agent can be cleanly split into six layers with distinct responsibilities:

    Layer Responsibility Main Carrier
    Rules layer Long-term context; defines “what it is” Rule files / memory / memory mechanisms
    Tools layer Action capabilities; defines “what it can do” Built-in tools, external tool protocols, plugins
    Skills layer On-demand methodology; defines “how to do it” Skills
    Control layer Forces certain behaviors to be constrained; doesn’t rely on self-discipline Hooks / permissions / sandboxes
    Isolation layer Context-isolated workers with controlled autonomy Subagents / working copies / forked sessions
    Verification layer Verification loop; guarantees verifiable, rollbackable, auditable Tests, lint, screenshots, logs, CI

    The single most important engineering principle here is this: strengthen only one layer and the whole system tips out of balance. Write the rule file too long, and the context pollutes itself first; pile on too many tools, and the model’s ability to choose actually degrades; spawn subagents everywhere, and state starts to drift; skip the verification step, and once something breaks you have no idea which stage failed. The six layers form a single whole—a shortfall in any one dimension drags down everything.

    3. Five Surfaces: Turning Vague Problems into a Troubleshooting Checklist

    On top of the six-layer architecture, you can use a “five surfaces” model to locate problems. It’s a genuinely handy troubleshooting checklist in practice:

    1. Context surface: Which information stays resident in context, and which is loaded on demand? Carriers include rule files, memory, and skills. Common problem—too much resident information scatters the model’s attention.
    2. Action surface: What action capabilities does the agent currently have? This includes built-in tools, external tool protocols, and plugins. Common problem—too many tools make selection hard.
    3. Control surface: Which actions must be constrained, blocked, or audited? Carriers are permissions, sandboxes, and hooks. Common problem—missing guardrails lead to accidental deletion or modification.
    4. Isolation surface: Which tasks need isolated context and permissions? Carriers are subagents, working copies, and forked sessions. Common problem—every task crammed into one context, interfering with the others.
    5. Verification surface: How do you tell whether a task is genuinely done and trustworthy? Carriers are tests, lint, screenshots, logs, and continuous integration. Common problem—no verification, so failures go unnoticed.

    Check these five surfaces one by one, and the vast majority of “performance got worse” problems can be quickly classified and located.

    4. Context Governance: Controlling the Boundary Between “Always-On” and “On-Demand”

    Context is the scarcest resource and the one most easily wasted. The core principle of governance is layered loading: keep the minimum necessary information resident, and pull everything else on demand.

    Concretely, this means:

    • Trim resident content: rule files should focus on the “hard constraints that must be obeyed” and “key project conventions,” rather than cramming in every detail. Every increment of resident content costs an increment of attention budget.
    • Load methodology on demand: distill recurring ways of working into skills, and load them only when a matching task appears, avoiding resident pollution.
    • Archive and compress promptly: long conversations should be summarized in stages, compressing history into conclusions rather than letting the raw record swell without limit.
    • Isolate long-tail tasks: one-off, context-heavy exploratory tasks should be handed to a separate session so they don’t pollute the main context.

    A practical rule of thumb: if a piece of information isn’t something that “must be obeyed every time,” it most likely shouldn’t be resident—it should be loaded on demand instead.

    5. Skills and Hooks: Turning Discipline into Mechanism

    Skills and hooks are mechanisms that solve two different kinds of problems, and they shouldn’t be mixed up.

    Skills solve “how to do it.” A skill is a reusable methodology brief that describes the standard workflow, cautions, and output format for a class of tasks. The design essentials are:

    1. Skill = trigger scenario + standard steps + constraints and counter-examples + acceptance criteria

    A good skill should be “short, executable, and clearly bounded”—not yet another long document.

    Hooks solve “what must be done.” A hook is a behavior that’s forced to trigger on a specific event, catching the bottom lines that can’t depend on the model’s self-discipline—for example:

    • Force a formatter to run before writing a file;
    • Force tests or lint to run before a commit;
    • Intercept dangerous operations (such as deletion or forced overwrite) or require confirmation.

    The key distinction: anything the model could “forget to do” should be handed to a hook for enforcement; only what the model needs to “learn how to do” should be written as a skill.

    6. Using Subagents Correctly: Trading Isolation for Stability

    The value of subagents lies in isolation—throwing a subtask that needs heavy exploration and may involve repeated trial and error into a separate context, and passing only the conclusion back to the main agent. This keeps the intermediate process from polluting the main context.

    The right way to use them:

    • Isolate exploratory tasks: large-scope searches, bulk file analysis, and cross-module investigation belong to subagents.
    • Converge the output: a subagent should return only a refined conclusion, not the full process.
    • Controlled autonomy: give subagents clear permission boundaries and goals so they don’t overstep or drift.

    The anti-pattern is equally clear: don’t spawn subagents everywhere. Frequent creation, unshared state, and mutually contradictory conclusions make the overall state drift and actually harder to converge. A subagent is an “isolation scalpel,” not a “handy hammer.”

    7. The Architectural Impact of Prompt Caching: Stable Structure Yields Gains

    Prompt caching can significantly cut the overhead of repeated computation, but its gains depend heavily on the stability of the request structure. Caching typically reuses matches by prefix, so:

    • Put stable content first: fixed parts such as rules, system prompts, and long-term background should be placed up front and kept unchanged, so the prefix stays reusable.
    • Put volatile content last: the user’s current input and temporary data go at the end, so edits don’t pollute the prefix.
    • Avoid needless changes: inserting timestamps or random IDs into the prefix—content that breaks the cache hit—effectively disables the cache.

    From this angle, the caching strategy is actually shaping your context organization in reverse: the more orderly the structure and the clearer the separation of stable versus volatile content, the cleaner the context is and the higher the cache hit rate.

    8. How to Write Rule Files That Are Actually Useful

    A rule file (such as a project-level instruction document) is the core carrier of the rules layer, and also the easiest thing to write badly. A genuinely useful rule file should do the following:

    1. Write constraints, not tutorials: keep only the hard rules that must be obeyed and the key project conventions—don’t drag general documentation in.
    2. Be specific and executable: use clear statements like “must run X before committing” or “modifications to directory Y are forbidden,” rather than empty phrases like “try to ensure quality.”
    3. Control length: the more resident a rule is, the shorter it must be. Verbose rules dilute attention and actually lower compliance.
    4. Organize by layer: put long-term hard constraints in the main file, and split scenario-specific details into on-demand skills.
    5. Be verifiable: ideally each rule maps to a verification method (tests, lint, check scripts), so it’s not just a “wish” but a “mechanism.”

    A handy test: treat the rule file like an onboarding note for a new colleague—if even a human can’t get through it, the model won’t follow it well either.

    Conclusion

    The key to using an AI coding agent well isn’t coaxing it as a chatbot over and over. It’s designing it as a layered, governable agent system. First see its operating loop clearly, then use the six-layer architecture to separate responsibilities, use the five surfaces to locate problems, and manage context, actions, control, isolation, and verification one by one—and you’ll find that the vast majority of “poor performance” scenarios are, at root, a layer that was ignored or overloaded. Only when each layer does its job and the verification loop is complete does the agent’s stability and output quality genuinely step up a level.