AI Coding Agents: A Six-Layer Architecture and Governance Framework

    Reliable AI coding agents require more than carefully written prompts. This article presents a six-layer architecture covering persistent context, action capabilities, on-demand methods, enforceable controls, isolated collaboration, and verification. It also introduces four governance planes for diagnosing failures and a phased implementation path for building agent systems that are controllable, verifiable, auditable, and recoverable.

    From Chatbots to Agent Systems: Why User Experience Problems Are Architecture Problems

    Many developers approach AI coding agents with the same mental model they use for chatbots: describe a requirement, paste some code, and wait for an answer. That can work for short tasks. Once an agent takes on real engineering work, however, problems tend to accumulate.

    Conversation context becomes cluttered, and later information buries earlier constraints. As more tools become available, tool selection becomes harder and execution paths less predictable. Project rule files grow longer but are still ignored in practice. Outputs look plausible, yet their correctness is difficult to establish, and mistakes are hard to roll back.

    These may appear to be prompt-writing problems. More fundamentally, they arise from treating a question-and-answer interface as an agent system.

    An AI coding agent is not simply a larger chat interface. It is an execution system that repeatedly operates within a controlled environment: gather context, take action, verify the result, and, if verification fails, use the feedback to gather more context or revise the plan. Different architectural capabilities support each step. When those capabilities are mixed together, individual steps can look reasonable while the overall process remains uncontrollable.

    For analysis and governance, this system can be divided into six layers:

    1. Persistent context: Defines what the system should know, including project rules, architectural boundaries, business terminology, historical memory, and the current task.
    2. Action capabilities: Defines what the system can do, including built-in tools, external connectors, extension actions, and their invocation constraints.
    3. On-demand methods: Defines how to approach tasks through procedures, playbooks, checklists, examples, and task templates.
    4. Enforceable controls: Defines which behaviors must be blocked, approved, or audited rather than left to the agent’s judgment.
    5. Isolated collaboration: Divides complex tasks among subagents or isolated workers while controlling context and permission boundaries.
    6. Verification and feedback: Uses tests, static checks, logs, diffs, and interface evidence to make results verifiable, reversible, and auditable.

    Overdeveloping one layer or leaving another absent creates imbalance. Excessive persistent context can pollute the agent’s working context. Too many tools complicate selection. Too many subagents allow state to drift. Skipping verification makes failures difficult to locate.

    The following sections examine each layer.

    1. Persistent Context: Load What Is Needed, Not Everything

    The persistent context layer answers a basic question: What should the system know right now?

    It typically includes project rules, module boundaries, dependency conventions, terminology, security requirements, the current task description, and reusable historical memory. Its main challenge is often not missing information but information overload and conflicting instructions.

    A common mistake is to put every convention, lesson learned, and code snippet into a single long instruction file, expecting the agent to follow all of it on every task. In practice:

    • Temporary information dilutes stable rules.
    • Conflicting older rules remain active without an expiration mechanism.
    • Task-specific context becomes mixed with project-wide context.
    • The system loses track of priorities, and its decisions become harder to explain.

    A better approach separates context into four categories:

    • Stable global context: Security baselines, compliance requirements, and basic engineering principles. These change infrequently and have high priority.
    • Stable project context: Architectural boundaries, module responsibilities, dependency directions, and review requirements. These are maintained alongside project versions.
    • Temporary task context: The current objective, relevant files, acceptance criteria, and non-goals. This context is archived or discarded when the task ends.
    • Memory: Reusable, sourced facts with an expiration policy, applicability scope, and review process.

    Context organization should move from keeping full documents permanently loaded to index-first, on-demand loading. Persistent content should contain navigation, constraint summaries, and loading rules. Detailed guidance can be retrieved, referenced, or loaded when a task requires it.

    Each context document should identify its owner, version, last review date, and conflict-resolution priority. More text does not automatically produce better decisions. Presenting both old and new rules without resolving their relationship can instead make behavior inconsistent.

    An illustrative configuration:

    1. Context layers:
    2. Stable global context:
    3. Priority: Highest
    4. Content: Security baselines, compliance requirements, basic engineering principles
    5. Stable project context:
    6. Priority: High
    7. Content: Architectural boundaries, module responsibilities, dependency rules, review requirements
    8. Temporary task context:
    9. Priority: Highest
    10. Lifecycle: Current task
    11. Content: Objective, relevant files, acceptance criteria, non-goals
    12. Memory:
    13. Priority: Medium
    14. Requirements: Source, applicability scope, expiration policy

    The governance goal is to expose the right information at the right time—not all information on every turn.

    2. Action Capabilities: More Tools Are Not Always Better

    The action capability layer defines what the agent can do to the engineering environment. Reading files, searching code, editing content, running tests, inspecting logs, creating patches, and calling external services all belong here.

    Greater capability makes an agent a more effective executor. It also increases the potential impact of mistakes.

    As the tool inventory grows, the first problem is often not an inability to act but an inability to choose the right action. Overlapping functionality, vague descriptions, unclear parameter boundaries, and unstructured failure feedback encourage repeated trial and error across competing execution paths.

    Some tools also have side effects, such as writing, deleting, publishing, or sending notifications. Without explicit side-effect classifications and permission constraints, an apparently reasonable decision can cause irreversible damage.

    Tools should have four basic properties:

    1. Atomic: Each tool should perform one clearly defined action where possible. Broad, composite tools can conceal multiple side effects.
    2. Well-described: Purpose, input structure, preconditions, outputs, failure reasons, and side-effect level should be explicit.
    3. Constrainable: Writes, external calls, and high-risk changes should be intercepted by policy or require approval.
    4. Diagnosable: Failures should return structured errors rather than vague failure messages.

    Registering a tool should not automatically expose it to every task. A better strategy is to assemble the smallest suitable toolset for each task.

    Read-only tasks should receive search and inspection capabilities by default. Controlled write access can be enabled when changes are necessary. Changes to external systems should require additional approval. This reduces both selection complexity and the likelihood of unintended actions.

    An illustrative action description:

    1. Action name: Controlled code-region modification
    2. Purpose: Modify permitted files within a specified workspace
    3. Preconditions: File is inside the workspace, write permission is granted, change description has been generated
    4. Side-effect level: Write
    5. Idempotent: No
    6. Failure feedback: Failure location, error reason, and diff summary
    7. Rollback: Restore from a pre-change snapshot

    This layer should prioritize clear boundaries, straightforward selection, and explainable failures—not an exhaustive tool catalog.

    3. On-Demand Methods: Separate Procedures from Persistent Prompts

    The on-demand method layer answers: How should the agent approach this type of task?

    Bug diagnosis, API refactoring, test coverage improvements, dependency upgrades, performance investigation, and pre-release checks each require different steps, checkpoints, and precautions. Keeping all these procedures in persistent context quickly consumes the context window. Providing none leaves the agent to improvise.

    A better approach packages procedures into task-specific playbooks or method packages. Each package should include:

    • Applicable scenarios
    • Preconditions
    • Steps
    • Key decision points
    • Examples
    • Verification requirements
    • Exit conditions

    The system identifies the task type, loads the most relevant package, and releases it when the task ends. Packages should be versioned and reviewable, and maintained separately from the tools and permissions they depend on.

    The distinction between layers matters:

    • Context describes facts and constraints.
    • Methods describe the sequence of work.
    • Actions provide executable capabilities.

    Mixing them creates a maintenance problem in which rules, tools, and procedures become nested inside one another.

    A method package might look like this:

    1. Method package:
    2. Name: Bug diagnosis and minimal fix
    3. Applicable scenario: An observed failure or error log is available
    4. Preconditions: Reproduction steps, relevant logs, and code scope are available
    5. Steps:
    6. 1. Establish a reproducible failing case
    7. 2. Narrow the problem scope
    8. 3. Propose a minimal fix
    9. 4. Run targeted verification
    10. 5. Add regression checks and a change description
    11. Key decision points: Is the failure reproducible? Should the search scope expand? May a public interface change?
    12. Verification requirements: Failing case passes, relevant checks pass, change scope is explainable
    13. Exit conditions: Verification evidence is complete, or the task is escalated to a human

    The value of this layer is turning expert knowledge into an asset that can be selected, maintained, and audited, rather than leaving it as a long, one-off prompt.

    4. Enforceable Controls: Do Not Rely on Agent Self-Restraint

    The control layer answers: Which actions must be restricted?

    In real engineering environments, prompts such as “do not delete files,” “do not expose secrets,” or “do not modify production configuration directly” are not reliable enforcement mechanisms. Constraints must be implemented through policies, permissions, sandboxes, and auditing.

    The core principles are deny by default, least privilege, approval for high-risk actions, and traceability throughout execution.

    Actions can be classified by their side effects:

    • Read-only inspection: Allowed by default within defined data boundaries, with restrictions on sensitive information.
    • Reversible writes in a sandbox: Allowed with diffs, snapshots, and workspace restrictions.
    • Changes to external systems: Require approval, a defined change window, an impact assessment, and a rollback plan.
    • Data deletion, permission changes, and production configuration changes: Require multiple approval levels and, when necessary, human execution.
    • Network access and outbound data transfer: Restricted by domain, protocol, and data classification, with sensitive data redacted where required.

    Policy checks should operate before and after execution. Before an action, validate parameters, permissions, and context. Afterward, record results, evidence, and exceptions.

    Audit logs should capture more than what happened. They should also record why the action was allowed, which policy authorized it, who approved it, and how it can be rolled back. Otherwise, incident investigation becomes an exercise in reconstructing decisions from incomplete information.

    An illustrative policy:

    1. Policy:
    2. Default behavior: Deny
    3. Allowed reads: Current workspace and authorized materials
    4. Allowed writes: Sandbox workspace
    5. Approval required:
    6. - External network access
    7. - Dependency changes
    8. - Production configuration changes
    9. Prohibited:
    10. - Reading sensitive information outside the authorized scope
    11. - Sending data externally without approval
    12. - Irreversible bulk deletion

    A mature control layer is not defined by the number of written rules. It is defined by how effectively it prevents violations and provides records, containment, and recovery when something goes wrong.

    5. Isolated Collaboration: Give Subagents Boundaries

    The isolated collaboration layer answers: How can complex tasks be divided without losing control?

    A task may require code exploration, solution design, implementation, and independent verification. Assigning all of that context to one executor increases the risk of context pollution and mistaken judgments.

    Isolated workers or subagents can separate responsibilities, context, permissions, and toolsets. For example:

    • An explorer searches and reads code.
    • An implementer makes changes in a sandbox.
    • A reviewer independently examines the result.
    • A verifier runs acceptance checks.

    More subagents do not automatically improve the system. Common failures include vague assignments, reliance on implicit shared memory, permissions that are not narrowed, inconsistent deliverable formats, and parent agents that merge results without verification.

    These failures produce state drift, duplicated work, conflicting edits, and uncertainty about how the final result was produced.

    Controlled collaboration requires the following:

    1. Each subagent has an explicit objective, inputs, constraints, expected deliverables, acceptance criteria, and non-goals.
    2. Each receives only the context, tools, and permissions necessary for its assignment.
    3. Handoffs use explicit artifacts rather than assumed conversational memory.
    4. The parent merges only verified deliverables. Conflicts are resolved through deterministic rules or human review.
    5. Subagent depth, concurrency, and lifetime are limited to prevent unbounded agent-tree growth.

    A handoff contract can be structured as follows:

    1. Handoff contract:
    2. Objective: State what this subtask must resolve
    3. Inputs: Necessary files, logs, reproduction steps, and context references
    4. Constraints: Permission scope, protected areas, time limits, and iteration limits
    5. Expected deliverables: Patch, report, test results, or evidence inventory
    6. Acceptance criteria: Machine-checkable completion criteria
    7. Non-goals: Explicitly excluded work

    The goal is controlled autonomy, not unrestricted expansion. Clearer boundaries make collaboration more stable.

    6. Verification and Feedback: No Evidence, No Completion

    The verification layer answers: How do we know the task is actually complete?

    Many disappointing agent experiences originate here. An output resembles an answer but has not been reproducibly checked. A change looks reasonable, but no one can establish whether it introduced a regression. When failure occurs, there may be no snapshot, diff, or recovery path.

    Verification should be defined before work begins, not added after execution. Every task should establish:

    • Its acceptance criteria
    • The checks that demonstrate those criteria
    • Where evidence will be stored
    • How failures will be rolled back
    • Which conditions require human escalation

    Verification can be organized from lower-cost checks to broader validation:

    1. Structural and syntax checks: Formatting, types, interface signatures, and configuration validity.
    2. Static checks: Dependency direction, coding standards, security rules, and complexity thresholds.
    3. Targeted tests: Reproduction cases, unit tests, and minimal integration checks.
    4. System-level validation: Integration tests, end-to-end workflows, performance, and stability checks.
    5. Security and permission checks: Sensitive information exposure, unauthorized access, external calls, and data-flow audits.
    6. Human-inspectable evidence: Logs, diffs, interface screenshots, and operation records.

    Verification should be as independent of implementation as practical. At minimum, the executor’s claim that it has finished must not be the only evidence. High-risk scenarios may still require human review after automated checks pass.

    Verification results should be stored in a structured format and linked to requirements, changes, and policy decisions. A task without verification evidence should be treated as incomplete, not as “probably fine.”

    Verification must also be paired with rollback capability. Prefer reversible operations. Irreversible actions require advance risk disclosure and approval. Save checkpoints or snapshots at critical steps.

    Auditability is not a report written after the event. It is traceability from task inputs through action execution to verification evidence.

    7. The Agent Loop and Four Governance Planes

    An AI coding agent is built around a controlled loop, not a one-time answer:

    1. Gather context → Select and execute actions → Verify results → Deliver if passed
    2. ↑ |
    3. └──────────── Feedback and correction ───────┘

    Within this loop:

    • Persistent context and memory support information gathering.
    • On-demand methods and action capabilities support execution.
    • Enforceable controls govern execution and verification.
    • Verification determines whether delivery is justified.
    • Isolated collaboration supports parallel work and division of responsibility in complex tasks.

    Optimizing only one part can improve local behavior while destabilizing the overall system.

    For practical diagnosis, four governance planes provide a useful framework:

    Governance plane Core question Main mechanisms Common symptoms Priority actions
    Context What stays loaded, and what is loaded on demand? Project rules, task descriptions, memory, method indexes Forgotten constraints, conflicting context, wasted context window Layering, retrieval, priorities, expiration mechanisms
    Action Which capabilities are currently available? Built-in tools, external connectors, extension actions Wrong tool selection, repeated calls, unclear side effects Minimal toolsets, structured descriptions, idempotency and rollback
    Control Which actions must be blocked, approved, or audited? Permissions, sandboxes, policy interception, audit logs Unauthorized actions, missing traceability, unintended edits Deny by default, risk classification, approvals and records
    Verification How is trustworthy completion established? Tests, static checks, logs, screenshots, continuous integration False completion, missed regressions, difficult rollback Early acceptance criteria, evidence inventories, independent verification

    Start troubleshooting with four questions:

    1. Is the information needed for the decision visible, without being buried in irrelevant material?
    2. Do the available actions match the task, and are their side effects clear?
    3. Do high-risk actions have enforceable constraints, approvals, and audit records?
    4. Is completion verifiable, and can failures be rolled back?

    Many complaints that “the model is not smart enough” ultimately point to one of these planes: incorrect context, overloaded capabilities, missing controls, or insufficient verification evidence.

    8. A Phased Engineering Implementation

    To turn an AI coding agent from a demonstration tool into an engineering capability, begin with a minimal complete loop and gradually increase autonomy.

    Phase 1: A Read-Only Task Loop

    Start with search, inspection, analysis, and verification. Require each task to provide its supporting context, an explanation of the analysis, and verification evidence.

    The priorities are context layering and evidence standards.

    Phase 2: Controlled Writes in a Sandbox

    Enable reversible code changes within a restricted workspace. Preserve before-and-after diffs, run targeted verification, and record policy decisions.

    The priorities are action descriptions, sandboxing, and rollback mechanisms.

    Phase 3: Approval for External Actions

    Introduce approval and auditing when tasks need external system access, dependency changes, or configuration adjustments.

    The priorities are risk classification, approval workflows, and sensitive information protection.

    Phase 4: Limited Isolated Collaboration

    Introduce explorer, implementer, reviewer, and verifier roles only when task complexity justifies them. Define handoff contracts and merge rules.

    The priorities are preventing state drift and permission expansion.

    Phase 5: Observability and Continuous Governance

    Record context usage, action selection, policy outcomes, verification evidence, and final results for each task. Use this operational data to identify bottlenecks.

    Useful metrics include:

    • Task success rate
    • Rework rate
    • Policy violation rate
    • Verification rejection rate
    • Mean recovery time
    • Context waste ratio

    Metrics should guide improvements rather than serve as decoration.

    Rules, methods, tool descriptions, policies, and verification scripts should all be versioned, reviewed, and rolled out gradually, like code. Context is not a one-time document, tools are not a permanent allowlist, methods should not grow indefinitely, and policies should not be updated only after incidents.

    Continuous maintenance should remove obsolete rules, deprecated tools, and low-quality memories.

    9. Common Mistakes

    Treating Prompts as Architecture

    Prompts express intent. They do not replace permissions, sandboxes, verification, or auditing. Telling a system to obey does not ensure that it cannot cross a boundary.

    Treating Long Rule Files as Capability

    Longer rules increase the opportunities for conflict and dilution. Stable constraints, task descriptions, procedural playbooks, and memory should be managed separately.

    Treating Tool Count as Capability

    More tools make selection more complex. Expose the smallest suitable set for each task, with clear descriptions, side effects, and failure feedback.

    Treating Subagent Count as Autonomy

    Without handoff contracts and permission boundaries, subagents create state drift. When additional complexity offers little benefit, prefer a single agent with a verification loop.

    Executing First and Verifying Later

    Define acceptance criteria at the start. Produce verification evidence alongside changes rather than adding a final explanation afterward.

    Treating Memory as a Dumping Ground

    Memory needs a source, scope, expiration policy, and review mechanism. Unreliable historical information can keep contaminating future tasks.

    Replacing Hard Controls with Verbal Instructions

    High-risk actions must be governed by policy and permissions, not just natural-language reminders.

    10. Conclusion

    Poor AI coding agent experiences often reflect an architecture that has not kept pace with growing capabilities, rather than a model that lacks intelligence. The context may be wrong, the toolset overloaded, the control boundaries missing, or the result impossible to verify and roll back.

    The six-layer model provides an architectural framework:

    • Persistent context determines what the system knows.
    • Action capabilities determine what it can do.
    • On-demand methods determine how capabilities are combined.
    • Enforceable controls determine what it must not do.
    • Isolated collaboration determines how complex work is divided.
    • Verification and feedback determine when completion is trustworthy.

    The four governance planes—context, action, control, and verification—provide practical entry points for troubleshooting.

    When these layers and planes form a complete loop, an AI coding agent becomes more than an inconsistent chatbot. It becomes an engineering system whose capabilities can be assembled, constrained, verified, rolled back, and audited.

    The investment that matters is not just better prompts. It is the boundaries, evidence, and governance that make autonomous execution dependable.