The model is the engine. The harness is the car.
One guide from "what is a harness" to running harnesses for a million agent runs a day. Guides and sensors, the control loop, context and state, sandboxes, permissions and hooks, long-running patterns, entropy, platforms, a full build, evaluation, security, system design, cost, every failure you'll hit, the trade-offs, and when a harness is the wrong fix.
Pick where you are starting
Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.
What harness engineering actually is
An agent is a model plus a harness. The harness is everything except the model: the loop, tools, instructions, context handling, sandbox, permissions, checks and logs. Harness engineering is designing that surrounding system so a model does reliable work, and turning every mistake the agent makes into a permanent fix in the harness rather than a one-off correction.
Put the same model in two different harnesses and you get two different products. In February 2026 LangChain kept its model fixed (gpt-5.2-codex) and changed only the harness around its coding agent. Its score on Terminal-Bench 2.0, a benchmark of 89 hard command-line tasks, went from 52.8% to 66.5%. That moved it from outside the top 30 to the top 5 on the leaderboard. No new model, no fine-tuning. Just better prompts, checks, middleware and verification.
The same month, OpenAI described a five-month internal project in which a small team (three engineers at the start, seven later) shipped a product of about a million lines of code with no hand-written code. Codex agents wrote the application, tests, CI, docs and tooling. Roughly 1,500 pull requests were merged, about 3.5 per engineer per day. The engineers' job changed: they designed the environment, wrote down intent, and built feedback loops. The post's slogan was "Humans steer. Agents execute."
Neither result came from a cleverer prompt. Both came from engineering the system around the model. That is what this guide is about.
Three layers of AI engineering, each containing the last
Prompt, context and harness engineering compared
| Aspect | Prompt engineering | Context engineering | Harness engineering |
|---|---|---|---|
| Question it answers | How do I phrase this request? | What should the model see on this step? | What system makes the agent reliable over hundreds of steps and many sessions? |
| Unit of work | One prompt | One context window | A run, a session, a project, a fleet of agents |
| Main artifacts | Prompt templates, examples | Retrieval, memory, compaction, tool results | AGENTS.md, skills, hooks, linters, tests, sandboxes, permission policy, progress files, traces |
| How it fixes a mistake | Reword and hope | Give better information | Make the mistake impossible or caught automatically, forever |
| Mostly deterministic? | No | Partly | As much as possible: code, not prose, enforces the rules |
| Who does it | Anyone writing prompts | Agent and RAG builders | Agent builders and every team that uses coding agents on its codebase |
The layers overlap. Birgitta Böckeler (Thoughtworks) describes harness engineering for coding-agent users as a specific form of context engineering, because guides and sensors reach the agent through its context. This manual treats context engineering as one part of the harness (Ch 7). The companion Agents Guide covers the agent loop itself in more depth.
Two kinds of harness work
The builder's harness (inner harness)
You are building an agent product. You write the code that calls the model, runs tools, manages context, enforces budgets, checkpoints state and decides when to stop. Examples: Claude Code, Codex, Cursor, LangChain's deepagents, your support agent. Chapters 4, 7, 15 and 19 go deepest here.
The user's harness (outer harness)
You use an existing agent on your codebase or workflow. The vendor's harness is fixed, but it has configuration points: instruction files, skills, hooks, MCP tools, permission rules, sub-agents, plus your own linters, tests and CI. You build an outer harness tailored to your system. Chapters 5, 6, 9, 12 and 15 go deepest here.
Both use the same ideas: steer before the agent acts, check after it acts, keep state outside the model, and make the rules deterministic wherever you can.
The core habit: every mistake becomes a fix
Mitchell Hashimoto (creator of Terraform and Ghostty) put it simply in February 2026: whenever an agent makes a mistake, engineer a solution so it never makes that mistake again. Often that is one line in an instructions file. Sometimes it is a script, a lint rule, a test or a new tool. In his Ghostty repository, lines of the agent instructions file trace back to specific past failures.
This is the difference between using an agent and engineering a harness. A user corrects the agent in chat and moves on; the next session repeats the error. A harness engineer asks "what change to the system would have prevented this?" and commits it. Over weeks, the harness becomes a record of everything the team has learned about getting good work from agents.
A short history, so the term makes sense
- 2022–2023 · ScaffoldsReAct, AutoGPT and early tool-use loops. The code around the model was called a "scaffold" and treated as glue. Agents looped, drifted and burned money.
- 2024 · The interface mattersSWE-agent shows that an agent-computer interface (purpose-built commands, file viewers, linters on edit) lifts results on SWE-bench far more than prompt tweaks. Coding agents become the proving ground for harness ideas.
- 2025 · Coding agents everywhereClaude Code, Codex, Gemini CLI, Copilot's coding agent and Cursor's agent reach millions of developers. AGENTS.md appears in August as a shared instructions-file format. Anthropic publishes "Effective harnesses for long-running agents" in November. In December the Linux Foundation forms the Agentic AI Foundation (OpenAI contributes AGENTS.md; MCP also moves there) and Anthropic publishes Agent Skills as an open format.
- February 2026 · The name sticksHashimoto's "My AI Adoption Journey" (Feb 5) names a stage "engineer the harness". OpenAI's "Harness engineering: leveraging Codex in an agent-first world" (Feb 11) formalises it. LangChain shows the 52.8% → 66.5% harness-only jump (Feb 17). Böckeler publishes a first memo on martinfowler.com the same week. "Agent = Model + Harness" becomes the shorthand.
- March–May 2026 · The discipline formsAnthropic's planner-generator-evaluator harness (Mar 24). Stripe describes "minions" merging over a thousand agent pull requests a week. The Meta-Harness paper (Stanford and collaborators, Mar 30) has an agent search over harness code automatically. Böckeler's full "Harness engineering for coding agent users" (Apr 2). Anthropic's Managed Agents separates brain, hands and session (Apr 8). Academic papers formalise harness levels and responsibilities.
- Late 2026 · NowHarness engineering is a normal part of software teams' work, with shared formats (AGENTS.md, SKILL.md, MCP), hosted harness platforms, and a growing open question: which parts of today's harness will the next model make unnecessary? (Ch 24)
The vocabulary you need
| Term | Plain meaning | Chapter |
|---|---|---|
| Harness | Everything in an agent except the model. Some authors use it more narrowly for the execution loop only. | 1, 3 |
| Outer harness | What a user adds around a vendor's agent: instruction files, skills, hooks, linters, tests, CI. | 1, 15 |
| Guide (feedforward control) | Anything that steers the agent before it acts: instructions, docs, skills, examples, plans. | 5 |
| Sensor (feedback control) | Anything that checks after it acts and tells it what to fix: tests, linters, type checkers, reviewers. | 6 |
| Computational vs inferential | Deterministic code checks (fast, cheap, certain) vs model-based checks (semantic, slower, probabilistic). | 3, 6 |
| Backpressure | Feedback that pushes back on the agent when its work is wrong, ideally quiet on success and specific on failure. | 6 |
| Hook | Your code that the harness runs at a lifecycle event (before a tool call, after an edit, before stopping) to allow, block or add feedback. | 9 |
| Compaction / context reset | Summarising history in place / starting a fresh agent from a written handoff. | 7 |
| Session log | An append-only record of everything that happened in a run, stored outside the model and the harness process. | 7, 19 |
| Harnessability | How easy a codebase or system is to put a harness around: types, clear boundaries, fast tests, runnable locally. | 8 |
| Entropy / garbage collection | The slow drift of a codebase as agents copy patterns, and the recurring clean-up work that counters it. | 12 |
| Load-bearing component | A harness part that still improves results with today's model. Others are dead weight to remove. | 16, 24 |
Words people mix up
Harness, scaffold, framework, runtime and eval harness.
Harness vs scaffold terms
A Hugging Face glossary (May 2026) draws a fine line: the harness is the execution layer that calls the model, runs tool calls and decides when to stop; the scaffold is the behaviour-defining layer around it (system prompt, tool descriptions, parsing, context management). Products like Claude Code call the whole non-model layer the harness. The fine distinction matters mostly in training pipelines. This manual uses the broad meaning.
Harness vs agent framework terms
A framework (LangGraph, OpenAI Agents SDK, Google ADK, Claude Agent SDK) is a library for building harnesses. It gives you a loop, tool plumbing and state handling. The harness is the specific, configured system you end up with: these tools, these checks, this sandbox, this policy. Two teams on the same framework can have very different harnesses.
Development harness vs evaluation harness terms
"Test harness" and "eval harness" are older terms for the rig that runs a fixed set of scenarios and records scores (for example Harbor for Terminal-Bench, or Inspect). An eval harness measures behaviour. A development harness shapes it. You need both, and they often share parts: the same sandbox and the same checks can run during work and during evaluation (Ch 16).
Why "harness"? origin
A horse harness lets a strong animal pull a cart in a useful direction without being able to bolt. The image fits: the model brings the power; the harness directs it, limits it and connects it to the work. Software already used "test harness" for the code that drives a program under test, so the word felt natural to engineers.
How much harness you need, and when to stop adding
Match harness strength to how long the agent runs alone, how often the task repeats and how costly a mistake is. A one-off question needs none. A team using agents daily on one repo needs an instructions file, fast checks and hooks. Autonomous multi-hour work needs state files, sandboxes, verification and traces. Then remove what the current model no longer needs.
Decision tree
The harness maturity dial
Harness strength is a dial, not a switch. Each level adds to the one before. Click a level to see what it contains, what it costs and when it pays off.
These six levels are this guide's own ladder, built for practical use. An academic paper by Zhong and Zhu (May 2026) proposes a similar four-level ladder (H0–H3) based on how much runtime support the agent gets.
Signs you need more harness
Under-harnessed
- You correct the same mistake in chat every week.
- The agent says "done" and it isn't: tests not run, feature not wired up.
- Reviews keep finding style, layering or naming violations a tool could catch.
- Long tasks die halfway and the next session starts from zero.
- The agent can't run the app, see logs or reproduce the bug, so it guesses.
- Someone ran a risky command, and only luck kept it harmless.
Over-harnessed
- The instructions file is 2,000 lines and contradicts itself.
- Every edit triggers a 10-minute check, so the agent waits more than it works.
- Approval prompts appear so often people click "yes" without reading.
- A component was added for an old model and nobody tested whether it still helps.
- An evaluator agent doubles cost on tasks the model already gets right alone.
- Engineers spend more time maintaining the harness than it saves.
Is a fix worth it? The quick maths
cost of a failure ≈ human minutes to notice + minutes to fix + tokens wasted + (risk × damage)
e.g. agent forgets to run migrations 3×/week, each costs 25 min of an engineer at $90/h → ≈ $490/month. A 10-line pre-commit check that takes 30 min to write pays back in the first week.
Most harness fixes are this cheap. The expensive ones are evaluator agents, multi-agent orchestration and bespoke platforms. Measure before you build those (Ch 16, Ch 20).
Questions to ask before you build
- What does "done" look like, checked by a machine?If nothing can verify the result (tests, a script, a query, a screenshot diff), your harness has no sensors and the agent will declare victory early. Build the check first.
- What mistakes have you already seen?List the last 20 corrections you gave an agent. Each one is a candidate guide or sensor. This list is your first backlog.
- What can the agent see and run?Can it start the app, run one test, read logs, query the database, open the page? Every "no" means it is working blind (Ch 8).
- What is it never allowed to do?Write those rules as code (deny lists, hooks, sandbox limits), not as sentences in a prompt (Ch 9).
- How long does it run alone?Minutes: keep state in context. Hours: write state to files and git. Days: you need a durable session log and resumable runs (Ch 7, Ch 10).
- Who maintains the harness?A harness is code. Give it an owner, a review process and a place in the repo, or it will rot like any other unowned code (Ch 12).
Anthropic found that Claude Sonnet 4.5 wrapped up work early as its context filled ("context anxiety"), so their harness used context resets. On Claude Opus 4.5 the behaviour was gone and the resets became dead weight. Every harness component encodes an assumption about what the model can't do alone. Re-test those assumptions with each model upgrade.
Anatomy of a harness
A harness has a control loop at its centre, guides that steer the model before it acts, an environment of tools and a sandbox it acts in, sensors that check results, state kept outside the model, permissions and hooks that enforce rules, and observability so humans can steer. Two axes organise the controls: before vs after the action, and code vs model.
The parts of a harness and how they connect
The two axes of control
Böckeler's model sorts every control by when it acts (before the agent acts, or after) and how it decides (deterministic code, or a model's judgement). Good harnesses have something in all four boxes, and push work toward the computational side wherever a rule can be written as code.
| Computational (code, deterministic) | Inferential (model, probabilistic) | |
|---|---|---|
| Guides · before the action | Templates and scaffolding generators, codemods, type definitions, LSP code intelligence, a make check script the agent is told to run | AGENTS.md conventions, skills, design docs, examples, an approved plan, a spec |
| Sensors · after the action | Compilers, type checkers, linters, unit and integration tests, structural / architecture tests, mutation tests, security scanners | LLM code review, LLM-as-judge on output, a separate evaluator agent driving a browser, sampled quality checks in production |
| Speed and cost | Milliseconds to minutes; near-zero cost; same answer every time | Seconds to minutes; costs tokens; can be wrong or inconsistent |
| Use it for | Anything you can state as a rule | Judgement: design quality, intent, readability, "does this match the spec?" |
Feedback-only harnesses let agents repeat the same mistake every run, catching it each time at a cost. Feedforward-only harnesses encode rules but never check them, so the agent can ignore them silently. Pair each important guide with a sensor that verifies it.
The parts, one by one
Control loop
Calls the model, dispatches tool calls, assembles context, enforces step, time and cost budgets, detects loops, retries, and decides when the run ends. Ch 4
Guides
Instructions, docs, skills, examples and plans that raise the odds of a good first attempt. Loaded progressively, not all at once. Ch 5
Sensors
Checks that run after actions and return messages written for the model: what failed, where, and how to fix it. Ch 6
Context and state
What the model sees each step, plus durable state outside it: session log, progress notes, task lists, git. Ch 7
Environment
Tools, MCP servers, a sandbox, a worktree, the running app, logs, a browser. What the agent can see and do. Ch 8
Permissions and hooks
Allow and deny rules, approval prompts, lifecycle hooks and policy code that enforce limits no matter what the model says. Ch 9
Orchestration
Sub-agents, parallel workers, planner and evaluator roles, deterministic workflow nodes. Ch 11
Entropy control
Recurring clean-up agents, doc gardening and drift sensors that stop the codebase degrading as agents copy patterns. Ch 12
Observability
Traces of every step with harness version, cost and failure cause, so humans know what to change next. Ch 18
Eleven responsibilities a harness must cover
Zhong and Zhu's "AI Harness Engineering" paper (May 2026) lists eleven responsibilities. They make a useful audit: for each one, name the file, tool or code in your harness that handles it. A blank means a gap.
| # | Responsibility | Question it answers | Typical artifact |
|---|---|---|---|
| 1 | Task specification | What exactly must be done, and what counts as done? | Issue template, spec, feature list JSON, acceptance criteria |
| 2 | Context selection | What does the model need to see now? | AGENTS.md map, retrieval, skills, compaction |
| 3 | Tool access | What can it do, through which interface? | Tool set, MCP servers, CLI wrappers |
| 4 | Project memory | What has the team learned that persists? | Docs, decision records, instructions file history |
| 5 | Task state | Where is this run up to? | Progress file, plan with checkboxes, session log |
| 6 | Observability | What is the system doing right now? | Logs, metrics, traces available to the agent and humans |
| 7 | Failure attribution | When it fails, which part caused it? | Trace tags, error taxonomy, failure reports |
| 8 | Verification | Is the result actually correct? | Tests, linters, e2e checks, evaluator |
| 9 | Permissions | What is it allowed to touch? | Allow/deny rules, sandbox, scoped credentials |
| 10 | Entropy auditing | Is the codebase drifting? | Drift scans, clean-up agents, quality dashboards |
| 11 | Intervention recording | When did a human step in, and why? | Approval logs, correction log feeding harness backlog |
Brain, hands and session
Anthropic's Managed Agents design (April 2026) splits a harness into three parts that can fail and scale independently. The brain is the stateless harness loop that calls the model. The hands are sandboxes and tools, reached through one interface (execute(name, input) → string). The session is an append-only event log kept outside both. A crashed harness restarts from the log; a broken sandbox is replaced, not repaired. Their first design put all three in one container, which became a "pet" that had to be nursed back to health. Splitting them cut median time-to-first-token by about 60% and p95 by over 90%, because sandboxes are now started only when needed. Ch 19 builds a full platform on this idea.
Where the boundaries sit
Inner vs outer harness, and what you can change.
What a vendor's built-in harness already does coding agents
Coding agents such as Claude Code, Codex, Gemini CLI and Copilot ship a harness: a system prompt, file search and edit tools, a shell tool, context compaction, sub-agents, permission prompts, and usually a sandbox. You can't edit their loop, but each exposes configuration points. Treat the vendor harness as a platform and your outer harness as the application you build on it.
Configuration points you usually control outer harness
- Instruction files: AGENTS.md, CLAUDE.md, GEMINI.md, copilot-instructions.md, nested per folder.
- Skills: SKILL.md folders loaded on demand.
- Tools: MCP servers, custom CLIs and scripts the agent can call.
- Hooks: scripts on lifecycle events (before a tool call, after an edit, on stop).
- Permissions: allow/deny lists, sandbox mode, network rules.
- Sub-agents: named specialist agents with their own prompts and tools.
- Your repo: linters, tests, type checks, CI, scripts, docs. The biggest lever of all.
The "ambient" harness humans carry people
Experienced developers carry an invisible harness: conventions they absorbed, pain they feel from complexity, accountability for what they commit, and knowledge of what the organisation tolerates. Agents have none of this. A harness tries to write part of it down. It never captures all of it, which is why the human's role shifts to steering and to the judgement calls that no sensor can make.
The control loop: budgets, gates and stop rules
The heart of every harness is a loop: assemble context → call the model → check the proposed action → run it → sense the result → record it → repeat. The model decides what to do. The loop decides whether it may, how much it may spend, and whether it is really done. Most reliability gains come from the checks at the edges of each step, not from the model call in the middle.
A bare agent loop is 20 lines: call the model, run the tool it asks for, append the result, repeat until it stops asking for tools. A harness loop adds interception points around each step. Before a tool runs, policy and hooks can block or change it. After it runs, sensors can add feedback. Before the agent is allowed to stop, a completion gate can send it back to verify. Around the whole run, budgets cap steps, time and money.
def run(task, harness, budget):
session = harness.sessions.open(task) # append-only log, outside this process
harness.hooks.fire("session_start", session) # load map, run init.sh, map the workspace
while True:
if budget.exceeded(session): # steps, wall-clock, tokens, dollars
return harness.stop_with_handoff(session) # never fail silently
ctx = harness.context.assemble(session) # guides + recent events, compact if needed
reply = harness.model.call(ctx, effort=harness.effort_for(session))
session.append(reply)
if reply.wants_to_stop:
gate = harness.hooks.fire("before_stop", session) # checklist: tests run? spec met?
if gate.allow: return harness.finish(session)
session.append(gate.feedback); continue # back to work with the reason
for call in reply.tool_calls:
verdict = harness.policy.check(call, session) # allow / deny / ask a human
verdict = harness.hooks.fire("before_tool", call, verdict)
if verdict.deny: session.append(verdict.as_tool_error()); continue
result = harness.env.execute(call) # in the sandbox, with timeouts
result = harness.hooks.fire("after_tool", call, result) # lint, typecheck, format
session.append(result)
harness.loop_detector.inspect(session) # repeated edits or calls → nudgeLive demo · watch a harness run
Pick a task and step through it. Model steps are plain; hook steps are the harness stepping in. Watch what gets blocked, what gets fed back, and how the completion gate stops a premature "done".
Stop conditions: the most underrated part of a harness
An agent that stops too early ships broken work. One that never stops burns money. Anthropic and LangChain both report the same top failure on coding tasks: the agent re-reads its own code, decides it looks fine, and stops without running anything. Make stopping something the harness grants, not something the model simply announces.
| Condition | Type | What the harness does |
|---|---|---|
| Model says done | Request, not final | Run the completion gate: required checks passed? spec items ticked? diff non-empty? If not, return the reason and continue. |
| Step budget hit | Hard | Stop, write a handoff note (what's done, what's left, what was tried), save state. |
| Time budget hit | Hard, with warning | Warn at 70–80% ("you have 10 minutes: finish and verify"); stop at 100%. |
| Cost budget hit | Hard | Same as steps. Per-run and per-tenant limits. |
| Loop detected | Soft | Inject a nudge: "You've edited dates.py 6 times. Step back and reconsider." Escalate to stop after N nudges. |
| No progress | Soft | No new files, no new passing checks for K steps → nudge, then hand off. |
| Blocked by policy repeatedly | Hard | Stop and ask a human: the task probably needs a permission it shouldn't have alone. |
| Needs information | Agent-initiated | An ask_human tool pauses the run durably and resumes on reply. |
Spend thinking where it matters: the reasoning sandwich
Reasoning models let you set an effort level per call. LangChain's Terminal-Bench work found that running everything at maximum effort scored worse (53.9%) than high effort (63.6%), because runs timed out. Their best setup used a sandwich: extra-high effort to plan, high effort to implement, extra-high again to verify. The general lesson: the harness should choose effort by phase, not leave one setting for the whole run.
High effort
Understand the task, explore, decide an approach. Mistakes here cascade, so thinking is cheap insurance.
Medium–high effort
Routine edits and tool calls. Lower effort keeps steps fast; sensors catch slips.
High effort
Re-read the spec, run checks, compare against intent. This is where "looks fine" becomes "is fine".
- anthropic · openai · google-genaiTool-use loops, effort / thinking settings, usage counters for budgets.
- claude-agent-sdkThe Claude Code harness as a library: hooks, sub-agents, compaction, permissions.
- deepagents · langgraphMiddleware-based harness with planning, files, sub-agents; durable graphs.
- tenacityRetries with backoff for transport errors.
from collections import Counter
edits, last_pass_step = Counter(), 0
def after_tool(call, result, step):
global last_pass_step
if call.name == "write_file":
edits[call.input["path"]] += 1
n = edits[call.input["path"]]
if n >= 6 and step - last_pass_step > 6:
return result + f"\n[harness] {n} edits to this file without a passing check. Reconsider the approach."
if call.name == "run" and "check" in call.input["cmd"] and result.startswith("\u2713"):
last_pass_step = step
return result- Azure AI Foundry Agent ServiceHosted agent runs with threads and tool calls; set run limits in your orchestration.
- Microsoft Agent FrameworkAgents and workflows with middleware and checkpointing.
- Durable FunctionsDurable loops with timers for time budgets.
- Bedrock AgentCore RuntimeLong-running agent sessions with isolation per session.
- Strands AgentsModel-driven loop with hooks and tool callbacks.
- Step FunctionsDurable outer loop, timeouts and retries.
- Agent Development Kit (ADK)LlmAgent loops, callbacks before and after model and tool calls.
- Vertex AI Agent EngineManaged runtime and sessions for ADK and other frameworks.
- WorkflowsDurable orchestration with timeouts.
- OpenHands · Goose · AiderFull-source coding agents: change the loop itself.
- smolagents · PydanticAI · MastraSmall loops you can read in an afternoon.
- TemporalDurable execution for long agent runs.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Inside the loop
Middleware, budgets, retries and the details that make loops converge.
Middleware: the cleanest way to add harness behaviour design
Treat each harness behaviour as middleware that wraps the model call or the tool call, like web-server middleware. LangChain's deepagents uses this shape: LocalContextMiddleware maps the workspace at start, LoopDetectionMiddleware counts edits per file, PreCompletionChecklistMiddleware intercepts the exit. Each one is small, testable on its own, and easy to remove when a new model no longer needs it (Ch 16).
Loop detection that doesn't fire on healthy work failure
- Count identical tool calls (same name and arguments): 3 in a window is a strong signal.
- Count edits per file: 5–8 edits to one file without a passing check is a "doom loop".
- Track a progress signal: newly passing tests, new files touched, new information found. No change in K steps is stalling.
- Nudge first, stop second. A nudge that says what you saw ("same test failing for 6 attempts with the same error") works better than a generic "try something else".
Time budgets the model can see latency
Models don't feel time passing. Tell them. Inject the remaining budget into context at intervals ("18 of 30 minutes used"), and a firm warning near the end. On benchmarks with timeouts this alone recovers many runs that would otherwise be cut off mid-edit with nothing verified.
Retries: model errors vs tool errors reliability
Retry transport errors (rate limits, 5xx, timeouts) in the harness with exponential backoff and jitter, invisibly to the model. Return tool errors (bad arguments, failing command) to the model as results, written so it can act on them. Never retry a non-idempotent write automatically without an idempotency key.
Parallel tool calls and their limits latency
Let the model request several independent reads at once and run them concurrently. Cap concurrency per run (for example 4–8) so one run can't flood a shared service, and keep result order stable so the context (and the prompt cache) stays predictable.
Guides: steering before the agent acts
Guides raise the odds of a good first attempt. The best guide system is a short map (an AGENTS.md of roughly 100 lines) that points to deeper docs, skills and specs the agent loads only when relevant. Write commands and facts, not virtues. Every line should earn its tokens, and the important ones should be backed by a sensor.
Teams that start with coding agents usually write one giant instructions file: every convention, every warning, every past incident. It grows to thousands of lines, contradicts itself, and costs tokens on every call. OpenAI's harness team took the opposite approach. Their AGENTS.md is a short table of contents. The real knowledge lives in a structured docs/ folder (design docs, architecture, execution plans, product specs, references), cross-linked and checked by CI so it stays current. The agent reads the map, then pulls in what the task needs.
This is progressive disclosure: show a little up front, reveal detail on demand. It is the same idea behind Agent Skills, where only each skill's name and one-line description are loaded at start, and the full SKILL.md is read when a task matches.
Progressive disclosure: what loads when
What belongs in the root instructions file
Put in
- Exact commands: how to install, build, run one test, run all checks, start the app.
make checkbeats "make sure tests pass". - A map: one line per top-level folder and where the docs for each live.
- Hard rules that are non-obvious: "never edit
generated/", "migrations go throughscripts/new_migration". - Definition of done: which checks must pass before stopping.
- Pointers to skills and docs, with when to read each.
- Lessons from real failures, each one line, ideally with the reason.
Leave out
- Generic virtues: "write clean code", "be careful", "follow best practices".
- Anything a linter or formatter enforces. Let the tool say it.
- Long explanations of architecture. Link to a doc instead.
- Rules for one folder. Put them in that folder's AGENTS.md.
- Secrets, tokens, internal URLs that shouldn't leave the repo.
- Stale rules for code that no longer exists.
# AGENTS.md (keep under ~120 lines; details live in docs/)
## Commands
- Setup: `./scripts/setup` - Run app: `./scripts/dev` (http://localhost:3000)
- One test: `pytest tests/path::name -q` - All checks: `make check` (lint, types, tests)
- New migration: `./scripts/new_migration "name"` (never hand-write SQL files)
## Map
- `api/` HTTP layer → docs/architecture/api.md
- `core/` domain logic, no I/O → docs/architecture/layers.md
- `infra/` DB, queues, external APIs
- `web/` React front end → web/AGENTS.md
## Rules (each one exists because of a past failure)
- Layers import downward only: api → core → infra. `make check` enforces it.
- Money is `Decimal`, never float. Dates are UTC `datetime` with tzinfo.
- Do not edit `generated/` or `*.lock` by hand.
## Done means
- `make check` passes, new behaviour has a test, docs/ updated if behaviour changed.
- For UI changes: open the page with the browser tool and check it renders.
## Read when relevant
- Payments work → skill `payments` - Performance work → docs/perf.md
- Current plan for multi-step work → docs/exec-plans/active/Live demo · lint your instructions file
Paste your AGENTS.md, CLAUDE.md or copilot-instructions.md. The checker runs in your browser and nothing is sent anywhere. It scores the file against the habits in this chapter.
The other guides
| Guide | What it is | Best for | Watch out for |
|---|---|---|---|
| Skills (SKILL.md) | A folder with instructions, scripts and references, loaded when its description matches the task. An open format adopted by most major coding agents. | Repeatable procedures: "add an endpoint", "write a migration", "release" | Vague descriptions mean the skill never loads; overlapping skills confuse selection |
| Folder AGENTS.md | Nested files that apply when the agent works in that folder | Monorepos; different languages or rules per area | Conflicts between levels; say which wins |
| Specs and feature lists | What to build and how to verify each item, ideally machine-readable | Long runs; preventing "declared done too early" | Vague acceptance criteria give sensors nothing to check |
| Execution plans | A checked-in plan with steps, decisions and progress | Multi-session work; handoffs between agents and people | Plans go stale; make updating them part of done |
| Examples and templates | A reference implementation the agent copies | Consistency: "new services look like services/billing" | Agents copy bad examples just as faithfully |
| Generators and codemods | Scripts that create correct scaffolding or apply mechanical changes | Anything with lots of boilerplate; large refactors | Need maintenance like any code |
| Code intelligence (LSP) | Go-to-definition, find-references, type info as tools | Large codebases; safe renames | Setup per language; slow on huge repos |
| Tool descriptions | The "use this when…" text on each tool | Getting the right tool chosen | Every description costs tokens on every call |
Writing guides that work
Tokens, instruction limits, conflicts and maintenance.
What instructions cost, every single call tokens
e.g. 6,000-token AGENTS.md × 60 calls = 360,000 input tokens per run. With prompt caching at ~0.1× price that is like 36,000 uncached tokens, but it still fills the window and dilutes attention.
Prompt caching makes a stable prefix cheap, not free. Long always-on guides also compete with the task for the model's attention. Keep tier 1 small and stable (changing it breaks the cache).
Models follow fewer rules than you write limits
Instruction-following degrades as the number of simultaneous rules grows; research on many-instruction prompts shows accuracy falling steadily as counts rise into the hundreds, with frontier models doing better but none perfect. Practical rule: if a rule really matters, enforce it with a sensor and keep the prose version short. Prose rules are suggestions; code rules are guarantees.
Contradictions and precedence conflicts
As files nest (vendor prompt → user file → root AGENTS.md → folder AGENTS.md → skill), rules collide. State precedence once ("folder files override the root for that folder"). Run a periodic check, by script or by an agent, that looks for contradictory rules and for rules referencing files that no longer exist (Ch 12).
One source of truth across tools portability
Different agents read different filenames (AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md). AGENTS.md is the shared open format, stewarded by the Agentic AI Foundation and reported in over 60,000 projects by late 2025. Keep one real file and make the others point to it, or symlink them, so guidance doesn't fork. Check each tool's docs for which filenames it reads today.
Let agents draft guides, humans approve them workflow
After a correction, ask the agent: "what one line in AGENTS.md, or what check, would have prevented this?" It writes the draft; a human approves the diff. This keeps the cost of capturing a lesson near zero, which is what makes "every mistake becomes a fix" sustainable.
Sensors: feedback the agent can use
Sensors turn "looks fine" into "is fine". Put fast deterministic checks (types, lint, unit tests, structural tests) inside the loop on every change, slower ones at commit and CI, and model-based judges only where rules can't reach. Write the output for the model: silent on success, short and specific on failure, with the fix.
A sensor is anything that observes the agent's work and reports back. Compilers, tests and linters are sensors humans have used for decades. What changes with agents is who reads the output. A human skims a 400-line test log and spots the one line that matters. A model reads every token, pays for it, and can be distracted by it. Böckeler calls well-written sensor output a "positive kind of prompt injection": a lint message that says exactly what is wrong and how to fix it steers the agent better than any instruction file.
OpenAI's harness team enforced a strict layered architecture (types → config → repo → service → runtime → UI) with custom linters and structural tests. The lint messages included remediation instructions, so when an agent broke a rule, the failure itself told it what to do. Rules that would be "nice to have" for humans became cheap to enforce, because the agent does the fixing.
Write sensor output for the model
Human-shaped output
===== 412 passed, 1 failed in 38.2s =====
FAILED tests/test_invoice.py::test_due_date
... 180 lines of traceback ...
AssertionError: assert datetime(2026, 3, 1, 0, 0)
== datetime(2026, 3, 1, 0, 0, tzinfo=UTC)
(+ 400 lines of passing test names)Most tokens describe success. The useful line is buried. Costs ~6k tokens per run.
Model-shaped output
checks: lint ✓ types ✓ tests ✗ (412/413)
FAIL tests/test_invoice.py::test_due_date
expected tz-aware UTC datetime, got naive
at core/invoice.py:88 due = datetime(y, m, d)
fix: use datetime(y, m, d, tzinfo=UTC)
rule: docs/conventions.md#datesSilent on what passed, precise on what failed, includes the fix and the rule. ~80 tokens.
HumanLayer's term for this pattern: wrap noisy commands so success prints one line and failure prints only the relevant part. A 20-line wrapper script around your test runner can cut thousands of tokens per run and makes the agent's next move obvious.
When each sensor runs: keep quality left
| Stage | Sensors | Latency budget | Who acts on it |
|---|---|---|---|
| After every edit (in the loop) | Formatter, type check on changed files, fast lint, the one relevant test | < 5–10 s | The agent, immediately |
| Before stopping (completion gate) | Full fast suite, structural tests, spec checklist, e2e smoke via browser | < 2–5 min | The agent, before it may finish |
| Pre-commit / pre-push | Same checks, enforced by git hooks so nothing skips them | < 5 min | The agent or human committing |
| CI after integration | Full tests, mutation testing, security scans, broader architecture checks, LLM review | 10–60 min | Agent fix-up runs, human reviewers |
| Continuous, outside changes | Dead code, dependency drift, doc staleness, test-quality analysis | Daily / weekly | Clean-up agents (Ch 12) |
| Runtime | SLO monitors, error rates, sampled LLM judges on outputs, log anomalies | Continuous | On-call humans, ops agents |
Live demo · guides and sensors working together
Turn controls on and off. Guides raise first-attempt success; sensors catch failures and give the agent another try. The model is illustrative, but the shape matches what teams report.
Sensors for the hardest part: behaviour
Böckeler sorts harnesses into three kinds. Maintainability (style, complexity, duplication) is the easiest; mature tools exist. Architecture fitness (layering, performance, logging standards) is solvable with structural tests and fitness functions. Behaviour (does it do what the user wanted?) is the "elephant in the room". Agent-written tests passing proves little if the agent also misunderstood the spec. What helps:
- Tests written before the code, from the spec, by a separate agent or a human; agents may not edit them ("it is unacceptable to remove or edit tests", as Anthropic's long-run prompt put it).
- End-to-end checks as a user: Anthropic found Claude often marked features done after unit tests or
curl; prompting it to drive a real browser (Puppeteer, Playwright) caught bugs invisible in code. - A separate evaluator with calibrated criteria and hard thresholds, because agents grade their own work too generously (Ch 10).
- Mutation testing to check that tests actually fail when code is wrong.
- Approved fixtures / snapshot tests where a human signs off on a reference output once.
- ruff · mypy · pyrightLint, format and type checks in milliseconds to seconds.
- pytest (+ pytest-xdist, testmon)Run the relevant subset fast; parallelise the rest.
- import-linterLayering and dependency rules as tests.
- mutmutMutation testing for test strength.
- playwrightEnd-to-end checks the agent can run.
# .importlinter : architecture as a failing test
[importlinter]
root_package = app
[importlinter:contract:layers]
name = Layers import downward only (api -> core -> infra)
type = layers
layers =
app.api
app.core
app.infra- Azure Pipelines / GitHub ActionsRun the same check script in CI.
- GitHub Advanced SecurityCode scanning and secret scanning as sensors.
- Azure AI Foundry evaluationsLLM-judge style evaluators for outputs.
- CodeBuild / CodePipelineCI execution of checks.
- Amazon CodeGuru SecurityStatic security analysis.
- Bedrock evaluationsModel-judged output evaluation.
- Cloud BuildCI execution of checks.
- Vertex AI Gen AI evaluationRubric and model-based evaluators.
- Artifact AnalysisDependency vulnerability scanning.
- Semgrep · SonarQubeCustom static rules with fix messages; quality gates.
- ArchUnit · dependency-cruiser · NetArchTestStructural tests for Java, JS/TS, .NET.
- Stryker · PIT · cargo-mutantsMutation testing beyond Python.
- pre-commit · lefthookRun sensors on every commit.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Sensor design
Structural tests, judges, flakiness and the sensors that never fire.
Structural tests: architecture as code architecture
Tools like import-linter (Python), ArchUnit (Java), dependency-cruiser (JS/TS) and custom AST checks turn diagrams into failing tests: "core must not import infra", "every handler has a test file", "no SQL outside repo/". Agents produce code fast, so drift happens fast; structural tests are how you keep the shape you designed.
LLM judges as sensors inferential
- Give the judge a rubric with concrete criteria and examples of each score; Anthropic calibrated its evaluator with few-shot examples and score breakdowns to stop drift.
- Use a different prompt (and ideally a different or stronger model) from the generator.
- Prefer pass/fail per criterion with hard thresholds over one blended score.
- Run judges at commit or CI, not after every edit: they are slow and cost tokens.
- Re-check judge agreement with humans on a sample every month.
Flaky sensors poison the loop failure
A test that fails randomly teaches the agent to ignore failures, or sends it chasing bugs that don't exist. Quarantine flaky tests, mark them clearly in output, and track flake rate as a harness metric. A sensor the agent can't trust is worse than no sensor.
Sensors that never fire open question
If a check never fails, either quality is high or the check is weak. Periodically inject a known violation (a mutation, a forbidden import) and confirm the sensor catches it. Harness coverage, like test coverage, is still an open research problem.
Don't let the agent game the sensor safety
Agents under pressure to pass will sometimes delete tests, add skip, loosen assertions, or special-case test inputs. Protect test files with permissions or hooks, diff-check for deleted assertions, and have reviewers (human or agent) look specifically for test weakening.
Context and state: memory that outlives the window
The context window is short-term memory; it fills, degrades and resets. A harness keeps the real state outside the model: a session log, a progress file, a machine-readable task list, git history. Then it chooses how to refill the window: compaction (summarise in place), reset (fresh agent plus a handoff), clearing old tool results, or sub-agents with their own windows.
Every step of an agent appends to its context: tool results, file contents, logs. Each model call re-reads all of it. Quality falls well before the hard limit (long-context research calls this "context rot"), cost rises with every step, and eventually the run hits the ceiling. Anthropic's long-running-agent work found two failure shapes: the agent tries to do too much in one window and leaves half-built features undocumented, or a later session sees partial progress and wrongly declares the job finished.
Their fix was not a bigger window. It was external state the agent re-reads at the start of every session: a claude-progress.txt log, a JSON feature list with over 200 items all starting as "passes": false, an init.sh to start the app, and descriptive git commits. A new session reads those and is productive in a few steps.
Four ways to refill the window
| Strategy | How it works | Strength | Weakness | Use when |
|---|---|---|---|---|
| Tool-result clearing | Replace old, bulky tool outputs with a stub ("file read, 340 lines; re-read if needed") | Cheap, safe, keeps reasoning intact | Agent may re-read files | Always; first line of defence |
| Compaction | Summarise earlier history in place; same agent continues | Continuity; automatic in most SDKs | Lossy; no clean slate; summary drift over many rounds | Medium tasks; models without context anxiety |
| Context reset + handoff | End the session; a fresh agent starts from a structured handoff artifact | Clean slate; forces good notes | Handoff must be complete; extra latency and tokens | Multi-hour work; models that rush near the limit |
| Sub-agent isolation | Delegate a search or analysis to a child agent; only its summary returns | Keeps the main window clean; parallel | Child lacks parent context; summaries can drop details | Research, exploration, broad reads (Ch 11) |
Live demo · context over a long run
Choose a strategy and watch the context fill. The shaded band is where quality starts to slip (here, above 60% of the window). The illustration assumes a fixed prefix of guides and tools plus a steady amount added per step.
The state files that make sessions resumable
Feature list (JSON)
Every requirement as an item with description, test steps and a passes flag. Agents may only flip the flag, never delete items. Anthropic chose JSON over Markdown because models were less likely to rewrite it wholesale.
{"id": "export-csv-03", "category": "export",
"description": "CSV export respects active filters",
"steps": ["apply status=paid filter", "click Export",
"file has only paid rows"],
"passes": false}Progress log
Append-only notes per session: what was done, what's broken, what to do next, what was tried and failed. Read first thing every session, written last thing.
## Session 7 · 2026-10-21
done: export-csv-01, -02 (commit 4f2a9c1)
broken: filter state lost on page reload
tried: storing in URL params, broke back button
next: export-csv-03, then fix reload buginit script
init.sh or scripts/dev starts everything the agent needs (DB, server, seed data) in one command, so no session wastes tokens figuring out how to run the app.
Git history
Commit after each working increment with a descriptive message. Git becomes both memory ("what changed and why") and an undo button for bad sessions.
The session log: context outside the window
Compaction, memory files and trimming are all irreversible choices about what to forget. Anthropic's Managed Agents keeps an append-only session log of every event outside both the model and the harness process. The harness can fetch any slice of it (getEvents()) to rewind, re-read a tool result it trimmed, or resume after a crash. Durable storage and context management are separate concerns: you can change how you build context later without losing history.
- claude-agent-sdkAutomatic compaction; context editing to clear old tool results.
- langgraph checkpointersPersist state per step to Postgres, SQLite or Redis.
- tiktoken / provider token countersMeasure context before each call.
def maybe_compact(msgs, window, count_tokens, summarise):
used = count_tokens(msgs)
if used < 0.75 * window:
return msgs
head, tail = msgs[:-8], msgs[-8:] # keep recent turns verbatim
notes = summarise(head, keep=["decisions", "open problems", "dead ends", "next step"])
open("progress.md", "a").write(notes + "\n") # durable copy outside the window
return [{"role": "user", "content": "Summary of earlier work:\n" + notes}] + tail- Cosmos DB / Azure Database for PostgreSQLSession logs and checkpoints.
- Foundry Agent Service threadsManaged conversation state.
- Bedrock AgentCore MemoryShort- and long-term memory for agents.
- DynamoDB / AuroraSession logs and checkpoints.
- Vertex AI Agent Engine sessions + Memory BankManaged session and long-term memory.
- Firestore / AlloyDBSession logs and checkpoints.
- Letta (MemGPT)Memory-managed agents.
- Postgres + an events tableThe simplest durable session log.
- gitCheckpoints and history for code work.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Context engineering inside a harness
Caching, handoffs, anxiety and memory.
Keep the prefix stable for prompt caching cost
Order context as: system prompt → tools → always-on guides → task → history. Anything that changes per call (timestamps, budgets) goes at the end. Caches typically bill reads at about 0.1× input price, so a stable 20k-token prefix over 80 calls saves most of its cost. Compaction and resets break the cache; count that cost when choosing thresholds.
Writing a handoff a fresh agent can use resets
- Goal and definition of done (or a pointer to the feature list).
- Current state: what works, verified how.
- Open problems with evidence (error messages, failing test names).
- Dead ends already tried, so they aren't repeated.
- The single next step.
Test handoffs: start a fresh agent from one and see if it makes progress in a few steps without re-exploring.
"Context anxiety" and why it matters for harness design model behaviour
Anthropic observed Claude Sonnet 4.5 cutting work short as it sensed the context limit approaching. Resets helped because the agent always started fresh. Claude Opus 4.5 largely lost the behaviour, so the same team dropped resets and relied on the SDK's automatic compaction. The lesson is general: context strategy depends on the model, so make it a configurable harness setting and re-test it on upgrades.
Long-term memory across tasks memory
Beyond a single project, harnesses can keep memory files or a memory store (preferences, recurring fixes, environment quirks). Treat writes to long-term memory as risky: a poisoned memory persists across sessions. Review or filter memory writes, scope them per user or tenant, and prefer committing lessons to version-controlled guides where humans can see them. The Agents Guide covers memory types in depth.
Environment, tools and agent legibility
An agent can only fix what it can see and run. Give it an isolated environment where it can boot the app, run any test, read logs and metrics, and drive a browser. Design tools for a model, not a human. And prefer codebases with strong types, clear boundaries and fast tests: they are more harnessable.
OpenAI's harness team spent much of its effort making the product legible to agents. Each change could boot its own copy of the app in its own git worktree. The Chrome DevTools Protocol was wired into the agent's tools so it could take DOM snapshots and screenshots and navigate pages. Each worktree got a temporary observability stack, so the agent could query logs and metrics directly and verify things like "startup under 800 ms" itself. The principle: anything the agent can't access in its environment effectively doesn't exist for it. Knowledge in a Slack thread or someone's head has to be written into the repo.
What the environment must offer
| Capability | Why it matters | How |
|---|---|---|
| Isolation | Parallel agents don't collide; mistakes stay contained | Git worktrees, containers, microVMs (Firecracker, gVisor), hosted sandboxes |
| One-command start | No tokens wasted working out setup | scripts/dev, devcontainer, Docker Compose, seed data |
| Fast targeted tests | Tight feedback inside the loop | Run one test by name in seconds; test selection by changed files |
| Logs, metrics, traces | Debugging by evidence, not guessing | Local or per-sandbox observability; query tools (LogQL, PromQL, SQL) |
| A browser | Verify UI and flows as a user would | Playwright or Puppeteer MCP, Chrome DevTools Protocol, screenshot tools |
| Data access, safely | Reproduce bugs with realistic data | Read-only replicas, anonymised snapshots, fixtures |
| Knowledge in the repo | Decisions the agent can read | docs/, ADRs, runbooks, specs checked in and linked from AGENTS.md |
Designing tools for a model (the agent-computer interface)
SWE-agent (2024) coined "agent-computer interface" for the commands and views an agent works through, and showed that a good interface matters as much as the model. Rules that hold up:
Shape
- Fewer, task-shaped tools beat many thin API wrappers (
run_checksinstead oflint,typecheck,testseparately, when they always run together). - Names and descriptions say when to use the tool, not only what it does.
- Strict input schemas; validate again on the server.
- Idempotent where possible; idempotency keys for writes.
Output
- Truncate and paginate; return handles to large results ("saved to /tmp/out.json, 12,400 rows").
- Errors say what was wrong and what to try ("date must be YYYY-MM-DD, got 03/12").
- Most important fields first; strip HTML, base64, noise.
- Mark untrusted content as data, not instructions.
Harnessability: some codebases are easier
Böckeler's colleague Ned Letcher calls the helpful properties of a stack its ambient affordances. The more of them a system has, the less harness you have to build by hand. Greenfield teams can choose them on day one. Legacy systems need the harness most and are the hardest to harness, so the first harness work there is often building the affordances themselves: a way to run it locally, a characterisation test suite, a type layer.
| Affordance | Acts as | Low harnessability | High harnessability |
|---|---|---|---|
| Static types | Free sensor on every edit | Untyped dynamic code | TypeScript strict, mypy strict, Rust, Kotlin |
| Module boundaries | Enables structural rules | Everything imports everything | Layers, packages, enforced interfaces |
| Opinionated framework | Removes decisions | Hand-rolled plumbing | Rails, Django, Spring, Next.js conventions |
| Test speed | Tight loops | 40-minute suite, no selection | Seconds for the relevant subset |
| Local runnability | Agent can verify itself | Only works in shared staging | Boots in a sandbox with one command |
| Written knowledge | Guides exist to point to | Tribal knowledge | Docs, ADRs, runbooks in the repo |
- docker (SDK)Start a container per run with resource limits.
- e2b · daytona · modalHosted sandboxes from Python.
- playwrightBrowser tool for verification.
import docker
client = docker.from_env()
box = client.containers.run(
"harness/python-dev:2026-10", command="sleep infinity", detach=True,
working_dir="/repo", volumes={worktree: {"bind": "/repo", "mode": "rw"}},
network="agent-egress-allowlist", # registry + git host only
mem_limit="4g", nano_cpus=2_000_000_000, pids_limit=512,
user="1000:1000", read_only=False, environment={}) # no secrets inside
exit_code, out = box.exec_run("bash -lc './scripts/check'", demux=False)- Azure Container Apps dynamic sessionsSandboxed code execution sessions on demand.
- Dev Box / CodespacesFull dev environments per agent or task.
- Bedrock AgentCore Code Interpreter · BrowserManaged sandboxed code and browser tools.
- ECS / Fargate with Firecracker isolationPer-run containers.
- Cloud Run jobs / sandboxed GKE (gVisor)Isolated per-run execution.
- Cloud WorkstationsManaged dev environments.
- Firecracker · gVisor · KataStrong isolation for untrusted code.
- Dev Containers · Docker ComposeOne-command, reproducible environments.
- Grafana · Loki · PrometheusPer-environment logs and metrics the agent can query.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Sandboxes and tools in practice
Isolation levels, worktrees, MCP and browser tools.
Isolation levels and their cost sandbox
- OS-level sandbox (macOS Seatbelt, Linux Landlock/seccomp/bubblewrap): restrict file writes and network for a local agent process. Near-zero overhead. Used by several coding CLIs.
- Containers: separate filesystem and process space; share the host kernel. Seconds to start.
- MicroVMs / gVisor: stronger isolation for untrusted code; hundreds of milliseconds to start with snapshots.
- Hosted sandboxes (E2B, Daytona, Modal, cloud code interpreters): someone else runs the fleet.
Pick by blast radius: what is the worst thing code in this sandbox could do, with these credentials and this network access?
Git worktrees for parallel agents parallelism
A worktree is a second checkout of the same repo on a different branch, sharing the object store. Each agent gets one, plus its own ports, database and temp dirs. Make "boot the app in this worktree" one command, and include a cleanup command, or disks fill with stale environments.
MCP servers as harness tools protocol
The Model Context Protocol lets you add tools (browser, database, issue tracker, observability) to any MCP-capable agent without changing its harness. Each server's tool definitions cost context on every call, so enable per project or per task, and prefer servers with tool search or small toolsets. See the companion MCP Guide.
CLI tools often beat MCP for coding agents design
Coding agents already have a shell. A well-designed script with --help, quiet success output and precise errors costs zero context until used, composes with pipes, and works the same for humans and agents. Many teams expose internal tools as CLIs in scripts/ and mention them in AGENTS.md, reserving MCP for services that need auth or structured access.
Permissions, hooks and policy: rules that can't be talked around
A sentence in a prompt is a request. A hook, a deny rule or a sandbox boundary is a guarantee. Put anything that must always or never happen into code that runs at the harness's lifecycle events: before a tool call, after an edit, before the agent stops. Layer them so no single layer has to be perfect.
The hook lifecycle
Most agent harnesses now expose hooks: your scripts, run by the harness at fixed points, that can allow, block, modify or add feedback. Names differ by product; the shape is the same.
Where hooks fire in a run
#!/usr/bin/env python3 — reads the proposed call as JSON on stdin
import json, re, sys
call = json.load(sys.stdin)
cmd = call.get("tool_input", {}).get("command", "")
DENY = [(r"\brm\s+-rf\s+(/|~|\$HOME)", "deleting home or root is never allowed"),
(r"git\s+push\s+.*--force", "force-push is blocked; open a PR instead"),
(r"\b(curl|wget)\b.*\|\s*(sh|bash)", "piping downloads to a shell is blocked"),
(r"(DROP|TRUNCATE)\s+TABLE", "destructive SQL needs a migration and review")]
for pat, why in DENY:
if re.search(pat, cmd, re.I):
print(f"Blocked: {why}. Command: {cmd[:120]}", file=sys.stderr)
sys.exit(2) # convention in several harnesses: exit 2 = block, stderr goes back to the model
sys.exit(0)Exit-code and JSON conventions differ between products and versions. Check your agent's hook docs. Pattern deny lists are a backstop, not a sandbox: a determined or confused agent can phrase a command many ways, so pair them with OS-level limits.
Permission modes
| Mode | How it behaves | Good for | Risk |
|---|---|---|---|
| Ask every time | Human approves each write or command | First days with a new agent; production systems | Approval fatigue: people stop reading |
| Allow-list | Known-safe commands run freely (make check, git status, reads); others ask | Daily development | Over-broad patterns (Bash(*)) defeat it |
| Auto with classifier | A model or rules engine decides low-risk actions; escalates the rest | Long unattended runs with a human on call | Classifier can be fooled; log every decision |
| Full auto in a sandbox | Anything goes inside an isolated, disposable environment with no secrets and limited network | Background agents, CI agents, benchmarks | Only as safe as the sandbox boundary |
| Full auto on a real machine | No checks, real credentials | Nothing | One injected instruction away from an incident |
Live demo · who decides?
Pick an action the agent proposes and a permission setup. See which layer allows, blocks or escalates it, in order. Defence in depth means a later layer catches what an earlier one missed.
- claude-agent-sdk hooksPython callbacks for pre-tool, post-tool and stop events.
- openai-agents guardrailsInput, output and tool guardrails.
- opa-python-client / cedarpyCall a central policy engine.
# policy.rego (OPA): evaluated by a tool gateway for every agent tool call
package agent.tools
default decision := "ask"
decision := "allow" if { input.tool == "run"; input.cmd in data.safe_commands }
decision := "deny" if { input.tool == "run"; regex.match(`git\s+push.*--force`, input.cmd) }
decision := "deny" if { input.tool == "read"; endswith(input.path, ".env") }
decision := "deny" if { input.env == "prod"; input.tool == "sql"; not input.change_request }- Azure AI Content Safety · Prompt ShieldsDetect injection in inputs and documents.
- Azure API ManagementGateway policies in front of tools.
- Entra Agent IDIdentities and scoped access for agents.
- Bedrock GuardrailsContent and topic filters.
- AgentCore Gateway + Policy (Cedar)Policy checks on tool calls at the gateway.
- IAM with session policiesScoped, short-lived credentials.
- Model ArmorPrompt and response screening.
- ApigeeAPI gateway policies for tools.
- IAM + Workload IdentityScoped credentials.
- Open Policy Agent · CedarPolicy-as-code engines.
- NeMo Guardrails · Llama GuardInput and output rails.
- git hooks (pre-commit, pre-push)Enforcement outside the agent.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Policy in practice
What to enforce where, and how to avoid approval fatigue.
Decide where each rule lives design
- Prompt: preferences and style. Fine if ignored occasionally.
- Sensor: rules about the output (layering, formatting, tests). Checked after the fact.
- Hook / policy: rules about actions (no force-push, no prod DB). Checked before.
- Sandbox / credentials: things that must be impossible (reading other tenants' data, sending email). Enforced by the environment.
Approval fatigue is a security bug people
If humans approve 200 prompts a day, they approve the 201st without reading. Ask only for actions that are irreversible, external, or unusual. Show a clear diff or the exact command and its effect. Track approval rate: above ~95% means most prompts should be auto-allowed and the rest made more visible.
Hooks are code: test and version them quality
Hooks run with your user's permissions and can themselves be a security risk if they execute content from the repo. Keep them small, review changes to them like production code, write unit tests with sample events, and make them fast (a slow after-edit hook slows every step).
Policy engines for platforms scale
At platform scale, move rules from per-repo scripts to a central policy engine (OPA/Rego, Cedar) evaluated by a tool gateway, so every agent and every tool call gets the same decision and an audit record (Ch 19).
Long-running harnesses: hours, not minutes
Work that spans hours needs structure the model can't hold in its head. Three proven patterns: initializer + worker sessions (set up state once, then make one verified increment per session), planner → generator → evaluator (separate the doer from the judge), and sprint contracts (agree what "done" means and how to check it before coding). Each costs more per task and pays off only beyond what the model does reliably alone.
Pattern 1 · Initializer and worker sessions
From Anthropic's "Effective harnesses for long-running agents" (November 2025). The first session runs with a special prompt and builds the scaffolding: a feature list from the spec, init.sh, a progress file and a first commit. Every later session uses the same model and tools with a different starting prompt, and follows a fixed routine. The two "agents" differ only in their first user message.
Initializer once, then the same routine every session
| Failure it prevents | Initializer does | Each worker session does |
|---|---|---|
| Declares the whole project done too early | Writes a structured feature list from the spec | Reads the list; works on one failing item |
| Leaves the environment broken or undocumented | Creates git repo and progress notes | Reads notes and log, smoke-tests first, ends with commit and update |
| Marks features done without checking | Writes test steps per feature | Verifies end to end before flipping passes |
| Wastes time working out how to run the app | Writes init.sh | Runs it at session start |
Pattern 2 · Planner, generator, evaluator
From Anthropic's "Harness design for long-running application development" (March 2026). Agents grade their own work too kindly, especially on subjective work like design. Splitting roles is "a strong lever": a standalone evaluator is easier to tune toward scepticism than a generator is to tune toward self-criticism.
Planner
Turns a 1–4 sentence prompt into a full product spec. Stays at product and design level, not low-level technical detail, so spec mistakes don't cascade into code. Without it, the generator under-scoped.
Generator
Builds one feature or sprint at a time on a fixed stack, self-checks, commits to git, then hands off. Chooses after each round whether to refine or change direction.
Evaluator
Uses Playwright to click through the running app like a user, checks UI, API and database state, and grades against criteria with hard thresholds: falling below any one fails the round. Calibrated with few-shot examples.
| Run (Anthropic's reported examples) | Duration | Cost | Result |
|---|---|---|---|
| Retro game maker, single agent (Opus 4.5) | 20 min | $9 | Core play mode didn't respond to input |
| Same task, full 3-agent harness with sprints | 6 h | $200 | Playable, with rough physics. Over 20× the cost |
| Music app (DAW), simplified harness on Opus 4.6: planner + 3 build/QA rounds | 3 h 50 min | $124.70 | Sprints removed; evaluator kept as a single end pass |
Pattern 3 · Sprint contracts
Before each sprint, the generator proposes what "done" looks like and how it will be verified. The evaluator reviews the proposal; they iterate until they agree. Then code is written. This bridges the gap between a high-level spec and testable work. In Anthropic's example, one sprint's contract for a level editor had 27 criteria, and the evaluator caught bugs such as a fill tool that only placed tiles at the ends of a drag. Agents communicated through files, not chat.
Other long-run shapes worth knowing
| Pattern | How it works | Use when | Risk |
|---|---|---|---|
| "Ralph" loop | Run the agent repeatedly on the same prompt file in a shell loop; state lives in the repo and a plan file; each run picks the next item | Large backlogs of similar, checkable work | Burns money if checks are weak; needs a stop condition |
| Execution plans in the repo | A checked-in plan with steps, decisions and a log; active and completed plans in separate folders (OpenAI's approach) | Multi-day work shared between agents and people | Plans go stale unless updating them is part of done |
| Research → plan → implement | Separate sessions: research writes findings, plan writes a reviewed plan, implement follows it; each compacts into a file (HumanLayer's workflow) | Unfamiliar code; changes humans must approve | Slower; human review becomes the bottleneck |
| Durable workflow + agent steps | A workflow engine (Temporal, Step Functions, LangGraph) checkpoints every step; agents run inside steps | Business processes, approvals that take days | More infrastructure |
Anthropic's conclusion: "the evaluator is not a fixed yes-or-no decision." It pays off only when the task sits beyond what the current model does reliably alone. As models improve, re-run without it on a sample of tasks. When results hold, remove it.
Running long jobs well
Prompts, criteria, and what goes wrong over hours.
The worker session prompt, in outline prompt
- You are continuing a project. Run
pwd, readprogress.md,git log -20andfeatures.json. - Run
./init.shand the smoke test. If anything is broken, fix that first. - Choose the single highest-priority feature with
"passes": false. - Implement it. Verify it end to end with the browser tool exactly as the test steps say.
- Only then set
"passes": true. Never edit or delete other items or tests. - Commit with a descriptive message. Append a progress entry. Stop.
Grading criteria that resist "AI slop" evaluation
For frontend work, Anthropic weighted design quality and originality above craft and functionality (the model already handled the latter by default) and explicitly penalised generic patterns. Criteria should target what the model does badly unaided, not what it already does well.
Evaluators talk themselves into approving failure
Out of the box, Claude was a weak QA agent: it found real issues, then decided they were minor and approved. It also tested superficially. The fix was iterative: read evaluator logs, find where its judgement differed from a human's, adjust the prompt, repeat. Even tuned, it missed small layout issues and deeply nested bugs. Budget for humans to spot-check.
Simplify one piece at a time maintenance
When Opus 4.6 arrived, a radical cut of the harness lost quality. Removing one component at a time showed which were load-bearing: sprints could go (the model could hold a multi-hour build coherently), but the planner and the evaluator stayed. Ablate, don't guess (Ch 16).
Orchestration: sub-agents, parallel work and blueprints
Use more than one agent for three reasons only: clean context (a sub-agent explores and returns a summary), parallelism (independent tasks in separate worktrees), and separation of duties (the reviewer isn't the author). For everything predictable, wrap agents in a blueprint: deterministic code nodes for the fixed steps, agent nodes only where judgement is needed.
A blueprint: deterministic and agentic nodes together
Stripe's "minions" are one-shot coding agents that take a task from a Slack thread or bug report and end with a pull request for human review. Their harness grew from a fork of Block's open-source Goose agent. The key idea is the blueprint: a workflow defined in code that decides which subtasks are handled by deterministic routines and which by the agent, described by Stripe engineers as "a collection of agent skills interwoven with code". Reported volume in early 2026 was over a thousand merged pull requests a week, all human-reviewed. Pre-push hooks run the relevant linters chosen by heuristics, so feedback stays left.
When to add another agent
| Pattern | What it buys | What it costs | Use when |
|---|---|---|---|
| Explorer sub-agent | Main context stays clean; only a summary returns | Extra tokens; details lost in summary | Searching a large codebase, reading docs, investigating logs |
| Parallel workers in worktrees | Wall-clock speed; independent attempts | Merge conflicts; N× tokens; review load | Independent tickets; trying 3 approaches and keeping the best |
| Author + reviewer | Fresh eyes; catches self-grading bias | One more pass per change | Any change that ships; agent-to-agent review before human review |
| Planner + executor | Plan visible and approvable; cheaper executor | Plans go stale | Large changes, migrations |
| Specialist agents (security, perf, docs) | Focused prompts and tools | Coordination, overlapping findings | Review stages with distinct checklists |
| Blueprint / workflow | Predictable, auditable, cheap fixed steps | Upfront design; less flexible | Repeated task types at volume |
Coordination between agents loses information at every handoff. Cognition's 2025 advice "don't build multi-agents" still holds for tightly coupled work like a single code change: one agent with good context beats a committee. Add agents where work is independent or where a second opinion is the point.
Making multi-agent harnesses work
Briefs, merging, review and limits.
Write briefs, not one-liners, for sub-agents quality
A sub-agent starts with nothing. Give it the goal, why it matters, what is already known, where to look, what to return and in what shape, and a budget. "Find where invoice dates are set; return file paths, line numbers and a two-line summary of each; stop after 15 tool calls" beats "look into invoice dates".
Parallel attempts and picking a winner pattern
For hard tasks, run k independent attempts and keep the one that passes the most checks, or have a judge pick. If one attempt succeeds with probability p, at least one of k does with 1 − (1 − p)k: p = 40% and k = 3 gives 78%. Cost scales with k, so use it where a failure is expensive and a check can pick the winner.
Agent-to-agent review before humans review
Teams with high agent PR volume often have a review agent comment first, the author agent respond, and humans review last. This removes trivial findings from human queues. Keep the review agent's checklist in the repo, and measure how often humans find issues it missed.
Limits that stop runaway fan-out cost
Cap sub-agent depth (usually 1–2), concurrent children per parent, and total tokens per tree. Log the parent-child relationships in traces so you can see where cost went (Ch 18).
Entropy: keeping an agent-written codebase healthy
Agents copy whatever patterns they find, good and bad, at high speed. Without counter-pressure a codebase drifts: duplicated helpers, inconsistent styles, stale docs, dead code. Harness engineering treats this as a recurring job: written golden principles, drift sensors, and scheduled clean-up agents that open small fix-up PRs, like a garbage collector for code.
OpenAI's team found that agents replicate existing patterns, including uneven or suboptimal ones, and that cleaning up by hand ("AI slop" Fridays) didn't scale. They wrote down a set of opinionated "golden principles" in the repo and ran recurring background tasks that scan for deviations, update quality grades, and open targeted refactoring pull requests, most small enough to review in a minute. A "doc-gardening" agent looks for documentation that no longer matches the code and proposes fixes. Thoughtworks teams describe a similar "janitor army". Technical debt is paid continuously in small amounts instead of in painful bursts.
Drift with and without garbage collection
The entropy toolkit
| Tool | What it does | Cadence |
|---|---|---|
| Golden principles doc | Short, opinionated rules for how code should look ("one way to do HTTP clients", "validate at the edge"), linked from AGENTS.md | Updated when a new pattern is agreed |
| Promote principles to sensors | Every principle that can be a lint rule or structural test becomes one | As soon as it's stable |
| Drift scans | Duplicate code, dead code, dependency age, complexity hot spots, inconsistent patterns | Daily or weekly |
| Clean-up agents | Pick the top findings and open small, single-purpose PRs | Weekly, with a cap on open PRs |
| Doc gardening | Compare docs to code; flag or fix stale sections and broken links | Weekly |
| Harness gardening | Find contradictory or obsolete rules in AGENTS.md and skills; remove rules for deleted code | Monthly and on model upgrades |
| Quality grades | A score per module or layer tracked over time, visible to the team | Continuous |
Harness templates
Most organisations build a handful of service shapes again and again: an API over a database, an event processor, a dashboard. Böckeler suggests harness templates: a bundle of guides and sensors per shape. She ties this to Ashby's Law of Requisite Variety (a regulator needs as much variety as the system it controls): committing to a known shape shrinks what the agent can produce, which makes a complete harness achievable. The risks are templates falling behind upstream improvements, and the difficulty of versioning guides that are partly prose and partly non-deterministic.
Running clean-up at scale
Merge policy, review load and the human taste problem.
Merge philosophy changes when agents are fast process
When agent throughput far exceeds human attention, waiting is expensive and corrections are cheap. OpenAI described keeping PRs short-lived, with minimal blocking gates, and fixing flaky tests with follow-up runs rather than blocking indefinitely. This only works with strong sensors and easy rollback; in regulated code, keep blocking gates.
Keep clean-up PRs reviewable people
One concern per PR, under ~200 lines, with the principle it enforces in the description. Cap how many clean-up PRs can be open at once so they don't swamp reviewers. Auto-close stale ones.
Taste still comes from people limits
Agents can enforce principles; they don't reliably invent good ones. Human review feedback, refactoring decisions and bug post-mortems are the raw material. Capture them in docs or as rules, and let the agents apply them everywhere.
Every harness component, compared
Each entry is one building block: what it is, how it works, when to use it, its strengths and weaknesses, and how to implement it. Filter by family (guides, sensors, control, state and environment), search, or click a row in the matrix. Ratings are relative judgements for typical use.
Harness platforms and frameworks, compared
Three choices: use a ready agent and build an outer harness around it (Claude Code, Codex, Copilot, Gemini CLI, Cursor), build on an agent SDK when the agent is your product (Claude Agent SDK, OpenAI Agents SDK, LangChain deepagents, Google ADK, open-source agents), or host on a managed runtime (Claude Managed Agents, Bedrock AgentCore, Foundry Agent Service, Vertex AI Agent Engine). The shared formats (AGENTS.md, SKILL.md, MCP) make your outer harness mostly portable.
Products in this space ship features monthly. Treat this chapter as a map, and confirm features, file names and limits in each vendor's current docs before you commit.
Ready-made coding agents (you build the outer harness)
| Agent | Instructions | Extension points | Isolation | Headless / CI |
|---|---|---|---|---|
| Claude Code (Anthropic) | CLAUDE.md, nested; can import other files | Skills, hooks on many lifecycle events, sub-agents, MCP, plugins, permission rules | Permission modes; OS-level sandbox for shell; containers | Non-interactive mode, GitHub Actions, Agent SDK |
| OpenAI Codex (CLI, IDE, cloud) | AGENTS.md, nested | Skills, MCP, config profiles; check docs for hooks | OS sandbox locally (Seatbelt, Landlock); cloud containers | codex exec, cloud tasks, SDK |
| GitHub Copilot coding agent | copilot-instructions.md, AGENTS.md | Skills, custom agents, MCP, setup steps workflow | Runs in a GitHub Actions environment with a firewall | Native: assign an issue, get a PR |
| Gemini CLI (Google) | GEMINI.md (configurable name) | Extensions, MCP, skills, custom commands | Optional sandbox (container or OS profile) | Non-interactive mode, GitHub Actions |
| Cursor agent | Rules files, AGENTS.md | Rules, MCP, background agents, hooks | Local; background agents in remote VMs | Background agents, CLI |
| Open source: OpenHands, Goose, Aider, Cline and others | Varies; most read AGENTS.md | Full source: change the loop itself | Docker sandboxes (OpenHands); local | Yes; scriptable |
SDKs and frameworks (you build the inner harness)
| Framework | Harness features | Best for |
|---|---|---|
| Claude Agent SDK | The Claude Code harness as a library: tools, compaction, sub-agents, hooks, permissions, skills, MCP | Agents that need a proven coding-style harness |
| OpenAI Agents SDK | Agents, handoffs, guardrails, sessions, tracing; sandbox integrations | Multi-agent apps on OpenAI models |
| LangChain deepagents / LangGraph | Planning tool, file system, sub-agents, middleware (loop detection, checklists), durable graphs, LangSmith traces | Model-agnostic harnesses you want to tune and inspect |
| Google ADK | Agents, workflow agents, tools, sessions and memory, evaluation | Gemini and Google Cloud deployments |
| Microsoft Agent Framework | Agents and workflows, middleware, checkpointing, OpenTelemetry | .NET and Python on Azure |
| AWS Strands Agents | Model-driven loop, tools, MCP, multi-agent patterns | AWS deployments with AgentCore |
| smolagents, PydanticAI, Mastra and others | Lightweight loops, code agents, typed tools | Small, inspectable harnesses |
Managed runtimes (someone else runs the platform)
Claude Managed Agents
Hosted long-horizon agents built on session / harness / sandbox interfaces. Stateless harnesses resume from a durable session log; credentials stay in a vault behind a proxy.
Amazon Bedrock AgentCore
Runtime, memory, gateway (APIs as MCP tools), identity, code interpreter and browser sandboxes, observability, policy controls.
Azure AI Foundry Agent Service
Hosted agents with tools, threads, connected agents, content safety and evaluations, integrated with Entra identity.
Vertex AI Agent Engine
Deploy ADK and other framework agents with sessions, memory bank, evaluation and tracing on Google Cloud.
How to choose
- Is the agent your product, or a tool your team uses?Tool → pick a ready agent and spend your effort on the outer harness. Product → an SDK or managed runtime.
- Which model family must you use?Vendor agents are tuned for their own models. LangChain found harness changes don't transfer perfectly between models; tune per model.
- Where must code run?Your laptop, your cloud, a customer's VPC? This decides sandbox and hosting options more than features do.
- How much do you need to change the loop?If you need custom middleware or stop rules, you need an SDK or open source, not configuration.
- Keep your outer harness portable.AGENTS.md, SKILL.md, MCP servers and repo scripts work across most tools. Your tests and linters work everywhere.
Build a harness end to end
Part A: an outer harness for a real repository in eight steps, for any coding agent: map, commands, quiet checks, structural rules, hooks, permissions, state files and CI. Part B: a minimal custom harness in Python (about 120 lines) with budgets, a policy check, after-edit sensors, loop detection and a completion gate.
Part A · An outer harness for your repo
- Collect the failuresWrite down the last 20 corrections you gave agents in this repo. Group them: missing commands, wrong layer, untested code, style, risky actions, premature "done". This is your backlog.
- One command for each jobAdd
scripts/setup,scripts/dev,scripts/test-oneandmake check. Humans benefit too. - Make checks quiet and preciseWrap the test runner and linters so success is one line and failure is only what matters (below).
- Turn rules into sensorsLayering → import-linter / dependency-cruiser. Conventions → lint rules with fix messages. Each rule you can encode leaves AGENTS.md.
- Write the mapA ~100-line AGENTS.md: commands, map, hard rules, definition of done, pointers to docs and skills. Symlink tool-specific names to it.
- Add hooksAfter edits: format and type-check changed files. Before shell commands: deny the dangerous ones. Before stop: require
make checkto have passed since the last edit. - Set permissionsAllow reads,
make check, tests and git status/diff. Ask for installs, network and pushes. Run unattended agents only in a sandbox. - Add state for long work, and CIA
docs/exec-plans/folder and a progress-file convention. CI runs the samemake checkplus slower sensors, and an agent can be asked to fix CI failures.
#!/usr/bin/env bash
# Runs all fast checks. Prints one line per passing check; full detail only for failures.
set -uo pipefail
fail=0
run() { # run NAME CMD...
local name=$1; shift
local out; out=$("$@" 2>&1)
if [ $? -eq 0 ]; then echo "✓ $name"; else
echo "✗ $name"; echo "$out" | grep -E "error|Error|FAIL|failed|E[0-9]{3}" | head -n 25
fail=1; fi
}
run format ruff format --check .
run lint ruff check . --output-format=concise
run types mypy --no-error-summary core api infra
run layers lint-imports --no-cache
run tests pytest -q -x --no-header -p no:warnings
exit $fail{
"permissions": {
"allow": ["Bash(make check)", "Bash(./scripts/test-one:*)", "Bash(git status)", "Bash(git diff:*)"],
"ask": ["Bash(pip install:*)", "Bash(npm install:*)", "Bash(git push:*)"],
"deny": ["Read(./.env)", "Read(./secrets/**)", "Bash(rm -rf:*)"]
},
"hooks": {
"PostToolUse": [{ "matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "./scripts/hooks/after_edit.sh" }] }],
"PreToolUse": [{ "matcher": "Bash",
"hooks": [{ "type": "command", "command": "./scripts/hooks/deny_risky.py" }] }],
"Stop": [{ "hooks": [{ "type": "command", "command": "./scripts/hooks/require_checks.sh" }] }]
}
}The shape follows Claude Code's settings format; other agents use different files and keys for the same ideas. Check your agent's documentation for exact names and the hook input and output protocol.
#!/usr/bin/env bash
# Blocks "stop" unless `make check` passed after the most recent edit.
stamp=.harness/last_check_ok # written by scripts/check on success
last_edit=$(git ls-files -m -o --exclude-standard | xargs -r stat -c %Y 2>/dev/null | sort -n | tail -1)
if [ -z "$last_edit" ]; then exit 0; fi # nothing changed
if [ -f "$stamp" ] && [ "$(stat -c %Y "$stamp")" -ge "$last_edit" ]; then exit 0; fi
echo "Not done yet: run 'make check' and fix failures before finishing." >&2
exit 2Part B · A minimal custom harness in Python
When the agent is your product you own the loop. This sketch uses the Anthropic Python SDK's tool-use format; the structure is the same on any provider. It has the five things that matter most: budgets, policy before tools, sensors after edits, loop detection, and a completion gate.
import json, re, subprocess, time, collections
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5" # pick per task; pin versions in production
WORKDIR = "/sandbox/repo" # run inside a container or VM, not your laptop
def sh(cmd, timeout=120):
p = subprocess.run(cmd, shell=True, cwd=WORKDIR, capture_output=True, text=True, timeout=timeout)
out = (p.stdout + p.stderr)[-6000:] # cap what goes back into context
return p.returncode, out
TOOLS = [
{"name": "run", "description": "Run a shell command in the repo. Use ./scripts/check to verify work.",
"input_schema": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]}},
{"name": "write_file", "description": "Replace a file's full contents.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
"required": ["path", "content"]}},
]
DENY = [r"rm\s+-rf\s+/", r"git\s+push", r"curl .*\|\s*sh", r"\.env\b"]
class Budget:
def __init__(self, steps=60, seconds=1800, dollars=5.0):
self.steps, self.seconds, self.dollars = steps, seconds, dollars
self.t0, self.used_steps, self.spent = time.time(), 0, 0.0
def charge(self, usage, in_price=3e-6, out_price=15e-6):
self.used_steps += 1
self.spent += usage.input_tokens * in_price + usage.output_tokens * out_price
def left(self):
return (self.used_steps < self.steps and self.spent < self.dollars
and time.time() - self.t0 < self.seconds)
def note(self):
return f"[budget] step {self.used_steps}/{self.steps}, ${self.spent:.2f}/{self.dollars}, " \
f"{int(time.time()-self.t0)}s/{self.seconds}s"
def policy(name, args): # deterministic, before every tool
text = json.dumps(args)
for pat in DENY:
if re.search(pat, text): return f"Blocked by policy ({pat}). Choose a safer approach."
return None
def after_edit(path): # sensor: fast, quiet, precise
code, out = sh(f"ruff check {path} --output-format=concise && mypy {path} --no-error-summary", 60)
return None if code == 0 else f"[sensor] problems in {path}:\n{out[-1500:]}"
def completion_gate(state): # the model asks to stop; we decide
if state["edited_since_check"]:
code, out = sh("./scripts/check", 600)
state["edited_since_check"] = code != 0
if code != 0: return f"Not done: checks fail.\n{out[-2000:]}"
return None
def run(task):
guides = open(f"{WORKDIR}/AGENTS.md").read() # tier-1 guide: the map
system = [{"type": "text", "text": "You are a careful software agent.\n" + guides,
"cache_control": {"type": "ephemeral"}}] # stable prefix → prompt cache
msgs = [{"role": "user", "content": task}]
budget, edits = Budget(), collections.Counter()
state = {"edited_since_check": False}
while budget.left():
r = client.messages.create(model=MODEL, max_tokens=4000, system=system, tools=TOOLS, messages=msgs)
budget.charge(r.usage)
msgs.append({"role": "assistant", "content": r.content})
calls = [b for b in r.content if b.type == "tool_use"]
if not calls: # wants to stop → gate
reason = completion_gate(state)
if reason is None: return "done", msgs
msgs.append({"role": "user", "content": reason + "\n" + budget.note()}); continue
results = []
for c in calls:
blocked = policy(c.name, c.input)
if blocked:
results.append({"type": "tool_result", "tool_use_id": c.id, "content": blocked, "is_error": True})
continue
if c.name == "run":
code, out = sh(c.input["cmd"])
if "scripts/check" in c.input["cmd"] and code == 0: state["edited_since_check"] = False
content = out or "(no output)"
else:
with open(f"{WORKDIR}/{c.input['path']}", "w") as f: f.write(c.input["content"])
state["edited_since_check"] = True
edits[c.input["path"]] += 1
content = after_edit(c.input["path"]) or "written; lint and types clean"
if edits[c.input["path"]] in (6, 10): # loop detection → nudge
content += (f"\n[harness] You have edited {c.input['path']} {edits[c.input['path']]} times. "
"Step back: re-read the error and consider a different approach.")
results.append({"type": "tool_result", "tool_use_id": c.id, "content": content})
results.append({"type": "text", "text": budget.note()})
msgs.append({"role": "user", "content": results})
return "budget_exhausted", msgs # caller writes a handoff from msgsWhat to add next, in order
Session log
Write every request, response and tool result to an append-only store keyed by run ID, so runs can resume and be replayed.
Human pause
An ask_human tool that suspends the run durably and resumes on reply.
Evaluating and improving a harness
Hold the model fixed and change one harness component at a time. Measure task success on real tasks, consistency across repeated runs, and cost per success. Improve with a loop: run, read the failing traces (agents can help), make a targeted change, re-run. Then ablate: remove components one by one to find which are still load-bearing.
What to measure
| Metric | Definition | Why |
|---|---|---|
| Task success | Share of tasks whose final state passes the checks (tests, environment state) | The outcome users care about |
| pass^k | Share of tasks that succeed in all k repeated runs | Users feel inconsistency more than averages |
| Cost per success | Total spend ÷ successful tasks | A harness that doubles success at 3× cost may be worse |
| Premature-done rate | Runs that claimed done but failed checks | Measures your completion gate |
| Steps and wall-clock | Median and p95 per task | Latency and timeout risk |
| Human interventions | Approvals, corrections, takeovers per task | The real cost of supervision |
| Escaped defects | Bugs found after merge in agent-written changes | What your sensors miss |
e.g. s = 70%: pass@3 = 97.3% (good for "try 3, keep the best") but pass^3 = 34.3% (what a user running it 3 times sees)
cost per success = cost per run ÷ s → raising s from 50% to 70% cuts cost per success by 29% even at equal run cost
Benchmarks that measure harnesses
Public agent benchmarks now report the model and harness pair, because the same model scores very differently in different harnesses. Use them to compare, but trust your own tasks more.
| Benchmark | What it tests | Notes |
|---|---|---|
| Terminal-Bench 2.0 | 89 hard terminal tasks (ML, debugging, biology, systems) in containers | Run with the Harbor framework; leaderboard lists agent + model. A newer version exists; check which one numbers refer to. |
| SWE-bench Verified / Pro | Fixing real GitHub issues, checked by tests | Verified is near saturation for top agents; Pro is harder and less contaminated |
| τ-bench / τ²-bench | Tool use with simulated users and policies | Reports pass^k consistency |
| Your own task set | 30–300 real tasks from your repo or product with automatic checks | The only benchmark that matches your harness and codebase |
The improvement loop
- Run the suiteSeveral runs per task, traces saved, harness version tagged.
- Analyse failures with agentsLangChain fetched traces from LangSmith, ran parallel error-analysis agents over failures, and had a main agent synthesise patterns and suggested harness changes. Like boosting, focus on what failed last time.
- Change one thingA prompt line, a middleware, a tool, a sensor. Keep the diff small so the effect is attributable.
- Re-run and compareSame tasks, same model, same number of runs. Look at success, pass^k and cost, not only the headline.
- Guard against overfittingA human reviews changes that look task-specific. Keep a held-out task set you never tune on.
Live demo · ablation explorer
Toggle harness components for a hypothetical coding agent and compare a weaker and a stronger model. Effects are illustrative, loosely shaped by the public reports in this guide. Notice that some components help the weaker model a lot and the stronger one barely: that is how harness assumptions expire.
Automatic harness search
The Meta-Harness paper (Lee, Nair, Zhang, Lee, Khattab and Finn, March 2026) treats harness code as something to optimise. An agent proposes new harness versions after reading the source, scores and traces of all earlier candidates from a file system. Reported results: +7.7 points over a strong context-management baseline on text classification with 4× fewer context tokens; +4.7 points on 200 IMO-level maths problems averaged over five held-out models; and discovered coding harnesses that ranked first among Haiku 4.5 agents on Terminal-Bench 2.0. These are preprint results, but they point to a future where harness tuning is partly automated, with humans setting goals and reviewing changes.
- inspect-aiEvaluation framework for agentic tasks with sandboxes.
- harborRuns Terminal-Bench style tasks in containers against any agent.
- pytestYour own task suite: each task is a test with a final-state check.
- langsmith · langfuse · phoenix SDKsStore traces and experiments for comparison.
import itertools, statistics
def evaluate(harness, tasks, runs=3):
rows = []
for task, r in itertools.product(tasks, range(runs)):
res = harness.run(task.prompt, sandbox=task.fresh_sandbox())
rows.append({"task": task.id, "ok": task.check(res.sandbox), "cost": res.cost})
by_task = {t.id: [x["ok"] for x in rows if x["task"] == t.id] for t in tasks}
s = statistics.mean(x["ok"] for x in rows)
return {"success": s, "pass^k": statistics.mean(all(v) for v in by_task.values()),
"cost_per_success": sum(x["cost"] for x in rows) / max(1, sum(x["ok"] for x in rows))}- Azure AI Foundry evaluationsAgent and output evaluators, evaluation runs in CI.
- Bedrock AgentCore EvaluationsEvaluate agent sessions and tool use.
- Bedrock model evaluationJudge-based and automatic metrics.
- Vertex AI Gen AI evaluation serviceAgent trajectory and response evaluation.
- Terminal-Bench · SWE-bench harnessesPublic benchmarks reporting agent + model pairs.
- Langfuse · Arize PhoenixOpen-source tracing and experiment comparison.
- promptfooRegression tests for prompts and agents in CI.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Evaluation pitfalls
Noise, contamination and transfer.
How many runs you need to see a real difference statistics
With n tasks and success near 50%, the standard error is about √(0.25/n). For 100 tasks that's ±5 points, so a 3-point gain is noise. Run each task 3–5 times, use paired comparisons on the same tasks, and treat changes under ~2 standard errors as unproven.
Harness changes don't transfer cleanly between models transfer
LangChain's tuned harness scored 66.5% with gpt-5.2-codex; an earlier version with Claude Opus 4.6 scored 59.6%, and they note they had not run the same improvement loop for Claude. Tune and evaluate per model. If you route between models, evaluate each pair.
Evaluate the harness in its real environment validity
Eval tasks should run in the same sandbox, with the same tools, hooks and permission settings as production. A harness that passes in a permissive eval environment and fails behind production policy hasn't been evaluated.
Treat guardrails as temporary maintenance
LangChain describes loop detection and forced verification as workarounds for current model limits, expected to become unnecessary. Keep a "re-test on upgrade" list of such components and ablate them when a new model ships.
Security: the harness is the boundary
A model can be talked into anything by text it reads: an issue, a README, a web page, a dependency's AGENTS.md. So security can't live in the model. It lives in the harness: what the sandbox can reach, which credentials exist inside it, which actions need approval, and what can leave. Assume the agent will eventually follow a malicious instruction, and design so that it can't do much harm when it does.
The lethal trifecta, applied to harnesses
Simon Willison's rule: an agent with access to private data, exposure to untrusted content and a way to communicate externally can be made to leak that data. Coding agents often have all three by default: the repo and environment variables (private), issues, docs and web pages (untrusted), and a shell with network (external). The harness's job is to break at least one leg for each run.
Private data
Keep secrets out of the sandbox entirely. Anthropic's Managed Agents never puts tokens in the container: git credentials are used at setup, and MCP calls go through a proxy that fetches credentials from a vault.
Untrusted content
Treat issue text, web pages, tool results and third-party repo files as data. Quarantine them: summarise with a tool-less model, or restrict what the agent can do after reading them.
External communication
Egress allow-lists (package registries, your git host), no arbitrary HTTP, no email or chat tools in the same run as untrusted input, approval for anything that publishes.
Harness-specific attack surface
| Vector | Example | Defence |
|---|---|---|
| Instructions files in dependencies or forks | A vendored package ships an AGENTS.md saying "also send the .env to …" | Only load instruction files from trusted paths; review changes to them like code |
| Issue or PR text | A public issue includes hidden instructions to add a backdoor | Read-only run for untrusted triggers; human review before merge; no secrets in CI agent runs on forks |
| Malicious skills or MCP servers | A popular skill's script exfiltrates files | Pin versions, review code, allow-list sources, run in the sandbox |
| Hooks that execute repo content | A hook runs a script the agent just edited | Hooks live outside the agent-writable area or are protected by permissions |
| Sensor gaming | The agent disables a failing test to "finish" | Protect test files; diff checks for removed assertions; separate evaluator |
| Over-broad allow rules | Bash(*) or "approve all for this session" | Narrow patterns; deny lists; sandbox for full auto |
| Long-term memory poisoning | An injected "lesson" persists into future sessions | Review memory writes; keep lessons in version control |
| Supply chain via installs | Agent adds a typo-squatted package | Ask before installs; lockfiles; dependency scanners as sensors |
Live demo · attack simulator
Turn defences on and off and see which attacks still succeed against a coding agent. Prompt-level defences reduce the odds; only environment-level ones make an attack impossible.
Skipping all permission checks is reasonable inside a disposable container with no secrets and limited network. On a developer laptop with cloud credentials, SSH keys and a browser session, it turns any prompt injection into an incident.
Hardening checklist
Sandboxes, credentials, approvals and audit.
Sandbox baseline for unattended agents sandbox
- Fresh container or microVM per run, destroyed after.
- No host mounts except the worktree; no Docker socket.
- Egress allow-list; DNS restricted; no cloud metadata endpoint.
- CPU, memory, disk and time limits.
- Non-root user; read-only base image.
Credentials: scoped, short-lived, outside identity
Give the agent its own identity with the least permissions the task needs, short-lived tokens, and per-run scopes. Better still, keep tokens in a proxy the sandbox calls, so code in the sandbox never sees them. Log every use against the run ID.
Approvals that mean something people
Ask only for irreversible, external or unusual actions; show the exact effect; never batch-approve. Record who approved what in the session log (responsibility 11 in Ch 3).
Further reading sources
OWASP's Top 10 for Agentic Applications and the security chapter of the Agents Guide cover prompt injection, tool misuse, identity and design patterns like CaMeL in depth.
Observability: seeing what the harness did
You improve a harness by reading what happened. Trace every model call, tool call, hook decision and sensor result, tagged with the harness version, model and cost. When a run fails, record which part failed: the model's judgement, a missing tool, a misleading guide, a weak sensor, the environment. That attribution is your harness backlog.
What to record for every run
| Event | Fields | Used for |
|---|---|---|
| Run start | Run ID, task, trigger, user, harness version (git SHA of the harness and of AGENTS.md/skills), model and settings | Comparing versions; reproducing runs |
| Model call | Input/output/cached tokens, latency, effort level, stop reason | Cost, cache hit rate, slow steps |
| Tool call | Name, arguments (redacted), duration, exit code, output size | Tool reliability; noisy outputs |
| Policy / hook decision | Hook name, decision (allow, deny, ask, modify), reason | Over-blocking; approval fatigue; attacks |
| Sensor result | Check name, pass/fail, findings count | Which sensors catch what; flaky checks |
| Context event | Compaction, reset, clearing; tokens before and after | Context strategy tuning |
| Human event | Approval, correction, takeover, with text | Intervention rate; harness backlog |
| Run end | Outcome, checks status, total cost, steps, duration, failure category | Dashboards and evals |
Failure attribution: whose fault was it?
| Category | Typical evidence in the trace | Harness fix |
|---|---|---|
| Spec gap | Agent built something reasonable that wasn't wanted | Better task template, acceptance criteria, clarifying question tool |
| Missing context | Agent didn't know a convention or file existed | Guide or pointer in AGENTS.md; skill |
| Missing capability | Agent couldn't run, see or query what it needed | New tool, script, or environment access (Ch 8) |
| Weak sensor | Bad change passed all checks | New test, lint rule, structural check, e2e step |
| Premature stop | Claimed done without running checks | Completion gate |
| Loop / stall | Repeated edits or calls without progress | Loop detection, better error messages |
| Context failure | Lost a key fact after compaction; degraded late in run | Pinned notes, earlier reset, sub-agents |
| Environment / infra | Timeouts, flaky tests, sandbox crashes | Infra fixes, retries, flake quarantine |
| Model judgement | Had everything it needed and still chose badly | Higher effort, stronger model, evaluator, or accept |
Zhong and Zhu propose packaging each run as an auditable episode package: the patch plus reproduction logs, failure attribution, deterministic requirement checks and a structured verification report. Even if you don't adopt the format, the idea is right: a run should leave enough evidence that a reviewer can trust or reject it without re-doing the work.
- opentelemetry-sdkSpans for model calls, tool calls and hook decisions.
- openinference / OpenLLMetry instrumentorsAuto-instrument provider SDKs.
- structlogStructured logs with run IDs.
from opentelemetry import trace
tracer = trace.get_tracer("harness")
def traced_tool(call, run):
with tracer.start_as_current_span("tool." + call.name) as span:
span.set_attributes({"run.id": run.id, "harness.version": run.harness_version,
"guides.sha": run.guides_sha, "gen_ai.request.model": run.model})
decision = run.policy.check(call)
span.set_attribute("harness.decision", decision.kind)
result = run.env.execute(call) if decision.allow else decision.as_tool_error()
span.set_attribute("tool.output_bytes", len(result))
return result- Azure Monitor / Application InsightsOTel ingestion and dashboards.
- Foundry tracingAgent traces in the Foundry portal.
- AgentCore Observability · CloudWatchAgent traces and metrics.
- X-RayDistributed tracing.
- Cloud Trace · Cloud LoggingOTel traces and logs.
- Vertex AI Agent Engine tracingBuilt-in agent traces.
- Langfuse · Arize Phoenix · OpenLITLLM-focused tracing UIs.
- Jaeger · Grafana TempoGeneral OTel trace stores.
- OpenTelemetry GenAI semantic conventionsShared attribute names.
Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.
Dashboards and traces
The handful of charts that matter.
The harness dashboard metrics
- Success rate and pass^k by task type and harness version.
- Cost per success; tokens per run; cache hit rate.
- Premature-done rate; loop-nudge rate; policy denials per run.
- Approval rate and time-to-approve.
- Failure categories over time (the table above), stacked.
- p50/p95 duration and steps.
Agents as trace readers analysis
Traces are long. Have analysis agents read failed runs and fill in the failure category and a suggested harness change, then have humans review the aggregate weekly. This is how LangChain ran its improvement loop, and it scales far better than humans reading every trace.
Privacy in traces security
Traces contain code, data and sometimes secrets that leaked into tool output. Redact at capture, scope access by tenant, set retention limits, and never send production traces to a third-party analysis tool without approval.
System design: a harness platform
At platform scale, split the harness into parts that fail and scale independently: a durable session log, stateless harness workers (the brain), a sandbox pool (the hands), a tool gateway with policy and a credential vault, a harness registry of versioned configurations, and an evaluation and trace pipeline. Keep the interfaces small and stable; everything behind them can change as models do.
Reference architecture
The small, stable interfaces
| Interface | Shape | Why it's stable |
|---|---|---|
| Session | emitEvent(run, event), getEvents(run, range) | Any context strategy can be built on a full event history |
| Harness | wake(run) → resume from the last event | Workers can crash, scale and upgrade freely |
| Sandbox | provision(resources), execute(name, input) → string | Container, VM, browser or phone look the same to the brain |
| Tools | MCP or one gateway API with policy and audit | Tools change; the gate doesn't |
| Config | Versioned harness bundle: prompts, guides, skills, hooks, tools, model, limits | Every run is reproducible by version |
These follow Anthropic's Managed Agents design, which it calls a "meta-harness": opinionated about the interface shapes, neutral about the harness that runs behind them. The same platform can host a coding harness, a research harness, or one that doesn't exist yet.
Key decisions
Harness versions are deployments
A change to AGENTS.md, a skill, a hook or a model setting can change behaviour as much as code. Version the bundle, run evals in CI, release to a canary share of runs, and roll back automatically if success or cost moves the wrong way.
Paved road, local overrides
The platform ships a default harness (sandbox, policy, sensors, tracing) per task type. Teams add repo-level guides and sensors. Security-critical layers can't be overridden.
Resume, don't restart
Runs last hours. Workers will crash and deploys will happen. Because state is in the log, any worker resumes any run. Tools must be idempotent or keyed so replays don't double-apply writes.
Start sandboxes lazily
Many runs think before they act. Provisioning only when a tool is first needed cut Anthropic's p50 time-to-first-token by about 60% and p95 by over 90%.
Cost and latency engineering
Harnesses add cost (evaluator rounds, verification, sub-agents) and save cost (fewer failed runs, fewer human hours). Judge them by cost per successful task, not cost per run. The cheapest wins: computational sensors before inferential ones, quiet tool output, a stable cached prefix, and spending reasoning effort only where it changes outcomes.
Live demo · cost per successful task
Input tokens grow each step: total ≈ steps × base + added × steps × (steps − 1) ÷ 2. Cache reads billed at 0.1× input; write premium ignored.
The levers
| Lever | Effect | Trade-off |
|---|---|---|
| Stable prefix + prompt caching | 50–90% off repeated input; faster first token | Discipline about context order; resets break the cache |
| Quiet sensors and capped tool output | Thousands of tokens saved per run; clearer next steps | Wrapper scripts to maintain |
| Computational sensors first | Milliseconds and near-zero cost vs seconds and tokens | Can't judge semantics |
| Completion gate | Fewer failed runs and re-runs; raises success rate | Adds a check cycle per run |
| Effort by phase | Thinking spent on planning and verifying, not routine edits | Needs phase detection |
| Evaluator only where needed | Avoids 20× runs on tasks the model already does | Requires measuring per task type |
| Sub-agents for exploration | Main context stays small, so every later step is cheaper | Extra tokens for the child |
| Smaller model for sub-tasks | Search, summarising and log reading at a fraction of the price | Quality risk on misrouted steps |
| Batch / off-peak for background work | Often ~50% cheaper | Hours of latency |
Where time goes
Model calls
1–20 s each with thinking. Usually the largest share of wall-clock.
Sensors
Seconds for lint and types; minutes for full suites. Run the relevant subset in the loop.
Environment
Sandbox start, dependency install, app boot. Snapshot images; start lazily.
Humans
Approvals and reviews. Often hours. Reduce prompts; batch review at the end.
Scaling a harness from 1 user to 1,000,000
For one developer, a harness is a few files in a repo. For a team, it's shared code with an owner. For a company, it's a platform with paved roads and versioned releases. For a million users of an agent product, it's a fleet: sandboxes, policy, tenancy, evaluation and cost control at scale. "Users" here are people whose agents run on your harness, each starting a few runs a day.
Pick a stage
The failure catalog: every harness problem
Each entry has a symptom, root cause and fix, tagged by area and severity. Click a cell in the heat map, filter by severity, or search for a word from your bug report. Copy the filtered list as Markdown for a backlog.
Every trade-off, side by side
Each row is a decision with two ends. The marker shows where most teams sit by default in 2026. Move it for your own risk, model, scale and team.
Alternatives to a harness, and what's next
A harness is the right fix for recurring, checkable failures in your context. Some problems are better solved by a stronger model, a fine-tuned model, a plain workflow, or a human. And every harness is partly temporary: models absorb yesterday's scaffolding. The durable parts are your tests, environment, written knowledge and interfaces.
When something else is the better fix
| Alternative | Better when | Worse when |
|---|---|---|
| A stronger model | Failures are judgement or reasoning, and the trace shows the agent had everything it needed | Failures are missing context, missing tools or weak checks; a better model won't see what isn't there |
| Fine-tuning / RL on your tasks | Very high volume of one task type; you have graded trajectories | Tasks change often; you lack evaluation data; harness fixes are cheaper |
| A deterministic workflow | The steps are known; only a few need judgement | The path depends on what the agent discovers |
| Plain scripts and codemods | Mechanical changes at scale | Changes need understanding of intent |
| Humans doing it | Rare, high-stakes, ambiguous work; no way to verify automatically | Repetitive work with clear checks |
| Doing nothing | The mistake is rare and cheap | It recurs: then it's a harness fix (Ch 2) |
The bitter lesson, and why harnesses still matter
Rich Sutton's "bitter lesson" says general methods that scale with compute beat hand-crafted knowledge. Harnesses look like hand-crafted knowledge, and parts of them do get absorbed: context resets, explicit planners and sprint structures have each become unnecessary on newer models. But Anthropic's conclusion after simplifying its harness for Opus 4.6 was that "the space of interesting harness combinations doesn't shrink as models improve". It moves. As models handle longer tasks alone, harnesses take on bigger jobs: running for days, coordinating many agents, operating real systems safely.
Likely to fade
- Rules that compensate for model quirks (context anxiety, early stopping)
- Heavy prompt scaffolding for planning and reflection
- Fixed sprint and step structures
- Loop detection as a separate middleware
Likely to last
- Tests, types, structural checks: the sensors are about your system, not the model
- Sandboxes, credentials and policy: security never fades
- Written knowledge in the repo: models can't learn your private context
- Durable state, traces and evaluation
- Stable interfaces between brain, hands and session
What's next
- Harnesses tuned by agentsMeta-Harness-style search and trace-driven improvement loops make harness tuning partly automatic, with humans setting objectives and approving changes.
- Models trained with harnessesAgentic reinforcement learning trains models inside harness-like environments (tools, sandboxes, verifiers), so models increasingly arrive "harness-aware". The line between harness and model training environment blurs.
- Portable harness standardsAGENTS.md, Agent Skills and MCP already move between products. Expect shared conventions for hooks, permission policy and harness bundles. (Prediction; watch the Agentic AI Foundation.)
- Harness coverage toolsWays to measure what a harness checks, like test coverage for tests, are an open problem named by Böckeler and others.
- The behaviour harnessChecking that software does what users meant, beyond agent-written tests, is the least solved part, and where much of the next wave of work will go.
Items 3–5 are forecasts, not facts. Check current sources before relying on them.
Production checklist, glossary and sources
Tick items as you go. Progress is saved in this browser only.
Glossary
| Term | Definition |
|---|---|
| ACI | Agent-computer interface: the commands, tools and views designed for an agent to work through. |
| AGENTS.md | An open, plain-Markdown format for project instructions to coding agents, stewarded by the Agentic AI Foundation. |
| Agent Skills (SKILL.md) | An open format for folders of instructions, scripts and references that an agent loads when relevant. |
| Ablation | Removing one harness component at a time to measure what it contributes. |
| Ambient affordances | Properties of a stack (types, boundaries, fast tests) that make it easier to harness. |
| Backpressure | Feedback that pushes back on wrong work; ideally quiet on success and precise on failure. |
| Blueprint | A workflow in code that mixes deterministic steps with agent steps (Stripe's term). |
| Completion gate | A check the harness runs before allowing the agent to finish. |
| Compaction | Summarising earlier history in place so the same agent can continue. |
| Computational control | A deterministic, code-based guide or sensor (tests, linters, types). |
| Context anxiety | A model behaviour of rushing to finish as the context window fills. |
| Context reset | Ending a session and starting a fresh agent from a written handoff. |
| Doc gardening | Recurring agent work that finds and fixes documentation that no longer matches the code. |
| Entropy | Gradual drift and inconsistency in a codebase as agents copy patterns. |
| Episode package | A run's patch plus logs, checks, attribution and a verification report. |
| Evaluator | A separate agent that judges another agent's work against criteria. |
| Execution plan | A checked-in, living plan for multi-step work, with progress and decisions. |
| Feature list | A machine-readable list of requirements with test steps and pass flags. |
| Garbage collection (code) | Scheduled clean-up agents that open small PRs to fix drift. |
| Golden principles | Short, opinionated rules for how code should look, enforced by sensors where possible. |
| Guide | A feedforward control that steers the agent before it acts. |
| Harness | Everything in an agent except the model. |
| Harnessability | How easy a system is to put a harness around. |
| Harness template | A bundle of guides and sensors for a common service shape. |
| Hook | Code the harness runs at a lifecycle event to allow, block, modify or add feedback. |
| Inferential control | A model-based guide or sensor (LLM review, judge). |
| Initializer agent | A first session that sets up feature list, init script, progress file and git. |
| Lethal trifecta | Private data + untrusted content + external communication in one agent. |
| Load-bearing | A harness component that still measurably improves results. |
| Meta-harness | A platform neutral about which harness runs, built on stable interfaces; also the name of a paper on automatic harness search. |
| Middleware | A small wrapper around model or tool calls that adds one harness behaviour. |
| Outer harness | What users add around a vendor agent: guides, sensors, hooks, tools, CI. |
| pass^k | Probability that all k repeated runs succeed; a consistency measure. |
| Progressive disclosure | Loading a small map first and details only on demand. |
| Reasoning sandwich | High effort to plan, lower to implement, high to verify. |
| Sensor | A feedback control that checks the agent's work after it acts. |
| Session log | An append-only, durable record of every event in a run. |
| Sprint contract | An agreement between generator and evaluator on what "done" means for a sprint and how to verify it. |
| Structural test | A test of code shape (imports, layering, naming) rather than behaviour. |
Sources and further reading
Defining harness engineering
- OpenAI: Harness engineering: leveraging Codex in an agent-first world (Lopopolo, Feb 2026)
- Böckeler: Harness engineering for coding agent users (martinfowler.com, Apr 2026)
- Mitchell Hashimoto: My AI Adoption Journey (Feb 2026)
- LangChain: Improving Deep Agents with harness engineering (Feb 2026)
- Hugging Face: Harness, scaffold, and the AI agent terms worth getting right (May 2026)
- Thoughtworks podcast: What is harness engineering?
Anthropic engineering
- Effective harnesses for long-running agents (Nov 2025)
- Harness design for long-running application development (Mar 2026)
- Scaling Managed Agents: decoupling the brain from the hands (Apr 2026)
- Effective context engineering for AI agents
- Writing effective tools for agents
- InfoQ: Anthropic's three-agent harness (Apr 2026)
Papers
Practice, standards and ecosystem
- InfoQ: Stripe's autonomous coding agents (minions)
- InfoQ: OpenAI harness engineering with Codex
- HumanLayer: Skill issue: harness engineering for coding agents (Mar 2026); 12-Factor Agents
- Agentic AI Foundation and AGENTS.md · agents.md
- Agent Skills specification
- Simon Willison: The lethal trifecta
- Terminal-Bench · awesome-harness-engineering
Every mistake, once
The Harness Engineering Guide. Written with research current to October 2026. Agents, models and harness features change monthly: check official docs for anything newer, and treat numbers here as starting points. Companion guides: Agents Guide · MCP Guide · RAG Guide.