System Architecture Design for Coding Agents: Key Decisions Beyond the Model
This article breaks down the system architecture behind coding agents and why it matters as much as the underlying LLM. It covers five core modules—context engineering, tool system design, prompt caching stability, memory mechanisms, and long-session continuity—along with their design principles, common failure modes, and practical engineering patterns such as context assembly, structured tool interfaces, cache-friendly prompt ordering, and explicit task-state tracking. The goal is to help developers evaluate existing tools and build or customize their own agentic harnesses.
System Architecture Design for Coding Agents: Key Decisions Beyond the Model
1. Introduction: Architecture Shapes the Experience as Much as the Model
LLM-powered agentic coding tools have become a major direction in software development. These tools are not just a chat box. They systematically wrap the model at the application layer—commonly referred to as an agentic harness—and add mechanisms such as context management, tool invocation, and state maintenance so the model can handle complex tasks in a real development environment: writing code, debugging, refactoring, and testing.
The key premise is this: the real-world performance of a coding agent depends not only on the choice of the underlying model, but also on the surrounding system architecture. The same model can perform several times better or worse under different architectural frameworks. Repository context construction, tool interface design, prompt caching stability, memory mechanisms, and long-session continuity together determine whether the tool is actually usable and how it feels to use.
This article examines these five core modules one by one, covering their design principles, common problems, and key engineering practices.
2. Context Engineering: Showing the Model the Right Code
2.1 The Core Problem
Context windows keep growing, but for real mid-sized and large projects, dumping all the code into the context is neither feasible nor economical. The central challenge for coding tools is: how to give the model the most task-relevant information within a limited context budget.
2.2 Key Strategies for Context Construction
(1) Code retrieval and ranking
- Retrieve relevant files and code snippets by semantic similarity rather than simple keyword matching;
- Use code structure signals (function signatures, class definitions, call graphs) as ranking features to improve retrieval precision;
- Chunk oversized files intelligently so that chunk boundaries do not break the semantic integrity of the code.
(2) Multimodal context integration
- Beyond source code, consider project structure, dependency configuration files, test files, error logs, and Git commit history;
- In some scenarios, UI screenshots or design mockups can supplement the context.
(3) Dynamic allocation of the context window
- Split the limited context budget into priority regions (system prompt, retrieved code, current file, conversation history) and adjust the ratio dynamically by task phase;
- As the context approaches its limit, decide which historical information can be compressed or dropped.
2.3 Engineering Practice
A common pattern is to run a lightweight “context assembler” before each request to filter and order candidates, prioritizing the currently edited file, related dependency interfaces, and recent changes. Illustrative pseudocode:
def build_context(task: Task, repo: Repository) -> Context:candidates = []# 1. Currently active filescandidates += repo.get_active_files()# 2. Semantically retrieved snippetscandidates += repo.semantic_search(task.description, top_k=5)# 3. Recent changescandidates += repo.get_recent_changes(limit=3)# 4. Deduplication and budget trimmingreturn budget_manager.assemble(candidates, max_tokens=32000)
3. Tool System Design: The Agent’s Interface to the World
3.1 Why Tool Design Matters
What separates an agent from a pure chat model is its ability to act—reading and writing files, executing commands, searching code, and running tests. These capabilities are exposed to the model as “tools,” and the quality of the tool interfaces directly determines whether the agent can complete tasks correctly and safely.
3.2 Core Principles
(1) Atomicity and orthogonality
- Each tool should perform one clear, atomic operation (such as “read a specified file” or “run a specified command”); avoid overly broad composite tools;
- Tools should be as orthogonal as possible (non-overlapping) to reduce confusion when the model chooses among them.
(2) Structured return values
- Tool results should be structured and parseable so the model can interpret them easily;
- For execution tools, separate stdout, stderr, and exit codes so the model can judge the outcome.
(3) Safety and sandboxing
- All tool calls should pass permission checks and run in a sandbox;
- High-risk operations (deleting files, network requests) should include a confirmation step or an operation log.
(4) Friendly error handling
- When a tool fails, return meaningful error information instead of a raw exception stack trace;
- Error messages should carry enough context for the model to understand the cause and adjust its strategy.
3.3 A Typical Tool Set
[{"name": "read_file","description": "Read the contents of a file at a given path","parameters": {"path": "string", "start_line": "int?", "end_line": "int?"}},{"name": "run_command","description": "Run a shell command in a specified working directory","parameters": {"command": "string", "timeout": "int?"}},{"name": "search_code","description": "Search the codebase for matching code snippets","parameters": {"pattern": "string", "file_pattern": "string?"}}]
4. Prompt Caching Stability: A Key Variable for Cost and Latency
4.1 What Prompt Caching Is
Prompt caching stores the repeated, long prompt prefix of a request and reuses it in later requests, cutting computation and response latency. In coding tools, the system prompt, tool definitions, and repository context often stay unchanged across many requests, which makes them well suited to caching.
4.2 Factors Affecting Cache Stability
(1) Prefix consistency
- Caching typically relies on exact or approximate prefix matching. Tiny differences in the prompt prefix on each request (timestamps, random values, dynamically concatenated information) cause frequent cache misses;
- Recommendation: push dynamic content to the end of the prompt and keep static content at the front.
(2) Cache lifetime management
- Cache entries usually have a time-to-live. High-frequency scenarios need to watch the expiration policy so that frequent invalidation does not push costs back up;
- Monitor the cache hit rate to evaluate how well the policy works.
(3) Coordination with streaming output
- With streaming, make sure cache-hit requests still generate tokens normally and do not introduce compatibility problems.
4.3 Impact on User Experience
A stable caching mechanism directly affects two core experience metrics: time to first token (TTFT) and request cost. For iterative development scenarios (repeatedly editing the same piece of code), every 10% improvement in cache hit rate can bring a noticeable gain in response speed and cost savings.
5. Memory Mechanisms: Retaining Knowledge Across Sessions
5.1 Why Memory Is Needed
A stateless model “forgets” everything from one request to the next. But software development is highly continuous work, and the agent needs to remember the project’s architecture conventions, user preferences, the context of past changes, and mistakes it made before. Memory mechanisms exist to solve this amnesia problem.
5.2 Types and Implementations
(1) Short-term memory (working memory)
- Essentially the retained conversation history, usually attached directly to the context window;
- It needs a summarization strategy that compresses history when it grows too long instead of truncating it outright.
(2) Long-term memory (persistent storage)
- Persist key information in a structured form and retrieve it on demand in later sessions;
- Common implementations:
- Key-value storage: use a file path or task identifier as the key and store related context;
- Vector databases: store code snippets and decision records as embeddings for semantic retrieval;
- Structured notes: record project conventions and user preferences in Markdown or JSON.
(3) Selecting and forgetting memories
- Not everything is worth remembering. Design a policy for what should be written to long-term memory (explicitly stated user preferences, project architecture decisions) and what should be ignored or forgotten (stale code snippets, resolved temporary issues).
5.3 Practical Considerations
- Privacy and security of memory: long-term memory may contain sensitive code or business logic, so access control and data isolation are required;
- Freshness: support expiration and update mechanisms for memory entries so stale information does not mislead later decisions;
- Retrieval quality: the precision of long-term memory retrieval directly affects results, so the embedding model and retrieval strategy need continuous tuning.
6. Long-Session Continuity: Keeping Complex Tasks Consistent
6.1 The Scenario
In real development, implementing one feature may take dozens of turns: understand the requirement, find the relevant code, write the implementation, run tests, debug and fix failures, then do a code review. Throughout the process, the agent must maintain a coherent understanding of the task goal.
6.2 Core Challenges
(1) Context overflow and compression loss
- As the session grows, the context approaches the window limit and history must be compressed;
- Information lost during compression can make the agent “forget” key early decisions.
(2) Goal drift
- Over many turns, the agent may gradually drift away from the initial goal, especially on complex tasks;
- The original goal needs to be re-anchored at each key checkpoint.
(3) State synchronization
- The repository may be modified externally during a session (commits from other developers, manual edits by the user);
- The agent must detect these changes and update its own understanding.
6.3 Continuity Design Strategies
(1) Explicit task-state maintenance
- Break a complex task into a list of subgoals and explicitly track the completion status of each;
- Inject the subgoal state into the context on every turn so the agent always knows what it is doing and what comes next.
(2) Proactive summarization of key information
- When compressing the context, do not simply truncate; summarize selectively based on task relevance;
- Keep: the original requirement description, work completed, and current blockers;
- Discard: intermediate exploration and abandoned approaches.
(3) Version awareness and change tracking
- Record the code changes the agent itself made, and detect external changes in later turns;
- When a conflict is detected, proactively ask the user to confirm.
7. Summary and Outlook
The technical architecture of a coding tool is a typical systems engineering problem. Model capability is the foundation, but turning it into a reliable, efficient, and safe development experience depends on careful architectural design. The five core modules covered here—context engineering, the tool system, prompt caching, memory mechanisms, and long-session continuity—are interrelated and together form the technical backbone of an agentic harness.
A few directions are worth watching:
- Multi-agent collaboration: combining agents with different specialties (code review, test generation, documentation) to divide and complete complex tasks;
- Finer-grained context management: introducing structured information such as a code graph and project knowledge base to improve context quality;
- Device-cloud collaboration: running lightweight inference locally and using cloud resources such as Baidu AI Cloud for complex tasks, balancing privacy against compute;
- Observability: building logging, monitoring, and alerting so the agent’s behavior chain can be traced and analyzed for performance.
For developers and enterprise engineering teams, understanding these architectural elements helps both in evaluating and selecting existing coding tools and in building or customizing an agent platform of your own.
