Code Agent Engineering: Execution Frameworks and Harness Engineering

    This article explains how a Code Agent is built beyond the base model. It covers the modules around the model, including context management, tool execution, sandboxing and permissions, verification and recovery, and observability. It also describes harness engineering, the practice of constraining model-generated actions with verifiable, reversible, and auditable system design.

    1. Problem Boundary: A Code Agent Is More Than a Model and a Chat Box

    The industry has discussed cases where the client source code of an AI coding tool was unintentionally exposed because of a packaging configuration mistake. The more useful question is not why a source map file ended up in the release. The more important point is what was exposed. It was not the foundation model itself, but the client and execution framework around it.

    This boundary needs to be clear first. A foundation model provides general reasoning, code understanding, and text generation. A Code Agent adds an engineering system on top of the model. That system includes context management, tool invocation, permission control, execution sandboxing, result verification, failure recovery, and observability. The model determines whether code can be generated. The surrounding system determines whether tasks can be completed reliably in a real codebase.

    So the implementation of a Code Agent cannot be discussed only at the level of prompts. The factor that determines product usability is the constraint engineering outside the model, which the industry often calls harness engineering. The core idea is simple. Instead of hoping the model never hallucinates, the system is designed to keep uncertain generation within tracks that can be verified, rolled back, and audited. The model proposes hypotheses and actions. The execution framework supplies facts, boundaries, and feedback.

    From an engineering perspective, a complete Code Agent includes at least the following modules: an interaction layer, session and context management, planning and decision-making, a tool executor, sandboxing and permissions, verification and recovery, observability and evaluation, and persistence. Together they form a closed loop: understand the goal, gather context, make a plan, call tools, observe results, verify the outcome, revise the plan, and repeat until the task is complete or escalated to a human. If any part of this loop is missing, the agent tends to degrade into a chatbot that can call a few tools.

    2. Architecture: Placing Generation Inside an Executable Loop

    A practical Code Agent architecture can be organized into the following layers:

    • Interaction and session layer: Receives natural language tasks, maintains multi-turn session state, and displays plans, tool calls, diffs, and verification results.
    • Context and code indexing layer: Handles codebase search, file selection, dependency analysis, summaries of past changes, and context budget control.
    • Planning and decision layer: Breaks high-level goals into executable steps and decides whether the next step is reading a file, modifying code, running verification, or requesting human confirmation.
    • Tool execution layer: Provides a minimal, structured, and auditable set of tools, such as file reading, diff application, test execution, static checks, and command execution.
    • Sandbox and permission layer: Limits workspace scope, network access, command permissions, and access to sensitive files so that execution stays controlled.
    • Verification and recovery layer: Confirms results through tests, compilation, static analysis, and diff review. When a step fails, it classifies the failure and then retries, rolls back, or escalates to a human.
    • Observability and evaluation layer: Records full execution traces, tool call metrics, failure causes, and cost and latency, which supports production debugging and offline regression testing.
    • Persistence layer: Stores sessions, plans, tool results, patches, and audit logs so that runs can be reproduced and traced.

    The boundaries between these modules should be explicit. The planning layer does not operate on files directly. The tool layer does not decide permissions on its own. The verification layer does not depend on the model’s belief that its output is correct. The system connects the layers through structured protocols, so that every action has defined inputs, outputs, failure semantics, and audit records. This keeps the model’s free-form generation within a scope that engineering can manage.

    3. The Core Execution Loop: Continuous Closed-Loop Work, Not a Single Generation

    The core of a Code Agent is not producing code once. It is a loop that includes observation and verification. The following pseudocode illustrates the idea:

    1. def run_agent(task, workspace):
    2. ctx = build_context(task, workspace)
    3. plan = planner(ctx)
    4. for step in range(MAX_STEPS):
    5. action = policy(plan, ctx)
    6. if action.type == "tool":
    7. obs = execute_tool(
    8. action,
    9. sandbox=workspace.sandbox,
    10. permission=permission_policy
    11. )
    12. ctx = update_context(ctx, action, obs)
    13. plan = replan_if_needed(plan, ctx)
    14. elif action.type == "verify":
    15. result = run_verification(ctx)
    16. if result.passed:
    17. return finalize_with_summary(ctx)
    18. plan = repair_plan(plan, result)
    19. elif action.type == "final":
    20. return verify_and_finalize(action, ctx)
    21. return escalate_to_human(ctx)

    The loop reflects several key principles. First, the model outputs an action intent, not a fact. The action must be carried out by the tool executor. Second, tool observations are written back into the context and become the factual basis for the next decision. Third, verification is a first-class part of the loop, not an option. An agent without verification is only a text generator. Fourth, the loop needs a maximum step count, timeouts, retry limits, and a path for escalation to a human, which prevents endless attempts and runaway costs.

    In implementation, tool call protocols should be as structured as possible. An action can include the tool category, target path, parameters, expected result, and risk level. A tool response should include status, structured data, error codes, duration, and a display-ready summary. This lets the planning layer decide whether to retry, change strategy, or ask a human, based on the type of failure. It should not treat error messages as plain text to guess from.

    4. Context Engineering: Show the Model What Matters, Not Everything

    Codebases usually exceed the context window, so context engineering is a core capability of a Code Agent. Typical implementations include code indexing, file selection, dependency graph analysis, summaries of past changes, localization of test failures, and context budget control. A common mistake is to paste large numbers of files into the prompt. This wastes budget, adds noise, and can cause the model to overlook key constraints.

    A better approach is to build context in layers:

    1. Task-level context: the user’s goal, acceptance criteria, constraints, and areas that must not be modified.
    2. Repository-level context: directory structure, build method, test entry points, coding standards, and key dependencies.
    3. File-level context: the most relevant file segments, interface definitions, call chains, and recent changes.
    4. Execution-level context: structured results from the previous tool call, failure logs, diff summaries, and items awaiting verification.

    Context budget also needs active control. Keep the most relevant fragments first, summarize long files, aggregate repeated logs, and redact sensitive information. Tool results should be structured where possible, rather than returning entire terminal output to the context. The goal of context updates is not to remember everything. The goal is to give the next decision enough clean, factual information to work from.

    5. Tool Design: A Minimal Tool Surface With Clear Failure Semantics

    The tool set for a Code Agent should follow the principles of least privilege and a minimal tool surface. Common tool categories include file reading, file search, diff application, command execution, test running, static analysis, dependency queries, and result display. Fewer tools with clearer semantics make it easier for the model to use them correctly and easier for the system to audit them.

    Tool design should focus on several points:

    • Separate reads from writes: Reading tools and modifying tools should be distinct. Modifications should produce reviewable diffs instead of overwriting large sections of files directly.
    • Structured inputs and outputs: Parameters should have explicit types and ranges. Responses should include a success status, error codes, a summary, and necessary data.
    • Clear failure semantics: Distinguish cases such as “file not found,” “permission denied,” “test failed,” “timeout,” and “command rejected,” so the planning layer can handle each one appropriately.
    • Timeouts and resource limits: Every tool should have a timeout, an output size limit, and a concurrency limit, so that a single action cannot stall the session.
    • Auditability: Record who invoked which tool, in what context, with which parameters, what the result was, and whether a human approved it.

    For example, a tool call can be expressed as follows:

    1. {
    2. "tool": "apply_patch",
    3. "args": {
    4. "target": "workspace/src/module",
    5. "diff": "...",
    6. "reason": "Fix null pointer check"
    7. },
    8. "risk": "write"
    9. }

    The executor checks the permission policy before running the call and returns a structured observation afterward. The model then does not need to imagine what happened. It can reason from actual feedback.

    6. Permissions, Sandboxing, and Security: Tight by Default, Human in the Loop

    A Code Agent can run commands and modify files, so its security boundaries must be tight by default. The basic policies include: isolating the workspace root, keeping network access off by default or allowing it only with approval, using command allowlists and risk levels, excluding sensitive files, reviewing write operations as diffs, and keeping complete audit logs. High-risk actions, such as deleting files, changing build configuration, running external commands, or accessing the network, should require human confirmation.

    The sandbox should allow execution but prevent escape. File system access is limited to the project workspace. Process resources are constrained. Environment variables are minimized. Temporary directories can be cleaned up. Commands run with timeouts and output truncation. Permission policies should be set through configuration rather than scattered through the code. In enterprise settings, teams also need to consider multi-tenant isolation, keeping secrets out of the context, redacting logs, and recording operations.

    Human oversight is not a patch for weak capability. It is a necessary design element for high-risk systems. The agent can propose plans, generate diffs, and run verification, but important changes should be confirmed by a person. This keeps the efficiency of automation while keeping irreversible risks within acceptable limits.

    7. Verification and Failure Recovery: Replace “I Think It Is Correct” With Facts

    Verification is what separates a system that generates code from one that completes tasks. Verification methods include compilation, unit tests, integration tests, static analysis, format checks, diff review, and replay of critical paths. Verification results should be returned in a structured form, such as passed, failed, skipped, or environment error, along with the failure location and a summary.

    Recovery should be tiered. Retryable errors, such as temporary timeouts, get a limited number of retries. Fixable errors, such as test failures, move into a repair plan. Unrecoverable errors, such as permission denials or missing environments, are escalated to a human. High-risk failures, such as large-scope diffs or cases where verification cannot cover the change, require human review. Each repair should keep its diff and verification record, and the system should support rolling back to the last stable state when needed.

    The model can explain a failure, but it cannot replace verification. The system should rely on tool output and test results. It should not let the model use natural language to claim the task is done. A task is closed only when verification passes and the diff can be reviewed.

    8. Observability and Evaluation: Make Agent Behavior Explainable and Regression-Testable

    The complexity of a Code Agent means it must be observable. Execution traces should record the task goal, a context summary, plan steps, tool call parameters and results, verification outcomes, retry reasons, points where a human intervened, total duration, and cost. Useful metrics include task success rate, first-pass verification rate, average number of tool calls, distribution of failure categories, human escalation rate, rollback rate, and context budget usage.

    Evaluation cannot rely only on individual demo cases. Teams should build an offline regression set that covers scenarios such as locating code, making small changes, refactoring across files, fixing tests, permission denials, and environment anomalies. In production, sampled and redacted logs can reveal real failure patterns. Evaluation results should feed back into tool descriptions, permission policies, context selection, and planning prompts. They should not be attributed simply to “the model not being strong enough.”

    9. Engineering Checklist

    To build a usable Code Agent, teams can follow this checklist:

    1. Define the boundary: Separate model capability from execution framework capability. Build a verifiable closed loop first, then pursue more complex autonomy.
    2. Design the protocol: Use a unified structured protocol for actions, observations, verification, and errors so that layers stay decoupled.
    3. Keep the tool surface minimal: Implement four core capabilities first: reading, diff-based modification, test running, and verification. Expand gradually.
    4. Secure by default: Isolate the workspace, restrict network access, classify commands by risk, exclude sensitive files, and keep audit logs.
    5. Budget the context: Establish mechanisms for file selection, summarization, log aggregation, and redaction to prevent context pollution.
    6. Prioritize verification: Include tests and static checks in the loop, and handle every failure by category.
    7. Keep humans in the loop: Require approval for high-risk actions, and support rollback and manual takeover.
    8. Make it observable: Record full traces and metrics, and build a regression set and a failure classification system.
    9. Control costs: Set limits on steps, timeouts, retries, and tool output size to prevent infinite loops.
    10. Roll out gradually: Start with low-risk tasks, expand automation scope step by step, and adjust policies based on data.

    10. Summary

    The key to implementing a Code Agent is not getting the model to write correct code in one attempt. It is using engineering systems to let the model keep producing correct results in a real codebase over time. The foundation model provides reasoning and generation. The execution framework provides facts, boundaries, verification, and recovery. Context engineering determines what the model sees. Tool design determines what the model can do. Permissions and sandboxing determine what the model cannot do. The verification loop determines whether results can be trusted. Observability determines whether the system can keep improving.

    Seen this way, constraint engineering does not tell the model how to work. It lays executable, verifiable, and auditable tracks for the model’s generation. The competitiveness of a Code Agent ultimately depends on how stable, clear, and operable those tracks are.