AI Coding Agent Architecture: A Complete Guide to the Harness Engineering Layer
This article explains why a large language model alone cannot form a reliable coding agent and how the Harness engineering layer fills that gap. It breaks down six core modules—context engineering, tool execution sandboxes, iteration control, context compression, structured test-failure feedback, and memory with sub-agent coordination—and presents a layered reference architecture. It also covers common engineering pitfalls and how general-purpose cloud capabilities can support such systems in production.
1. Why a Model Alone Is Not Enough for a Coding Agent
A large language model’s capability can be summarized in one sentence: it takes tokens as input and produces tokens as output. This seemingly simple contract immediately exposes three gaps in real engineering scenarios.
First, the model has no environment awareness. It does not know which files exist in the repository, how directories are organized, whether dependency versions conflict, or whether its previous edit was actually written to disk.
Second, the model has no execution feedback. Whether tests pass, whether static checks report errors, and whether build artifacts are usable are all pieces of information that live outside the model and must be collected and fed back.
Third, the model has no persistent state. Preferences and conventions that span tasks and sessions can only rely on a limited context window without external storage, so long-running tasks inevitably degrade.
Using the model directly as an agent usually yields a system that “looks like it can write code but cannot deliver results.” Closing this gap requires an engineering layer outside the model. The industry commonly calls this layer the Harness (the orchestration or scaffolding layer), and it can be defined abstractly as: everything except the model itself.
Expressed as a formula:
Agent = Model + Harness
The most important implication of this formula is decoupling: the model handles reasoning and generation, while the Harness handles orchestration, execution, validation, and state management. The two evolve independently. Optimizing the Harness does not require retraining the model, and upgrading the model does not require rewriting existing engineering implementations.
2. Six Core Modules of the Harness Layer
2.1 Context Engineering and Prompt Orchestration
The goal of context engineering is not “writing better prompts” but “constructing the highest-density input within a limited token budget.” In practice, this usually involves three layers:
- Static layer: project conventions, tech stack agreements, and directory descriptions that can be cached and reused;
- Dynamic layer: file snippets, interface definitions, and data structures relevant to the current task;
- Interaction layer: summaries of prior conversation, reasons for the previous failure, and newly added user constraints.
The key design is the retrieval and trimming strategy: first recall candidate files by task intent, then rank them by relevance, and finally truncate them by budget. A sketch of the logic:
def build_context(task, repo_index, budget=32000):static = load_project_rules() # static rules, cacheablehits = repo_index.search(task.intent, top_k=20)dynamic = [h.snippet for h in hits if h.score > 0.6]history = summarize(task.history) # compress the interaction layerparts = [static, history] + dynamicreturn truncate_by_budget(parts, budget) # trim everything to the budget
2.2 Tool Invocation and Execution Sandbox
Tools are the agent’s hands and feet. Common categories include file read/write, command execution, test running, dependency lookup, and log retrieval. There are three design priorities:
- Least privilege: read-only by default; write operations require explicit authorization, and dangerous commands require a second confirmation;
- Structured returns: tool output is normalized into “exit code + standard output + error summary” so the model can parse it easily;
- Environment isolation: execution happens in a container or a separate workspace to avoid polluting the host environment.
The tool descriptions themselves are also part of the context. The more precise the description, the lower the model’s misuse rate.
2.3 Iteration Control and Fault Tolerance
In real tasks, the probability of getting it right in one pass is low, so iteration control is the source of stability. You need to define explicitly:
- a maximum round limit to prevent infinite loops from consuming resources;
- failure classification: syntax errors, missing dependencies, assertion failures, and timeouts, each matched with a different repair strategy;
- retry and rollback: retryable errors are retried automatically, while unrecoverable errors roll back to the last working state and are reported.
for round in range(MAX_ROUNDS):patch = model.propose(context)result = sandbox.apply_and_test(patch)if result.passed:return patchcontext = context.append(result.failure_report)
2.4 Context Summarization and Compression
Long tasks inevitably hit the window limit. Compression strategies usually mix three techniques: extracting key points from prior conversation; producing signature-style summaries of file content (keeping interfaces and types while dropping implementation details); and root-cause localization of failure logs (keeping only the first root-cause error and key stack trace). Compression must be reversible and traceable, meaning references to the original information are retained so it can be fetched again when needed.
2.5 Test Failure Feedback
This is the critical step that closes the loop. Failure information should not be just a text log; it should be structured as much as possible: the identifier of the failing test case, expected versus actual values, the relevant code location, and any necessary runtime environment details. Feeding this information back to the model is what drives targeted repair in the next round instead of blind rewriting.
2.6 Memory System and Sub-Agent Coordination
Memory is usually layered: short-term memory within a session, mid-term memory at the task level, and long-term memory at the project level (coding standards, historical decisions). Sub-agent coordination addresses the division of labor: the main agent handles decomposition and acceptance, while sub-agents each take on subtasks such as retrieval, implementation, and testing, working in parallel through a shared workspace and result aggregation. The key to coordination is clear interface contracts and conflict-handling rules to prevent multiple sub-agents from modifying the same file at the same time.
3. A Layered Reference Architecture
┌─────────────────────────────────────┐│ Interaction: task input / progress ││ display / human confirmation │├─────────────────────────────────────┤│ Orchestration: task decomposition / ││ sub-agent scheduling / round control│├─────────────────────────────────────┤│ Execution: toolset / sandbox / ││ testing and build │├─────────────────────────────────────┤│ State: context storage / memory / ││ summary index │├─────────────────────────────────────┤│ Model: reasoning and code generation││ (replaceable) │└─────────────────────────────────────┘
This layering brings three direct benefits: the model is replaceable, avoiding tight coupling to a single model; capabilities are pluggable, so adding a tool or validation step does not affect the main flow; and behavior is observable, since the input and output of every layer can be recorded for easier debugging.
4. Common Pitfalls in Engineering Practice
- Overstuffing the context: adding too many irrelevant files dilutes key information and leads the model to focus on the wrong things;
- No hard round limit: the task falls into a “modify—fail—modify again” loop;
- Coarse failure feedback: giving only a single error message leaves the model guessing, resulting in a low repair hit rate;
- Overly broad permissions: unconstrained write and execution operations create risks of unintended changes and data loss;
- Neglecting observability: without trace records, problems cannot be reviewed, and optimization relies on guesswork.
The corresponding improvements are equally clear: budgeted context, an explicit state machine, structured failure reports, least-privilege tools, and full-chain logging with monitoring and alerting.
5. Working with General-Purpose Cloud Capabilities
To run this kind of system in production, you usually only need to combine general-purpose cloud capability categories: use a container platform to host sandboxes and parallel tasks; use object storage to keep workspace snapshots and build artifacts; use a message queue for task distribution and peak shaving; use log services with monitoring and alerting for full-chain observability; and use a key management capability to hold credentials. Baidu AI Cloud offers corresponding product forms in these general categories, which can be combined as needed without binding to a specific model.
6. Conclusion
The competitiveness of AI coding agents depends less and less on the capability of a single model and more and more on whether the engineering orchestration layer outside the model is complete. Once the six pieces—context engineering, tool execution, iteration fault tolerance, summarization and compression, failure feedback, and memory with multi-agent coordination—are in place, the model can truly move from “generating code” to “delivering results.” For developers, the most practical path to building a stable and controllable AI coding tool is to first define the layers and contracts, then fill in the modules step by step.
