Building a Code Agent from Scratch: A Practical Guide to Harness Architecture

    This article explains why strong model capabilities alone do not produce a reliable code agent, and how the Harness layer bridges that gap. It breaks down four core Harness responsibilities—context engineering, tool and action design, execution sandboxing, and evaluation feedback loops—then walks through a typical six-stage agent cycle from requirements to verified delivery. You will also find common failure modes with practical countermeasures, plus a staged adoption path for teams building code agents from the ground up.

    1. Where the Problem Starts: Model Capability Is Not Product Capability

    A new kind of role is appearing across the industry: product managers and software engineers assigned together to a direction called “Harness,” with the goal of turning frontier model capabilities into agent products for desktop and coding scenarios. Job descriptions keep repeating one judgment—everything beyond the model itself falls under the Harness umbrella. That statement captures the central tension in agent engineering today: the capability curve of the underlying model is steep, but an entire engineering system sits between “can answer” and “can deliver.”

    An abstraction makes this clear. An agent can be split into two layers: a model core responsible for reasoning and generation, and a runtime framework wrapped around the model that handles orchestration and constraints—commonly known as the Harness. The former sets the ceiling; the latter determines the floor and the stability. What users actually perceive as “easy to use” comes mostly from the latter.

    Why pull this layer out separately? Three reasons:

    • The model is stateless. It does not automatically remember project structure, past decisions, or failed attempts; all of that must be injected explicitly from outside.
    • The model’s actions are nondeterministic. The same input can produce different paths, so external permission boundaries, retry policies, and rollback mechanisms are needed as a safety net.
    • The model’s field of view is a text window. The real engineering world is a file system, a terminal, a dependency graph, and a test suite. A layer is needed to translate the world to the model, and the model’s intent back to the world.

    2. Harness Responsibilities: Four Core Capabilities

    2.1 Context Engineering

    Context is the agent’s only working memory, and the resource most likely to spiral out of control. The mature approach is to manage context in layers:

    • Stable layer: project conventions, directory standards, and coding style—long-lived and reusable from cache.
    • Task layer: the current requirement description, acceptance criteria, and summaries of relevant files.
    • Dynamic layer: retrieved code snippets, results of past tool calls, and error stack traces.

    The key design is “load on demand plus budget control.” Do not stuff the entire repository into the window at once; instead, provide a structural index first and let the model initiate retrieval on its own. Illustrative context assembly logic (pseudocode, expressing only the layering and budget ideas):

    1. def build_context(task, repo_index, budget=120_000):
    2. parts = []
    3. parts.append(("stable", load_conventions())) # high priority, always resident
    4. parts.append(("task", task.spec)) # requirements and acceptance criteria
    5. for need in task.declared_needs: # retrieval intents declared by the model
    6. parts.append(("dynamic", repo_index.search(need)))
    7. return fit_to_budget(parts, budget) # trim by layer when over budget

    The trimming priority should be: never trim the task layer, compress the stable layer into a summary, and evict the dynamic layer by relevance. This is how you avoid the context bloat that makes an agent “more confused the longer it runs.”

    2.2 Tools and Action Space

    An agent’s capability boundary equals the set of tools it can call. The design principle is “minimally sufficient”: enough is enough, and too many tools significantly reduce selection accuracy. A typical toolset includes file reading, targeted search, patch writing, build and test execution, and log inspection.

    The quality of tool descriptions directly determines call success rates. Each tool needs to state four things clearly: purpose, input constraints, side effects, and the shape of the return value on failure. Side effects in particular must be declared explicitly, because they determine how the permission layer intercepts calls.

    2.3 Execution Sandbox and Security Boundaries

    Code agents are inherently high-risk because they write files and run commands, so a sandbox is not optional. A common industry approach is container-based isolation paired with a least-privilege account: writable directories are restricted to the workspace, network access is allowed by whitelist, and resource consumption is capped.

    For permission design, tiered confirmation is recommended: read operations pass freely; writes inside the workspace are logged and allow rollback; writes outside the workspace and installation-type commands require explicit confirmation. All actions flow into a unified audit stream, forming a traceable execution chain.

    2.4 Evaluation and Feedback Loops

    An agent without evaluation cannot iterate. A workable minimal loop has three layers:

    • Single-step checks: after each tool call, verify that the return matches the expected structure.
    • Task-level checks: use build passing, tests passing, and static checks passing as objective signals.
    • Regression set: maintain a set of historical real tasks, rerun them after every change, and watch success rate and average step count.

    Objective signals take priority over subjective scoring. If a compiler and a test suite can do the talking, do not rely on model self-assessment.

    3. A Typical Work Cycle: From Requirements to Verified Delivery

    A stable code agent cycle usually has six stages: understand the requirement, form a hypothesis, locate code, generate a patch, run verification, and summarize for delivery. The two stages most often missing are “form a hypothesis” and “run verification.”

    Without a hypothesis, the model jumps straight to writing code, causing broad, unrelated changes; without verification, the model tends to claim completion while the result does not actually run. The engineering constraints are straightforward: make “state the modification plan and expected impact surface first” a hard process constraint, and make “the task cannot end until the build and tests pass” the termination condition.

    Illustrative loop control logic:

    1. while not done and steps < MAX_STEPS:
    2. plan = model.propose_plan(context) # plan and impact surface first
    3. patch = model.generate_patch(plan) # then produce a minimal patch
    4. result = sandbox.apply_and_test(patch) # verify inside the sandbox
    5. if result.passed:
    6. done = True
    7. else:
    8. context.add(result.failure_digest) # feed the failure digest back into context

    Feeding the failure digest back is a key detail: do not push the full log back into context; compress it into a structured summary (failing file, error type, key line), which both saves budget and raises the fix hit rate.

    4. Common Failure Modes and Countermeasures

    • Context pollution: early failed attempts linger in the window and repeatedly mislead the model. Countermeasure: reset in segments and clear the dynamic layer when switching tasks.
    • Tool misuse: the model uses a read tool to guess the contents of a large file. Countermeasure: provide structured indexes and summary interfaces to reduce blind reads.
    • Over-modification: a single change spans dozens of files. Countermeasure: minimal-patch constraints and impact-surface declaration.
    • False completion: claims a fix without verification. Countermeasure: enforce objective gates.
    • Cost overrun: no limits on step count or retrieval count. Countermeasure: set triple limits on steps, budget, and timeout, and prioritize the cacheable stable layer.

    Step one: build a read-only agent with only retrieval and explanation capabilities, and validate the accuracy of context engineering and tool descriptions. Step two: open up writes and execution inside the workspace, and bring in the sandbox and audit. Step three: introduce a regression evaluation set, with success rate and average step count as core metrics. Step four: then consider session management, permission policies, and observability for desktop and multi-project scenarios, which can be carried by general cloud capabilities such as container platforms, logging services, and monitoring and alerting.

    The point to emphasize is that the value of Harness lies not in piling up features but in locking uncertainty inside an engineering cage. The model determines how fast this machine can run; the Harness determines whether it hits a wall. For teams starting to build a code agent from scratch, laying the four foundations—context, tools, sandbox, and evaluation—before discussing product form is the lowest-risk path.