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.

Mohd ShubairJune 7, 202611 min read

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.

LayerResponsibilityExample
ModelPropose an action or answerRequest a file read
Tool interfaceDefine the operation and input shapeRead one repository file
RuntimeValidate and execute the requestEnforce the workspace boundary
VerificationCheck the resulting behaviorOpen the route and test the interaction
StatePreserve decisions and evidenceRecord 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:

json
{
"tool": "read_file",
"arguments": {
"path": "package.json"
}
}

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.

AI Brain
Narrator — text generator

"I need to create a file called app.js with the Express server."

json
{
"tool": "create_file",
"arguments": {
"path": "src/app.js",
"content": "..."
}
}
Harness
Executor — real side effects

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.

MODELdecides *what*to writeInstructionsStateVerificationScopeSession Lifecycle
Instructions

What to do, in what order, and what to read first.

AGENTS.md / CLAUDE.md / feature_list / docs/
State

What has been done, what’s next, what’s blocked.

progress.md / feature_list / git log / session handoff
Verification

Only a passing test suite counts as evidence.

tests + lint + typecheck + smoke runs + e2e
Scope

Constrain the agent to one feature. No overreach.

one feature at a time / explicit definition of done
Session Lifecycle

Init at start. Clean state at end. Handoff for next session.

init.sh / clean-state checklist / handoff note

Each 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:

markdown
## Task
Add a retry action to the failed-upload state.
## Expected behavior
- Preserve the selected file after a network failure.
- Show the failure beside the upload control.
- Allow retry without selecting the file again.
## Verification
Simulate a failed request, retry it, and confirm that the file uploads once.

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:

json
{
"id": "upload-retry",
"status": "active",
"expectedBehavior": "Retry the retained file after a failed upload",
"checks": [],
"nextAction": "Test the failed-request path in the browser"
}

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.

status = "not_started"

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.

L1
Static Analysis
$ pnpm lint && pnpm typecheck
  • ESLint passes
  • TypeScript compiles
  • No unused imports
L2
Execution / Unit Tests
$ pnpm test
  • All unit tests green
  • No regressions
  • Coverage on new code
L3
End-to-End Flow
$ pnpm test:e2e
  • User flow works
  • DB round-trips succeed
  • Real HTTP response 200
Click Run on the highlighted layer to begin.
CheckWhat it can establishWhat it can miss
Static checksSyntax, types, selected code rulesWhether a user can finish the flow
Focused testsBehavior under controlled inputsReal configuration and wiring errors
Integration or browser checksConnected behavior in an actual environmentCases 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.

json
{
"check": "upload retry flow",
"result": "failed",
"observed": "The retry request has no file body",
"reproduce": [
"Select a file",
"Make the first request fail",
"Click Retry"
]
}

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?

markdown
# Progress
## Goal
Make failed uploads recoverable without losing the selected file.
## Completed
- Added an error state and Retry control.
- Preserved the File object between attempts.
## Evidence
- Type check passed.
- Browser check: failed request followed by a successful retry.
## Next
Review the upload state when navigating away during a request.
## Open questions
- Should navigation cancel an in-flight upload?

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.

typescript
type ToolCall = { name: string; input: unknown };
type Tool = (input: unknown, signal: AbortSignal) => Promise<unknown>;
export async function executeBatch(
calls: ToolCall[],
tools: Record<string, Tool>,
signal: AbortSignal,
maxCalls = 6,
) {
if (calls.length > maxCalls) throw new Error("Tool-call budget exceeded");
const results: unknown[] = [];
for (const call of calls) {
signal.throwIfAborted();
if (!Object.hasOwn(tools, call.name)) {
throw new Error(`Unknown tool: ${call.name}`);
}
// Each tool validates its input and honors the signal.
results.push(await tools[call.name](call.input, signal));
}
return results;
}

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.”

text
Check: upload retry browser flow
Result: failed
Observed: second request contains no file body
Evidence: artifacts/upload-retry-trace.zip
Next: inspect how the request body is rebuilt on retry

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.

1
2
3
4
5
Session #1
Fresh context
Running
session-1.log
$ harness.load --fresh
→ read progress.md, feature_list.json, repo state
$ harness.run --task="Build the TodoList component that renders an array of items from props."
→ working...
✅ Tests pass. Session killed. Fresh session starts.
session.kill()

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:

markdown
# Repository guide
## Environment
- Use the package manager and lockfile already in the repository.
- Read the relevant module before changing its public interface.
## Work
- Define the user-visible outcome before editing.
- Keep unrelated changes out of the task.
- Follow the existing component and styling conventions.
## Finish
- Run checks appropriate to the behavior that changed.
- Report what passed, what failed, and what was not checked.
- Leave a short handoff if work remains.

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.

Further reading

Share this article

Found it useful? Sharing helps others discover it too.

Code blocks and navigation by Rare UI.