Architecture Design and Core Modules of Intelligent Coding Agents

    Intelligent coding agents are often evaluated by model capability alone, but real coding experience depends on the agent harness built around the model. This article distinguishes LLMs, reasoning models, and agent layers, then breaks down six core modules: control loop and state management, context and codebase retrieval, tool interfaces and execution sandbox, action selection and planning, memory and session continuity, and verification feedback and safety governance. It also presents an iterative observe-inspect-choose-act loop and practical engineering guidance for building a stable, observable, and recoverable coding agent.

    I. Starting Point: Model Capability Is Not Agent Experience

    When discussing intelligent coding capability, a common mistake is to conflate “model capability,” “reasoning behavior,” and “coding agent product experience.” A large language model (LLM) is essentially a next-token prediction model and serves as the system’s base engine. A reasoning model is still an LLM, but it is usually optimized through training or prompting strategies so that it spends more inference-time computation on reasoning, verification, candidate-answer search, and related steps. The agent layer is the control loop built around the model. It decides what to observe next, what to inspect, which tools to call, how to update state, and when to stop.

    A useful, though imperfect, analogy is this: the LLM is the engine, the reasoning model is an enhanced engine, and the Agent Harness is the transmission, dashboard, steering wheel, and safety devices that place the engine inside a controllable system. In real coding tasks, the model is responsible only for local understanding and generation. The agent layer is responsible for decomposing tasks, feeding repository context to the model, converting model output into tool calls, converting tool results back into understandable state, and retrying, rolling back, or asking for clarification when failures occur.

    This also explains why the same model can feel very different in a general chat interface and in an intelligent coding agent. A chat interface usually has only conversation context and one-shot text output. A coding agent has system capabilities such as repository navigation, file reading and writing, command execution, diff review, test feedback, memory compression, and long-session continuity. In many real applications, tool use, context management, and memory mechanisms affect the final result as much as the model itself.

    II. Six Core Building Blocks and the Iterative Loop

    A practical coding agent is typically composed of six core modules:

    1. Control loop and state management;
    2. Context and codebase retrieval;
    3. Tool interfaces and execution sandbox;
    4. Action selection and planning;
    5. Memory and session continuity;
    6. Verification feedback and safety governance.

    Together, these modules support an iterative loop: observe → inspect → choose → act, followed by verification and state update. The minimal closed loop can be expressed in pseudocode as follows:

    1. state = init(task, repo_context)
    2. while not done(state):
    3. observation = observe(state)
    4. facts = inspect(observation, state.context, state.memory)
    5. action = choose(facts, state.tools, state.policy)
    6. result = act(action, state.sandbox)
    7. state = update(state, result)
    8. done = verify(state) or budget_exhausted(state)

    The loop looks simple, but the engineering difficulty is that every step must be observable, controllable, and recoverable. The six modules are described below.

    III. Module 1: Control Loop and State Management

    The control loop is the skeleton of the agent. It needs to maintain the task goal, current plan, to-do items, observed facts, executed actions, tool return results, error information, verification status, and remaining budget. The key to state management is not “recording everything,” but organizing state into a structure that the model can consume and the program can evaluate.

    A robust control loop should have clear termination conditions: task completion, verification passing, reaching the iteration budget, consecutive failures exceeding a threshold, requiring human confirmation, or the existence of a safety risk. Otherwise, the agent can easily fall into repeated reading, ineffective modification, or infinite retries. In practice, it should also set timeouts, maximum tool-call counts, maximum context length, and maximum modification scope to prevent a single task from getting out of control.

    State updates should distinguish “facts” from “assumptions.” File contents returned by tools, test results, and diff contents are facts. The model’s judgment of the root cause is an assumption. The agent layer should encourage reading before modifying, making small changes before verification, and retaining failed attempts in state to prevent repeated mistakes later.

    IV. Module 2: Context and Codebase Retrieval

    One of the core differences between a coding agent and a chatbot is that the coding agent must deal with a real codebase. Codebase context cannot simply be inserted into the model in full; otherwise, the context budget is quickly exhausted, and noise dilutes key information. Therefore, layered retrieval is needed: repository structure, module boundaries, symbol definitions, dependency relationships, test mappings, recent changes, task-related files, and key snippets.

    Context management should follow the principles of “read on demand, expand gradually, and summarize structurally.” The agent first locates candidate areas through directory and file indexes, then reads symbol and interface definitions, and only then expands specific implementations. For long files, it should prioritize extracting function signatures, type definitions, call sites, and test cases rather than copying the entire file. When compressing context, it should preserve verifiable facts and reference locations to avoid losing key constraints in summaries.

    Prompt-cache stability also deserves attention. If context is rearranged on every request or large amounts of irrelevant content are inserted, cache hit rates will drop, increasing latency and cost. In engineering practice, stable context (project conventions, tool descriptions, long-term memory) and dynamic context (current observations, recent results) can be organized in layers to reduce unnecessary fluctuation.

    V. Module 3: Tool Interfaces and Execution Sandbox

    Tools are the boundary through which the agent interacts with the real environment. Tool design should provide clear contracts: name, parameters, return structure, error codes, permission requirements, idempotency, and side-effect descriptions. The number of tools should not be large at the beginning. The minimal set should first cover reading files, listing directories, searching symbols, applying patches, running tests, and executing restricted commands, then expand according to task needs.

    The execution sandbox is critical for safety and stability. File reads and writes should distinguish read-only from writable scopes. Command execution should set resource limits, timeouts, working-directory isolation, and output truncation. Destructive operations should require confirmation or be disabled by default. Tool results should be structured with success status, summary, key output, error type, and retry suggestions so that the control loop can make judgments.

    The tool layer should also record audit logs: who called which tool in what state, parameter summaries, result summaries, and latency. Logs are not only a basis for troubleshooting but also a data source for later optimizing context and tool strategies. In cloud environments, container platforms can host isolated execution environments, and logging and monitoring services can complete the observability loop. Baidu AI Cloud’s general-purpose services can also be used for such foundational hosting and observability scenarios.

    VI. Module 4: Action Selection and Planning

    The action selection module decides “what to do next.” It needs to combine current facts, tool capabilities, task plans, and safety policies to rank candidate actions. Common actions include continuing retrieval, reading files, asking clarifying questions, generating patches, running verification, rolling back changes, or ending the task.

    Planning granularity should be moderate. Plans that are too coarse can lead to large-scale modifications that are difficult to verify. Plans that are too fine increase iteration count and context overhead. A more reliable approach is “coarse plan + small steps”: first form a stage-level goal, then advance through verifiable small steps. For highly uncertain tasks, the agent should prioritize collecting evidence rather than directly generating large blocks of code.

    Action selection must also handle failure branches. When a tool reports an error, the agent should distinguish parameter errors, permission errors, environment errors, and logic errors. When verification fails, it should determine whether the modification is wrong, tests are missing, or the environment is unstable. High-risk actions should introduce human confirmation, and repeated failures should trigger strategy changes or requests for more information.

    VII. Module 5: Memory and Session Continuity

    Memory can be divided into short-term working memory, task memory, and long-term project memory. Short-term working memory stores observations and results from the current loop. Task memory stores the plan, completed steps, failed attempts, and items awaiting verification. Long-term project memory stores project conventions, module maps, common pitfalls, and stable conclusions. The three should not be mixed; otherwise, they can easily contaminate context.

    Continuity in long sessions depends on summary compression and persistence. The agent should periodically compress verbose tool output into structured facts, write confirmed conclusions into task memory, and move expired observations out of active context. During compression, it should preserve reference locations and confidence levels and avoid writing model guesses as facts. For cross-session tasks, it should also design memory loading and conflict-handling mechanisms to prevent old conclusions from overwriting new code states.

    VIII. Module 6: Verification Feedback and Safety Governance

    Verification is key to closing the loop for a coding agent. Code generation without verification is only a text suggestion. With static checks, test execution, diff review, and rollback mechanisms, the agent can gradually converge in a real repository. Verification results should be fed back into state and drive the next round of action selection.

    Safety governance should run throughout the process: sensitive-information protection, command allowlists, file-write scope limits, dependency-change review, destructive-operation confirmation, output redaction, and audit trails. Governance policies should not rely only on prompt constraints; they should be enforced in tool contracts and sandbox permissions. For actions whose safety cannot be determined, the default should be to downgrade to read-only inspection or request human intervention.

    IX. Engineering Implementation Recommendations

    When implementing the system, it is advisable to start with a minimal closed loop: a stable control loop, a small number of highly reliable tools, basic context retrieval, structured result returns, and simple verification. Then gradually add memory compression, plan management, sandbox isolation, and observability metrics. Evaluation metrics can include task completion rate, verification pass rate, tool error rate, average iteration count, context hit rate, human intervention rate, and rollback rate.

    In short, the competitiveness of an intelligent coding agent comes not only from the model but also from the Agent Harness built around it. Only by clearly designing the six modules—control loop, context, tools, planning, memory, and verification governance—can model capability be reliably converted into deliverable results in real software engineering tasks.