Building Reliable AI Coding Agents: Architecture, Permission Boundaries, and Verification Loops

    AI coding agents are not just code generators—they are task execution systems that combine large language models, tooling, runtime state management, and verification. This article breaks down the core architecture of repository-level coding agents: the execution main loop, permission boundaries, context and task decomposition, and layered verification. It explains why model capability alone cannot guarantee safe and reliable software engineering, and how engineering design closes the loop from intent to verifiable results. Developers and technical decision-makers will learn how to evaluate, design, and deploy coding agents that stay auditable, scoped, and trustworthy in real-world repositories.

    1. First, Clarify the Essence: An AI Coding Agent Is an Execution System

    To understand AI coding agents, start by separating two things: a model’s ability to generate code, and a system’s ability to safely and continuously complete development tasks. These are not the same problem.

    A model can infer implementation approaches from input, generate functions, or explain errors. But real software engineering tasks also involve locating entry points, understanding dependencies, modifying multiple files, running checks, analyzing failures, and confirming that existing behavior hasn’t been broken. These steps cannot be reliably completed with a single text generation.

    A repository-level coding agent can therefore be defined as:

    A task execution system in which a large language model handles semantic understanding and decision-making, tools provide environment-operation capabilities, and the runtime manages state, permissions, and feedback.

    Its performance depends not only on model capability, but also on tool design, context quality, permission policies, and verification mechanisms. Swapping in a stronger model may improve reasoning and code generation, but it will not automatically solve problems like unauthorized execution, environment pollution, or insufficient verification.

    Architecturally, such a system can be split into four layers:

    1. Execution main loop: converts a task into a series of executable, observable steps.
    2. Permission boundary: decides which resources are accessible and which operations require approval.
    3. Context and task decomposition: organizes information to keep irrelevant content from interfering with decisions.
    4. Verification loop: uses check results to determine whether the task is truly complete.

    These four layers are not independent—they jointly determine the agent’s reliability.

    2. The Execution Main Loop: From One-Shot Generation to Continuous Execution

    1. Why One-Shot Code Generation Falls Short

    Suppose a developer asks: “Add time-range filtering to the order query API, and keep the existing interface behavior compatible.”

    If the model generates code directly from this sentence alone, it has to guess where the interface lives, the parameter structure, the data-access pattern, time formats, and error-handling conventions. Even if the local implementation looks correct, it may conflict with the actual rules in the repository.

    A more reliable approach is to first read the relevant code and tests, then propose an implementation plan, then make limited modifications, and finally verify the results.

    This process can be abstracted as:

    Receive goal → gather evidence → form a plan → execute tools → observe results → update decisions.

    Here, “executing a tool” is not the model claiming in text that it did something—it is the runtime actually invoking controlled capabilities, such as reading files, searching code, applying patches, or running tests.

    2. Separate Model Decisions from Tool Execution

    In a typical design, the model proposes actions, the runtime validates and executes them, and tool results are returned to the model as new observations.

    The logic looks like this. The following is conceptual pseudocode, not an actual product interface:

    1. Initialize task goal, permission policy, and task state
    2. Loop:
    3. Summarize current evidence, pending items, and recent feedback
    4. Ask the model to propose the next action
    5. If the action is "finish the task":
    6. Check whether completion conditions are met
    7. If yes, output the conclusion; otherwise, continue processing
    8. If the action is a tool call:
    9. Validate parameters, permissions, and resource limits
    10. Request human approval if needed
    11. Execute the action in a controlled environment
    12. Record the result and update task state
    13. If the execution budget is exhausted or an unrecoverable block is hit:
    14. Stop and explain why

    The key to this loop is not letting the model “try” endlessly, but ensuring every attempt has a clear purpose, defined boundaries, and traceable results.

    3. State Should Not Rely Entirely on Chat History

    A reliable runtime should maintain structured state, including:

    • The user’s goal and acceptance criteria;
    • Confirmed repository facts;
    • Unverified assumptions;
    • Modified files and a summary of changes;
    • Checks that have been run and their results;
    • Current blockers and next steps.

    For example, “this function probably handles permission validation” is an assumption; only after reading call relationships or related tests can it be promoted to a confirmed fact. Explicitly distinguishing facts from speculation reduces the risk that the model treats guesses as evidence in long-running tasks.

    The system also needs stop conditions—on tool calls, execution time, and repeated failures—to prevent the agent from falling into meaningless loops.

    3. Permission Boundaries: Being Able to Execute Doesn’t Mean Being Allowed To

    1. Risk Comes from Environment Operations, Not Just Code Quality

    AI coding agents can operate on the development environment, so the risks go beyond generating bad code:

    • Modifying files outside the task scope;
    • Reading credentials or other sensitive information;
    • Deleting data or overwriting unsaved work;
    • Running untrusted scripts;
    • Sending internal content to external addresses;
    • Causing irreversible effects on shared environments.

    Permission control must therefore be a runtime capability—it cannot rely solely on prompt instructions telling the model to “be careful.”

    Prompts can influence behavioral tendencies, but real safety boundaries must be enforced at the tool execution entry point.

    2. Decompose Permissions into Resources, Actions, and Conditions

    A general permission policy can be built around three dimensions.

    Resource scope defines what the agent can touch—for example, a specific repository, temporary directories, or allowed network targets.

    Action types distinguish reading, writing, executing, deleting, external communication, and deployment/release operations.

    Execution conditions specify which actions can run automatically, which require human confirmation, and which should be rejected outright.

    For example, reading ordinary source files in the current repository can be a low-risk operation; file modifications can be restricted to an approved scope; deleting directories, reading credentials, or touching shared environments requires stricter controls.

    Risk assessment should also consider the specific object: two “write file” operations can have very different impact depending on whether they modify business logic or release configuration.

    3. Restrict Side Effects During Planning

    Separating investigation from implementation helps reduce the chance of wrong modifications. The planning phase mainly answers:

    • Which modules does the requirement involve?
    • What are the existing behaviors and edge conditions?
    • Which files are expected to change?
    • Where does uncertainty remain?
    • How should compatibility be verified?

    But “research only” is not inherently safe. Some commands that look like read-only checks may also execute repository scripts, write caches, or access the network. Which tools are allowed during planning must still be defined by explicit policy.

    4. Approval, Isolation, and Auditing Must Work Together

    Human approval cannot replace environment isolation. Even when a user approves an operation, they may not be able to fully understand what a complex script does.

    A more robust combination includes:

    • Applying least privilege;
    • Running in a separate working directory or isolated environment;
    • Limiting accessible files and network ranges;
    • Requiring approval for high-risk actions;
    • Logging tool calls, file changes, and check results;
    • Keeping a recovery path.

    The agent’s understanding of the task and the runtime’s judgment of risk should form two distinct lines of defense.

    4. Context and Task Decomposition: Manage Information, Don’t Pile It Up

    1. More Context Doesn’t Mean Better Understanding

    Repository-level tasks generate large volumes of text: code snippets, search results, build logs, test output, historical discussions, and intermediate speculation. If everything is dumped into a single session, key constraints can get drowned in noise.

    Common problems include:

    • Outdated information still influencing decisions;
    • Temporary assumptions being treated as final conclusions;
    • Large logs crowding out useful context;
    • Task goals gradually drifting over many rounds of execution;
    • Information from unrelated modules interfering with the current change.

    The goal of context management is not “read as much as possible,” but ensuring the current decision has sufficient, accurate, and relevant evidence.

    2. Retrieve on Demand and Summarize in Layers

    A common approach is to locate first, then go deeper:

    1. Understand the directory structure and module boundaries;
    2. Find the entry points and symbols related to the requirement;
    3. Read necessary code along call relationships;
    4. Cross-check behavior against relevant tests;
    5. Organize key conclusions into summaries with sources.

    Summaries should retain locating clues—file paths, function names, and related test locations—so later steps can return to the original source to verify. A summary should not be an unverifiable statement like “I have understood this module.”

    For error logs, keep the failing test cases, key errors, and exit status, and store the full log as a record that can be re-read when needed.

    3. The Value and Limits of Subtask Isolation

    For complex tasks, exploration, design research, and test analysis can be delegated to execution units with independent contexts. The value lies in isolating information and limiting responsibilities—not in the number of agents itself.

    For example:

    • An exploration unit locates modules and returns evidence and impact scope;
    • A planning unit organizes implementation steps and risks;
    • An implementation unit completes scoped changes;
    • A verification unit checks whether changes meet requirements.

    However, independent context does not automatically mean an independent security boundary. Each execution unit’s tool permissions, resource scope, and isolation level still depend on the specific system implementation.

    Task decomposition also introduces summary loss, repeated reads, and coordination costs. Small tasks may not need multiple execution units at all, and parallel modifications should avoid contending for the same files. Ultimately, the overall change still needs unified verification—local conclusions cannot simply be stitched together.

    5. The Verification Loop: Judge Completion with Evidence

    1. Generation Complete ≠ Engineering Complete

    When an agent says “fixed,” that only means it has formed a completion judgment—it does not prove the code is correct.

    Trustworthy completion conditions should be translated into observable results, such as:

    • Changes conform to the agreed conventions;
    • Basic checks pass;
    • Targeted tests pass;
    • Relevant regression tests show no new issues;
    • Changes stay within the task scope;
    • Unverified parts are explicitly disclosed.

    Verification should be designed around the requirement—not just running whichever checks are easiest to pass.

    2. Build a Verification Hierarchy from Low to High Cost

    A general hierarchy has five layers:

    Layer 1: Change review. Inspect file diffs, accidental deletions, sensitive information, and unrelated modifications.

    Layer 2: Basic checks. Confirm that syntax, types, and static rules show no obvious problems.

    Layer 3: Targeted tests. Verify new behavior, error paths, and boundary conditions.

    Layer 4: Regression checks. Cover affected modules and adjacent call chains.

    Layer 5: Environment verification. When necessary, check dependency configuration, persistence behavior, concurrency conditions, or external interactions.

    For time-range filtering specifically, at minimum you need to consider: whether boundaries are inclusive, whether time representations are consistent, how missing parameters are handled, what happens when the start time is later than the end time, and whether omitting parameters preserves the old behavior.

    Test scope should match impact scope. Passing a few local tests should not be reported as “the entire system has been verified.”

    3. Failure Feedback Must Be Triaged

    Check failures can come from new defects, pre-existing issues, missing environment conditions, or unreasonable test expectations. Different causes require different handling.

    The agent should first determine whether the failure relates to the current change before deciding the next step:

    • New defect: narrow down the cause and fix it;
    • Pre-existing issue: record the evidence and avoid expanding the task on its own;
    • Environment issue: report the missing conditions;
    • Requirement ambiguity: ask for confirmation rather than deciding on the user’s behalf.

    Above all, the agent must not delete assertions or skip critical tests just to produce a “passing” result.

    6. Applying the General Architecture to a Repository Task

    Using “add a query parameter while preserving compatibility” as an example, an auditable workflow can be organized as follows.

    Phase 1: Clarify the Contract

    Confirm the parameter’s meaning, default behavior, error handling, and acceptance criteria. For ambiguities that affect compatibility, ask the user first.

    Phase 2: Build the Evidence Base

    Read entry points, business logic, the data-access layer, and related tests; form a brief call map; distinguish confirmed facts from unverified assumptions.

    Phase 3: Form a Limited Plan

    List the expected modification locations, test additions, and major risks. Prefer the minimal necessary change and avoid bundling in unrelated refactoring.

    Phase 4: Controlled Implementation

    Confirm the workspace state, make changes step by step within authorized scope, and inspect diffs after key steps to avoid overwriting the user’s existing work.

    Phase 5: Layered Verification

    Run lower-cost checks first, then targeted tests and relevant regressions. When something fails, adjust the plan based on evidence instead of blindly expanding the changes.

    Phase 6: Deliver a Factual Summary

    The final report should include what changed, check results, verification that was not completed, and remaining risks. “Checks passed” and “not run due to environment limitations” must be clearly distinguished.

    7. How to Evaluate Reliability and Real-World Value

    Evaluating an AI coding agent should not be limited to code generation speed or how smooth a demo looks. What matters more:

    • How much rework is needed after task completion;
    • Whether unrelated or unauthorized changes appear;
    • Whether the agent recognizes insufficient evidence and stops proactively;
    • Whether tests cover the real requirement;
    • Whether tool actions are traceable;
    • Whether long tasks maintain goals and constraints stably;
    • Whether time and resource costs are reasonable;
    • Whether sensitive data and shared environments are protected.

    Different tasks should also get different levels of automation. Local fixes, well-defined test additions, and repetitive refactoring are usually easier to define acceptance criteria for; operations involving permissions, critical data, or production environments need stricter human review.

    Conclusion: Reliability Comes from System Design, Not Model Promises

    The core of an AI coding agent is embedding model capability into a controlled software engineering process: the main loop drives the task forward, the permission layer constrains behavior, context management keeps information quality high, and the verification loop validates results.

    The model determines what solutions it can propose; the runtime determines what it can safely do; and evidence determines what we can believe. A truly deployable system is not one that executes to the end with unbounded confidence, but one that keeps investigating when evidence is insufficient, asks for confirmation when risk rises, and clearly states its limits when results cannot be verified.