Engineering Code Agents: Constraints, Execution, and Closed Loops
Building production-ready Code Agents requires more than just powerful large language models; it demands robust "harness engineering." This article explores the essential engineering practices for Code Agents, including stateful multi-step execution loops, layered architecture, context budget management, secure tool design, permission controls, failure recovery, and comprehensive observability. By treating the model as an engine and the engineering system as the chassis, developers can build reliable, safe, and governable AI coding assistants capable of consistently delivering code.
Starting from a Source Code Leak: The Real Focus Should Be on “Harness Engineering”
Recently, an AI coding tool experienced a source code leak due to a packaging misconfiguration that included debug map files in the release build, exposing the client-side code. While the incident itself is dramatic, the more valuable discussion for developers goes beyond mere curiosity. It is crucial to clarify a boundary first: what leaked was the client-side engineering code, not the model weights or training code. In other words, what the outside world saw was not “why the model is smart,” but how a coding agent product packages model capabilities into an executable, constrainable, and deliverable system.
This perfectly aligns with the concept of “harness engineering” frequently mentioned recently. Harness engineering is not a mystical new term, but a re-emphasis on engineering common sense: rather than hoping the model never makes mistakes, it is better to use a system to put reins on it. The model is like an engine, responsible for reasoning and generation; the harness, chassis, brakes, and seatbelts are responsible for transmitting power smoothly to the wheels. For a Code Agent, harness engineering at least includes context assembly, tool protocols, permission policies, execution sandboxes, state management, failure recovery, observability, and evaluation systems. Without these, no matter how powerful the model is, it is merely “chatting about code” and struggles to reliably “deliver code.”
The Essence of a Code Agent: A Stateful, Multi-Step Execution Closed Loop
A Code Agent is not simply a scaled-up version of code completion. Code completion typically involves a single input mapped to a single output. A Code Agent, on the other hand, revolves around a goal, repeatedly executing a “perceive—plan—act—observe—correct” loop within a codebase. It needs to understand the task, gather context, break down steps, call tools, read results, decide whether to continue, and ultimately produce verifiable changes.
Therefore, the capability boundaries of a Code Agent are jointly determined by two parts: the model dictates reasoning quality, while the engineering system dictates reliability, safety, cost, and observability. A viable Code Agent usually possesses the following characteristics: multi-step execution, stateful sessions, tool calling, file and command operations, permission approvals, execution isolation, failure recovery, trajectory logging, and offline evaluation.
Layered Architecture: Breaking Down “Intelligence” into Governable Modules
A relatively complete Code Agent can be divided into six layers based on responsibilities:
First, the Interaction and Session Layer. It is responsible for receiving tasks, clarifying ambiguities, presenting plans, requesting approvals, streaming feedback, and session persistence. It should not directly manipulate the codebase but rather translate user intent into structured tasks.
Second, the Context and Memory Layer. It is responsible for assembling the working set, retrieving relevant code, compressing history, and maintaining project conventions and decision logs. More context is not always better; the goal is to fit the “information most needed for the current decision” within a limited budget.
Third, the Planning and Decision Layer. It is responsible for breaking down goals into verifiable steps, maintaining the task state machine, and re-planning upon failure. Plans should be structured data rather than a paragraph of natural language description, facilitating validation, display, and replay.
Fourth, the Tool and Execution Layer. It abstracts capabilities like file read/write, code search, command execution, test running, and static checking into unified tools. Each tool must have a clear parameter schema, side-effect description, risk level, and return structure.
Fifth, the Security and Permission Layer. It handles policy checks, human approvals, sandbox execution, network egress controls, secret isolation, and auditing. This is the key to moving a Code Agent from demo to production.
Sixth, the Observability and Evaluation Layer. It records trajectories, metrics, costs, and failure reasons, supporting replay and evaluation. Without trajectories, it is impossible to locate “which step’s decision was wrong”; without evaluation, it is impossible to determine if a version upgrade is genuinely better.
On the deployment side, general container platforms, log services, monitoring and alerting, and object storage can be utilized to achieve isolated execution, log aggregation, metric alerting, and artifact archiving. For example, Baidu AI Cloud provides general container platforms, log services, monitoring and alerting, and object storage capabilities that can serve as deployment references, though the specific implementation should always be designed around your own security boundaries.
The Core Loop: Validation, Authorization, Sandbox, and Observation
The main loop of a Code Agent can be summarized with the following pseudocode:
def run_agent(task, workspace, policy):state = init_state(task)while not state.done:ctx = assemble_context(task, state, workspace, budget)decision = model_decide(ctx, tools)if decision.kind == "final":return finalize(decision, state)call = validate_tool_call(decision.tool_call)if not policy.allow(call, state):state = request_approval_or_reject(call, state)continueresult = sandbox_execute(call, workspace, limits)observation = normalize_and_truncate(result)state = update_state(state, call, observation)if no_progress(state) or over_budget(state):state = rollback_and_report(state)return state.result
The focus of this pseudocode is not the syntax but the sequence: after the model provides a tool call, structural validation must occur first, followed by policy authorization, then sandbox execution, and finally the standardized result is fed back into the state. Missing any step could amplify “model hallucinations” into real damage.
Context Engineering: Budget Management over Window Stuffing
Context engineering is the most easily underestimated part of a Code Agent. A common mistake is stuffing conversation history, full files, and tool outputs entirely into the window, which wastes costs and introduces noise. A more reasonable approach is layered management: task goals, current plans, current working file snippets, retrieved evidence, tool result summaries, compressed history, and hard constraints. Each type of information has different priorities and eviction policies.
Tool results should be structured as much as possible: retaining status codes, key summaries, artifact references, and truncation markers, rather than blindly concatenating full text. For large files, prioritize providing diffs over the full content; for long logs, prioritize error snippets and statistical summaries; for long conversation histories, periodically compress them into decision logs. Before write operations, the target file should be re-read to avoid modifying based on an outdated snapshot. Long-term memory can store project conventions, common commands, failure lessons, and approved decisions, but it must tag the source and time to prevent stale information from polluting judgments.
Tool Design: Narrow Interfaces, Strong Validation, and Rollback
Tools are the hands and feet of the Agent. Tool design should follow several principles: interfaces should be as narrow as possible, parameters strongly typed, side effects clear, returns parseable, and errors actionable. Tool descriptions should explain the purpose, parameters, risk level, and failure semantics, preventing the model from repeatedly testing between similar tools. Parameter validation should be split into two layers: structural validation ensures complete fields, while semantic validation ensures paths are within the workspace, commands are on the allowed list, and resources do not exceed boundaries.
Standardizing results is equally important. A tool return should not be a large block of unparseable text, but should contain status, summary, artifact reference, and truncation information. For high-risk tools, idempotency or rollback must be supported; for long-running tools, timeout and cancellation mechanisms are necessary; for tools with massive outputs, the full result should be dropped into object storage or a temporary artifact area, with only the reference kept in the context.
Permission and Security: Least Privilege, Tiered Approvals, and Sandbox Isolation
Once a Code Agent can modify files and run commands, it must be designed with “least privilege.” Permissions can be divided into levels such as read-only, low-risk write, high-risk execution, and external network access, combined with policy checks based on tasks, paths, commands, and resources. Low-risk operations can be automatically approved, while high-risk operations should require human approval. Approval is not a formality; it exposes irreversible actions to humans.
The sandbox is the second line of defense. Each task uses a temporary workspace with file system isolation, limited resource quotas, network disabled by default (and whitelisted on demand), no local secrets, and forced timeout termination. Paths must be normalized to prevent directory traversal; command execution should be array-based to avoid injection risks from string concatenation; and sensitive files should be forbidden from read/write. All tool calls must be recorded in an audit log: who initiated it, when, parameter summary, result summary, whether it was approved, and whether it was rolled back.
Planning and Failure Recovery: Plans as State Machines, Not One-Off Essays
A Code Agent’s plan should be executable, verifiable, and adjustable. Tasks are broken down to a granularity that can be “verified by tests or checks,” and the state machine maintains statuses like todo, in-progress, blocked, done, and failed. During execution, prioritize validation: run tests, static checks, builds, and diff reviews. Failures should be handled by classification: model decision errors, tool errors, environment errors, permission denials, or timeouts. Retriable errors use exponential backoff; non-retriable errors should be rolled back and reported; consecutive lack of progress should trigger replanning or request clarification.
To prevent infinite loops, step limits, cost limits, duplicate call detection, and no-progress detection should be set. Once a plan is presented to the user, the user should be allowed to adjust constraints, rather than letting the Agent run further in the wrong direction.
Observability and Evaluation: Trajectories as Core Assets
A Code Agent’s trajectory logs should record sessions, plans, tool calls, observation results, approvals, costs, and latency. Core metrics include task success rate, first-pass rate, average steps, tool failure rate, permission denial rate, token consumption, end-to-end latency, and rollback rate. Offline evaluation should use a fixed set of codebase tasks and assertions, while online risk is controlled through canary releases and human review. Log services are responsible for aggregation, monitoring and alerting for anomaly detection, and object storage for archiving large artifacts and trajectories, facilitating replay and review.
Conclusion: Competitiveness Lies in the “Harness,” Not Just the Model
The engineering implementation of a Code Agent is essentially about establishing a governable execution system beyond the model’s capabilities: context has a budget, tools have protocols, permissions have policies, execution has a sandbox, failures have recovery, processes have trajectories, and effects have evaluation. The source code leak incident reminds us that client-side engineering code contains a wealth of product design information; but what is more worth learning is not a specific product’s implementation, but the universal engineering methodology behind it. Only by putting reins on the wild horse that is the model and defining the track clearly can it consistently produce reliable work.
