Repository-Level AI Coding Agents: Runtime Architecture and Engineering Principles

    This article examines the runtime architecture that enables repository-level AI coding agents to handle complex engineering tasks. It explains four cooperating layers—the main loop, permission boundaries, context division, and the verification loop—and describes how controlled tool use, structured state, sub-agents, policy enforcement, and external validation turn a probabilistic model into a repository-level task executor. It also summarizes practical considerations for engineering implementation.

    The conclusion first: the reason repository-level AI coding agents can complete complex engineering tasks is not that the model has suddenly become “better at writing code.” The key is that the large model is embedded in a software engineering runtime that is constrained, observable, and verifiable. The model remains a probabilistic generation system. What really determines its engineering usability is how the runtime organizes context, how it invokes tools, how it limits permissions, and how it returns verification results.

    From an architectural perspective, the system can be divided into four layers: the main loop, permission boundaries, context division, and the verification loop. Together, these four layers transform an AI coding agent from a “code completion tool” into a “repository-level task executor.” Traditional completion-style tools are more like front-end assistants inside an integrated development environment, focusing on local completion, conversational Q&A, and small-scale edits. A repository-level agent is more like an engineering assistant that runs continuously: it first reads the codebase, understands the task, and lists a plan; then it calls tools to read and write files, execute commands, and run tests; and it repeatedly corrects its work based on the results.

    Industry trends also confirm this. In developer surveys in recent years, the adoption of repository-level AI coding agents has risen rapidly, indicating that its growth is not short-term hype but a benefit from engineering workflow demand. Its technical core can be summarized as follows: use a controlled runtime to confine the uncertainty of large models within the deterministic processes of software engineering.

    1. The Main Loop: Continuous Observation and Action, Not One-Shot Code Generation

    The core of a repository-level agent is not a single generation but an agent loop that runs continuously. A typical loop can be abstracted as:

    1. observe context -> form a plan -> call tools -> read results -> write back state -> decide the next step

    Compared with completion-style tools, the main loop differs in its larger “action space.” Completion-style tools mainly handle the current file, the area around the cursor, or snippets provided in a conversation. A repository-level agent must deal with the entire code repository, including directory structure, module dependencies, configuration files, test cases, build scripts, and clues from historical changes. It must first break the task into to-do items and then obtain evidence step by step through tools.

    A simplified runtime pseudocode example is as follows:

    1. state = init(task, repo_context)
    2. while not state.done:
    3. observation = collect(state)
    4. plan = model.plan(task, observation, state.memory)
    5. action = select_action(plan, state.tools)
    6. if not policy.allow(action):
    7. action = request_human_approval(action)
    8. result = execute(action)
    9. state.update(result)
    10. state.memory = compress_and_summarize(state.memory)
    11. state.done = check_stop_condition(task, state)

    There are four key points here:

    1. Context is not stuffed in all at once. The runtime dynamically collects evidence such as files, search results, and test output according to the current step, avoiding the crude approach of putting the entire repository into the context window.
    2. The plan is not decoration. The plan is used to constrain the next action and reduce the model’s jumping between irrelevant files.
    3. Tool calls are the main execution mechanism. Actions such as reading and writing files, searching symbols, and running build and test commands allow the model to move from “saying” to “doing.”
    4. State needs to be compressed and written back. The result of each step must be summarized, archived, or converted into to-do status; otherwise, the context will quickly expand.

    This is also why many users feel that a repository-level agent is “not like a completion plugin” when they first use one, but more like putting an engineering assistant that can get work done into a terminal or command-line workflow. Its product form is only the surface. Underneath is a task execution loop with tools, state, and termination conditions.

    2. Permission Boundaries: The Real Risk Is Unauthorized or Uninformed Writes

    The most critical underlying guardrail for AI coding agents is making permission modes a system capability rather than merely writing them into a prompt. The real danger in AI coding is often not that the model “cannot write,” but that it writes carelessly, writes beyond its authority, or writes without clearly understanding the boundaries. Examples include mistakenly modifying sensitive configurations, deleting unrelated files, executing high-risk commands, accessing directories it should not access, or performing large-scale refactoring without understanding dependency relationships.

    Mature solutions usually abstract permissions as runtime policies rather than relying on the model’s self-discipline. Permission dimensions include at least:

    • File path scope: read-only directories, writable directories, and a blacklist of sensitive files;
    • Command execution scope: which commands are allowed, whether approval is required, and whether network access is prohibited;
    • Change scope: whether single-file edits, cross-module edits, and batch renames require confirmation;
    • Environment isolation: whether the agent runs in a container sandbox, a temporary workspace, or a read-only snapshot;
    • Approval points: approval after planning, before editing, before command execution, and before merging;
    • Audit capability: recording who approved which action under what context for traceability.

    A policy-check pseudocode example can be expressed as follows:

    1. def before_tool_call(action, context):
    2. if action.type == "write_file":
    3. require(action.path in context.writable_paths)
    4. require(not is_sensitive(action.path))
    5. if action.type == "run_command":
    6. require(action.command in context.allowed_commands)
    7. require(context.sandbox_enabled or context.human_approved)
    8. if action.risk_level >= context.approval_threshold:
    9. return request_approval(action)
    10. return allow()

    Among these, the “read-only research mode” is particularly representative. After entering this mode, the agent first reads code, checks dependencies, and conducts research instead of rushing to modify files. The essence of this design is to reduce the probability of “changing A and breaking B”: let the model collect evidence first and then execute changes. Permissions are not just a switch in the product interface; they are interception and auditing performed by the runtime before every tool call. Without this layer, the stronger the agent’s capabilities, the greater the risk of misoperation.

    3. Context Division: Use Sub-Agents to Isolate Pollution, Not to Cram Everything into One Window

    The place where large models are most likely to break down on engineering tasks is when “finding clues, understanding the repository, writing the implementation, running verification, and explaining the reasons” are all crammed into a single context window. As steps increase, logs, errors, file snippets, and conversation history continue to accumulate. The context becomes increasingly dirty, the model’s attention is diluted by irrelevant information, and eventually it forgets constraints, makes repeated modifications, and attributes errors incorrectly.

    The essence of the sub-agent mechanism is context isolation. Different sub-agents have independent contexts, independent tool constraints, and independent permissions. For example:

    • An exploration sub-agent is responsible for reading the repository, locating modules, and collecting evidence;
    • A planning sub-agent is responsible for researching dependencies, decomposing tasks, and outputting a plan;
    • An implementation sub-agent is responsible for modifying code within a limited file scope;
    • A verification sub-agent is responsible for running tests, analyzing failures, and providing fix suggestions;
    • A review sub-agent is responsible for checking diffs, identifying risks, and proposing improvements.

    The main session retains only key decisions, task status, and structured summaries rather than all raw logs. Results returned by sub-agents should also be as structured as possible, such as “problem found, evidence location, suggested action, risk level,” rather than dumping large raw outputs directly back into the main context.

    1. summary = dispatch_subagent(
    2. role="explore",
    3. goal="locate the configuration loading path",
    4. tools=["search", "read_file"],
    5. permissions=["read_only"]
    6. )
    7. main_memory.add(summary.to_structured_note())

    The benefit of this approach is not only “more stable” operation but also cost and latency optimization: simple exploration does not require the main model to carry all context throughout, complex verification can run independently, and the main session focuses on decision-making. Its technical principle is not mysterious. The core is: split a large, messy task into multiple small agents with cleaner contexts.

    4. Verification Loop: From Generating Code to Proving the Change Works

    A repository-level agent cannot stop at generation. What truly forms an engineering closed loop is the verification loop: after applying changes, obtain external evidence through static checks, type checks, unit tests, integration tests, builds, and diff reviews, then return failure results to the agent to drive the next round of fixes.

    A typical verification cycle is as follows:

    1. change = apply_patch(plan)
    2. result = run_checks(change)
    3. while result.failed and retry < limit:
    4. diagnosis = analyze_failure(result, change, context)
    5. fix_plan = model.plan_fix(diagnosis)
    6. change = apply_patch(fix_plan)
    7. result = run_checks(change)
    8. report = summarize(change, result, risks)

    The value of the verification loop lies in introducing “external truth.” It is unreliable for the model to say that it has “fixed” something. Test results, build output, and static-check reports are verifiable evidence. Verification layers should be organized from low cost to high cost: first fast static checks, then unit tests, then integration tests, and finally human review of critical diffs. Failure results need to be classified, such as compilation errors, assertion failures, timeouts, environment issues, and missing dependencies, with different repair strategies for different categories.

    At the same time, verification sub-agents can be separated from implementation sub-agents to reduce confirmation bias from “changing it yourself and judging it yourself.” For high-risk changes, human approval and merge gates should still be retained. The runtime should also record key metrics, such as test pass rate, number of changed files, approval count, rollback rate, and average number of repair rounds, to continuously improve agent strategies.

    5. Engineering Implementation Considerations

    When implementing repository-level AI coding agents, it is advisable to prioritize designing the runtime rather than only tuning the model:

    1. Unified tool-layer interfaces: tools return structured results and support timeouts, retries, output truncation, and idempotency control;
    2. Layered memory in the context layer: distinguish task state, evidence references, historical summaries, and temporary logs to avoid window pollution;
    3. Policy-based permission layer: default to least privilege, require approval for sensitive actions, and make all tool calls auditable;
    4. Fast feedback in the verification layer: move tests and checks earlier, and make failure results locatable and returnable;
    5. Observability: record agent traces, tool calls, approval records, costs, and failure reasons;
    6. Human-machine collaboration boundaries: plan approval, diff review, and merge gates are indispensable; start semi-automatically and then gradually expand the scope of automation.

    For example, in a general cloud environment such as Baidu AI Cloud, container sandboxes, logging services, and monitoring and alerting can be used to support isolation, auditing, and runtime observability, but the specific implementation should align with the organization’s existing infrastructure and security policies.

    Conclusion

    The technical principle of repository-level AI coding agents can be summarized as four cooperating layers: the main loop is responsible for continuous execution, permission boundaries are responsible for constraining risk, context division is responsible for reducing pollution, and the verification loop is responsible for proving that changes work. It is not a sudden leap in a single model capability. Rather, it places a large model into a software-engineering runtime. Understanding these four layers is essential for designing, evaluating, and deploying AI coding capabilities with both an eye on efficiency gains and a clear view of security boundaries and engineering costs.