AI Agent Harness Engineering: Context, Tools, State Machines, and Evaluation
This article breaks down AI agent harness engineering into concrete design problems: how the runtime layer around a model handles context budgeting, tool contracts, execution state machines, recovery, observability, evaluation, and cost control. It explains where responsibilities should sit between the model and the harness, offers a practical four-layer context model with budget allocation, defines tool declaration fields that drive scheduling, and outlines a phased adoption roadmap for teams building long-running agents.
1. Introduction: What We Actually Mean by a Harness
The agent space has recently seen a clear shift in attention. General-purpose task agents took off overseas, domestic teams followed quickly with their own implementations, and arguments about copying followed. From an engineering standpoint, that debate points to a more fundamental question: does an agent’s core competitiveness live in the model, or in the engineering structure wrapped around it.
That structure is usually called a Harness (the runtime or carrier layer). It is not a marketing concept but a concrete set of engineering responsibilities: how context is organized and compressed, how tools are registered and authorized, how multi-step tasks are interrupted and resumed, how failures are retried and rolled back, and how the whole process is observed and evaluated. This article restates those topics in neutral technical language as design problems you can actually implement.
2. The Paradigm Shift: From “Can Chat” to “Can Deliver”
First-generation agents were essentially a prompt plus a single tool call, with value concentrated in the demo. The second generation emphasized long-horizon tasks, focusing on task decomposition, state retention, and failure recovery. The current bar is defined by two engineering metrics: delivery success rate and cost per task.
Three consequences follow directly:
- Evaluation changes: instead of a human skimming a few samples, teams build repeatable offline evaluation sets and online canary metrics.
- Architecture changes: instead of a monolithic prompt, the system becomes a layered structure of “model + scheduler + tool layer + state store”.
- Team structure changes: the boundaries between algorithm, backend, and operations dissolve, and the Harness becomes the shared interface.
3. Where the Model Ends and the Harness Begins
A common misjudgment is that “once models get stronger, the framework gets absorbed.” A more accurate statement: what the model absorbs is decision quality; what the framework carries is determinism and verifiability.
Models are good at semantic judgment and solution generation in open-ended space, but they are naturally bad at guaranteeing idempotency, bad at exact bookkeeping, and bad at restoring state after a crash. So any step that must “succeed exactly once” belongs in the framework layer. A practical split:
| Concern | Owner | Reason |
|---|---|---|
| Task understanding, solution selection | Model | Needs open-ended semantic generalization |
| Tool permissions and quotas | Harness | Needs determinism and auditability |
| Context trimming and summarization | Harness | Needs a controlled token budget |
| Retry, idempotency, rollback | Harness | Needs a strict state machine |
| Result validation and scoring | Harness + Model | Rules as the floor, semantics fill the gaps |
4. Context Engineering: The Hardest Part of the Harness
The leading cause of long-horizon failures is not that the model cannot do the work, but that context gets flooded with noise. A workable approach splits context into four layers, each with its own budget:
- System layer: role, boundaries, prohibitions. Keep it short and stable so it can be cached and reused.
- Task layer: goal, acceptance criteria, current progress. Rewritten as state changes.
- Evidence layer: tool returns, retrieved snippets, log summaries. Must carry source and timestamp.
- Memory layer: cross-session preferences and prior conclusions. Deduplicate and resolve conflicts before writing.
Illustrative budget allocation and trimming logic:
BUDGET = {"system": 800, "task": 1200, "evidence": 6000, "memory": 1000}def build_context(state):parts = [("system", state.system_prompt),("task", render_task(state.goal, state.progress)),("evidence", compress(state.evidence, limit=BUDGET["evidence"])),("memory", recall(state.memory, limit=BUDGET["memory"])),]# When evidence exceeds budget, drop low-relevance, unsourced fragments firstreturn [text for _, text in parts if text]
Three engineering details matter: evidence must be traceable, otherwise you cannot locate the source of an error later; summaries should keep pointers to the original citations rather than inlining full text; memory writes need a conflict policy, for example arbitrating on both update time and confidence.
5. Tool Layer Design: Caging the Uncertainty
Tools are the agent’s only point of contact with the real world, and the most concentrated source of risk. Follow three principles: least privilege, explicit declaration, full audit.
{"name": "query_metrics","scope": "read","rate_limit": "60/min","timeout_ms": 8000,"idempotent": true,"risk": "low"}
The risk and idempotent fields determine scheduling policy: high-risk, non-idempotent operations must go through human confirmation or a second validation channel; read-only, idempotent operations can run in parallel and be retried automatically. Normalize tool returns into “structured data + error code + citable identifier” instead of pushing large blocks of unstructured text back into context.
6. Execution Kernel: State Machines, Interruption, and Recovery
Modeling agent execution as an explicit state machine is the precondition for long-horizon stability. The minimal state set can be just five: pending planning, running, waiting on external, verifying, terminated.
PLANNING -> RUNNING -> VERIFYING -> DONE| | |+-> WAITING <+ +-> RETRY(backoff, max_n)
Engineering essentials: persist every state transition so you get a replayable event log; cover external waits with timeouts and compensation jobs rather than hanging indefinitely; retries must carry an idempotency key to avoid duplicate side effects such as placing an order twice; on recovery, resume from the most recent consistent snapshot rather than restarting the task.
7. General vs. Vertical: Layering, Not Replacement
General agents provide cross-domain planning and transfer ability; vertical agents provide in-domain determinism, compliance, and cost advantages. Their more realistic shape is layered collaboration: an upper general scheduler handles decomposition and selection, while lower vertical capabilities are invoked as controlled tools or sub-processes. To decide whether to build vertical capability in-house, self-check with three questions: is there a stable domain evaluation set, can the per-task cost be absorbed by a general solution, does the cost of errors require hard-constraint backstops. If two of the three are yes, vertical investment usually pays back.
8. Multi-Agent Collaboration: Gains from Isolation, Costs from Communication
Multi-agent is not better by default. Its real benefit is context isolation and permission isolation: splitting exploration, execution, and review into separate roles, each holding a lean context, significantly reduces cross-contamination. Its costs are communication overhead, conflicting results, and harder debugging.
A rule of thumb: use multi-agent when the task splits cleanly into parallel sub-goals and sub-results can be validated mechanically; when the task is tightly coupled and needs frequent sharing of intermediate state, a single agent with a more complete Harness is usually faster and cheaper. Collaboration protocols should explicitly define message schema, termination conditions, and conflict arbitration rules to avoid mutual waiting or repeatedly overturning conclusions.
9. Evaluation, Observability, and Cost Governance
A Harness without evaluation cannot iterate. Build at least three layers of metrics:
- Task layer: end-to-end success rate, average number of steps, human takeover rate.
- Process layer: tool failure rate, context hit rate, retry rate, number of state rollbacks.
- Cost layer: tokens consumed per task, number of tool calls, end-to-end latency percentiles.
In implementation, treat each execution as a trace identified by a trace ID, collected uniformly into your logging service and monitoring/alerting system; keep the evaluation set separate from production traffic, and require any model or prompt change to pass offline regression before canarying. Effective cost governance usually comes from context compression, result caching, and routing by risk level to different model sizes.
10. Security and Compliance: Turning Red Lines into Code
An agent’s permissions are equivalent to an account that can act autonomously, so security design cannot rely on prompt constraints. A minimal executable plan: deny high-risk actions by default and route them to approval; issue tool credentials short-lived and scoped per task; redact sensitive data before it enters context; log all operations to support after-the-fact tracing; guard against prompt injection by treating retrieved text as untrusted input rather than a source of instructions. If the product targets verified-identity or strong-audit scenarios, identity, authorization, and audit chains should be first-class citizens of the Harness, not patches added later.
11. Adoption Roadmap
- Phase 1 (1–2 weeks): close the loop on a single agent, fix the tool schema, persist event logs, and build an offline evaluation set of 30–50 cases.
- Phase 2 (3–4 weeks): add the state machine and recovery mechanism, context budgets and compression, and risk-tiered permission policies.
- Phase 3 (ongoing): introduce multi-agent and vertical capabilities, complete the cost dashboard and canary release, and establish an “evaluation-driven change” iteration rhythm.
12. Conclusion
Debate about the runtime layer eventually converges on engineering metrics: success rate, stability, observability, and unit cost. The model sets the ceiling on capability; the Harness determines whether that ceiling can be reproduced reliably. For developers, the most worthwhile first investment is not a more complex collaboration topology but four foundations: context budgets, tool contracts, recoverable state, and an evaluation loop. They determine whether every later optimization holds up. If you already have general infrastructure such as a cloud container platform, object storage, a message queue, and logging and monitoring, use it as the state store and observability base, and concentrate your effort on scheduling and evaluation, where real differentiation comes from.
