Harness Engineering GuideMODEL + HARNESS = AGENT
Harness engineering · October 2026

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.

25chapters
6scale stages, 1 → 1M
80+problems with fixes
8live demos
The harness around a model: guides steer the model before it acts, the model acts on the environment through tools, sensors check the result and feed it back. Permissions and budgets surround everything. harness · permissions · budgets · state GuidesAGENTS.md, skills,plans, docs Modeldecides the nextaction Environmenttools, sandbox,repo, app Sensorstests, lint, judges Session logstate outside the model feedback → next attempt

Pick where you are starting

Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.

ChapterFoundations

What harness engineering actually is

In one line

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

Harness engineering · 2026 → the whole system: loop, tools, sandbox, permissions, hooks, sensors, state, entropy control, human steering Context engineering · 2025 what the model sees on each step: retrieval, memory, tool results, compaction Prompt engineering · 2022 the words of one request: role, task, examples, format "What should it read?" the right tokens, at the right time, in a finite window "What stops it failing the same way twice?" deterministic checks and gates state that survives sessions a sandbox it can't escape feedback written for the model fixes that are permanent

Prompt, context and harness engineering compared

AspectPrompt engineeringContext engineeringHarness engineering
Question it answersHow 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 workOne promptOne context windowA run, a session, a project, a fleet of agents
Main artifactsPrompt templates, examplesRetrieval, memory, compaction, tool resultsAGENTS.md, skills, hooks, linters, tests, sandboxes, permission policy, progress files, traces
How it fixes a mistakeReword and hopeGive better informationMake the mistake impossible or caught automatically, forever
Mostly deterministic?NoPartlyAs much as possible: code, not prose, enforces the rules
Who does itAnyone writing promptsAgent and RAG buildersAgent 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

You write the loop

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.

You configure the loop

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

The rule

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

TermPlain meaningChapter
HarnessEverything in an agent except the model. Some authors use it more narrowly for the execution loop only.1, 3
Outer harnessWhat 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 inferentialDeterministic code checks (fast, cheap, certain) vs model-based checks (semantic, slower, probabilistic).3, 6
BackpressureFeedback that pushes back on the agent when its work is wrong, ideally quiet on success and specific on failure.6
HookYour 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 resetSummarising history in place / starting a fresh agent from a written handoff.7
Session logAn append-only record of everything that happened in a run, stored outside the model and the harness process.7, 19
HarnessabilityHow easy a codebase or system is to put a harness around: types, clear boundaries, fast tests, runnable locally.8
Entropy / garbage collectionThe slow drift of a codebase as agents copy patterns, and the recurring clean-up work that counters it.12
Load-bearing componentA harness part that still improves results with today's model. Others are dead weight to remove.16, 24
Deep dive

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.

ChapterFoundationsDecision

How much harness you need, and when to stop adding

Rule of thumb

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

Will this task (or kind of task) repeat? noyes H0 · just askchat or one agent session, read the output Does a human watch every step?pair-programming style yesno H1–H2 · guides + fast sensorsAGENTS.md, lint, types, tests in the loop Runs for more thanone context window? noyes H3 · + hooks, permissions, gatesdeterministic stop rules, sandbox, approvals H4 · + stateprogress, plans, resets Many teams or products? → H5 · platform (Ch 19)

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

value of a harness fix per month ≈ (failures prevented per month × cost of each failure) − (build cost ÷ months of life) − running cost
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

  1. 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.
  2. 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.
  3. 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).
  4. 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).
  5. 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).
  6. 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).
Harness assumptions expire

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.

ChapterFoundationsBuilder

Anatomy of a harness

The shape

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

Human steeringintent, review, harness changes harness Guidessystem promptAGENTS.md + docs/skills · examplesspecs · planstool descriptionscodemods · LSP hints Control loop Model context assemblytool dispatchbudgets · stop rulesloop detectioncompaction · retries sub-agentsreasoning effort permissions · hooks · policy Environmenttools · MCP serverssandbox / containerrepo, worktree, applogs · metrics · browsersecrets via proxy Sensors → feedback to the model State outside the modelsession log · progress file · feature list · git history · memory Observabilitytraces · cost · failure attribution · harness version · evals

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 actionTemplates and scaffolding generators, codemods, type definitions, LSP code intelligence, a make check script the agent is told to runAGENTS.md conventions, skills, design docs, examples, an approved plan, a spec
Sensors · after the actionCompilers, type checkers, linters, unit and integration tests, structural / architecture tests, mutation tests, security scannersLLM code review, LLM-as-judge on output, a separate evaluator agent driving a browser, sampled quality checks in production
Speed and costMilliseconds to minutes; near-zero cost; same answer every timeSeconds to minutes; costs tokens; can be wrong or inconsistent
Use it forAnything you can state as a ruleJudgement: design quality, intent, readability, "does this match the spec?"
Why both directions

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

