Engineering notes
Harness Engineering: Building Reliable AI Agents
How tools, state, verification, and bounded workflows turn model output into work you can trust—with interactive examples and practical templates.
Updated
An AI agent can produce a convincing explanation of a feature without actually finishing it. The files may exist, yet the route is broken. A test may pass, yet the real user flow still fails. The gap is often in the system around the model: what it can inspect, how it takes actions, and what evidence counts as completion.
That surrounding system is the harness. It connects a model to tools, working context, execution rules, and feedback. Harness engineering means designing those connections so that progress is observable and mistakes are recoverable.
This guide follows a coding task from the first request to a verified handoff. The same ideas apply to research assistants and other tool-using workflows, although their verification steps will differ.
A useful completion report tells you what changed, how it was checked, and what remains unresolved. Confident wording is not evidence.
1. Understand the model–runtime boundary
The model generates messages and may request tool calls. The runtime decides whether those calls are allowed, executes them, and returns results. Writing a shell command in a response does not execute it. Returning valid JSON does not prove that its contents are correct.
| Layer | Responsibility | Example |
|---|---|---|
| Model | Propose an action or answer | Request a file read |
| Tool interface | Define the operation and input shape | Read one repository file |
| Runtime | Validate and execute the request | Enforce the workspace boundary |
| Verification | Check the resulting behavior | Open the route and test the interaction |
| State | Preserve decisions and evidence | Record a passing check and the next task |
Keeping these responsibilities separate makes failures easier to diagnose. If a file was never written, inspect the tool result. If the file exists but the feature fails, inspect the implementation and its integration.
What a tool call actually does
Consider an assistant that needs to inspect a configuration file. A simplified request might look like this:
The application validates the tool name and arguments, resolves the path within the permitted workspace, and returns the file contents or an explicit error. The next model turn can then use that result.
Tool-Call Flow
Watch the loop. The brain only writes JSON. The harness only does the work.
"I need to create a file called app.js with the Express server."
Step 1 of 6 · Brain is thinking
This interactive flow is a teaching model. Real providers use their own message and tool-call formats, but the important boundary stays the same: a requested action and an executed action are different events.
A sandbox is an execution boundary
A sandbox limits access to resources such as files, processes, and network destinations. Its protection depends on its configuration. A workspace restriction, for example, does not automatically restrict an external database whose credentials were passed to a tool.
Give each tool the narrowest useful capability. Prefer a repository file reader over an unrestricted shell when the task only needs a file. Keep secrets out of tool output and use explicit approval for consequential external actions.
2. Design five connected parts
I find it useful to reason about a harness through five parts: instructions, state, verification, scope, and session lifecycle. This is a practical organizing framework rather than a universal standard.
The 5 Subsystems of a Harness
Hover any subsystem to see what it owns. Every harness needs all five.
What to do, in what order, and what to read first.
AGENTS.md / CLAUDE.md / feature_list / docs/What has been done, what’s next, what’s blocked.
progress.md / feature_list / git log / session handoffOnly a passing test suite counts as evidence.
tests + lint + typecheck + smoke runs + e2eConstrain the agent to one feature. No overreach.
one feature at a time / explicit definition of doneInit at start. Clean state at end. Handoff for next session.
init.sh / clean-state checklist / handoff noteEach part answers a different question. Instructions explain the task. State records where the work stands. Verification determines whether it works. Scope limits how much is attempted. Session handling makes the work resumable.
Instructions: make the next action clear
Start with the goal, relevant repository conventions, and a concrete completion condition. Load detailed guidance when the task reaches the part of the system that needs it. A long instruction file can become difficult to maintain and can crowd out more useful context.
For example, this instruction gives an agent a behavior to verify:
The expected behavior is specific enough for a reviewer to assess. It also leaves room for the agent to choose a suitable implementation instead of dictating unrelated details.
For more on selecting and maintaining useful context, see Anthropic’s context engineering discussion.
State: record facts that survive a new session
Conversation history is useful, but it should not be the only place where a long task’s decisions live. Keep a small progress record with the current objective, completed work, verification evidence, and next action.
For a feature tracker, a record can be as simple as:
Update the status from evidence. A feature should not become passing because the model predicts that its patch is correct.
Feature State Machine
The agent can only move between states via the allowed transitions. Try clicking the buttons.
Agent hasn't touched this yet. Up for grabs.
Anthropic’s long-running agent example uses an initialization phase, incremental work, and persistent artifacts to bridge sessions. It is one implementation pattern; it does not establish that every project needs multiple agents.
Verification: test the behavior at the right layer
A useful check should detect a failure that matters to the task. A compiler can catch a type mismatch, while a browser test can catch a button hidden behind an overlay. Neither replaces the other.
3-Layer Termination Check
Run each layer in order. The agent is not done until all three are green.
Static Analysis
$ pnpm lint && pnpm typecheck- ESLint passes
- TypeScript compiles
- No unused imports
Execution / Unit Tests
$ pnpm test- All unit tests green
- No regressions
- Coverage on new code
End-to-End Flow
$ pnpm test:e2e- User flow works
- DB round-trips succeed
- Real HTTP response 200
| Check | What it can establish | What it can miss |
|---|---|---|
| Static checks | Syntax, types, selected code rules | Whether a user can finish the flow |
| Focused tests | Behavior under controlled inputs | Real configuration and wiring errors |
| Integration or browser checks | Connected behavior in an actual environment | Cases the flow did not exercise |
Choose checks according to the change. A copy edit does not need a large test suite. An authentication change needs more evidence than a successful build.
When a check fails, return a compact diagnostic: the command, failure, relevant location, and reproduction steps. Avoid attaching a guessed fix as if it were established fact.
This gives the next turn something observable to investigate.
Scope: complete a useful slice
A task such as “finish the dashboard” leaves too many decisions open. A smaller slice—“show a recoverable empty state when the reports request fails”—has a clear trigger and outcome.
Work on one slice, verify it, then choose the next. Parallel work can help when changes are independent, but it also introduces coordination and integration costs. Add it when those costs are justified by the task.
Scope also belongs in the runtime. Bound model turns, tool calls, elapsed time, and output size. A retry should have a reason, a limit, and a stopping condition.
Session lifecycle: leave a usable handoff
A new session should be able to answer three questions quickly: what is the goal, what is already true, and what should happen next?
A handoff is a compact record of the work, not a transcript of every command. Record a limitation when it matters to the next person.
5 Conditions of a Clean State
The session is allowed to end only when every box is checked.
3. Make the execution loop bounded
An agent loop needs more than a request to “keep trying.” It needs an explicit budget and a way to reject invalid actions. The following TypeScript example illustrates bounded tool execution. It is a control-flow sketch, not a provider adapter or a sandbox.
The runtime still needs to create the deadline, validate each tool’s schema, and enforce resource access. An AbortSignal only cancels underlying work when the implementation honors it. For a process tool, for example, cancellation must terminate the process rather than merely stop awaiting its result.
When the budget runs out, save the evidence and return a useful partial result. Starting the same loop again without changing its inputs usually adds cost rather than progress.
4. Manage context deliberately
The context window is working space. Large logs, duplicated files, and irrelevant tool output make it harder to find the information that determines the next action.
Keep the full artifact available, but pass a concise result back to the model: what ran, what changed, whether it passed, and where to read the details. Summaries should preserve failures and uncertainty rather than flatten them into “everything looks good.”
Before a handoff, save decisions that would be expensive to rediscover. Do not store private user information merely because a persistent memory mechanism exists.
5. Adapt the workflow to local models
Local inference changes latency, memory limits, and model capability. It does not remove the need for clear tools and verification. Smaller tasks, concise tool results, and explicit state transitions can make the workflow easier to follow and inspect.
Ralph Loop — Relay Race Simulator
Click Next Runner to send a fresh, single-task session into the repo. Each one is killed after it finishes — no fatigue, no context rot.
Each runner owns ONE micro-task. No cross-contamination. No context rot. (Runner 1 of 5)
Treat this relay simulation as a metaphor for incremental work and handoffs. It is not a performance comparison between models or orchestration frameworks.
For structured output, use a supported schema mechanism where available, then validate the result in the application. Do not extract an arbitrary substring between braces and assume it is valid. Braces can appear inside strings, and syntactically valid JSON can still contain invalid actions.
If validation fails, return the specific schema error and allow a limited correction attempt. Repeated failures should end the run with a clear explanation.
6. Start with a small repository contract
A short repository guide can describe the environment without trying to encode every possible decision:
Enforce critical boundaries in tools and runtime policy. An instruction file is helpful guidance, but it cannot substitute for operating-system permissions, schema validation, or an execution budget.
7. Measure whether the harness helps
Choose a repeatable set of tasks and compare outcomes under the same conditions. Record completion against observable acceptance criteria, time to a useful result, tool failures, and interventions needed to recover.
Inspect unsuccessful runs as carefully as successful ones. Did retrieval miss a file? Did a command fail? Did the model misunderstand the task? Did the verification exercise the wrong behavior? Each answer points to a different change.
Avoid attributing every failure to the harness or every improvement to the model. Both matter, and results from one benchmark do not automatically transfer to a different repository or task.
What I would build first
Start with a single bounded loop, a small set of tools, a durable progress record, and a verification step that exercises the intended behavior. Add routing, delegation, and more elaborate memory only when a concrete failure calls for them.
The aim is a workflow that can explain its progress and recover from mistakes. A useful harness makes it easier to see why the agent succeeded—and easier to fix the system when it did not.