Deep Dive: Harness and Context Engineering in AI Coding Assistants
The same generation of LLM can deliver very different experiences across coding tools, and the reason usually isn't the model itself but the software scaffolding built around it—the harness. Taking an engineering-architecture view of terminal-based AI coding assistants, this article breaks down their core subsystems: state persistence and artifact management, context engineering, the tools and execution layer, and loop control with human collaboration. It also covers areas that are often overlooked, such as evaluation, observability, and cost governance, and closes with common pitfalls and a practical checklist for building a robust harness.
1. Introduction: The Model Isn’t the Whole Story
The code-understanding and code-generation capabilities of large models keep improving, yet one phenomenon is worth noting: the actual experience of the same model generation varies dramatically across different coding tools. Some people use it to smoothly complete cross-file refactors; others watch it repeatedly edit the same bug while slowly drifting away from the original requirement. Attributing the difference entirely to model capability is not rigorous. What really separates the tools is the layer of software engineering built around the model—what the industry often calls the Harness (roughly, a “load-bearing framework” or “shell”).
In a public talk, a well-known AI researcher used the concept of a “knowledge base for large models” to vividly illustrate one facet of the harness: continuously distilling state into artifacts, organizing knowledge into navigable Markdown files arranged by directory, and keeping humans “on the loop” rather than “in the loop.” The deeper implication is this: an agent should not cram all information into a limited context window, but should instead build a persistent, searchable, versionable external memory system on top of the file system.
This article does not discuss the source-code implementation of any specific product. Instead, from an engineering-architecture perspective, it systematically dissects the four core subsystems behind a terminal-based AI coding assistant: state persistence and artifact management, context engineering, the tools and execution layer, and loop control with human collaboration. It also supplements the often-neglected engineering concerns—evaluation, observability, and cost governance—to form an architectural framework that can directly guide practice.
2. What Is a Harness: From Model Capability to Task Completion Rate
A Harness refers to the entire engineering shell built around a large model. At minimum it usually includes: context assembly, tool interfaces, loop control, state persistence, permissions and auditing, and observability. To use an analogy: the model is the engine, while the harness is the transmission, chassis, and fuel lines—without both, the vehicle won’t actually run.
From the perspective of capability conversion, a simplified relationship captures it well:
delivered capability ≈ base model capability × harness engineering quality
Here, base model capability sets the theoretical ceiling; the harness determines how much of that ceiling can be reliably realized. A common misconception is treating “a prompt long enough” as the endpoint of context engineering. In fact, how context is organized, the information density returned by tools, and the error-recovery strategy within the loop have an equally significant—or even greater—impact on the final result.
Harness engineering typically revolves around three main threads:
- Context engineering: determines what the model “sees” at each step, including background knowledge, code structure, interaction history, and constraints;
- Tools and execution: determines what the model “can do,” including reading and writing files, searching code, running commands, and verifying results;
- Loop and human collaboration: determines how the model “acts,” including when to continue, when to pause, and when to ask for human confirmation.
The three are tightly coupled: content returned by tools becomes new context, and whether the context contains enough clues in turn affects how quickly the loop converges. As a result, harness design cannot optimize any single link in isolation.
3. State Persistence: Moving Memory Out of Context and into an Artifact Store
3.1 Why You Can’t Rely on Conversation History
The context window is a scarce and volatile resource: once a session ends, its history is lost; even while a session continues, early constraints get diluted as turns accumulate. The prevailing industry approach is “externalizing state”—writing key information to the file system and persisting it long-term as artifacts. This brings at least four benefits:
- Resumable: if a task is interrupted or the device is switched, a new session can pick up where it left off simply by reading the artifacts;
- Shareable: team members can review the same artifacts directly, without repeating conversations;
- Versionable: once artifacts are under version control, changes are traceable and reversible;
- Reviewable: humans can review an agent’s output the way they review code, instead of passively watching logs scroll by in a terminal.
3.2 A Three-Tier Artifact Structure
A well-tested way to organize artifacts is to divide them by “degree of processing” into three tiers:
| Tier | Directory example | Contents | Written by |
|---|---|---|---|
| Raw | raw/ |
Papers, web page snapshots, code repository mirrors, datasets, images | Human / tools |
| Distilled | wiki/ |
Index files, concept entries, document summaries, backlinks | Mostly the model |
| Output | out/ |
Reports, slide sources, chart scripts, runnable code | Mostly the model |
The key to this layering is a clear division of responsibility: the raw tier is read-only and tamper-proof, ensuring facts stay traceable; the distilled tier is the only “living” knowledge the model must continuously maintain; and the output tier holds the final deliverables meant for humans. The three tiers are linked through path references, avoiding situations where “a conclusion can’t be traced to its source.”
A typical directory layout looks like this:
my-research/├── raw/│ ├── papers/paper_001.md│ ├── articles/article_012.md│ └── images/fig_003.png├── wiki/│ ├── index.md # Master index: entry list + one-line summaries│ ├── papers/│ ├── concepts/│ │ ├── context-engineering.md│ │ └── tool-use.md│ └── entities/├── out/│ ├── reports/quarterly_review.md│ └── charts/trend.py└── AGENTS.md # Project conventions and operating rules for agents
3.3 Index, Summaries, and Backlinks
The navigability of the distilled tier depends on three mechanisms: an index file acts as a table of contents, listing every entry by topic along with a one-line summary; concept pages consolidate scattered source material under a unified concept, forming vertical aggregation; and backlinks record “which source material supports this conclusion,” letting the agent quickly trace back the chain of evidence when facing follow-up questions. This also means the data quality of the raw tier directly sets the ceiling for the distilled tier, so cleaning and structuring during ingestion are worth the investment.
3.4 Compilation-Style Maintenance and Incremental Updates
Comparing knowledge-base maintenance to “compilation” is an apt analogy: source material is like source code, distilled entries are like compiled artifacts, and the index is like the link output. The engineering lessons from this analogy include:
- Dependency tracking: each distilled entry records the paths of the raw files it depends on; when any raw file changes, only the affected entries need recompiling, avoiding a full rebuild;
- Staleness marking: mark entries that are outdated but not yet recompiled with a
staleflag, prompting the agent to verify them before use; - Idempotent replay: recompiling the same source material should yield stable results, which can be achieved through fixed prompt templates and structured-output constraints.
3.5 Relationship to Retrieval-Augmented Generation
A frequently overstated assumption is that a large knowledge base must first be paired with a complex vector-retrieval scheme. Practice shows that in the range of thousands to tens of thousands of entries and hundreds of thousands of words in total, having the model maintain the index and summaries itself and read key entries on demand is already quite usable. The value of vector retrieval shows up mainly in scenarios such as very large scale, high concurrency, and cross-lingual recall—not as the best solution for every case. Engineering decisions should be grounded in measurement at scale, not in technical preference.
4. Context Engineering: Giving the Model Exactly the Right Information
Context engineering is the most underrated yet most directly impactful part of the harness. Its core question is: within a limited token budget, how do you organize information to maximize the effectiveness per token?
4.1 The Four Layers of Context
- Static instruction layer: system prompts and project convention files (coding standards, build commands, directory descriptions); these should be concise, stable, and free of redundancy;
- Retrieval layer: file fragments read on demand, retrieval hits, and dependency summaries; these should have a high signal-to-noise ratio;
- Tool-return layer: command output, compile errors, and test logs; these should be truncated to the essential parts;
- Interaction history layer: records of completed tasks; these should be compressed or externalized into artifacts.
4.2 Retrieval over Exhaustion
A typical anti-pattern is “reading the entire repository into context.” A more robust approach is layered retrieval: first locate candidate files using keywords or structural information, then read the relevant line ranges precisely, and only expand dependencies when necessary. This coarse-to-fine, funnel-style strategy usually achieves equally good—or better—localization with significantly fewer tokens.
4.3 Compression and Forgetting Management
Long sessions require actively managing “forgetting”:
- Rolling summaries: compress completed stages into fixed-length structured summaries that replace the raw interactions;
- Bounding tool output: set hard limits on outputs like logs and directory listings, while keeping the key head and tail fragments;
- Externalizing completed work: move the history of finished tasks out of the main context, keeping only artifact path references.
It’s worth stressing that compression is a lossy operation. Which information must be retained (for example, confirmed interface conventions and rejected approaches) should be explicitly defined at the harness level, rather than left to the model’s discretion.
4.4 Context Rot and Self-Correction
The longer the context, the weaker the binding force of early instructions—a phenomenon that can be called “context rot.” Mitigation measures include: periodically restating goals and constraints, using files to carry factual information instead of relying on conversational memory, and starting a fresh session at key junctures that carries only the artifact index. At the same time, the model should be allowed to launch a second verification of an obviously wrong retrieval result, rather than unconditionally trusting the first hit.
5. Tools and the Execution Layer: Giving the Model Reliable Hands
5.1 A Minimal, Complete Tool Set
The tool set of a usable coding harness usually converges to five categories: file reading (supporting line ranges and structured previews), precise editing (anchor-based rather than whole-file rewrites), retrieval (full-text search and symbol-level locating), command execution (build, test, static checks), and the necessary external information retrieval. Adding tools often brings choice difficulty and a higher invocation error rate, so “few and precise” beats “many and messy.”
5.2 Tool Descriptions Are Prompts
The naming and description of a tool are themselves part of the model’s input. A good tool description should include: applicable scenarios, inapplicable scenarios, parameter semantics, return format, and failure modes. For example:
{"name": "search_symbol","description": "Search a codebase for definitions and references by symbol name. Used for locating only; does not return full file contents.","parameters": {"symbol": { "type": "string", "description": "Full symbol name; supports a qualified namespace" },"scope": { "type": "string", "enum": ["workspace", "current_file"], "default": "workspace" }},"returns": "A list of matches; each item contains file_path, line_range, and snippet (≤200 characters)"}
5.3 Structured and Parseable Returns
Tool returns should be as structured as possible: JSON or YAML is easy to parse reliably, whereas plain-text logs tend to break parsing once the format changes. At the same time, agree on “truncation semantics”—clearly telling the model whether the returned content has been clipped and what its original length was—so the model doesn’t make judgments based on incomplete information.
5.4 Permission Model and Execution Safety
The tool layer is where the security boundary is actually enforced. A common layering approach is:
- Read-only without confirmation: retrieval, reading, static checks;
- Writes require confirmation: file modifications and dependency installs, with an upper limit on the scope of changes;
- Hard block on high-risk operations: force pushes, deleting data volumes, deploying to production, and so on—blocked even if the model requests them;
- Isolated execution: commands run in containers or sandboxes with restricted network egress and filesystem visibility;
- Full auditing: record the inputs, outputs, and executor of every tool invocation for later tracing.
6. Loop Control: From In-the-Loop to On-the-Loop
6.1 The Basic Loop Skeleton
An agent’s execution is essentially a closed loop of “model reasoning → tool execution → result write-back”:
function run(task):ctx = load_static_rules() + load_index("wiki/index.md")messages = [user(task)]while budget_left and not terminal():resp = model(messages, tools=TOOLS)if resp.tool_calls:for c in resp.tool_calls:r = guardrail(c).execute(sandbox)messages.append(tool_result(truncate(r)))else:messages.append(await_user_input()) # on-the-loop: approval or follow-upcheckpoint(ctx, messages) # persist state as artifactsreturn summarize(artifacts())
6.2 Three Collaboration Modes
| Mode | How humans participate | Suitable scenarios |
|---|---|---|
| In-the-loop | Confirm every action step by step | High-risk changes, exploratory tasks |
| On-the-loop | Approve and review only at key checkpoints | Medium-to-low-risk, well-defined routine tasks |
| Autonomous | Review the output after the fact | Low-risk batch tasks |
The reason “on-the-loop” has become the mainstream compromise is that it preserves both efficiency and controllability: humans don’t need to watch every step, but retain the authority to course-correct at key junctures.
6.3 Termination Conditions and Failure Recovery
The loop must have a clear convergence criterion. Common combinations include: tests passing or a successful build, reaching the maximum number of turns, exhausting the token or time budget, or exceeding a threshold of consecutive failures. Failure-recovery strategies are equally important:
- After a tool error, feed the error message back verbatim so the model can rewrite the command rather than blindly retrying;
- When the same action fails consecutively up to a threshold, escalate the strategy (switch approaches, narrow the scope, or ask for human intervention);
- When signs of regression appear (for example, repeatedly editing the same file without progress), proactively trigger a “restate the goal” flow.
7. Evaluation, Observability, and Cost Governance
Every change to a harness needs quantifiable verification; otherwise it’s easy to fall into “tuning by feel.” It’s recommended to build a three-tier observability system:
- Task-level metrics: end-to-end success rate, average number of interaction turns, number of human interventions, and rework rate;
- Process-level logs: the inputs and latency of every tool invocation, context snapshots, and retrieval hit rates;
- Cost-level metrics: token consumption per task, cache hit rate, and average cost per task.
Regression testing against a fixed task set is especially important. Turning a batch of typical requirements into a test-case suite and re-running it after every change to prompts, the tool set, or the retrieval strategy can prevent local optimizations from introducing overall regressions. In addition, a stable prompt prefix combined with a varying suffix helps improve cache hit rates and reduce latency and cost. This is general engineering practice and does not depend on any specific product capability.
8. Common Pitfalls and an Engineering Checklist
A few pitfalls worth deliberately avoiding:
- Treating a long context as a cure-all: filling the window doesn’t mean adding effective information; instead it raises cost and the risk of context rot;
- Blindly expanding the tool set: every added tool consumes context and increases choice ambiguity;
- Missing permission boundaries: giving the model direct write access to production is a severe mismatch of risk and reward;
- No artifact persistence: when all state lives only in the session, tasks can’t be handed off or reviewed afterward;
- Skipping the evaluation loop: change effects can’t be attributed, and iteration degrades into empiricism.
The corresponding implementation checklist can be summarized as: first define the directory structure for state persistence and the responsibility for writing it; then converge on a minimal, complete tool set with clear permission tiers; next design the context layering and compression strategy; then set the loop termination conditions and failure-recovery paths; and finally build a task-set regression and cost-observability dashboard to enter a cycle of continuous iteration.
9. Conclusion
The value of harness engineering lies in turning “model capability” into “deliverable capability.” It asks developers to shift their focus from “how to write a good prompt” up to “how to design a sustainable agent system”: how state is persisted, how context is organized, how tools are constrained, how the loop converges, and how effectiveness is measured. When all five questions have clear answers, every improvement in model capability can be reflected more reliably in real productivity. When building such systems in the cloud, you can use object storage to preserve artifacts and versions, container platforms to isolate execution environments, and logging and monitoring services to build observability—letting general-purpose infrastructure support a robust harness architecture.
