How Repository-Level AI Coding Agents Work: Architecture and Design Principles

    This article breaks down repository-level AI coding agents into four core capability layers: the main loop, permission boundaries, context separation, and the verification loop. It explains why these agents differ from inline code completion, how each layer is designed, and what engineering teams should focus on when deploying them, along with practical recommendations and common pitfalls.

    How Repository-Level AI Coding Agents Work: Architecture and Design Principles

    Over the past two years, AI coding tools have evolved rapidly from “completion assistants inside the editor” into “engineering agents that take over tasks.” Many teams share the same confusion the first time they use one: it does not feel like a plugin, it lacks the immediacy of inline completion, yet it can read the repository in a terminal, lay out a plan, modify multiple files, run tests, and report results. This difference in experience is not a matter of interaction-layer preference; it reflects a split in the underlying technical approach. This article abstracts such repository-level agents into four capability layers—the main loop, permission boundaries, context separation, and the verification loop—and explains layer by layer “why they are designed this way” and what to focus on in engineering practice.

    1. The Main Loop: From “Completing a Snippet” to “Read Context, Plan, Call Tools, Write Back Results”

    The runtime model of traditional AI completion is a single mapping: given the text before and after the cursor, output a candidate piece of code. Its objective function is local relevance, so it naturally lacks a global view and cannot take responsibility for the result.

    The runtime model of a repository-level agent is a continuously running loop, roughly expressed as:

    1. while not done:
    2. ctx = assemble_context(goal, workspace, history)
    3. plan = model.reason(ctx) # decide the next action
    4. obs = tool.dispatch(plan.action) # read/write files, run commands, search
    5. state = integrate(obs) # structured write-back, not piled-up natural language
    6. done = check_exit(state, goal)

    This loop brings three fundamental changes.

    First, the action space expands from “text” to “tool calls.” The model no longer produces only code strings; it produces a structured intent with parameters, which the runtime executes and then feeds the real results (exit codes, standard output, test reports, file diffs) back to the model. This gives the agent the ability to “interact with the environment and observe the consequences.”

    Second, the plan becomes explicit. The task is first decomposed into verifiable sub-goals and then executed step by step. The value of an explicit plan is that it is interruptible, auditable, and re-plannable: when a step fails, you only need to roll back to the plan layer instead of discarding all the context and starting over.

    Third, the termination condition changes from “output is complete” to “goal is achieved.” Whether to stop depends on verification signals, not on the model’s own belief that it has finished writing. This is the entry point to the verification loop discussed later.

    One engineering caveat: the main loop must set a step limit, a per-step timeout, and budget constraints; otherwise it tends to burn resources repeatedly on wrong paths. At the same time, tool return results should be structurally trimmed (for example, keeping only error lines and failing test cases) so that the observation data itself does not blow up the context.

    2. Permission Boundaries: Make “What It Can Do” a System Capability, Not a Request in the Prompt

    The real risk in AI coding has never been “not knowing how to write”; it is “writing without seeing the boundaries clearly”: unauthorized modifications, collateral damage across modules, and execution of irreversible commands. Mature solutions therefore do not grant permissions by default; they model permissions as a first-class runtime concern, first answering “what is the agent allowed to see, what can it change this round, and which actions must stop and ask a human.”

    Common permission tiers can be abstracted into several progressive levels:

    Tier (generic naming) Semantics Typical scenarios
    Read-only / planning Search and reading only, writes forbidden Unfamiliar large repos, production-related directories
    Edit with confirmation Changes allowed, human confirmation required before writing to disk Everyday feature development
    Automatic editing Automatic writes within a whitelist Well-tested code, localized changes
    Restricted automatic Automatic execution but high-risk actions blocked Isolated branches and container environments
    Fully open No interaction, used only in a disposable sandbox Batch, scripted tasks

    Three implementation principles are what actually matter. First, default deny and least privilege: grant filesystem, network, and command execution separately, with paths and wildcards going through a whitelist. Second, action classification: classify “delete, force push, change permissions, access external networks, read credentials” as high-risk, requiring explicit confirmation or outright disabling regardless of the tier. Third, capabilities converge with the environment: they can be relaxed in an isolated container but must be tightened in directories close to production.

    Planning mode (research first, no file changes) is the most typical embodiment of this philosophy: it separates “collecting evidence” from “producing side effects” in time, significantly reducing the probability of “fixing A and breaking B.” In practice, it is advisable to pair it with path boundary validation and a command interception layer, placing policy enforcement in the runtime rather than in model self-discipline—security properties should not depend on probabilistic output.

    3. Context Separation: Isolating Context Pollution with Sub-Agents

    The most common failure mode of large models on engineering tasks is context pollution: search clues, repository understanding, writing the implementation, running verification, and explaining reasons are all stuffed into the same window. Tokens accumulate and get dirtier, early constraints are diluted, and the model starts forgetting conventions or repeating work already done.

    The solution is context isolation: split one large, messy task into several smaller agents with cleaner contexts, each with its own window, its own tool constraints, and its own permissions. A generic division of labor could be:

    1. Main session (decision maker): keeps the goal, constraints, acceptance criteria, key conclusions
    2. ├─ Exploration sub-agent: read-only search, produces a "file-symbol-call relationship" summary
    3. ├─ Planning sub-agent: produces steps and risk points based on the summary, writes no files
    4. ├─ Implementation sub-agent: receives the minimal necessary context, completes local changes
    5. └─ Verification sub-agent: runs builds and tests, reports structured failure information

    The key design here is “summaries go up, original text goes down on demand.” Sub-agents return only compressed conclusions and locating information upward, and the main session makes decisions accordingly; when details are needed, it reads precisely by path instead of keeping the entire repository history in the window all the time. This both controls token cost and prevents irrelevant information from interfering with judgment.

    Engineering conventions play a supporting role as well: a specification document at the repository root, directory-level notes, and a stable project structure all become high-quality sources for context assembly. The clearer the conventions, the more stable the agent’s retrieval and planning—this is the direct reason why “maintainability affects the quality of AI output.”

    4. The Verification Loop: Don’t Stop at Generation, Close the Loop on Evidence

    The fourth layer determines whether the product can be trusted. Generation is only a candidate; only verified changes count as done. A reliable verification loop includes:

    1. Static checks: type checking and static analysis catch low-level errors first;
    2. Build: confirm the changes compile and package within the overall project;
    3. Tests: run the cases related to the change first, then the regression suite;
    4. Diff review: output a structured diff and an impact description for human sign-off;
    5. Failure feedback: trim failure information and feed it back into the main loop for the next round of fixes.

    The quality of failure feedback determines the convergence speed. In practice, “error—locate—fix” should be made into a short feedback cycle: have the verification sub-agent report only the few most critical failures at a time, avoiding massive logs drowning out judgment; also set a maximum retry count, and when it is exceeded, stop and hand over to a human rather than patching automatically without end.

    5. Implementation Recommendations and Common Pitfalls

    • Pilot first in an isolated environment with a small repository, and evaluate “first-pass success rate” and “average number of interaction rounds” using a real task set, rather than only looking at demo effects.
    • Version permission policies and verification scripts, and review them together with the code; policy drift is the main source of security incidents.
    • Write verifiability into requirements: the clearer the acceptance criteria, the more reliable the agent’s termination judgment.
    • There are three common pitfalls: treating the prompt as a security boundary; letting a single session handle all sub-tasks; and only looking at generation speed while ignoring regression cost.

    To carry this kind of workload, the common approach is to put the agent runtime into a container platform for isolation and elastic scaling, use object storage to keep build artifacts and task snapshots, use a message queue to decouple long-running tasks, and use logging services and monitoring alerts to observe step counts, elapsed time, and failure rates. This both controls permissions and costs and makes the whole pipeline observable and traceable.

    Conclusion

    The principles behind repository-level AI coding agents are not mysterious: the main loop provides the skeleton for “interacting with the environment and self-correcting,” permission boundaries keep autonomy controllable, context separation solves information pollution, and the verification loop anchors results to evidence. Missing any one of the four, the experience degrades into “looks smart but is not trusted enough to use.” Understanding these four layers has more long-term value than memorizing any specific product form.