Heartbeat

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

Feedforward

Guides

Instructions, docs, skills, examples and plans that raise the odds of a good first attempt. Loaded progressively, not all at once. Ch 5

Feedback

Sensors

Checks that run after actions and return messages written for the model: what failed, where, and how to fix it. Ch 6

Memory

Context and state

What the model sees each step, plus durable state outside it: session log, progress notes, task lists, git. Ch 7

Hands

Environment

Tools, MCP servers, a sandbox, a worktree, the running app, logs, a browser. What the agent can see and do. Ch 8

Seatbelt

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

Coordination

Orchestration

Sub-agents, parallel workers, planner and evaluator roles, deterministic workflow nodes. Ch 11

Hygiene

Entropy control

Recurring clean-up agents, doc gardening and drift sensors that stop the codebase degrading as agents copy patterns. Ch 12

Eyes

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.

#ResponsibilityQuestion it answersTypical artifact
1Task specificationWhat exactly must be done, and what counts as done?Issue template, spec, feature list JSON, acceptance criteria
2Context selectionWhat does the model need to see now?AGENTS.md map, retrieval, skills, compaction
3Tool accessWhat can it do, through which interface?Tool set, MCP servers, CLI wrappers
4Project memoryWhat has the team learned that persists?Docs, decision records, instructions file history
5Task stateWhere is this run up to?Progress file, plan with checkboxes, session log
6ObservabilityWhat is the system doing right now?Logs, metrics, traces available to the agent and humans
7Failure attributionWhen it fails, which part caused it?Trace tags, error taxonomy, failure reports
8VerificationIs the result actually correct?Tests, linters, e2e checks, evaluator
9PermissionsWhat is it allowed to touch?Allow/deny rules, sandbox, scoped credentials
10Entropy auditingIs the codebase drifting?Drift scans, clean-up agents, quality dashboards
11Intervention recordingWhen 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.

Deep dive

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.

ChapterBuilderFoundations

The control loop: budgets, gates and stop rules

The core idea

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.

