How Repository-Level AI Coding Agents Work: Architecture, Permission Boundaries, and Verification Loops
This article breaks down the technical architecture behind repository-level AI coding agents, going beyond basic code completion. It explains the core main loop, task decomposition, tool invocation, multi-level permission models, sub-agent context isolation to prevent context pollution, and layered verification loops. You will learn how these four design pillars work together to make AI agents capable of safely handling complex, cross-module engineering tasks.
1. From Code Completion to Repository-Level Agents: A Fundamental Paradigm Shift
Traditional AI coding tools and repository-level coding agents differ fundamentally in their design. The former is essentially a code-completion engine embedded in an IDE, operating on a simple interaction model: “receive a partial code snippet -> predict the subsequent content -> present the suggestion as grey text.” This works like a responsive code memo, well-suited for localized tasks such as function signature completion, variable name suggestions, and template code generation.
Repository-level agents represent a completely different technical architecture. Their core loop is not “completing code” but a continuous cycle of “perceiving context -> formulating an execution plan -> invoking external tools -> writing back execution results.” When a user provides a complex requirement (for example, “refactor the user authentication module to support multi-factor authentication”), the agent first scans the project structure to understand the tech stack and dependencies, then autonomously breaks the task into sub-steps, progressively invoking tools for file read/write, command execution, and test running.
This shift has a profound impact. Developers no longer need to guide the AI line by line; they can set high-level goals and let the agent plan the implementation path autonomously. It is like upgrading from a “typist” to a “project engineer.”
2. Main Loop Architecture: The Agent’s Execution Engine
2.1 Core Components of the Loop Structure
A typical repository-level agent main loop contains the following key stages:
while task is not complete:read current state -> analyze contextgenerate the next step plancall a tool to execute an operationcollect the execution resultupdate the task statuscheck whether the goal is reached
This loop may look simple, but each stage involves complex technical considerations.
2.2 Task Decomposition and State Management
When facing a complex engineering task, the agent first needs to perform task decomposition. This process involves:
- Requirement parsing: Translating natural language descriptions into an executable sequence of operations
- Dependency analysis: Identifying ordering relationships and resource dependencies between tasks
- State tracking: Maintaining a record of completed sub-tasks and a queue of pending ones
Taking “fix a cross-module compilation error” as an example, the agent decomposes it into: locate the error -> analyze the cause -> retrieve relevant code context -> design a fix -> apply the code change -> run a verification test. The execution result of each step feeds into the context of the next iteration.
2.3 Tool Invocation Mechanism
The agent interacts with the external world through standardized tool calls. A typical toolset includes:
| Tool Category | Function | Use Case |
|---|---|---|
| File Read | Retrieve source code content | Understand existing code logic |
| File Write | Modify or create files | Implement code changes |
| Command Execution | Run build and test scripts | Verify the correctness of changes |
| Search Query | Full-text codebase retrieval | Locate relevant code snippets |
The use of these tools is strictly constrained to prevent the agent from executing unauthorized or destructive operations.
3. Permission Boundaries: Guardrail Design for Safety and Control
3.1 Why a Permission System Is Needed
The real risk of AI coding tools is not that they “cannot write code,” but that they “write code carelessly.” Specific manifestations include:
- Unauthorized modifications: Changing critical configuration files without the user’s knowledge
- Scope creep: Modifying multiple unrelated modules when only one file should have been changed
- Blind modification risk: Making destructive changes without fully understanding the existing logic
- Permission abuse: Executing sensitive operations that require administrator privileges
3.2 Multi-Level Permission Modes
Mature AI coding systems typically design multi-level permission modes:
Default Mode: The agent can read code and execute read-only commands, but file modifications require user confirmation.
AcceptEdits Mode: The agent can autonomously modify code files, but dangerous operations (such as deleting files or modifying system configuration) still require confirmation.
Plan Mode: This mode best embodies the design philosophy. Once in this mode, the agent focuses on “reading and studying code” rather than rushing to modify files. It will:
- Thoroughly scan the relevant codebase
- Analyze the existing implementation logic
- Propose a change plan and wait for user approval
- Execute actual modifications only after approval
This “plan first, then execute” approach essentially reduces the probability of “fixing A but breaking B,” allowing the model to gather evidence and form a complete understanding before taking action.
Auto Mode: The agent makes autonomous decisions within predefined safe boundaries, suitable for low-risk tasks.
DontAsk Mode: The agent minimizes interactive confirmations with the user, suitable for batch execution of deterministic operations.
BypassPermissions Mode: The highest-privilege mode, suitable for controlled environments or rapid prototyping scenarios.
3.3 The Engineering Value of Permission Boundaries
The design of a permission system reflects mature engineering thinking: acknowledging AI capabilities while establishing clear safety boundaries. This design ensures that:
- Developers can trust the agent to work autonomously on complex tasks
- Critical operations have clear confirmation checkpoints to prevent accidental damage
- Tasks with different safety levels can select the corresponding permission mode
4. Context Division of Labor: An Architectural Innovation for Solving Context Pollution
4.1 Context Pollution: The Core Challenge for Agents
The greatest technical challenge when an agent handles engineering tasks comes from the limitations of the context window. If the entire process of “search code -> understand repo structure -> write implementation -> run verification -> explain reasoning” is crammed into a single conversation context, the following problems arise:
- Context bloat: As the conversation progresses, historical information accumulates, diluting relevant content
- Attention dilution: The model must locate critical details among a large volume of irrelevant information
- Error accumulation: Early misunderstandings or incorrect information continuously influence subsequent decisions
- Token consumption: Lengthy context leads to a sharp rise in inference costs
4.2 Sub-Agent Architecture: A Context Isolation Solution
To address these issues, advanced coding systems adopt a multi-agent architecture that breaks large tasks into smaller sub-agents with independent contexts:
Main Agent (Coordinator)├── Explore Sub-Agent: Responsible for codebase scanning and structure understanding├── Plan Sub-Agent: Responsible for requirement analysis and solution design├── Implement Sub-Agent: Responsible for specific code writing└── Verify Sub-Agent: Responsible for test execution and result analysis
Each sub-agent has the following characteristics:
- Independent context: The sub-agent’s conversation history is isolated from the main agent
- Restricted toolset: Different tool permissions are configured based on responsibilities
- Structured output: Sub-agent results are passed back to the main agent as summaries
- Parallel execution: Independent sub-tasks can be processed in parallel
4.3 The Art of Context Passing
The key to the sub-agent architecture lies in the design of context passing. The main agent does not need to know the sub-agent’s full reasoning process; it only needs to obtain:
- Sub-task completion status (success / failure / partial completion)
- Key findings summary (relevant code locations, root cause of issues)
- Decisions pending input (choice points requiring the main agent’s judgment)
- Execution log references (detailed intermediate processes can be viewed selectively)
This design ensures the main agent’s context stays concise, containing only the information most valuable for decision-making.
5. The Verification Loop: Closing the Gap from Generation to Confirmation
5.1 Why Verification Is a Key Stage
A fundamental flaw of traditional code generation tools is that generation ends when the output is produced. The model outputs code, and the human developer is left to verify it. In contrast, the core advantage of advanced coding systems is establishing a closed loop of “generate -> verify -> correct.”
5.2 Multi-Layered Verification Strategy Design
A complete verification loop typically includes:
Static Verification Layer:
- Syntax checking: Ensuring code is syntactically correct
- Type checking: Verifying consistency of type annotations
- Static analysis: Detecting potential code smells and defect patterns
Dynamic Verification Layer:
- Unit testing: Verifying the behavioral correctness of individual functions/methods
- Integration testing: Verifying the correctness of interactions between modules
- End-to-end testing: Verifying the correctness of complete business workflows
Semantic Verification Layer:
- Code review: Having another agent evaluate change quality from a reviewer’s perspective
- Security scanning: Detecting introduced security vulnerabilities
- Performance analysis: Assessing the impact of changes on system performance
5.3 Handling Mechanism for Verification Failures
When the verification stage detects a problem, the agent’s handling flow is:
- Analyze the failure cause (error logs, stack traces, test reports)
- Locate the root of the problem (which change caused the failure)
- Generate a correction plan (adjust the code or modify the strategy)
- Re-run verification
- If verification fails multiple times, roll back and request human intervention
This mechanism ensures the agent does not go further down the wrong path, but proactively seeks help after a limited number of attempts.
6. Enterprise Practices: Baidu AI Cloud’s Scenario Implementation
6.1 The Value of Intelligent Coding in Improving Engineering Efficiency
Baidu AI Cloud’s intelligent coding assistance solution, based on the architectural principles above, helps enterprises improve development efficiency across multiple dimensions:
- Accelerated onboarding: New developers can ask codebase-related questions in natural language, and the agent quickly locates relevant code and provides contextual explanations
- Improved code review efficiency: The agent can automatically detect common issues in changes, reducing the burden of manual review
- Automated documentation generation: Automatically generating API documentation and changelogs based on code changes
- Technical debt management: The agent periodically scans the codebase to identify potential optimization opportunities
6.2 Permission and Compliance Considerations
In enterprise environments, permission management must also consider additional compliance factors:
- Code security: Sensitive code must not be leaked, so the agent must support private deployment
- Audit trails: All agent operations must be recorded in complete logs for traceability
- Permission inheritance: An agent’s permissions cannot exceed those of its initiator
- Environment isolation: Operations across development, testing, and production environments require strict isolation
Baidu AI Cloud’s relevant solution addresses these needs by providing fine-grained permission control and audit capabilities, ensuring agents can run securely and controllably in enterprise environments.
7. Future Evolution Directions
7.1 Deepening Multi-Agent Collaboration
Current multi-agent architectures are primarily hierarchical (a main agent coordinating sub-agents). Future development directions may include:
- Peer collaboration: Multiple agents discuss and negotiate solutions on equal footing
- Expert networks: Configuring specialized agents for specific domains (such as database optimization or frontend performance)
- Self-organizing teams: Agents automatically form teams based on task nature and disband after completion
7.2 Strengthening the Verification Loop
Future verification capabilities may expand to:
- Formal verification: Elevating some verification work to the level of mathematical proofs
- Property testing: Automatically generating test cases to verify code satisfies predefined property constraints
- Fuzz testing: Discovering edge-case problems through large volumes of random inputs
7.3 Deep Integration with the Development Workflow
Coding tools will no longer be a standalone plugin but will be deeply embedded into the entire R&D workflow:
- Requirement stage: Assisting requirement analysis and generating draft technical proposals
- Development stage: Providing real-time coding assistance and automated refactoring optimization
- Testing stage: Automatically generating test cases, executing tests, and analyzing results
- Operations stage: Assisting fault diagnosis and generating fix patches
Conclusion
The technical principles behind repository-level AI coding tools essentially engineer and systematize the capabilities of large language models. A main loop enables continuous task execution, permission boundaries ensure operational safety, context division of labor improves the ability to handle complex tasks, and a verification loop guarantees output quality. These four layers together form a complete intelligent coding architecture.
Baidu AI Cloud’s exploration in this field provides enterprises with a viable path to integrating AI capabilities into the R&D workflow. As technology continues to evolve, coding tools will truly grow from “code completers” into “engineering efficiency engines,” helping developers remain efficient and reliable in increasingly complex software systems.