python · a harness loop with interception points
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 → nudge

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

    ConditionTypeWhat the harness does
    Model says doneRequest, not finalRun the completion gate: required checks passed? spec items ticked? diff non-empty? If not, return the reason and continue.
    Step budget hitHardStop, write a handoff note (what's done, what's left, what was tried), save state.
    Time budget hitHard, with warningWarn at 70–80% ("you have 10 minutes: finish and verify"); stop at 100%.
    Cost budget hitHardSame as steps. Per-run and per-tenant limits.
    Loop detectedSoftInject a nudge: "You've edited dates.py 6 times. Step back and reconsider." Escalate to stop after N nudges.
    No progressSoftNo new files, no new passing checks for K steps → nudge, then hand off.
    Blocked by policy repeatedlyHardStop and ask a human: the task probably needs a permission it shouldn't have alone.
    Needs informationAgent-initiatedAn 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.

    Plan

    High effort

    Understand the task, explore, decide an approach. Mistakes here cascade, so thinking is cheap insurance.

    Implement

    Medium–high effort

    Routine edits and tool calls. Lower effort keeps steps fast; sensors catch slips.

    Verify

    High effort

    Re-read the spec, run checks, compare against intent. This is where "looks fine" becomes "is fine".

    Implement it withThe control loopBudgets, stop rules, loop detection and effort by phase
    run stops when steps ≥ S or tokens·price ≥ $B or t ≥ T  ·  loop flag when edits(file) ≥ k without a new passing check
    • 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.
    python / config
    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

    Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

    Deep dive

    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.

    ChapterBuilderFoundations

    Guides: steering before the agent acts

    Key insight

    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

    Tier 1 · always loadedevery call, so keep it tiny • vendor system prompt• root AGENTS.md (~100 lines)• skill names + one-liners• tool names + descriptions ≈ 2–8k tokenscached prefix Tier 2 · loaded on matchwhen the task touches it • folder-level AGENTS.md• full SKILL.md + scripts• architecture doc for a layer• the coding standard for a language ≈ 1–10k per itemread by the agent Tier 3 · fetched as neededby search or explicit pointer • product spec, exec plan• API references, runbooks• code search, LSP lookups• past decisions (ADRs) unboundedonly the slice it needs

    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 check beats "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 through scripts/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.
    markdown · a root AGENTS.md that works as a map
    # 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

      GuideWhat it isBest forWatch 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.mdNested files that apply when the agent works in that folderMonorepos; different languages or rules per areaConflicts between levels; say which wins
      Specs and feature listsWhat to build and how to verify each item, ideally machine-readableLong runs; preventing "declared done too early"Vague acceptance criteria give sensors nothing to check
      Execution plansA checked-in plan with steps, decisions and progressMulti-session work; handoffs between agents and peoplePlans go stale; make updating them part of done
      Examples and templatesA reference implementation the agent copiesConsistency: "new services look like services/billing"Agents copy bad examples just as faithfully
      Generators and codemodsScripts that create correct scaffolding or apply mechanical changesAnything with lots of boilerplate; large refactorsNeed maintenance like any code
      Code intelligence (LSP)Go-to-definition, find-references, type info as toolsLarge codebases; safe renamesSetup per language; slow on huge repos
      Tool descriptionsThe "use this when…" text on each toolGetting the right tool chosenEvery description costs tokens on every call
      Deep dive

      Writing guides that work

      Tokens, instruction limits, conflicts and maintenance.

      What instructions cost, every single call tokens
      guide tokens per run ≈ always-loaded tokens × model calls
      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.

      ChapterBuilderArchitect

      Sensors: feedback the agent can use

      Key insight

      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#dates

      Silent on what passed, precise on what failed, includes the fix and the rule. ~80 tokens.

      Context-efficient backpressure

      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

      StageSensorsLatency budgetWho acts on it
      After every edit (in the loop)Formatter, type check on changed files, fast lint, the one relevant test< 5–10 sThe agent, immediately
      Before stopping (completion gate)Full fast suite, structural tests, spec checklist, e2e smoke via browser< 2–5 minThe agent, before it may finish
      Pre-commit / pre-pushSame checks, enforced by git hooks so nothing skips them< 5 minThe agent or human committing
      CI after integrationFull tests, mutation testing, security scans, broader architecture checks, LLM review10–60 minAgent fix-up runs, human reviewers
      Continuous, outside changesDead code, dependency drift, doc staleness, test-quality analysisDaily / weeklyClean-up agents (Ch 12)
      RuntimeSLO monitors, error rates, sampled LLM judges on outputs, log anomaliesContinuousOn-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.

      –first-attempt success
      –shipped correct
      –bad work that ships unnoticed
      –relative cost per task

      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.
      Implement it withSensors and checksFast deterministic checks, structural tests, judges
      combined catch rate C = 1 − Π(1 − cᵢ) over independent sensors  ·  escaped defects ≈ (1 − p₁)·(1 − C)
      • 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.
      python / config
      # .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

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      ChapterBuilderArchitect

      Context and state: memory that outlives the window

      Key insight

      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

      StrategyHow it worksStrengthWeaknessUse when
      Tool-result clearingReplace old, bulky tool outputs with a stub ("file read, 340 lines; re-read if needed")Cheap, safe, keeps reasoning intactAgent may re-read filesAlways; first line of defence
      CompactionSummarise earlier history in place; same agent continuesContinuity; automatic in most SDKsLossy; no clean slate; summary drift over many roundsMedium tasks; models without context anxiety
      Context reset + handoffEnd the session; a fresh agent starts from a structured handoff artifactClean slate; forces good notesHandoff must be complete; extra latency and tokensMulti-hour work; models that rush near the limit
      Sub-agent isolationDelegate a search or analysis to a child agent; only its summary returnsKeeps the main window clean; parallelChild lacks parent context; summaries can drop detailsResearch, 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.

      –peak fill
      –input tokens across the run
      –compactions / resets
      –steps in the degraded zone

      The state files that make sessions resumable

      What to build

      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}
      What happened

      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 bug
      How to start

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

      Checkpoints

      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.

      Implement it withContext management and stateClearing, compaction, resets and durable state
      input tokens per run ≈ Σₛ (P + hₛ) where hₛ grows by Δ per step  →  ≈ S·P + Δ·S(S−1)/2 without management
      • 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.
      python / config
      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

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      ChapterBuilderArchitect

      Environment, tools and agent legibility

      Key insight

      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

      CapabilityWhy it mattersHow
      IsolationParallel agents don't collide; mistakes stay containedGit worktrees, containers, microVMs (Firecracker, gVisor), hosted sandboxes
      One-command startNo tokens wasted working out setupscripts/dev, devcontainer, Docker Compose, seed data
      Fast targeted testsTight feedback inside the loopRun one test by name in seconds; test selection by changed files
      Logs, metrics, tracesDebugging by evidence, not guessingLocal or per-sandbox observability; query tools (LogQL, PromQL, SQL)
      A browserVerify UI and flows as a user wouldPlaywright or Puppeteer MCP, Chrome DevTools Protocol, screenshot tools
      Data access, safelyReproduce bugs with realistic dataRead-only replicas, anonymised snapshots, fixtures
      Knowledge in the repoDecisions the agent can readdocs/, 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_checks instead of lint, typecheck, test separately, 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.

      AffordanceActs asLow harnessabilityHigh harnessability
      Static typesFree sensor on every editUntyped dynamic codeTypeScript strict, mypy strict, Rust, Kotlin
      Module boundariesEnables structural rulesEverything imports everythingLayers, packages, enforced interfaces
      Opinionated frameworkRemoves decisionsHand-rolled plumbingRails, Django, Spring, Next.js conventions
      Test speedTight loops40-minute suite, no selectionSeconds for the relevant subset
      Local runnabilityAgent can verify itselfOnly works in shared stagingBoots in a sandbox with one command
      Written knowledgeGuides exist to point toTribal knowledgeDocs, ADRs, runbooks in the repo
      Implement it withSandboxes and agent-legible environmentsIsolation, one-command boot, observability, browsers
      blast radius ≈ (what code can reach) × (credentials inside) × (network egress)  ·  aim for each factor near zero
      • docker (SDK)Start a container per run with resource limits.
      • e2b · daytona · modalHosted sandboxes from Python.
      • playwrightBrowser tool for verification.
      python / config
      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)

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      ChapterBuilderArchitect

      Permissions, hooks and policy: rules that can't be talked around

      Key insight

      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

      session startload map,run init prompt submitadd context,block secrets before toolallow / deny /rewrite / ask permission askauto-decide orroute to human after toolformat, lint,typecheck → feedback before compactsave notes,pin key facts before stopcompletion gate:checks passed? session endcommit, progressnote, metrics exact event names vary: e.g. SessionStart, UserPromptSubmit, PreToolUse, PermissionRequest, PostToolUse, PreCompact, SubagentStop, Stop, SessionEnd in Claude Code
      python · a before-tool hook that blocks risky shell commands
      #!/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

      ModeHow it behavesGood forRisk
      Ask every timeHuman approves each write or commandFirst days with a new agent; production systemsApproval fatigue: people stop reading
      Allow-listKnown-safe commands run freely (make check, git status, reads); others askDaily developmentOver-broad patterns (Bash(*)) defeat it
      Auto with classifierA model or rules engine decides low-risk actions; escalates the restLong unattended runs with a human on callClassifier can be fooled; log every decision
      Full auto in a sandboxAnything goes inside an isolated, disposable environment with no secrets and limited networkBackground agents, CI agents, benchmarksOnly as safe as the sandbox boundary
      Full auto on a real machineNo checks, real credentialsNothingOne 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.

      Implement it withHooks and policyDeterministic rules before and after actions
      decision = first match of (deny rules → policy engine → mode default)  ·  then the sandbox limits whatever runs
      • 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.
      python / config
      # 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 }

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

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

      ChapterBuilderArchitect

      Long-running harnesses: hours, not minutes

      The patterns

      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

      Initializerspec → feature listwrite init.shprogress filefirst git commit every worker session (same routine, repeated until all features pass) 1 · Orientpwd, git log,progress file,feature list 2 · Smoke testinit.sh, basice2e check: fixleftovers first 3 · One featurepick highestpriority failingitem only 4 · Verifyas a user, viabrowser; thenflip "passes" 5 · Leave cleancommit withmessage, updateprogress notes
      Failure it preventsInitializer doesEach worker session does
      Declares the whole project done too earlyWrites a structured feature list from the specReads the list; works on one failing item
      Leaves the environment broken or undocumentedCreates git repo and progress notesReads notes and log, smoke-tests first, ends with commit and update
      Marks features done without checkingWrites test steps per featureVerifies end to end before flipping passes
      Wastes time working out how to run the appWrites init.shRuns 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.

      Expand

      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.

      Build

      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.

      Judge

      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)DurationCostResult
      Retro game maker, single agent (Opus 4.5)20 min$9Core play mode didn't respond to input
      Same task, full 3-agent harness with sprints6 h$200Playable, with rough physics. Over 20× the cost
      Music app (DAW), simplified harness on Opus 4.6: planner + 3 build/QA rounds3 h 50 min$124.70Sprints 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

      PatternHow it worksUse whenRisk
      "Ralph" loopRun 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 itemLarge backlogs of similar, checkable workBurns money if checks are weak; needs a stop condition
      Execution plans in the repoA 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 peoplePlans go stale unless updating them is part of done
      Research → plan → implementSeparate 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 approveSlower; human review becomes the bottleneck
      Durable workflow + agent stepsA workflow engine (Temporal, Step Functions, LangGraph) checkpoints every step; agents run inside stepsBusiness processes, approvals that take daysMore infrastructure
      Is the evaluator worth it?

      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.

      Deep dive

      Running long jobs well

      Prompts, criteria, and what goes wrong over hours.

      The worker session prompt, in outline prompt
      1. You are continuing a project. Run pwd, read progress.md, git log -20 and features.json.
      2. Run ./init.sh and the smoke test. If anything is broken, fix that first.
      3. Choose the single highest-priority feature with "passes": false.
      4. Implement it. Verify it end to end with the browser tool exactly as the test steps say.
      5. Only then set "passes": true. Never edit or delete other items or tests.
      6. 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).

      ChapterArchitectBuilder

      Orchestration: sub-agents, parallel work and blueprints

      Key insight

      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

      Triggerticket, Slack, alert Set up envworktree, deps Agent: implementskills + guidesin the sandbox Lint + testsdeterministic Agent: fix-upmax 2 rounds Open PRtemplate, labels Human reviewmerge or comment Escalatestill failing → human pass fail rectangles in blue = agent nodes · others = plain code

      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

      PatternWhat it buysWhat it costsUse when
      Explorer sub-agentMain context stays clean; only a summary returnsExtra tokens; details lost in summarySearching a large codebase, reading docs, investigating logs
      Parallel workers in worktreesWall-clock speed; independent attemptsMerge conflicts; N× tokens; review loadIndependent tickets; trying 3 approaches and keeping the best
      Author + reviewerFresh eyes; catches self-grading biasOne more pass per changeAny change that ships; agent-to-agent review before human review
      Planner + executorPlan visible and approvable; cheaper executorPlans go staleLarge changes, migrations
      Specialist agents (security, perf, docs)Focused prompts and toolsCoordination, overlapping findingsReview stages with distinct checklists
      Blueprint / workflowPredictable, auditable, cheap fixed stepsUpfront design; less flexibleRepeated task types at volume
      Default to one agent

      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.

      Deep dive

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

      ChapterArchitectBuilder

      Entropy: keeping an agent-written codebase healthy

      Key insight

      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

      highlow weeks of agent work → no clean-up: drift compounds weekly GC agents + drift sensors illustrative shape, not measured data

      The entropy toolkit

      ToolWhat it doesCadence
      Golden principles docShort, opinionated rules for how code should look ("one way to do HTTP clients", "validate at the edge"), linked from AGENTS.mdUpdated when a new pattern is agreed
      Promote principles to sensorsEvery principle that can be a lint rule or structural test becomes oneAs soon as it's stable
      Drift scansDuplicate code, dead code, dependency age, complexity hot spots, inconsistent patternsDaily or weekly
      Clean-up agentsPick the top findings and open small, single-purpose PRsWeekly, with a cap on open PRs
      Doc gardeningCompare docs to code; flag or fix stale sections and broken linksWeekly
      Harness gardeningFind contradictory or obsolete rules in AGENTS.md and skills; remove rules for deleted codeMonthly and on model upgrades
      Quality gradesA score per module or layer tracked over time, visible to the teamContinuous

      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.

      Deep dive

      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.

      ChapterEveryoneBuilder

      Every harness component, compared

      How to use this

      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.

      ChapterBuilderArchitect

      Harness platforms and frameworks, compared

      The landscape

      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.

      Snapshot · October 2026

      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)

      AgentInstructionsExtension pointsIsolationHeadless / CI
      Claude Code (Anthropic)CLAUDE.md, nested; can import other filesSkills, hooks on many lifecycle events, sub-agents, MCP, plugins, permission rulesPermission modes; OS-level sandbox for shell; containersNon-interactive mode, GitHub Actions, Agent SDK
      OpenAI Codex (CLI, IDE, cloud)AGENTS.md, nestedSkills, MCP, config profiles; check docs for hooksOS sandbox locally (Seatbelt, Landlock); cloud containerscodex exec, cloud tasks, SDK
      GitHub Copilot coding agentcopilot-instructions.md, AGENTS.mdSkills, custom agents, MCP, setup steps workflowRuns in a GitHub Actions environment with a firewallNative: assign an issue, get a PR
      Gemini CLI (Google)GEMINI.md (configurable name)Extensions, MCP, skills, custom commandsOptional sandbox (container or OS profile)Non-interactive mode, GitHub Actions
      Cursor agentRules files, AGENTS.mdRules, MCP, background agents, hooksLocal; background agents in remote VMsBackground agents, CLI
      Open source: OpenHands, Goose, Aider, Cline and othersVaries; most read AGENTS.mdFull source: change the loop itselfDocker sandboxes (OpenHands); localYes; scriptable

      SDKs and frameworks (you build the inner harness)

      FrameworkHarness featuresBest for
      Claude Agent SDKThe Claude Code harness as a library: tools, compaction, sub-agents, hooks, permissions, skills, MCPAgents that need a proven coding-style harness
      OpenAI Agents SDKAgents, handoffs, guardrails, sessions, tracing; sandbox integrationsMulti-agent apps on OpenAI models
      LangChain deepagents / LangGraphPlanning tool, file system, sub-agents, middleware (loop detection, checklists), durable graphs, LangSmith tracesModel-agnostic harnesses you want to tune and inspect
      Google ADKAgents, workflow agents, tools, sessions and memory, evaluationGemini and Google Cloud deployments
      Microsoft Agent FrameworkAgents and workflows, middleware, checkpointing, OpenTelemetry.NET and Python on Azure
      AWS Strands AgentsModel-driven loop, tools, MCP, multi-agent patternsAWS deployments with AgentCore
      smolagents, PydanticAI, Mastra and othersLightweight loops, code agents, typed toolsSmall, 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

      1. 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.
      2. 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.
      3. Where must code run?Your laptop, your cloud, a customer's VPC? This decides sandbox and hosting options more than features do.
      4. 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.
      5. Keep your outer harness portable.AGENTS.md, SKILL.md, MCP servers and repo scripts work across most tools. Your tests and linters work everywhere.
      ChapterBuilder

      Build a harness end to end

      Two builds

      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

      1. 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.
      2. One command for each jobAdd scripts/setup, scripts/dev, scripts/test-one and make check. Humans benefit too.
      3. Make checks quiet and preciseWrap the test runner and linters so success is one line and failure is only what matters (below).
      4. Turn rules into sensorsLayering → import-linter / dependency-cruiser. Conventions → lint rules with fix messages. Each rule you can encode leaves AGENTS.md.
      5. 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.
      6. Add hooksAfter edits: format and type-check changed files. Before shell commands: deny the dangerous ones. Before stop: require make check to have passed since the last edit.
      7. Set permissionsAllow reads, make check, tests and git status/diff. Ask for installs, network and pushes. Run unattended agents only in a sandbox.
      8. Add state for long work, and CIA docs/exec-plans/ folder and a progress-file convention. CI runs the same make check plus slower sensors, and an agent can be asked to fix CI failures.
      bash · scripts/check: quiet on success, precise on failure
      #!/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
      json · Claude Code style hooks and permissions (.claude/settings.json)
      {
        "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.

      bash · scripts/hooks/require_checks.sh: the completion gate
      #!/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 2

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

      python · harness.py
      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 msgs

      What to add next, in order

      1

      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.

      2

      Context management

      Clear old tool results, then compact or reset near ~60% of the window (Ch 7).

      3

      Tracing

      OpenTelemetry spans per model call and tool call with harness version and cost (Ch 18).

      4

      Real sandbox

      Container or microVM per run, no secrets inside, egress allow-list (Ch 17).

      5

      Eval suite

      30–100 real tasks with checks; run on every harness change (Ch 16).

      6

      Human pause

      An ask_human tool that suspends the run durably and resumes on reply.

      ChapterBuilderArchitect

      Evaluating and improving a harness

      Key insight

      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

      MetricDefinitionWhy
      Task successShare of tasks whose final state passes the checks (tests, environment state)The outcome users care about
      pass^kShare of tasks that succeed in all k repeated runsUsers feel inconsistency more than averages
      Cost per successTotal spend ÷ successful tasksA harness that doubles success at 3× cost may be worse
      Premature-done rateRuns that claimed done but failed checksMeasures your completion gate
      Steps and wall-clockMedian and p95 per taskLatency and timeout risk
      Human interventionsApprovals, corrections, takeovers per taskThe real cost of supervision
      Escaped defectsBugs found after merge in agent-written changesWhat your sensors miss
      pass@k = 1 − (1 − s)k · pass^k = sk  (s = single-run success)
      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.

      BenchmarkWhat it testsNotes
      Terminal-Bench 2.089 hard terminal tasks (ML, debugging, biology, systems) in containersRun with the Harbor framework; leaderboard lists agent + model. A newer version exists; check which one numbers refer to.
      SWE-bench Verified / ProFixing real GitHub issues, checked by testsVerified is near saturation for top agents; Pro is harder and less contaminated
      τ-bench / τ²-benchTool use with simulated users and policiesReports pass^k consistency
      Your own task set30–300 real tasks from your repo or product with automatic checksThe only benchmark that matches your harness and codebase

      The improvement loop

      1. Run the suiteSeveral runs per task, traces saved, harness version tagged.
      2. 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.
      3. Change one thingA prompt line, a middleware, a tool, a sensor. Keep the diff small so the effect is attributable.
      4. Re-run and compareSame tasks, same model, same number of runs. Look at success, pass^k and cost, not only the headline.
      5. 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.

      –task success
      –pass^3 consistency
      –cost per run
      –cost per success

      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.

      Implement it withEvaluating harnessesTask suites, repeated runs, ablation
      pass@k = 1 − (1 − s)ᵏ · pass^k = sᵏ · SE ≈ √(s(1 − s)/n)  ·  cost per success = cost per run ÷ s
      • 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.
      python / config
      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))}

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      ChapterArchitectBuilder

      Security: the harness is the boundary

      Key insight

      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.

      Leg 1

      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.

      Leg 2

      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.

      Leg 3

      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

      VectorExampleDefence
      Instructions files in dependencies or forksA 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 textA public issue includes hidden instructions to add a backdoorRead-only run for untrusted triggers; human review before merge; no secrets in CI agent runs on forks
      Malicious skills or MCP serversA popular skill's script exfiltrates filesPin versions, review code, allow-list sources, run in the sandbox
      Hooks that execute repo contentA hook runs a script the agent just editedHooks live outside the agent-writable area or are protected by permissions
      Sensor gamingThe agent disables a failing test to "finish"Protect test files; diff checks for removed assertions; separate evaluator
      Over-broad allow rulesBash(*) or "approve all for this session"Narrow patterns; deny lists; sandbox for full auto
      Long-term memory poisoningAn injected "lesson" persists into future sessionsReview memory writes; keep lessons in version control
      Supply chain via installsAgent adds a typo-squatted packageAsk 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.

      "Full auto" is a sandbox setting, not a trust setting

      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.

      Deep dive

      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.

      ChapterBuilderArchitect

      Observability: seeing what the harness did

      Key insight

      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

      EventFieldsUsed for
      Run startRun ID, task, trigger, user, harness version (git SHA of the harness and of AGENTS.md/skills), model and settingsComparing versions; reproducing runs
      Model callInput/output/cached tokens, latency, effort level, stop reasonCost, cache hit rate, slow steps
      Tool callName, arguments (redacted), duration, exit code, output sizeTool reliability; noisy outputs
      Policy / hook decisionHook name, decision (allow, deny, ask, modify), reasonOver-blocking; approval fatigue; attacks
      Sensor resultCheck name, pass/fail, findings countWhich sensors catch what; flaky checks
      Context eventCompaction, reset, clearing; tokens before and afterContext strategy tuning
      Human eventApproval, correction, takeover, with textIntervention rate; harness backlog
      Run endOutcome, checks status, total cost, steps, duration, failure categoryDashboards and evals

      Failure attribution: whose fault was it?

      CategoryTypical evidence in the traceHarness fix
      Spec gapAgent built something reasonable that wasn't wantedBetter task template, acceptance criteria, clarifying question tool
      Missing contextAgent didn't know a convention or file existedGuide or pointer in AGENTS.md; skill
      Missing capabilityAgent couldn't run, see or query what it neededNew tool, script, or environment access (Ch 8)
      Weak sensorBad change passed all checksNew test, lint rule, structural check, e2e step
      Premature stopClaimed done without running checksCompletion gate
      Loop / stallRepeated edits or calls without progressLoop detection, better error messages
      Context failureLost a key fact after compaction; degraded late in runPinned notes, earlier reset, sub-agents
      Environment / infraTimeouts, flaky tests, sandbox crashesInfra fixes, retries, flake quarantine
      Model judgementHad everything it needed and still chose badlyHigher 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.

      Implement it withTracing and failure attributionOpenTelemetry spans with harness metadata
      every span carries: run.id · harness.version · guides.sha · model · tokens (in/out/cached) · cost · decision · outcome
      • opentelemetry-sdkSpans for model calls, tool calls and hook decisions.
      • openinference / OpenLLMetry instrumentorsAuto-instrument provider SDKs.
      • structlogStructured logs with run IDs.
      python / config
      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

      Cloud product names and features change often. Treat these as pointers and confirm current availability, regions and pricing in each provider's docs.

      Deep dive

      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.

      ChapterArchitect

      System design: a harness platform

      The design

      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

      TriggersIDE, CLI, Slackissues, alertsschedules (GC)API Run API + queueauth, quotasprioritiesidempotent runs Harness workers (brain)stateless; any workercan resume any runloop · context · budgetshooks · gates · nudgeswake(runId) → replay log Model gatewayrouting, fallback, cache Harness registryversioned configs Session logappend-only events per runemitEvent · getEvents Tool gatewaypolicy enginecredential vault proxyMCP · APIs · audit Sandbox pool(hands)containers,microVMs, browsersprovision on demandreplace, don't repairno secrets inside Evaluation & observability pipelineOTel traces → failure attribution agents → dashboards · eval suites per harness version · canary + rollback · cost attribution per teamdrift sensors and scheduled clean-up runs · approval and intervention logs · security alertspromotes harness versions in the registry when evals pass

      The small, stable interfaces

      InterfaceShapeWhy it's stable
      SessionemitEvent(run, event), getEvents(run, range)Any context strategy can be built on a full event history
      Harnesswake(run) → resume from the last eventWorkers can crash, scale and upgrade freely
      Sandboxprovision(resources), execute(name, input) → stringContainer, VM, browser or phone look the same to the brain
      ToolsMCP or one gateway API with policy and auditTools change; the gate doesn't
      ConfigVersioned harness bundle: prompts, guides, skills, hooks, tools, model, limitsEvery 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%.

      ChapterArchitectBuilder

      Cost and latency engineering

      Key insight

      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

      –cost per run
      –cost per successful task
      –per run without caching
      –per month

      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

      LeverEffectTrade-off
      Stable prefix + prompt caching50–90% off repeated input; faster first tokenDiscipline about context order; resets break the cache
      Quiet sensors and capped tool outputThousands of tokens saved per run; clearer next stepsWrapper scripts to maintain
      Computational sensors firstMilliseconds and near-zero cost vs seconds and tokensCan't judge semantics
      Completion gateFewer failed runs and re-runs; raises success rateAdds a check cycle per run
      Effort by phaseThinking spent on planning and verifying, not routine editsNeeds phase detection
      Evaluator only where neededAvoids 20× runs on tasks the model already doesRequires measuring per task type
      Sub-agents for explorationMain context stays small, so every later step is cheaperExtra tokens for the child
      Smaller model for sub-tasksSearch, summarising and log reading at a fraction of the priceQuality risk on misrouted steps
      Batch / off-peak for background workOften ~50% cheaperHours 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.

      ChapterArchitect

      Scaling a harness from 1 user to 1,000,000

      Pattern

      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

      ChapterArchitectBuilder

      The failure catalog: every harness problem

      How to use this

      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.

      ChapterArchitectBuilder

      Every trade-off, side by side

      Read the dial

      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.

      ChapterEveryoneStrategy

      Alternatives to a harness, and what's next

      The honest view

      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

      AlternativeBetter whenWorse when
      A stronger modelFailures are judgement or reasoning, and the trace shows the agent had everything it neededFailures are missing context, missing tools or weak checks; a better model won't see what isn't there
      Fine-tuning / RL on your tasksVery high volume of one task type; you have graded trajectoriesTasks change often; you lack evaluation data; harness fixes are cheaper
      A deterministic workflowThe steps are known; only a few need judgementThe path depends on what the agent discovers
      Plain scripts and codemodsMechanical changes at scaleChanges need understanding of intent
      Humans doing itRare, high-stakes, ambiguous work; no way to verify automaticallyRepetitive work with clear checks
      Doing nothingThe mistake is rare and cheapIt 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

      1. Harnesses tuned by agentsMeta-Harness-style search and trace-driven improvement loops make harness tuning partly automatic, with humans setting objectives and approving changes.
      2. 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.
      3. 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.)
      4. Harness coverage toolsWays to measure what a harness checks, like test coverage for tests, are an open problem named by Böckeler and others.
      5. 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.

      ChapterEveryone

      Production checklist, glossary and sources

      Tick items as you go. Progress is saved in this browser only.

      Glossary

      TermDefinition
      ACIAgent-computer interface: the commands, tools and views designed for an agent to work through.
      AGENTS.mdAn 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.
      AblationRemoving one harness component at a time to measure what it contributes.
      Ambient affordancesProperties of a stack (types, boundaries, fast tests) that make it easier to harness.
      BackpressureFeedback that pushes back on wrong work; ideally quiet on success and precise on failure.
      BlueprintA workflow in code that mixes deterministic steps with agent steps (Stripe's term).
      Completion gateA check the harness runs before allowing the agent to finish.
      CompactionSummarising earlier history in place so the same agent can continue.
      Computational controlA deterministic, code-based guide or sensor (tests, linters, types).
      Context anxietyA model behaviour of rushing to finish as the context window fills.
      Context resetEnding a session and starting a fresh agent from a written handoff.
      Doc gardeningRecurring agent work that finds and fixes documentation that no longer matches the code.
      EntropyGradual drift and inconsistency in a codebase as agents copy patterns.
      Episode packageA run's patch plus logs, checks, attribution and a verification report.
      EvaluatorA separate agent that judges another agent's work against criteria.
      Execution planA checked-in, living plan for multi-step work, with progress and decisions.
      Feature listA 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 principlesShort, opinionated rules for how code should look, enforced by sensors where possible.
      GuideA feedforward control that steers the agent before it acts.
      HarnessEverything in an agent except the model.
      HarnessabilityHow easy a system is to put a harness around.
      Harness templateA bundle of guides and sensors for a common service shape.
      HookCode the harness runs at a lifecycle event to allow, block, modify or add feedback.
      Inferential controlA model-based guide or sensor (LLM review, judge).
      Initializer agentA first session that sets up feature list, init script, progress file and git.
      Lethal trifectaPrivate data + untrusted content + external communication in one agent.
      Load-bearingA harness component that still measurably improves results.
      Meta-harnessA platform neutral about which harness runs, built on stable interfaces; also the name of a paper on automatic harness search.
      MiddlewareA small wrapper around model or tool calls that adds one harness behaviour.
      Outer harnessWhat users add around a vendor agent: guides, sensors, hooks, tools, CI.
      pass^kProbability that all k repeated runs succeed; a consistency measure.
      Progressive disclosureLoading a small map first and details only on demand.
      Reasoning sandwichHigh effort to plan, lower to implement, high to verify.
      SensorA feedback control that checks the agent's work after it acts.
      Session logAn append-only, durable record of every event in a run.
      Sprint contractAn agreement between generator and evaluator on what "done" means for a sprint and how to verify it.
      Structural testA test of code shape (imports, layering, naming) rather than behaviour.

      Sources and further reading

      The idea behind it all

      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.