Agent Native
Read every book
Harness Engineering
Agent Native·A book for AI engineers

Harness Engineering

If two teams call the same model and get very different agents, the difference is the harness.

13 chapters + appendix·Interactive figures and runnable code·Current to October 2026·Agent Native, 2026

Chapter 1 · The case

The Harness Is What You Ship

One model wired to three harnesses with their Terminal-Bench 2.0 scores

The model is the part of an agent you pick. The harness is the part you build, and it shapes what your agent can do, what it costs and how it fails.

In May 2026, Anthropic was merging roughly 2,500 code changes a day. By September, the company says, it was merging more than 30,000 a day.

The strain moved to everything around the code. Source control, builds, continuous integration and review had all been built for the pace at which people write code, and they became the bottlenecks. When Anthropic wrote about it in October, it said that internally “coding is no longer the bottleneck.”

Anthropic's engineers kept the judgment. The company says they are still the ones who understand how the parts of the system interact and which tradeoffs to make. And they often have to tell Claude “no” when it satisfies the task in front of it by breaking an architectural constraint.

So writing code got cheap. Deciding what to build did not, and neither did keeping the system coherent, proving that a change works or getting it merged. All of that happens around the model, and that is where the harness lives.

A model on its own answers one request and stops. Everything that turns it into an agent is harness: the loop that calls it again, the tools it can reach, what it reads on each turn, the rules about what it may touch, and the checks that decide when the work is done.

That is the part of the agent you control, and it is what you ship.

In under a year, harness engineering has gone from a phrase in a post on X to a job title and a conference track, and the numbers quoted for it have multiplied. Some of those numbers fall apart on a second look.

The ones that hold make a narrower case.

A harness matters most when the model is weaker, the context budget tight or the task long, and it changes what the work costs even where it barely moves the score. By the end of this chapter you'll know how to tell a harness claim that holds from one that doesn't, and how to make every fix to your own agent stay fixed.

Who this book is for and what you will build

We wrote this book for two kinds of engineers. If you build agents, you write a harness. If you run a coding agent such as Claude Code, Codex, OpenCode or Deep Agents on a production codebase, you configure a harness someone else wrote. You do it through instruction files, hooks, permission rules and skills, and through the repository the agent works in.

Section 5 calls these the builder harness and the user harness. We show every mechanism both ways, as code you own and as the Claude Code or Codex configuration that does the same job.

The code you'll build is hx, a small Python package that grows by one module per chapter. Chapter 2 writes the core. You get a run() loop over the Anthropic Messages API, the Tool and State types, and an event log that can rebuild the exact request sent on any turn.

You also get four middleware hooks: before_request, before_tool, after_tool and before_stop. The last three mirror Claude Code's PreToolUse, PostToolUse and Stop events. Each later chapter plugs one module into those hooks, and Chapter 13 assembles them into a background agent that takes an issue to a reviewed pull request, with its unit economics.

It all targets Python 3.11 or later and the anthropic SDK, with claude-sonnet-5-5 as the default model. The chapters follow the subsystem map in section 7:

  • Chapters 1 and 2: the case for the harness, and the loop one turn at a time.
  • Chapters 3 to 5: what the model sees and does, from context through caching, compaction and memory to tools.
  • Chapters 6 and 7: what checks and constrains it, with feedback first, then permissions, sandboxes and the network.
  • Chapters 8 and 9: work across agents and across hours, through orchestration and long-running work.
  • Chapters 10 and 11: the environment and the team, meaning the repository, then review and merge.
  • Chapters 12 and 13: measuring and evolving a harness, then one built end to end. An appendix of sources closes the book.

Section 5 lays a second map over the same chapters: seven control surfaces, the questions every harness has to answer, from what you mean to build to whether your team still understands what it owns.

From this chapter you take away two programs and a habit. first_turn_audit.py measures what a harness spends before the model even reads your task, and ledger.py keeps the failure ledger that later chapters build on. The habit comes from Mitchell Hashimoto, and section 9 puts it to work. When your agent makes a mistake, you change the harness so it can't make that mistake again.

Same model, different scores

The Terminal-Bench 2.0 authors ran each model in several harnesses on the same 89 tasks, with 95% intervals of two to three points. The figure takes GPT-5, Gemini 2.5 Pro and Sonnet 4.5 from the paper, and Opus 4.6 and Haiku 4.5 from the board snapshot of August 28, 2026.

Pick a model to see its rows, then turn on VERIFIED ONLY to hatch the rows the board hasn't verified.

For Opus 4.6, the toggle cuts the spread from 18.4 points to 4.9. Haiku 4.5's only falls from 21.6 to 15.9, so the weaker model keeps most of its spread.

A leaderboard row bundles more than the harness, though. Configuration, infrastructure, trial count and date all come along with it, so the stronger evidence holds the model fixed and changes only the harness.

LangChain did exactly that with its own deepagents-cli. In “Improving Deep Agents with harness engineering”, it describes keeping the model fixed at gpt-5.2-codex and moving from 52.8% to 66.5% on Terminal-Bench 2.0, from just outside the top 30 to the top 5. It sums the whole thing up in one line: “We only changed the harness.”

LangChain counted the reasoning budget as a harness setting, and turning it all the way up hurt. Running at xhigh throughout scored 53.9%, because runs hit timeouts. Running at high throughout scored 63.6%. The final 66.5% came from a “reasoning sandwich” of xhigh, then high, then xhigh.

Sydney Lewis's “Same Model, Different Harness” changed much less. It ran one harness two ways: with the full transcript, and with old tool results mechanically shortened plus stall handling. On SWE-bench Verified at a 20,480-token window, the mean fail-to-pass fraction rose from 28% to 49%.

The abstract reports the effect holding for three more models without retuning, and its conclusion is this book's premise: “coding-agent evaluations should treat the model and harness together as the tested solver.”

Can Bölük changed a single tool. In “The harness problem”, he replaced the patch edit format with “hashline”, which tags every line the model reads so that edits can point at the tags. Hashline beat patch for 14 of 16 models, by 15 points on average.

It took Grok Code Fast 1 from 6.7% to 68.3%, and the whole experiment cost about $300 of benchmarking. Chapter 5 comes back to edit formats.

Agentic Harness Engineering, or AHE, hands the tuning to an agent. Over ten rounds of evaluating, analyzing and improving, about 32 hours with GPT-5.4 held at high effort, it lifted a bash-only seed harness from 69.7% to 77.0% on Terminal-Bench 2. That put it past the hand-built OpenCode, Terminus-2 and Codex harnesses on the same model.

The parts did not add up. Swapped into the seed one at a time, the evolved memory, tools and middleware gain 11.1 points between them, and the evolved system prompt costs 2.3. Yet the whole evolved harness gains 7.3. Components interact, so test the harness you'll run as a whole.

Cline ran the same kind of comparison in production. It moved its VS Code extension, with more than 11 million users, from a roughly 76,000-line monolith to its SDK harness. For over a week it ran the old and new builds near 50/50 behind a feature flag.

By Cline's own count, the share of tasks ending in task.mistake_limit_reached, the stop after three consecutive mistakes, fell from 6.34% to 0.62%.

Cline traces the gain to an assumption that had expired. The 2024 harness parsed XML tool calls out of the text stream, and “Models in 2026 are RL-trained to call tools natively.”

Independent measurement points the same way.

Epoch AI found that switching scaffold on SWE-bench Verified makes a difference of up to 11% for GPT-5 and up to 15% for Kimi K2 Thinking. Its write-up concludes that “The choice of scaffold has the single biggest impact on the overall performance.”

StudyHeld fixedBenchmarkWhat changedResultGrade
LangChain, Feb 2026gpt-5.2-codexTerminal-Bench 2.0, 89 tasksprompt, tools, middleware, reasoning budget52.8% to 66.5%primary; a vendor tuning its own agent
Bölük, Feb 2026each of 16 models180 edit tasks on React files, 3 runsthe edit tool onlyGrok Code Fast 1: 6.7% to 68.3%primary
AHE, Apr 2026GPT-5.4, high effortTerminal-Bench 2, 89 tasksan agent evolves the harness, 10 iterations69.7% to 77.0%primary
Lewis, Aug 2026one model, three more checked169 SWE-bench Verified tasks, 20,480-token windowold tool results trimmed, stall handlingfail-to-pass 28% to 49%primary (abstract)
Fan et al., Sep 2026Nemotron-3 550BSWE-bench Verified, 32k budgetsummarization against no context management6.40% to 58.40%primary
Cline, Sep 2026five production modelsproduction A/B, 11M+ userslegacy harness to SDK harnessmistake-limit stops 6.34% to 0.62%company self-report

These studies measure different things on different scales, so the figure gives each one its own axis, with the starting harness hatched and the changed one in white.

You can switch between the studies to compare them.

How large the effect is, and when it shrinks

Strong models leave a harness less room. Several careful studies find its effect on their success small or absent:

  • METR measured time horizons inside the product harnesses and found that “neither Claude Code nor Codex outperform the default scaffolds METR uses.” For Opus 4.5, Claude Code beat METR's ReAct scaffold in 50.7% of bootstrap samples, a coin flip. For GPT-5, Codex beat Triframe in 14.5%. Neither difference was significant.
  • Scale and Reflection's SWE-Bench Pro V2 harness study ran GLM-5.3, Kimi K3 and Inkling through mini-swe-agent, Pi and OpenCode on 642 tasks under a locked budget. For the strongest models the harnesses came out on par, with one exception, Inkling on Pi. Reflection's advice is “Pick the harness for the bill, not the score.”
  • Arena.ai's HarnessTax study, which we know only secondhand, reports that across 21 model and harness pairs the harness moved success by no more than about 2% on SWE-bench Lite and about 5% on Terminal-Bench 2.0. Cost moved more. On SWE-bench Lite, Claude Code cost about twice as much as Pi.
  • Qwen Code's regression table holds Qwen 3.7 Max fixed across seven harness versions, and its average on SWE-bench Verified stays between 76.40% and 77.80%.

So the effect concentrates where the model has less room: weaker or cheaper models, tight context budgets and long terminal tasks.

You saw that unevenness in the first figure, where Haiku 4.5 kept most of its spread on verified rows. The Terminal-Bench 2.0 paper's own table shows it across models. The spread across harnesses is 15.7 to 16.9 points for GPT-5, Haiku 4.5 and Gemini 2.5 Pro, and only 2.7 to 3.2 points for Sonnet 4.5 and Opus 4.1.

The clearest dose-response comes from Fan and colleagues' empirical study of harness design. They ran a fixed ReAct loop over 176 matched settings and compared them with exact McNemar tests.

At a 32k token budget, context management was worth 35.7 points on SWE-bench Verified. Without it, 78.7% of runs overflowed. At 128k it was worth 2.7, and Terminal-Bench 2.1 shows the same decline.

“Beyond the Model” splits the effect by task. As models improve, it reports, complex harnesses give diminishing gains on SWE-style repair, but they still help stronger models on open-ended repository tasks.

The benchmark moves under the harness, too. Terminal-Bench 2.1 fixed 28 of the 89 tasks, most of them broken by external dependency drift or resource mismatches.

Opus 4.6 in Claude Code rose from 58.0% to 70.1%, the largest gain of any pair, while the same model in Terminus 2 moved from 62.9% to 63.8%. So broken tasks explain part of why Claude Code ranked last among the Opus 4.6 submissions on 2.0. Chapter 12 covers benchmark versions and noise.

Before you quote a leaderboard spread
Meerkat's audit found the top three Terminal-Bench 2 submissions guilty of cheating. It caught a Meta-Harness Opus 4.6 trace that printed “PASS” to fool a verifier, and it argues that harness-level cheating is often “meta” reward hacking by the coding agents that developers use to build their harnesses.

Where success barely moves, cost still does. Whatever a harness sends ahead of your task goes out again on every turn.

Systima compared the first request that Claude Code and OpenCode send on claude-sonnet-4-5. Before the model even saw the task, Claude Code 2.1.207 had sent about 32,800 tokens, from a long system prompt and the schemas of 27 tools. OpenCode 1.17.18 sent about 6,900, with 10 tools.

Claude Code also wrote up to 54 times more cache tokens, and a two-subagent fan-out turned a 121K-token task into 513K tokens.

You can take the same measurement yourself, with two scripts, on any harness that speaks the Anthropic Messages API.

Start the first one and it stands in for the API on localhost, saving every request body your harness sends. Point your harness at it, send one short message, and hand the captures to the second script, which counts what each layer of the largest request costs.

capture_requests.py
python
#!/usr/bin/env python3
"""Record the Messages API requests a harness sends, then refuse them.

1. python capture_requests.py            (listens on 127.0.0.1:8787)
2. In your repository, in a second terminal, start the harness against it:
       ANTHROPIC_BASE_URL=http://127.0.0.1:8787 ENABLE_TOOL_SEARCH=true claude
   and send one short message. The harness reports an API error; that is expected.
3. python first_turn_audit.py captured/

Bodies are saved to captured/NNN.json; headers, which carry your key, never are.
A proxy URL turns Claude Code's MCP tool search off by default, and
ENABLE_TOOL_SEARCH=true keeps MCP tools deferred, as in a direct session.
"""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

OUT = Path("captured")
REFUSAL = json.dumps({"type": "error", "error": {
    "type": "invalid_request_error", "message": "captured by capture_requests.py"}}).encode()


class Capture(BaseHTTPRequestHandler):
    def read_body(self) -> bytes:
        if self.headers.get("transfer-encoding", "").lower() == "chunked":
            body = b""
            while size := int(self.rfile.readline().split(b";")[0].strip() or b"0", 16):
                body += self.rfile.read(size)
                self.rfile.readline()  # CRLF after each chunk
            return body
        return self.rfile.read(int(self.headers.get("content-length", 0)))

    def do_POST(self) -> None:
        body = self.read_body()
        if self.path.split("?")[0].endswith("/v1/messages"):
            OUT.mkdir(exist_ok=True)
            path = OUT / f"{len(list(OUT.glob('*.json'))):03d}.json"
            path.write_bytes(body)
            print(f"saved {path} ({len(body):,} bytes)")
        self.send_response(400)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(REFUSAL)))
        self.end_headers()
        self.wfile.write(REFUSAL)

    def log_message(self, *args) -> None:  # silence the default access log
        pass


HTTPServer(("127.0.0.1", 8787), Capture).serve_forever()
first_turn_audit.py
python
#!/usr/bin/env python3
"""Count what a harness spends on its first request, layer by layer.

    python first_turn_audit.py captured/                  # the largest captured request
    python first_turn_audit.py request.json --model claude-sonnet-4-5 --window 200000

Each layer is counted as the tokens it adds to a one-line request, with the
Messages API token counter (needs ANTHROPIC_API_KEY). Any request body in
Messages API format works: a capture, or what hx's rebuild_request() returns.
"""
import argparse
import json
from pathlib import Path

import anthropic

client = anthropic.Anthropic()
PING = [{"role": "user", "content": "hi"}]


def count(model: str, **parts) -> int:
    parts = {k: v for k, v in parts.items() if v}  # drop empty layers
    parts.setdefault("messages", PING)
    return client.messages.count_tokens(model=model, **parts).input_tokens


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("path", type=Path)
    ap.add_argument("--model", help="defaults to the model named in the request")
    ap.add_argument("--window", type=int, default=200_000)
    args = ap.parse_args()

    files = sorted(args.path.glob("*.json")) if args.path.is_dir() else [args.path]
    req = max((json.loads(f.read_text()) for f in files), key=lambda r: len(r.get("tools", [])))
    model = args.model or req["model"]

    system = req.get("system") or None
    if isinstance(system, list):  # keep the text, drop cache_control and other keys
        system = [{"type": "text", "text": b["text"]} for b in system if b.get("type") == "text"]
    # The counter rejects server tools (web search, tool search); deferred tools are not in the prompt.
    tools = [{k: t[k] for k in ("name", "description", "input_schema") if k in t}
             for t in req.get("tools", []) if "input_schema" in t and not t.get("defer_loading")]
    first = next(m for m in req["messages"] if m["role"] == "user")
    content = first["content"] if isinstance(first["content"], list) else [{"type": "text", "text": first["content"]}]
    blocks = [b["text"] for b in content if b.get("type") == "text" and b["text"].strip()]

    base = count(model)
    rows = [("system prompt", count(model, system=system) - base)] if system else []
    single = [(t["name"], count(model, tools=[t]) - base) for t in tools]
    overhead = 0
    if len(tools) > 1:  # every single-tool count repeats any fixed tool-use preamble
        together = count(model, tools=tools) - base
        overhead = max(0, (sum(n for _, n in single) - together) // (len(tools) - 1))
        rows.append(("tool-use overhead", overhead))
    rows += [(f"tool {name}", n - overhead) for name, n in single]
    for i, text in enumerate(blocks):
        head = text.strip().splitlines()[0][:44]
        rows.append((f"user block {i}: {head}", count(model, messages=[{"role": "user", "content": text}]) - base))

    user = [{"role": "user", "content": [{"type": "text", "text": t} for t in blocks]}] if blocks else PING
    total = count(model, system=system, tools=tools, messages=user)
    width = max((len(name) for name, _ in rows), default=10) + 2
    print(f"{'layer':<{width}}{'tokens':>9}{'share':>8}")
    for name, n in sorted(rows, key=lambda r: -r[1]):
        print(f"{name:<{width}}{n:>9,}{n / total:>8.1%}")
    print(f"{'first request':<{width}}{total:>9,}  {total / args.window:.1%} of a {args.window:,}-token window")
    if skipped := len(req.get("tools", [])) - len(tools):
        print(f"{skipped} server or deferred tools not counted")


if __name__ == "__main__":
    main()

Each row in the output is the tokens one layer adds to a one-line request, so the rows sum to roughly the total. Your CLAUDE.md or AGENTS.md shows up in whichever row the harness puts it.

To compare with Systima's figures, pass --model claude-sonnet-4-5. Their measurement put Claude Code's tool schemas at more than three times the size of its system prompt, so read the tool rows first.

If one row looks heavy, Chapters 3 to 5 cover what to do about it. For shrinking what a long session carries, see our field guide to context compression.

The first build and the tenth change

Every score so far grades an agent on a fresh task. Your software gets built once and then changed for years, so the test that matters for your codebase comes later, when the agent has to change code it wrote itself.

Two research benchmarks look at the two ends of that life. E2E-SWE, released in September 2026, gives agents 186 tasks in 11 languages, each a complete repository to build from a specification. Across the 13 frontier models it tested, pass@1, the share solved on the first attempt, ran from 11.7% to 67.7%. So building from a description is turning into something the best agents can do.

SlopCodeBench looks at the other end. Its latest revision has agents extend software they wrote themselves, again and again, across 36 problems and 196 checkpoints. No agent it evaluated finished a single problem end to end, and the best one passed 14.8% of the checkpoints.

The code also wore down as it grew. By the benchmark's measures, structural erosion showed up in 77% of trajectories, and verbosity grew in 75.5% of them. Set against 473 open-source Python repositories, the agents' code came out substantially more verbose and more structurally eroded.

Switch between FIRST BUILD and LATER CHANGES. The two views come from different benchmarks with different measures, so read each one on its own scale.

We call what piles up in those later changes generation debt. It is code that passes today's request while making the next change harder, and nobody decides to take it on. Technical debt is often taken on knowingly. Generation debt builds while the system looks locally correct and the tests pass, because every turn of the agent optimizes for the request in front of it.

These are research benchmarks with different tasks, so you can't draw one line through them, and neither one is production data. Still, they agree with the “no” that Anthropic's engineers so often have to say. In both, the agent serves the request at hand, and the structure that later requests depend on takes the damage.

So the harness's job runs from the first build to the tenth change, and the tenth change is where we judge it. Chapter 10 measures generation debt in your own repository, and Chapter 12 lays out an eval that takes a system through ten changes and grades every one.

What the word covers: two harnesses and seven questions

“Harness” replaced “scaffold” in about a year.

In January 2025, Anthropic's SWE-bench post defined an agent as “the combination of an AI model and the software scaffolding around it.” By January 2026, its post on evals wrote “agent harness (or scaffold)” and kept that apart from the evaluation harness that runs the tests. And the Claude Code glossary now puts it flatly: “Claude Code is the harness; Claude is the model inside it.”

The definitions in circulation agree on where the model ends and the harness begins, and differ on whether they describe the builder's side or the user's.

SourceIn their wordsSide it describes
LangChain, Vivek Trivedy, Mar 2026“Agent = Model + Harness.” “If you're not the model, you're the harness.” “A harness is every piece of code, configuration, and execution logic that isn't the model itself.”both, written from the builder's side
Anthropic, Lance Martin, Apr 2026“the software scaffolding around a model: the loop, tools, context management, and guardrails”; design is “deciding what belongs in that scaffolding and, as models improve, what you can take out”builder
Claude Code docs, glossary, Oct 2026“The tools, context management, and execution environment that turn a language model into a capable coding agent.”builder
Birgitta Böckeler, martinfowler.com, Apr 2026“everything in an AI agent except the model itself”; three bounded contexts: the model, the coding agent's builder harness, and the user harness as an outer ringnames both
Dex Horthy, HumanLayer, Nov 2025“applying context engineering principles to how you use an existing agent”; the commands, hooks, skills, agents and MCPs a user plugs inuser
Barbaste et al., arXiv 2609.00006, Jul 2026“the design and evolution of that runtime”; a harness is not quite a scaffold, not an agentic framework and not an evaluation harness (“Same word, opposite direction of wrapping.”)builder, as the shipped runtime

So two people can say “harness engineering” and mean different jobs. OpenAI's “Harness engineering” post is about the user and repository side: the docs, linters and observability that let Codex work in a codebase. Anthropic and LangChain mostly write about the builder side, meaning the loop, the tools and compaction. Most sources never name the split, so readers talk past each other.

Birgitta Böckeler's article names it and files the user side under a larger idea: “Engineering a user harness for a coding agent is a specific form of context engineering.”

Which one contains the other is still unsettled. Horthy, HumanLayer and Böckeler put harness engineering inside context engineering, and LangChain calls today's harnesses “delivery mechanisms for good context engineering.” Databricks takes the opposite view: “Prompt and context engineering both live inside harness engineering.” And Andrej Karpathy, in the June 2025 post where he endorsed the term context engineering, already called it “one small piece of an emerging thick layer of non-trivial software.”

In this book we use three terms. The harness is everything in a running agent that is not the weights. The builder harness is the code of the loop, its tools and its middleware, like hx in this book or Claude Code's own source. The user harness is what you add around a harness you didn't write: CLAUDE.md and AGENTS.md files, hooks, permission rules, skills, Model Context Protocol (MCP) servers, and the repository's docs, lints and tests.

“Evaluation harness” always means the thing that runs a benchmark, and “scaffold” appears in quotations and in its research sense, the wrapper a study puts around a model. Section 9 writes one rule for both the builder harness and the user harness.

Those terms say who wrote the harness. You can also slice it by where each piece lives. Some of it works around the agent: the context it reads, the tools and permissions it gets, and the roles and checks it works under. The rest lives inside the software the agent works on: the written intent, the module boundaries and interfaces, and the invariants and tests. We count both as harness work, and Chapter 10 builds most of the second half.

Put the halves together and every harness answers seven questions. We call them control surfaces, and each one has chapters that build it:

  • Intent. Why are we building this, and what counts as success? Chapter 10.
  • Structure. What shapes may the implementation take? Chapter 10.
  • Context. What does the agent need to know right now? Chapters 3 and 4.
  • Execution. What is the agent allowed to do? Chapters 5 and 7.
  • Evidence. How does anyone know the work is right? Chapters 6 and 12.
  • Coordination. How does work survive, run in parallel and combine? Chapters 8 and 9.
  • People. How do the humans keep their judgment, their ownership and their ability to learn? Chapter 11.

Pick a group to see which surfaces shape the agent, which live inside the software, and which cover the proof and the people. Hover over a surface, or tab to it, to read its usual artifacts and the chapters that build it.

Where the term came from

On November 4, 2025, Dex Horthy of HumanLayer wrote a post on X introducing a concept “which I'll call ‘harness engineering’”. He meant applying context engineering principles to how you use an existing agent, and for Claude Code he listed “the commands, hooks, skills, agents, mcps, etc that a consumer of the tool plugs into the existing harness.”

That post is the earliest documented use of the exact phrase, so the term started on the user side. On Hacker News it arrived later. No story or comment there uses the phrase in any month from January to November 2025, and the first comment with it appears on December 19, 2025.

From scaffold to harness engineering

  1. Scaffolding around the model
    2025-01-06
    Anthropic's SWE-bench post defines an agent as “the combination of an AI model and the software scaffolding around it” and advises keeping the scaffolding minimal.
  2. Context engineering
    2025-06-19 to 2025-06-25
    Tobi Lütke prefers “context engineering” to prompt engineering. Andrej Karpathy adds that it is one piece of a “thick layer” of software around model calls.
  3. “Agent Harness” and the Claude Agent SDK
    2025-09-23 to 2025-09-29
    Vivek Trivedy defines an agent harness and coins “Harness as a Service”, without the phrase “harness engineering”. Anthropic renames the Claude Code SDK the Claude Agent SDK, “the agent harness that powers Claude Code”.
  4. Horthy names harness engineering
    2025-11-04
    The earliest documented use of the exact phrase, in a post on X.
  5. “The Codex harness”
    2026-01-23 and 2026-02-04
    OpenAI's Michael Bolin and Celia Chen describe “the Codex harness”, the agent loop and logic under every Codex surface.
  6. Hashimoto: Engineer the Harness
    2026-02-05
    Step 5 of “My AI Adoption Journey” says to engineer each mistake away so the agent never makes it again. The post reaches 984 points on Hacker News.
  7. OpenAI's “Harness engineering”
    2026-02-11
    Ryan Lopopolo's post on building a product with no hand-written code. It never defines the term and never claims to have coined it.
  8. Bölük, LangChain, Böckeler
    2026-02-12 to 2026-04-02
    Bölük's “The harness problem” reaches 832 points on Hacker News. LangChain publishes “Improving Deep Agents with harness engineering”, Trivedy's first located use of the phrase. Böckeler writes a memo, then her article on the builder and user harness.
  9. A track, a job title, a product category
    2026-04 to 2026-09
    “Agent Harness Engineer” job postings appear. The AI Engineer World's Fair gets a Harness Engineering track, and 18 of its 561 session titles say “harness” while 2 say “context engineering”. Vercel, Microsoft and OpenAI ship harness products, and a Wikipedia article calls the attribution contested.

Then the credit got tangled. None of the prominent published attributions cites Horthy. HumanLayer, in March 2026, and Addy Osmani, in April, credit Vivek Trivedy. But Trivedy's first located use of the exact phrase is LangChain's post of February 17, 2026, and his 2025 post defines an agent harness without ever saying “harness engineering.”

The source-code study by Barbaste and colleagues says Hashimoto used it first and Trivedy then defined it, citing a secondary source, and elsewhere calls it “a phrase coined in a vendor blog post.” Wikipedia calls the attribution contested between those two. And Horthy co-founded HumanLayer, the very company that credits Trivedy.

OpenAI's post never claims the coinage, though InfoQ covered it as “a new internal engineering methodology called Harness engineering,” and Hashimoto's use came six days earlier. InfoQ also attributed to Ryan Lopopolo a quotation about “Harness” that doesn't appear in the post, so we don't repeat it. We write “earliest documented use” and cite Horthy because earlier uses may exist.

And the words for the next layer up have already arrived. On June 7, 2026, Peter Steinberger wrote that “You should be designing loops that prompt your agents,” and Osmani's “Loop Engineering” placed itself “one floor above the harness.” The appendix tracks how the term spread.

The subsystem map

Open up enough production harnesses and they start to look alike. A source-code study read 11 of them, about 4 million lines, from Claude Code and Codex CLI to Aider, Pi and OpenClaw. None imports a general agent framework, and none retrieves code with embeddings.

SKILL.md appears in nine of them and MCP in eight, and the authors derive a 90-line minimum harness. Our teardown of that study walks through its patterns. VILA Lab's reading of the Claude Code v2.1.88 source puts “AI decision logic” at 1.6% of the codebase, which leaves the rest to the harness.

This book follows one map of that shape. The model sits in the middle with the loop around it. Next come the parts that feed the loop, act for it and check it, and around all of them sit the repository, review and measurement. Of the seven control surfaces in section 5, intent and people are the two this map draws least, and Chapters 10 and 11 take them on.

Hover over a part, or tab through them, to read its job, what breaks without it and the chapter that builds it.

The parts meet inside every request. In “Unrolling the Codex agent loop”, OpenAI gives the order in which Codex assembles one. First come the model's instructions, then the tools and a permissions message. Next come the AGENTS.md files from the project root down to the working directory, up to 32 KiB, then an environment-context message, and only after all of that, the user's message.

Every turn resends that prefix, which makes the loop quadratic in JSON sent, and only exact-prefix cache hits make sampling “linear rather than quadratic.” Change the tools, the model, the sandbox, the approval mode or the working directory mid-conversation and the cache breaks. So context, permissions, tools and caching all answer to the same prefix, and Chapter 4 works through the arithmetic.

Now turn the map on your own setup. Each item in the scorecard is the smallest working version of one subsystem, and its note names the chapter that builds it.

Audit your harness against the map

0% (Foundational)

Every component encodes an assumption

Remember Cline's 2024 harness from section 2, still parsing XML tool calls out of the text stream for models that now call tools natively? Prithvi Rajasekaran of Anthropic Labs gives the general rule in a post on harness design for long-running application development: “every component in a harness encodes an assumption about what the model can't do on its own.”

Those assumptions, he writes, “can quickly go stale as models improve,” and the space of interesting harness combinations “doesn't shrink as models improve. Instead, it moves.”

Anthropic's own harnesses show it. Sonnet 4.5's “context anxiety” made compaction alone insufficient, so the long-running harness reset the context and passed handoff files between sessions. Then came Opus 4.5. In the words of the Managed Agents post, “the behavior was gone. The resets had become dead weight,” and the harness moved to the Agent SDK's automatic compaction.

For Opus 4.6 the sprint construct went too, and the evaluator moved to a single pass at the end. The planner stayed, because without it the generator under-scoped. Anthropic now designs for that churn. It says its Managed Agents architecture keeps stable concepts such as the session, the harness and the sandbox apart from the implementations it expects to change underneath them.

Assumptions can flip back, too. Amp replaced compaction with handoffs in October 2025 and restored it in May 2026, because “Today's leading frontier models are great at handling compaction.”

Claude Code is the best-documented case. As the Pragmatic Engineer reported from an interview with Boris Cherny in September 2025, “with the 4.0 models, we deleted around half the system prompt.” Then, in July 2026, an Anthropic post on the new rules of context engineering went further: “We removed over 80% of Claude Code's system prompt for models like Claude Opus 5 and Claude Fable 5 with no measurable loss on our coding evaluations.”

Its author, Thariq Shihipar, writes that “we were overconstraining Claude Code, both through our system prompt and in our CLAUDE.md files and skills.” He describes trading rules for judgment, examples for interfaces and upfront instructions for progressive disclosure.

One old line shows the shift. “In code: default to writing no comments. Never write multi-paragraph docstrings...” became “Write code that reads like the surrounding code: match its comment density, naming, and idiom.”

The tools the model sees shrank as well. Version 2.1.117 took Glob and Grep out of native macOS and Linux builds in favor of search through the Bash tool. Version 2.1.233 stopped offering the to-do and task tools to Opus 4.8, Sonnet 5, Fable 5, Mythos 5 and newer models.

Meanwhile the product around the prompt kept growing. The docs list 33 hook event types, 46 built-in tool names and six permission modes, and Claude Code shipped between 20 and 29 releases in every month of 2026 through September. So “thin harness” has two meanings that are easy to mix up: what the model reads, which keeps shrinking, and what you configure, which keeps growing.

The left half plays the two prompt cuts and the tool removals, each cut measured against the prompt of its day, so read them as separate events. The right half counts the configurable surface alongside each month's releases.

In practice the idea becomes an ablation. In his YC Startup School talk, as a third party transcribed it, Cherny described deleting “the entire system prompt” for each new model and bringing it back “line by line.” He advised users to delete their CLAUDE.md, skills and hooks every six months.

Claude Code now ships /doctor prompt-audit, which looks for “instructions written for older models,” and its model guidance for Fable says “Skip the verification reminders: it verifies its own work with less prompting.”

Deletion is a harness change like any other, and harness changes can regress without anyone noticing. Anthropic's April 2026 postmortem traced degraded Claude Code quality to three harness-side changes, with the API unaffected.

First, the default effort dropped from high to medium, and the postmortem says so plainly: “This was the wrong tradeoff.” Second, a change meant to clear old thinking from idle sessions shipped with a bug that cleared it on every turn. It passed review, tests and dogfooding, and it took over a week to find. Third, one line asking for brevity, “keep text between tool calls to ≤25 words,” cost 3% on one evaluation for both Opus 4.6 and 4.7.

So removing scaffolding needs the same measurement as adding it, and Chapter 12 builds that measurement.

Turning a failure into a permanent fix

Mitchell Hashimoto's “My AI Adoption Journey” names the operator's core habit. When an agent makes a mistake, “you take the time to engineer a solution such that the agent never makes that mistake again.” His fixes take two forms: better implicit prompting, which means AGENTS.md lines, and “actual, programmed tools” such as screenshot scripts and filtered test runs.

The example he links, Ghostty's src/inspector/AGENTS.md, is four bullet rules, each written after an observed bad behavior. One is a build flag, -Demit-macos-app=false. Another is the line “There are no unit tests in this package.” By his account, “it almost completely resolved them all.”

The habit scales past one person. Tobi Lütke reports that River, the agent that authors one in eight merged Shopify pull requests, raised its merge rate from 36% to 77% over two months, with no retraining and no model switch. People watched where it got stuck and wrote down what it should have known.

OpenAI's harness post treats each struggle the same way, as a signal that asks “what capability is missing, and how do we make it both legible and enforceable for the agent?”

Turn that habit on your own repository and you get a working rule. Every correction you repeat is a check you haven't written yet. If you keep telling the agent not to call a layer directly, write an architecture test that fails when it does. If you keep saying “always run these tests,” make it a hook or a CI rule. If you keep fixing the shape of its output, write a schema.

Products are moving the same way. GitHub now exposes pre- and post-tool hooks for policy enforcement and workflow integration, so instructions given in conversation can become constraints that run.

A fix can live at different heights. Anthropic's steering post lists seven mechanisms in Claude Code, from CLAUDE.md, rules and skills through subagents and hooks to output styles and system-prompt appends. It sums up the choice in one line: “Each method trades context cost against authority.”

The memory docs call CLAUDE.md “context, not enforced configuration” and point to a PreToolUse hook when something must be blocked. The permission-mode docs warn that a boundary stated in conversation, such as “don't push,” “can be lost if context compaction removes the message,” and that a hard guarantee needs a deny rule.

Hover over a rung, or tab to it, to see how it fails, with an example. Start each fix at the lowest rung that holds, and climb one rung when the same failure comes back.

Take one failure up the ladder. Your agent force-pushes over a teammate's commits. A chat instruction can vanish with compaction, and an AGENTS.md line is advisory. A permission rule such as Bash(git push --force *) holds better, but it matches command text, and the permission docs say a rule on git push misses git -C . push and git 'push'.

A hook can parse the command instead. The script in the first tab handles git's global options, quoting and command chains. It also catches sh -c strings, bundled short flags and the +branch refspec, which forces a push without any flag.

Claude Code and Codex both pass the hook the command as tool_input.command and treat exit code 2 as a block whose stderr the model reads, so one script serves both. The last tab is the same rule in the builder harness you'll write in Chapter 2.

One rule, five places: no force pushes
.claude/hooks/no_force_push.py
python
#!/usr/bin/env python3
"""PreToolUse hook: refuse git force pushes however they are spelled.

Claude Code and Codex both send {"tool_input": {"command": "..."}} on stdin for
Bash calls and treat exit code 2 as a block, showing stderr to the model.
Not exhaustive (aliases, scripts, eval); the server-side setting is the backstop.
"""
import json
import shlex
import sys

FORCE = {"-f", "--force", "--force-with-lease", "--force-if-includes"}
WRAPPERS = {"command", "env", "exec", "nice", "nohup", "time"}
BREAKS = {"&&", "||", ";", "|", "&", "|&", "(", ")", "{", "}"}


def commands(line: str) -> list[list[str]]:
    """Split a shell command into simple commands, including sh -c strings."""
    out: list[list[str]] = []
    for physical in line.splitlines():
        lex = shlex.shlex(physical, posix=True, punctuation_chars=True)
        lex.whitespace_split = True
        cur: list[str] = []
        for tok in lex:
            if tok in BREAKS:
                out.append(cur)
                cur = []
            else:
                cur.append(tok)
        out.append(cur)
    nested = [c for argv in out
              if len(argv) > 2 and argv[0].split("/")[-1] in ("sh", "bash", "zsh") and argv[1] in ("-c", "-lc")
              for c in commands(argv[2])]
    return [argv for argv in out if argv] + nested


def is_force_push(argv: list[str]) -> bool:
    while argv and (argv[0] in WRAPPERS or ("=" in argv[0] and not argv[0].startswith("-"))):
        argv = argv[1:]  # drop wrappers and VAR=value prefixes
    if not argv or argv[0].split("/")[-1] != "git":
        return False
    i = 1
    while i < len(argv) and argv[i].startswith("-"):  # git -C dir, -c key=value, --no-pager
        i += 2 if argv[i] in ("-C", "-c") else 1
    if i >= len(argv) or argv[i] != "push":
        return False
    for arg in argv[i + 1:]:
        if arg in FORCE or arg.startswith("--force-with-lease=") or arg.startswith("+"):
            return True
        if arg.startswith("-") and not arg.startswith("--") and "f" in arg[1:]:
            return True  # bundled short flags such as -fu
    return False


def main() -> None:
    command = json.load(sys.stdin).get("tool_input", {}).get("command", "")
    try:
        found = any(is_force_push(argv) for argv in commands(command))
    except ValueError:  # unbalanced quotes: refuse anything that looks like a push
        found = "git" in command and "push" in command
    if found:
        print("Blocked: force pushes rewrite shared history. Push to a new branch "
              "and open a pull request instead.", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()

Make the hook executable with chmod +x. Codex's prefix rules have a blind spot of their own. A pattern must match an exact prefix, so the rule refuses git push --force origin main and lets git push origin main --force through.

The not_match entry records that gap, and codex execpolicy check tests any command against the file. Codex also asks you to review a new hook with /hooks, and it records your trust against the hook's hash.

The top rung for this failure sits on the server. Set receive.denyNonFastForwards on the shared repository and Git refuses a non-fast-forward update “even if that push is forced,” whichever harness, model or person sent it. If you can, set that first. We'd keep the hook anyway, because it stops the push before it leaves the machine and tells the model what to do instead.

Where a “don't” belongs
A rule that must hold every time needs a rung that enforces it: a deny rule, a hook, a test, or a change to the repository or the server. AGENTS.md is for what the agent can't find out on its own, like Ghostty's build flag. Each line costs context on every turn, and Claude Code's memory docs target “under 200 lines per CLAUDE.md file” because “Longer files consume more context and reduce adherence.”

The habit needs a memory, or you end up fixing the same failure again at the same rung. So keep a ledger, a JSON Lines file in the repository with one entry per failure.

Each entry records when the failure happened, which harness and model, and the symptom. It points to the transcript, names the rung the fix went to and the file it changed, and keeps a short exact phrase from the fix so the report can find it. Copy the transcript next to the ledger so it survives the harness's own cleanup, and when a fixed failure comes back, add an entry that names the original in recurs.

failures.jsonl
json
{"id": "F-001", "date": "2026-09-29", "harness": "claude-code 2.1.291, claude-sonnet-5-5", "symptom": "ran the whole test suite after a one-line change", "transcript": "ledger/F-001.jsonl", "layer": "agents_md", "file": "AGENTS.md", "fix": "Run only the tests for the package you changed"}
{"id": "F-002", "date": "2026-09-30", "harness": "claude-code 2.1.291, claude-opus-5-5", "symptom": "force-pushed over a teammate's commits on a shared branch", "transcript": "ledger/F-002.jsonl", "layer": "hook", "file": ".claude/hooks/no_force_push.py", "fix": "def is_force_push"}
{"id": "F-003", "date": "2026-10-01", "harness": "claude-code 2.1.291, claude-opus-5-5", "symptom": "hand-edited the generated API client in src/gen/", "transcript": "ledger/F-003.jsonl", "layer": "agents_md", "file": "AGENTS.md", "fix": "Never edit files under src/gen/"}
{"id": "F-004", "date": "2026-10-03", "harness": "claude-code 2.1.291, claude-opus-5-5", "symptom": "edited src/gen/client.ts again despite the AGENTS.md line", "transcript": "ledger/F-004.jsonl", "recurs": "F-003", "layer": "hook", "file": ".claude/settings.json", "fix": "Edit(/src/gen/**)"}
{"id": "F-005", "date": "2026-10-04", "harness": "claude-code 2.1.291, claude-sonnet-5-5", "symptom": "imported a server-only module into the browser bundle", "transcript": "ledger/F-005.jsonl", "layer": "lint", "file": "eslint.config.js", "fix": "no-restricted-imports"}
{"id": "F-006", "date": "2026-10-05", "harness": "codex 0.160.1, gpt-6.1-sol", "symptom": "could not find how to boot the app and guessed a port", "transcript": "ledger/F-006.jsonl", "layer": "none"}

ledger.py reads that file and prints four things. First come the fixes and recurrences per rung, then each recurrence, with a suggestion to climb when the new fix sits no higher than the one that failed. After that come the open failures, and last the AGENTS.md lines that no logged failure justifies.

ledger.py
python
#!/usr/bin/env python3
"""Report on the failure ledger: fixes per rung, recurrences, and the
AGENTS.md lines that no logged failure justifies.

    python ledger.py failures.jsonl --agents-md AGENTS.md

Each entry names the rung its fix went to ("layer"), the file it changed and a
short exact phrase from the fix ("fix"); a recurrence names the original in "recurs".
"""
import argparse
import json
from collections import Counter
from pathlib import Path

# The fix ladder, lowest rung first. "hook" covers permission rules as well
# (Claude Code deny and ask rules, Codex prefix_rule).
LADDER = ["chat", "agents_md", "skill", "hook", "lint", "test", "structure"]


def load(path: Path) -> list[dict]:
    rows = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
    for r in rows:
        if r.get("layer", "none") not in LADDER + ["none"]:
            raise SystemExit(f"{r['id']}: unknown layer {r['layer']!r}")
    return rows


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("ledger", type=Path)
    ap.add_argument("--agents-md", type=Path)
    args = ap.parse_args()
    rows = load(args.ledger)
    by_id = {r["id"]: r for r in rows}

    fixed = Counter(r["layer"] for r in rows if r.get("layer", "none") != "none")
    # A recurrence counts against the rung of the fix that did not hold.
    again = Counter(by_id[r["recurs"]]["layer"] for r in rows if r.get("recurs") in by_id)
    print(f"{'rung':<11}{'fixes':>6}{'recurred':>10}")
    for rung in LADDER:
        if fixed[rung] or again[rung]:
            print(f"{rung:<11}{fixed[rung]:>6}{again[rung]:>10}")

    print()
    for r in rows:
        first = by_id.get(r.get("recurs", ""))
        now = r.get("layer", "none")
        if first:
            note = f"{first['id']} ({first['layer']}) came back as {r['id']}, "
            note += f"now fixed at {now}" if now != "none" else "still open"
            if now in LADDER and LADDER.index(now) <= LADDER.index(first["layer"]) < len(LADDER) - 1:
                note += f"; climb to {LADDER[LADDER.index(first['layer']) + 1]} or higher"
            print(note)
        elif now == "none":
            print(f"open: {r['id']} {r['symptom']} ({r['transcript']})")

    if args.agents_md:
        text = args.agents_md.read_text()
        mine = [r for r in rows if r.get("file") == args.agents_md.name and r.get("fix")]
        rules = [ln.strip() for ln in text.splitlines() if ln.lstrip().startswith(("- ", "* "))]
        orphans = [ln for ln in rules if not any(r["fix"].lower() in ln.lower() for r in mine)]
        print()
        print(f"{args.agents_md}: {len(rules)} rules, {len(orphans)} with no logged failure")
        for ln in orphans:
            print(f"  {ln}")
        for r in mine:
            if r["fix"].lower() not in text.lower():
                print(f"stale: the fix for {r['id']} is no longer in {args.agents_md}")


if __name__ == "__main__":
    main()

Run it on the six entries above and the report shows the climb from F-003 to F-004, with F-006 still open. AGENTS.md lines with no failure behind them deserve a second look. Some carry knowledge the agent could never discover, and the rest are candidates for the deletions of section 8.

Chapter 3 uses the ledger to decide what AGENTS.md keeps, Chapter 6 turns repeated “done but not done” entries into gates, and Chapter 12 turns entries into evaluation tasks, the step our post on turning failures into evals walks through.

Reading a harness claim

A benchmark number means little until you know what produced it. So every number in this book carries a triple: the model, with its effort setting when the source gives one; the harness, with its version; and the benchmark version.

Terminal-Bench 2.0, 2.1, 3.0 and 4.0 are different benchmarks, and so are SWE-bench Verified, SWE-bench Pro and SWE-Bench Pro V2. You saw the same Opus 4.6 and Claude Code pair score 58.0% on Terminal-Bench 2.0 and 70.1% on 2.1. Boards change between snapshots, too. On October 6, 2026 the Terminal-Bench 2.0 board lists Opus 4.6 in ten harnesses, one more than in August.

Past the triple, five things decide how far a number carries:

  • Trials and intervals. The Terminal-Bench 2.0 paper reports 95% intervals of two to three points, so a smaller gap needs more trials before it means anything.
  • Who ran it. Verified rows and author-run tables carry more weight than vendor results or self-submitted entries.
  • Resources and configuration. In Anthropic's infrastructure-noise study, resources alone moved Terminal-Bench 2.0 by 6 points, and the study warns that “leaderboard differences below 3 percentage points deserve skepticism until the eval configuration is documented and matched.”
  • Leakage. Could the agent reach the tests, the answers or a verifier that trusts its output? The cheating Meerkat found in section 3 is what that looks like.
  • Cost. Tokens and dollars per solved task move even when success doesn't, which is where Reflection's “Pick the harness for the bill” comes in.

We grade every fact in this book by its source, and the wording tells you which grade a claim rests on.

GradeWhat it meansHow the text writes itExample in this chapter
PrimaryRead at the source: a paper, docs page, changelog, data file or the company's own postStated plainly, with a linkThe Terminal-Bench 2.0 board rows; Claude Code's hook and permission docs
Primary, abstract onlyOnly the paper's abstract was readUses only what the abstract statesLewis's 28% to 49%
SecondarySeen only in someone else's reportAttributed in the sentence: “as reported by”Cherny's “around half the system prompt”, via the Pragmatic Engineer
Vendor or company self-reportPrimary as a record of what the company said, with the claim itself unverified“X reports”, with no claim of independent measurementCline's 6.34% to 0.62% A/B
UnconfirmedSeen only in a search answer or on a page that could not be readLeft out, or named as circulating and unconfirmedNone used in this chapter

Try the grades on the number in this chapter's header image. “Opus 4.6 spans 18.4 points across nine harnesses on Terminal-Bench 2.0” has a full triple and a snapshot date, and it is primary as to what the board shows.

But seven of the nine rows are unverified. The board doesn't control resources or configuration, as an independent analysis of it noted. And Meerkat caught a trace from the top row printing “PASS” to fool a verifier.

What survives is narrower. On verified rows the spread is 4.9 points. In the controlled studies of section 2, harness changes moved fixed models by about 7 to 21 points, and much further in the extreme cases of a poor edit format or a tight context budget. For strong models on SWE-style tasks, several studies find almost no effect on success and a clear one on cost.

The posts from Anthropic, OpenAI and other heavy users need a caution of their own. They describe shops that run far more agent work than most, like Anthropic with its more than 30,000 merged changes a day. Read them as case studies from the frontier, which tell you what worked in one unusual place. Research benchmarks such as E2E-SWE and SlopCodeBench need the same care, because a research task is a long way from your production code.

So when a vendor tells you its harness is better, ask for the triple and the trials. Ask who ran it, on what resources, and what each solved task cost. Then run both harnesses on your own tasks, several trials each, on the rig Chapter 12 builds. Our book Evaluating Agentic AI covers pass^k and paired comparisons in depth.

Before you can test a harness, though, you need to see what it does on a single turn. Chapter 2 takes one turn apart, then has you write the loop yourself, with a turn cap, a dollar cap and a log that can rebuild every request the model saw.

Chapter 1 in one page

Key takeaways
10 items
  • 1With the model held fixed, harness changes alone moved scores by about 7 to 21 points in controlled studies. LangChain's agent went from 52.8% to 66.5% on Terminal-Bench 2.0.
  • 2Check a leaderboard spread before you quote it. Opus 4.6's 18.4 points across nine Terminal-Bench 2.0 harnesses fall to 4.9 on verified rows, so look at the verified flag, the snapshot date and the integrity notes.
  • 3The harness matters most for weaker models, tight context budgets and long terminal tasks. In one study, context management was worth 35.7 points at a 32k budget and 2.7 at 128k. For strong models on SWE-style tasks it mostly moves the cost.
  • 4Agents are getting good at the first build and are still poor at changing what they built. On SlopCodeBench no agent finished a problem end to end and structure eroded in 77% of trajectories, so judge a harness by the tenth change.
  • 5The harness is everything that is not the model. The builder harness is code you own, like hx. The user harness is the configuration and repository you add to a harness someone else wrote. Keep the two apart.
  • 6Every harness answers seven questions, the control surfaces: intent, structure, context, execution, evidence, coordination and people. Some shape the agent and some live inside the software it works on.
  • 7The earliest documented use of “harness engineering” is Dex Horthy's post on X of November 4, 2025, though the prominent attributions credit Vivek Trivedy or Mitchell Hashimoto.
  • 8Every component encodes an assumption about the model, and assumptions expire. Claude Code removed over 80% of its system prompt for Opus 5 and Fable 5 with no measurable loss, and Anthropic dropped context resets once Opus 4.5 stopped needing them. Measure a deletion like any other change.
  • 9Every correction you repeat is a check you haven't written yet. Log each failure with its transcript, fix it at the lowest rung that holds, and climb when it recurs. A rule that must always hold belongs in a deny rule, a hook, a test or on the server.
  • 10Read every number by its triple of model and effort, harness and version, and benchmark version. Then check its grade: primary, secondary or self-report.

What to do on Monday. Add failures.jsonl to the repository your agent works in, and log the next three failures, each with its transcript and the rung you fixed it at. Run capture_requests.py and first_turn_audit.py once against the harness you use most, and write down its first-request total. Then run ledger.py with --agents-md AGENTS.md and delete one line that no failure justifies.

Chapter 2 · The loop

The Loop, One Turn at a Time

The agent loop: context, model, tool call and observation, with stop rules

We take one turn of a coding agent apart in Codex and Claude Code, and then you build the loop yourself, as a small Python harness with stop rules, a dollar cap and a log that can rebuild every request the model saw.

At the top of the Terminal-Bench 3.0 board sits a research script. It is called mini-SWE-agent, its agent class is about 100 lines of Python, and its only tool is bash.

Running Claude Opus 5, it scores 42.7%. That puts it ahead of GPT-5.6 Sol in Codex and Claude Fable 5 in Claude Code, the harnesses OpenAI and Anthropic build for their own models. A script written to see how simple an agent could get is outscoring the products.

The newer Terminal-Bench 4.0 board tells the other half. There the vendor harnesses lead, with Opus 5.5 in Claude Code at 64.85% as of October 6, 2026. Read the two boards together and the small loop becomes the baseline, the thing every component you add has to beat on your own tasks. That is why the harness in this book starts as one.

Strip any coding agent down and you find the same cycle. The harness sends the model a request, reads back a tool call and runs it, then appends the result and decides whether to go again. Claude Code, Codex and that 100-line script all run it, and they differ in what they put into each request and what they let out of it.

By the end of this chapter you will have written that loop yourself, in about 140 lines of Python, with a turn cap, a dollar cap and a log that can rebuild every request the model saw.

A harness in one sentence

Chapter 1 settled where the harness ends, and Vivek Trivedy put it in one line: “If you're not the model, you're the harness.” To build one, you also need to know what it does, and the rest of the book works from one sentence:

A harness is the program that decides what the model sees on every request and what happens to everything the model asks for.

The first half is context: the instructions and tool definitions, the files and earlier results, and the order they go in. The second half is action: which calls run and where, under what limits, and what comes back.

The loop that joins the two halves is the one in Simon Willison's definition of an agent, “Agents run tools in a loop to achieve a goal”. Claude Code's docs split that loop into three phases that blend into one another: gather context, take action, verify results.

In the terms Birgitta Böckeler uses on martinfowler.com, what we build here is a builder harness: the loop, tools and compaction a vendor ships. The user harness that wraps around it, from instruction files and skills to hooks and checks, comes in Chapters 3, 6 and 10. Building ours from nothing gives those chapters something concrete to plug into.

Whoever writes it, the core stays small. An audit of eleven production harnesses, including Claude Code, Codex CLI and Pi, found that none of their roughly 4 million lines imports a general agent framework. It closes with a 90-line minimum harness, and our post on what 11 production coding agents share walks through it.

Anatomy of a turn

Before you cap turns, pin the word down, because the sources use it for different things. DeepSeek Harness counts a turn as zero or more steps, each one a model request plus its tool calls. The Codex App Server counts it as one unit of agent work started by user input.

This book follows the Claude Agent SDK, whose maxTurns counts “tool-use round trips”. For us, a turn is one model request and the tool calls in its response, so max_turns=30 means at most 30 model calls.

Now look inside one of those requests. OpenAI's Michael Bolin, in Unrolling the Codex agent loop, gives the order in which Codex assembles it:

  1. instructions: the file named by model_instructions_file if set, otherwise the model's bundled base prompt, such as gpt-5.2-codex_prompt.md.
  2. tools: shell, update_plan, web_search and any Model Context Protocol (MCP) tools.
  3. input items, in this order:
    • a developer message describing permissions, built from snippets such as workspace_write.md and on_request.md;
    • an optional developer_instructions message;
    • a user message with the aggregated instructions: AGENTS.override.md or AGENTS.md from CODEX_HOME, then each folder from the project root down to the working directory, up to 32 KiB, then skills metadata;
    • a user message holding <environment_context> with the working directory and shell;
    • last, the user's message.

The figure opens on a finished turn, which becomes the prefix of the next request. Press NEXT to rebuild it layer by layer and watch who writes what: of the nine layers, the harness writes five, you write two, and the repository and the model supply one each.

Three details are decisions for your own harness. Stable parts come first, because the cache hits only on an exact prefix. The sandbox “applies only to the Codex-provided shell tool”, so MCP tools “are responsible for enforcing their own guardrails”. And when the sandbox, the approval mode or the working directory changes mid-session, Codex appends the change as a new message, which leaves the prefix intact.

Claude Code builds its request in the same order, according to its prompt caching page. The system prompt and tool definitions go first, then project context such as CLAUDE.md, auto memory and unscoped rules, then the conversation. Thariq Shihipar gives the reason in Prompt caching is everything: “At Claude Code, we build our entire harness around prompt caching.”

In one turn, the harness assembles the request, sends it and parses the response. It decides whether each tool call may run, runs it and turns the output into an observation. Then it appends that observation, logs everything and checks the stop rules. The model's whole part is sampling the response.

Stateless requests, growing transcripts

The model keeps nothing between requests, so the harness sends the whole conversation every time. Codex does not use the Responses API's previous_response_id. Bolin writes that keeping requests “fully stateless” supports Zero Data Retention, with encrypted reasoning from earlier turns decrypted on the server.

hx works the same way. state.messages is the session, and every call sends all of it.

So each request contains the previous one as an exact prefix, and the loop is quadratic in the JSON it sends. With prompt-cache hits, Bolin writes, sampling becomes “linear rather than quadratic”, as long as the prefix stays exact.

Take the task from Anthropic's What a task costs on Opus 5.5. Its context grows from 20K to 120K tokens over 40 turns, and the figure draws that growth as a straight line.

Drag the slider to run the task further; each bar is one request, about 2,564 tokens longer than the one before. Then switch to PREFIX CACHE and watch how much of each request comes back from cache.

Do the arithmetic once. Forty requests growing in a straight line from 20,000 to 120,000 tokens add up to forty times their midpoint of 70,000. That is 2.8 million input tokens to build a 120,000-token transcript.

The post prices that on Opus 5.5 at $11.20 uncached and about $1.62 at a 90% cache hit rate. A perfect prefix cache would serve about 96% of it, the post's $0.99 case, because only the transcript's own 120,000 tokens are ever processed new.

Turns are a cost lever of their own. Run the same growth in 25 turns and the loop sends about 1.75 million tokens, about $1.02 against $1.62 at the same cache rate. Chapter 4 does the economics.

All of this depends on the prefix staying exact, and Bolin lists what has broken it in Codex. Changing the tools or the model mid-conversation did it, and so did changing the sandbox configuration, the approval mode or the working directory. An MCP bug that listed tools in inconsistent order did it too, and so did notifications/tools/list_changed messages.

So both vendors append changes instead of editing the prefix. Anthropic's API even accepts mid-conversation messages with role system, because “editing the top-level system field changes the very beginning of the prompt and invalidates the cache for everything that follows”. In hx, before_request may rewrite history, as Chapter 4's reduction ladder does, and the price is a cache miss after the change.

Stateless is a choice

Statelessness costs speed. OpenAI's WebSocket mode keeps a connection-scoped, in-memory copy of the previous response state, keyed by previous_response_id, and OpenAI reports agent loops 40% faster end to end with it. Codex gives that up for Zero Data Retention and for requests any process can rebuild. hx stays stateless for the second reason, and section 7 shows what that buys you.

The smallest loop that scores

The SWE-agent team built mini-SWE-agent, the script from the top of the chapter, around a question in its README: “What if our agent was 100x simpler, and still worked nearly as well?”

The README calls its agent class “some 100 lines of python”. Bash is the only tool, the history is fully linear, and each action runs in its own subprocess, with a 30-second timeout by default in version 2. The team claims a score above 74% on SWE-bench Verified.

Open version 2's agent file and it runs to 190 lines. It uses native tool calling with one bash tool, and a run ends when the model issues echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT. Its AgentConfig sets cost_limit 3.0 and max_consecutive_format_errors 3, and leaves step_limit at 0, which switches it off.

Mario Zechner's Pi makes the same bet with four tools: read, write, edit and bash. In his words, “pi's system prompt and tool definitions together come in below 1000 tokens.”

In November 2025 Pi had no to-do list, no plan mode and no MCP. It had no background bash, no subagents and no permission prompts either, and Zechner concluded that “these four tools are all you need for an effective coding agent”.

The studies from Chapter 1, the ones that hold the model fixed and swap the harness, point the same way. Scale and Reflection ran GLM-5.3, Kimi K3 and Inkling through mini-swe-agent, Pi and OpenCode on 642 SWE-Bench Pro V2 tasks under a locked budget, and the strongest models came out on par, except Inkling on Pi.

Reflection's advice in the Scale Labs write-up is “Pick the harness for the bill, not the score”. And in a research note, METR found that neither Claude Code nor Codex beat its simple scaffolds on time horizon.

The people who build the big harnesses say the same. Claude Code's Boris Cherny told Latent Space that “when the model is so good, the simple thing usually works”. And in The new rules of context engineering, Anthropic reports that it “removed over 80% of Claude Code's system prompt for models like Claude Opus 5 and Claude Fable 5 with no measurable loss on our coding evaluations”.

Minimal loops do lose ground in places. On the verified rows of the Terminal-Bench 2.0 leaderboard, GPT-5 scores 49.6% in Codex CLI and 33.9% in mini-SWE-agent. A study of ten Qwen and DeepSeek models reports in its abstract that complex harnesses help less on SWE-style repair as models improve, but still help stronger models on open-ended repository tasks.

Local models show the same dependence on fit, which we covered in model plus loop fit beats the biggest context. So we'd start with the small loop and add a part only when your own tasks show it pays. Section 10 maps where it breaks.

Stop rules and budgets

A loop needs two kinds of exit. The natural one is the model saying it is done. In hx that is a response with no tool call; in mini-SWE-agent, the sentinel command. Everything else is a stop rule, a condition the harness checks between requests that ends the run or sends it back to work.

The natural exit fails both ways. Models stop early. In LangChain's Terminal-Bench 2.0 work, the most common failure was that “the agent wrote a solution, re-read its own code, confirmed it looks ok, and stopped”.

Models also fail to stop, and those runs cost you the most. Scale and Reflection found that failed runs used more steps and tokens than solved ones, at the median, in 8 of 9 model-harness combinations.

Six stop rules turn up across the sources, each with published defaults. The repeat detector's thresholds come from the harness study in arXiv 2609.20804, and the turn cap and stall timeout from OpenAI's Symphony spec.

RuleWhat it catchesDefaults in the sourcesIn hx
Turn caploops that never convergeSymphony agent.max_turns 20; Agent SDK maxTurns; mini-SWE-agent step_limit (0, off)max_turns in the core
Dollar capruns whose context or output balloonsmini-SWE-agent cost_limit 3.0; Agent SDK maxBudgetUsd; Claude Code --max-budget-usdmax_usd in the core, priced from usage
Completion checkstopping at the first plausible answerClaude Code Stop hook, overridden after 8 consecutive blocks; /goal; LangChain PreCompletionChecklistMiddlewarebefore_stop (Chapter 6)
Repeat detectorthe same failing call, again and againreminder after 5 identical calls, stop after 8 identical failing calls (arXiv 2609.20804); LangChain LoopDetectionMiddlewaremiddleware (Chapter 6)
Malformed-call limitcalls the harness cannot runmini-SWE-agent max_consecutive_format_errors 3; Cline aborts after three consecutive mistakesMalformedLimit in section 6
Stall timeouta command or session that never returnsSymphony stall_timeout_ms 300000 (5 minutes); Claude Code BASH_DEFAULT_TIMEOUT_MS 120000the bash tool's 60-second timeout

A cap ends every runaway run, but late, and all it tells you is that the run was long. A detector ends it earlier and names a reason, such as an eighth identical failing call.

The figure runs five failing sessions against five of these rules, starting with the two caps the hx core has switched on. Toggle the rules and watch the outcome column.

Follow the run that polls a stuck job. Its calls succeed, so the repeat detector only reminds it. The run that says it is done without testing gets past every cap, and only a completion check that can tell tested from untested catches it, which is Chapter 6's job.

In Claude Code the completion check is a Stop hook, which can block a stop and hand the model a reason to keep going. Claude Code overrides the hook after 8 consecutive blocks, so a broken hook cannot loop forever, and the hooks reference documents CLAUDE_CODE_STOP_HOOK_BLOCK_CAP for raising that limit.

/goal wraps the same mechanism. Its docs describe a small, fast model that judges the transcript after each turn as “not yet met”, “met” or “impossible”.

A stop rule's firing rate doubles as a health metric, and Chapter 1 already showed you one. By Cline's own count, tasks ending in task.mistake_limit_reached, which fires after three consecutive mistakes, fell from 6.34% to 0.62% when Cline's VS Code extension moved to a new SDK harness.

hx checks the caps before each request, so a run overshoots max_usd by at most one response. The model never sees them, so they can only cut the run off. LangChain's time-budget warnings tell the agent to wrap up instead.

Anthropic's task budgets tell the model how much of its token budget remains, through output_config.task_budget under the beta header task-budgets-2026-03-13, or through taskBudget in the Agent SDK, which is still alpha.

The same rules in Claude Code and Codex
  • Claude Code takes both caps as flags, claude -p --max-turns 30 --max-budget-usd 1.00, and both work only in print mode.
  • In the Agent SDK, a run stopped by maxTurns or maxBudgetUsd ends with a result whose subtype is error_max_turns or error_max_budget_usd.
  • In Codex, App Server goals carry a tokenBudget, and codex exec --json reports token usage on every turn.completed event, so a wrapper script can enforce a cap.

Build: a minimal harness

Let's write it. The whole core comes to about 140 lines with comments, smaller than mini-SWE-agent's 190-line agent file, and run() is about 80 of them. You need Python 3.11 or later and the anthropic package.

We'll take it in two halves. The first half is only types, the ones every later chapter imports, so it pays to read them slowly.

hx/loop.py (part 1 of 2): types and prices
python
"""hx/loop.py: the core loop of the hx harness (Harness Engineering, Chapter 2).

pip install anthropic   (Python 3.11+; the client reads ANTHROPIC_API_KEY)
"""
import json
from dataclasses import dataclass, field
from typing import Callable

import anthropic

from hx.events import EventLog, build_request, fingerprint

# USD per million tokens: input, output, cache read, 5-minute cache write.
# Anthropic pricing page, accessed 2026-10-06. Add a row before using another model.
PRICES = {
    "claude-sonnet-5-5": (2.00, 10.00, 0.20, 2.50),
    "claude-opus-5-5": (4.00, 20.00, 0.20, 5.00),
    "claude-fable-5-1": (10.00, 50.00, 0.25, 12.50),
    "claude-haiku-4-5-20251001": (1.00, 5.00, 0.10, 1.25),
}
MAX_TOKENS = 16_000  # output cap per response


@dataclass
class Tool:
    name: str
    description: str
    input_schema: dict              # JSON Schema for the tool input
    run: Callable[[dict], str]      # returns the observation text the model reads


@dataclass
class State:
    task: str
    system: str
    messages: list[dict]            # Anthropic Messages API format
    turn: int = 0
    usage: dict = field(default_factory=lambda: {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0})
    cost_usd: float = 0.0
    stop_reason: str | None = None  # "done" | "max_turns" | "budget" | "gate" | "error"


class Middleware:                   # no-op defaults; subclasses override what they need
    def before_request(self, state: State) -> None: ...
    def before_tool(self, state: State, name: str, args: dict) -> str | None: return None
    def after_tool(self, state: State, name: str, args: dict, result: str) -> str: return result
    def before_stop(self, state: State, final_text: str) -> str | None: return None


def price(model: str, u) -> float:
    p_in, p_out, p_read, p_write = PRICES[model]
    return (u.input_tokens * p_in + u.output_tokens * p_out
            + (u.cache_read_input_tokens or 0) * p_read
            + (u.cache_creation_input_tokens or 0) * p_write) / 1_000_000

PRICES holds Anthropic's list prices from its pricing page as of October 6, 2026, and Sonnet 5.5, the default, costs $2 per million input tokens and $10 per million output. Every response is priced from its usage field, cache columns included, so the dollar cap will count the discount once Chapter 4 adds caching.

Below the prices sit three types. A Tool pairs a name and a JSON Schema with the function that runs it, State holds the session, and Middleware is four hooks that do nothing until a subclass overrides one. The second half, run(), is the loop that uses them.

hx/loop.py (part 2 of 2): run()
python
def run(task: str, tools: list[Tool], *, system: str = "", model: str = "claude-sonnet-5-5",
        max_turns: int = 50, max_usd: float = 5.0, middleware: list[Middleware] | None = None,
        log_path: str | None = None) -> State:
    if model not in PRICES:
        raise ValueError(f"no price for {model}; add it to PRICES so the dollar cap works")
    client, mws, log = anthropic.Anthropic(), middleware or [], EventLog(log_path) if log_path else None
    by_name = {t.name: t for t in tools}
    specs = [{"name": t.name, "description": t.description, "input_schema": t.input_schema}
             for t in tools]
    state = State(task=task, system=system, messages=[])

    def emit(kind: str, data: dict) -> None:
        if log:
            log.append(kind, state.turn, data)

    def add(message: dict) -> None:
        state.messages.append(message)
        emit("message", message)

    def call_tool(name: str, args: dict) -> tuple[str, bool]:
        verdicts = [m.before_tool(state, name, args) for m in mws]
        denial = next((v for v in verdicts if v is not None), None)     # first denial wins
        if denial is not None:
            return denial, True
        try:
            out = by_name[name].run(args) if name in by_name else f"error: no tool named {name!r}"
        except Exception as e:                       # a tool crash becomes an observation
            out = f"error: {type(e).__name__}: {e}"
        for m in mws:
            out = m.after_tool(state, name, args, out)
        return out, False

    emit("start", {"model": model, "max_tokens": MAX_TOKENS, "system": system, "tools": specs})
    add({"role": "user", "content": task})
    while state.stop_reason is None:
        if state.turn >= max_turns or state.cost_usd >= max_usd:
            state.stop_reason = "max_turns" if state.turn >= max_turns else "budget"
            break
        state.turn += 1
        before = json.dumps([state.system, state.messages])
        for m in mws:
            m.before_request(state)
        if json.dumps([state.system, state.messages]) != before:       # history was rewritten
            emit("rewrite", {"system": state.system, "messages": state.messages})
        if state.stop_reason:                                           # or the run was ended
            break
        request = build_request(model, MAX_TOKENS, state.system, specs, state.messages)
        emit("request", {"sha256": fingerprint(request), "messages": len(state.messages)})
        try:
            resp = client.messages.create(**request)
        except anthropic.APIError as e:
            emit("error", {"error": repr(e)})
            state.stop_reason = "error"
            break
        u = resp.usage
        state.usage["input"] += u.input_tokens
        state.usage["output"] += u.output_tokens
        state.usage["cache_read"] += u.cache_read_input_tokens or 0
        state.usage["cache_write"] += u.cache_creation_input_tokens or 0
        state.cost_usd += price(model, u)
        emit("response", {"stop_reason": resp.stop_reason, "usage": u.to_dict(mode="json"),
                          "cost_usd": round(state.cost_usd, 6)})
        add({"role": "assistant",
             "content": [b.to_dict(mode="json", exclude_none=True) for b in resp.content]})
        calls = [b for b in resp.content if b.type == "tool_use"]
        if not calls:                                 # a reply with no tool call: may it stop?
            final = "".join(b.text for b in resp.content if b.type == "text")
            nudges = [m.before_stop(state, final) for m in mws]
            nudge = next((n for n in nudges if n is not None), None)
            if nudge is None:
                state.stop_reason = state.stop_reason or "done"
            else:
                add({"role": "user", "content": nudge})
            continue
        results = []
        for c in calls:
            args = dict(c.input)
            out, denied = call_tool(c.name, args)
            emit("tool", {"id": c.id, "name": c.name, "args": args, "result": out, "denied": denied})
            results.append({"type": "tool_result", "tool_use_id": c.id, "content": out})
        add({"role": "user", "content": results})
    emit("stop", {"stop_reason": state.stop_reason, "cost_usd": round(state.cost_usd, 6)})
    return state

Follow one request through run(), and you meet its decisions in this order:

  • Caps first. Both caps are checked before every request. A middleware can also end the run by setting state.stop_reason, which Chapter 6's gates set to gate and the limit below sets to error.
  • Only before_request rewrites history. Any change it makes goes into the log as a rewrite event, so the log can still rebuild requests after compaction.
  • Messages stay plain dictionaries. Content blocks go through the SDK's to_dict, so middleware can edit them and the log can store them as JSON.
  • Tool failures become observations. An unknown tool or a tool that throws comes back as an error: string the model reads. An API error ends the run instead, with error as the reason.
  • Every hook runs in list order, and the first answer wins. The first string from before_tool denies the call and becomes its result, which is how Chapter 1's NoForcePush middleware refuses a force push. The first string from before_stop goes back to the model. before_tool, after_tool and before_stop mirror Claude Code's PreToolUse, PostToolUse and Stop hooks.
  • Three gaps wait for later chapters. There is no cache_control, so every turn pays the full input price until Chapter 4. There is no sandbox until Chapter 7, and no output budget beyond a character cut until Chapter 5.

Four hooks may sound thin. DeepSeek Harness has six interception points, LangChain's agent middleware has six hooks from before_agent to after_agent, and Claude Code has 33 hook events plus mods, “hooks that ship inside plugins”. hx's four still cover what those harnesses intercept, so a check you write as hx middleware maps onto each of them.

Every emit call in run() lands in hx/events.py. It stores each request in parts and folds them back together on demand, and section 7 explains why.

hx/events.py
python
"""hx/events.py: the hx session log (Harness Engineering, Chapter 2).

One JSON object per line, appended and never edited. Model-visible means logged:
every request run() sends can be rebuilt from the events logged before it.
"""
import hashlib
import json
import sys
import time
from pathlib import Path


class EventLog:
    def __init__(self, path: str):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)

    def append(self, kind: str, turn: int, data: dict) -> None:
        line = json.dumps({"ts": round(time.time(), 3), "kind": kind, "turn": turn, "data": data})
        with self.path.open("a", encoding="utf-8") as f:   # one write per event; a crash
            f.write(line + "\n")                            # can tear only the last line


def build_request(model: str, max_tokens: int, system: str, tools: list, messages: list) -> dict:
    """The request body, built the same way to send it and to rebuild it."""
    request = {"model": model, "max_tokens": max_tokens, "messages": messages}
    if system:
        request["system"] = system
    if tools:
        request["tools"] = tools
    return request


def fingerprint(request: dict) -> str:
    return hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()[:16]


def read_events(path: str) -> list[dict]:
    events = []
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        try:
            events.append(json.loads(line))
        except json.JSONDecodeError:    # a line torn by a crash; everything before it is intact
            break
    return events


def requests(path: str):
    """Fold the log; yield (turn, logged fingerprint, rebuilt request) per request."""
    start, system, messages = {}, "", []
    for e in read_events(path):
        kind, data = e["kind"], e["data"]
        if kind == "start":
            start, system = data, data["system"]
        elif kind == "message":
            messages.append(data)
        elif kind == "rewrite":
            system, messages = data["system"], list(data["messages"])
        elif kind == "request":
            yield e["turn"], data["sha256"], build_request(
                start["model"], start["max_tokens"], system, start["tools"], list(messages))


def rebuild_request(path: str, turn: int) -> dict:
    """The exact request body run() sent on that turn."""
    for t, _, request in requests(path):
        if t == turn:
            return request
    raise KeyError(f"no request for turn {turn} in {path}")


def verify(path: str) -> None:
    """Rebuild every request, check its fingerprint, and flag turns that broke the prefix."""
    prev = None
    for turn, logged, req in requests(path):
        status = "ok" if fingerprint(req) == logged else "MISMATCH"
        same_prefix = prev is None or (req.get("system") == prev.get("system")
                                       and req["messages"][:len(prev["messages"])] == prev["messages"])
        note = "" if same_prefix else "  prefix changed (cache misses after the change)"
        print(f"turn {turn:>3}  {status}  {len(req['messages']):>3} messages{note}")
        prev = req


if __name__ == "__main__":
    verify(sys.argv[1])

The loop and the log build requests with the same build_request, and fingerprint checks that the sent and rebuilt requests match.

The last file is the example script. Until Chapter 5 builds the full bash tool, hx/tools/bash.py, a minimal one lives here, beside a middleware that ends the run after three unrunnable tool calls in a row, mini-SWE-agent's limit.

example_run.py
python
"""example_run.py: one bash tool, one middleware and one run of the hx loop (Chapter 2).

HX_WORKDIR=~/scratch/some-repo python example_run.py "Run pytest -q and fix what fails."
POSIX only. The tool runs commands as you: use a throwaway clone or a container.
"""
import contextlib
import os
import signal
import subprocess
import sys

from hx.loop import Middleware, State, Tool, run

WORKDIR = os.path.expanduser(os.environ.get("HX_WORKDIR", "."))
TIMEOUT_S = 60
KEEP = 8_000  # characters the model sees; Chapter 5's bash tool budgets output properly


def bash(args: dict) -> str:
    proc = subprocess.Popen(["bash", "-c", args["command"]], cwd=WORKDIR,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            encoding="utf-8", errors="replace",
                            start_new_session=True)     # own process group: a timeout kills it all
    try:
        out, _ = proc.communicate(timeout=TIMEOUT_S)
        status = f"exit code {proc.returncode}"
    except subprocess.TimeoutExpired:
        with contextlib.suppress(ProcessLookupError):
            os.killpg(proc.pid, signal.SIGKILL)
        out, _ = proc.communicate()
        status = (f"killed after {TIMEOUT_S} s. For a long job, run it in the background "
                  "with its output in a log file, then read the log in later calls")
    if not out.strip():
        out = "(the command printed nothing)"
    elif len(out) > KEEP:
        cut = len(out) - KEEP
        out = f"{out[:KEEP // 2]}\n[... {cut} characters cut from the middle ...]\n{out[-KEEP // 2:]}"
    return f"{status}\n{out}"


BASH = Tool(
    name="bash",
    description=(f"Run one bash command in the repository; returns the exit code and output. "
                 f"Commands are killed after {TIMEOUT_S} s. Output over {KEEP} characters "
                 "keeps its start and end."),
    input_schema={"type": "object",
                  "properties": {"command": {"type": "string", "description": "The command to run."}},
                  "required": ["command"]},
    run=bash,
)


class MalformedLimit(Middleware):
    """End the run after limit tool calls in a row that the harness could not run."""

    def __init__(self, limit: int = 3):
        self.limit, self.streak = limit, 0

    def after_tool(self, state: State, name: str, args: dict, result: str) -> str:
        self.streak = self.streak + 1 if result.startswith("error:") else 0
        if self.streak >= self.limit:
            state.stop_reason = "error"
        return result


SYSTEM = ("You are a coding agent in a git repository. Use the bash tool to read code, edit files "
          "and run checks. Run the tests before you say you are done. When the task is complete, "
          "reply with a two-line summary and no tool call.")

if __name__ == "__main__":
    task = " ".join(sys.argv[1:]) or "Run pytest -q, fix the first failing test, and rerun pytest -q."
    state = run(task, [BASH], system=SYSTEM, max_turns=30, max_usd=1.00,
                middleware=[MalformedLimit()], log_path="runs/session.jsonl")
    print(f"{state.stop_reason}: {state.turn} turns, ${state.cost_usd:.4f}, {state.usage}")
The bash tool runs as you

Every command the model writes runs with your permissions and your network access, in HX_WORKDIR. Use a throwaway clone inside a container or a virtual machine, and an API key with a spending limit. Chapter 7 covers sandboxes and the network boundary.

Put the three files in place. Point the script at a disposable repository with a failing test, and give it a dollar cap you are willing to lose.

Run it
bash
# Layout: hx/__init__.py (empty), hx/loop.py, hx/events.py, example_run.py
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
export ANTHROPIC_API_KEY=sk-ant-...        # your key

# A throwaway clone of a small repository with a failing test
git clone --depth 1 https://github.com/<you>/<small-repo>.git ~/scratch/target

HX_WORKDIR=~/scratch/target python example_run.py \
  "Run pytest -q, fix the first failing test, and rerun pytest -q."

python -m hx.events runs/session.jsonl   # rebuild every request from the log and check it

A run prints its stop reason, its turns and its cost in dollars and tokens, and leaves the session in runs/session.jsonl. We wrote the output below for this page. It was not recorded, and the repository is made up.

A run, illustrative output
text
$ HX_WORKDIR=~/scratch/target python example_run.py "Run pytest -q, fix the first failing test, and rerun pytest -q."
done: 6 turns, $0.0453, {'input': 16712, 'output': 1187, 'cache_read': 0, 'cache_write': 0}

$ jq -c '[.turn, .kind]' runs/session.jsonl | head -n 9
[0,"start"]
[0,"message"]
[1,"request"]
[1,"response"]
[1,"message"]
[1,"tool"]
[1,"message"]
[2,"request"]
[2,"response"]

$ jq -c 'select(.kind == "tool") | [.turn, .data.args.command, (.data.result | split("\n")[0])]' runs/session.jsonl
[1,"pytest -q","exit code 1"]
[2,"sed -n '1,60p' dateparse/core.py","exit code 0"]
[3,"grep -rn \"def parse_date\" dateparse tests","exit code 0"]
[4,"python - <<'EOF2'\n...\nEOF2","exit code 0"]
[5,"pytest -q","exit code 0"]

$ python -m hx.events runs/session.jsonl
turn   1  ok    1 messages
turn   2  ok    3 messages
turn   3  ok    5 messages
turn   4  ok    7 messages
turn   5  ok    9 messages
turn   6  ok   11 messages

The event kinds trace the loop. Each turn logs the same five, from the request to the tool-result message, and then the next request begins.

Six turns made six requests, each two messages longer than the last. And the final command before the reply was the test suite exiting with code 0, as the system prompt asked.

Log everything the model sees

When a run goes wrong on turn twenty, you need the exact request the model saw. DeepSeek Harness makes that a rule in its architecture doc: “Model-visible means logged”. Every model request must be reconstructable from the session log, and hx/events.py implements it.

hx also takes DeepSeek's second rule, “There is no privileged core to patch”, which is why every later chapter plugs in through hooks.

Logging whole requests would grow the log quadratically, like the traffic in section 3, so the log stores parts. start sets the model, the system prompt and the tools. Each message appends a message, a rewrite replaces the history, and each request marks a send with its fingerprint.

requests() folds the parts back together. verify rebuilds every request, checks its fingerprint and flags any turn whose predecessor is no longer its prefix, the turn that costs a cache miss.

The figure follows the hx log through a session that crashes halfway. Press NEXT to walk it from the first event, and watch harness A die with request 2 in flight.

Harness B rebuilds that request from the log, checks the fingerprint and resends it without editing a line, and the labels under it show what Anthropic's Managed Agents calls the same two operations. Only the lost response is sampled again, so it can come out different.

A log that can rebuild every request pays off in four ways.

  • Debugging what the model saw. Anthropic's April 2026 postmortem describes a feature meant to clear thinking from idle sessions, clear_thinking_20251015 with keep:1. Through a bug, it cleared thinking on every turn. It got past review and tests, then automated verification and dogfooding, and took “over a week” to find. It changed what the model saw, which is what a request log records.
  • Finding cache breaks. According to its changelog, Claude Code v2.1.275 fixed a restored memory file's “age note” that changed between requests and caused cache misses. The prefix check in verify flags that kind of bug on the first turn it happens.
  • Surviving crashes. Managed Agents reboots a crashed harness from its “append-only log”, which turned harnesses and containers from “pets” into “cattle”. OpenHands reports in its SDK paper that event-sourced state cut system-attributable failures by 61%, with crash recovery under 20 milliseconds. Chapter 9 builds a restartable driver on the hx log.
  • Evaluating runs. The log is the transcript Chapter 12 grades, and the raw material for turning a failure into a regression case, as our post on trace promotion and pass^k gates shows.

Log at the boundary the model sees. hx records each tool result after after_tool has shaped it. For raw output, write a file and log its path, which is what Claude Code's context window docs describe for tool results over 50,000 characters.

Observations the model can use

The model never sees the terminal. Everything it learns about what its call did comes from the observation the harness hands back, and the harnesses that do well write those observations by a few consistent rules.

Raw resultWhat the model should readWho does this
The command printed nothinga line saying it ran and printed nothingSWE-agent replaces empty output with “Your command ran successfully and did not produce any output”
A nonzero exit statusthe exit code, every timeClaude Code treats exit code 1 as benign only for grep, rg, find, diff, test, git diff, git grep and a few others
Output too long for the windowthe head and the tail, with a note saying how much was cutCodex keeps head and tail around a “…N tokens truncated…” marker under a “Warning: truncated output” header, 10,000 tokens by default; Claude Code keeps about 30,000 characters inline, then gives a file path and a 2,000-character preview
A command that hangsa kill after a timeout, and a message saying what happened and what to tryClaude Code BASH_DEFAULT_TIMEOUT_MS 120000 (maximum 600000); mini-SWE-agent v2 defaults to 30 seconds
Output the agent may need latera file it can read or tail when it needs itCursor writes long shell and MCP output to files; Claude Code persists tool results over 50,000 characters
A failed checkthe error, plus the context needed to fix itSWE-agent's lint gate shows the error, the rejected edit and the original snippet

Models treat observations as instructions, so the wording changes what they do next. In the SWE-agent paper's ablations, leaving the original snippet out of the lint gate's message made the agent repeat the same command more often.

Under mini-swe-agent's 30-second timeout, Scale and Reflection saw GLM-5.3 and Kimi K3 learn on their own to start long builds in the background and poll them with sleep 29; cat /tmp/build.log, a sleep one second shorter than the timeout. The timeout message in example_run.py spells that technique out for any model that has not learned it.

Cursor moved long outputs into files because truncation “can lead to data loss”, and in Dynamic context discovery it reports fewer unnecessary summarizations. The other rows come from Codex's output-truncation source and from Claude Code's tools reference and environment variables.

The tools reference also shows an observation that tells the model what to do next. An oversized read now returns a PARTIAL view notice that explains offset and limit, instead of an error.

Hold the bash tool from section 6 up against the table and it follows four of the six rules. It reports the exit code and names empty output. It cuts the middle out of long output with a note, and it kills a hung command with an explanation. Chapter 5 replaces it with tools that budget output in tokens, write long results to files and phrase errors as instructions.

The same loop, hosted

You do not have to own the loop. OpenAI's range runs from the Codex SDK to a hosted Agents API, and Anthropic's Agent SDK overview compares four routes:

  • the Agent SDK, which runs the loop in your process;
  • the Claude Code CLI;
  • the Client SDK, where you write your own tool loop as hx does, or use the beta tool runner;
  • Managed Agents, a hosted harness.

The Claude Agent SDK is “a library that runs the Claude Code binary”, and TypeScript SDK v0.3.291 bundles Claude Code v2.1.291, so when you upgrade the SDK, you upgrade the harness.

Two defaults matter when you compare it with hx. The migration guide says the default system prompt “covers tool calling but omits the rest of the claude_code preset's content, including its security and safety instructions”. And settings files load unless you pass an empty settingSources.

The example task through the Agent SDK and the CLIs
loop_sdk.ts
typescript
// loop_sdk.ts: the example_run.py task through the Claude Agent SDK (Chapter 2).
// npm install @anthropic-ai/claude-agent-sdk, then: HX_WORKDIR=~/scratch/target npx tsx loop_sdk.ts
import { query } from "@anthropic-ai/claude-agent-sdk";

const SYSTEM =
  "You are a coding agent in a git repository. Use the bash tool to read code, edit files " +
  "and run checks. Run the tests before you say you are done. When the task is complete, " +
  "reply with a two-line summary and no tool call.";

async function main(task: string) {
  for await (const message of query({
    prompt: task,
    options: {
      model: "claude-sonnet-5-5",
      cwd: process.env.HX_WORKDIR ?? process.cwd(),
      systemPrompt: SYSTEM,
      tools: ["Bash"], // the only tool that exists in this session
      allowedTools: ["Bash"], // and it runs without a permission prompt
      permissionMode: "dontAsk", // anything not pre-approved is denied, never asked
      settingSources: [], // ignore user, project and local settings files
      maxTurns: 30,
      maxBudgetUsd: 1.0,
    },
  })) {
    if (message.type === "assistant") {
      for (const block of message.message.content) {
        if (block.type === "tool_use") console.log("bash:", JSON.stringify(block.input));
      }
    } else if (message.type === "result") {
      // subtype: success | error_max_turns | error_max_budget_usd | error_during_execution
      console.log(message.subtype, message.num_turns, "turns", "$" + message.total_cost_usd.toFixed(4));
    }
  }
}

main(process.argv.slice(2).join(" ") || "Run pytest -q, fix the first failing test, and rerun pytest -q.");

In the first two tabs, tools decides which tools exist, while allowedTools only pre-approves them, and the reference says allowedTools “does not restrict Claude to only these tools.” A permissionMode of dontAsk denies anything not pre-approved instead of prompting, which an unattended run needs. A capped run ends with a result whose subtype names the cap.

In return for Claude Code's tools and compaction, hooks and session files, part of each request now comes from the bundled binary instead of your own code.

Anthropic's Managed Agents moves the loop off your machine and splits it three ways. The session is an “append-only log”, the same idea as the hx log. The harness is the loop that calls Claude and routes tool calls, and the sandbox is where tools run.

Small interfaces join the three, such as execute(name, input), which returns a string, along with wake(sessionId) and getEvents(). Anthropic calls it “a meta-harness” and notes that “The harness doesn't know whether the sandbox is a container, a phone, or a Pokémon emulator.”

Anthropic's first design ran all three in one container. It was a pet, and its only debugging window was the WebSocket event stream.

After the split, a dead container comes back to Claude as a tool-call error, a crashed harness reboots from the session log, and “The harness is never made aware of any credentials.” And provisioning a container only when a tool call needs one cut median time to first token by roughly 60%, Anthropic says.

The launch post prices Managed Agents at token rates plus $0.08 per session-hour of active runtime. The docs put it behind the managed-agents-2026-04-01 beta header and say it is not eligible for Zero Data Retention or a HIPAA business associate agreement.

OpenAI's Agents API offers “the same harness and infrastructure that powers Codex”. A session starts with client.beta.agents.sessions.create, which takes an agent naming the model, the tools and an optional multi_agent block. It also takes vault_ids and an environment of type openai_hosted or self_hosted, and compaction, tool search and programmatic tool calling are managed for you.

Among OpenAI's customer claims, Hypha reports 86% fewer failed responses “by separating the agent harness from the sandbox”, the same split Anthropic made. And the Codex SDK drives the same harness from your own code, through new Codex(), startThread() and thread.run().

Claude Agent SDKAnthropic Managed AgentsOpenAI Agents API
Where the loop runsyour process, through the bundled Claude Code binaryAnthropic's hosted harnessOpenAI's hosted Codex harness
Where tools runyour machine, with a sandbox optionan Environment: Anthropic's cloud or a self-hosted sandboxan openai_hosted or self_hosted environment
Session statesession files on disk (persistSession); sessionStore mirrors them elsewherean append-only session log; wake(sessionId), getEvents()hosted sessions (client.beta.agents.sessions)
Context handlingClaude Code's compactioncompaction, reported as agent.thread_context_compacted eventsmanaged automatic compaction
Price beyond tokensnone; it is a library$0.08 per session-hour of active runtime“no additional fees” beyond tokens and tools
Status, October 2026TypeScript v0.3.291, Python v0.2.163public beta since 2026-04-08; not eligible for ZDR or a HIPAA BAApublic beta since 2026-09-10

Whichever you pick, ask it the three questions hx answers in code: where the session log lives, where tools run, and which caps end a run.

Where the minimal loop breaks

The minimal loop works under three conditions: the model is strong, the task fits one context window, and nothing the model might do is dangerous. Real work breaks those conditions in five recurring ways, and each one gets a chapter of its own.

Five ways the minimal loop breaks

Step 1 / 5
1. Context overflow and rot (Chapters 3 and 4)
Every turn appends the response and the full observation, and nothing ever leaves. In the harness study behind section 5's repeat detector, runs without context management overflowed the window on 78.7% of SWE-bench tasks at 32K tokens and on 8.7% at 128K, while managed runs never did. Past that point the API returns a 400 invalid_request_error, “prompt is too long”, and hx stops with error. A second study found that shortening old tool results and handling stalls raised one harness's mean fail-to-pass from 28% to 49% on SWE-bench Verified at a 20,480-token window. Chapters 3 and 4 budget the window and shrink what fills it.

The minimal loop has one more limit, and it comes from its shape. One context does every job. It works out what the task means and makes the plan, then writes the code and judges its own work. Later chapters split those jobs. Chapter 6 hands the judging to a separate evaluator, and Chapter 8 gives planning and research to agents that write no code.

None of these fixes needs a bigger core. Each later chapter adds one hx module through the four hooks, and Chapter 13 assembles them into a background agent that goes from an issue to a reviewed pull request.

Every turn of the loop you just wrote adds to the window, and nothing ever leaves it. So the next question is what deserves a place in that window at all, and that is where Chapter 3 begins.

Chapter 2 in one page

Key takeaways
8 items
  • 1A harness decides what the model sees on every request and what happens to everything it asks for.
  • 2Put stable layers first, as Codex and Claude Code do, because caches hit only on an exact prefix.
  • 3Every request resends the transcript, so 20K to 120K tokens over 40 turns comes to about 2.8M input tokens, about 96% of them cacheable with a perfect prefix. Append changes instead of editing the prefix.
  • 4Treat a minimal loop as the baseline; mini-SWE-agent leads Terminal-Bench 3.0 with one bash tool, and Pi's prompt and four tools fit in under 1,000 tokens.
  • 5Keep a turn cap and a dollar cap priced from usage in the core. Completion checks, repeat detectors and malformed-call limits are middleware, and their firing rates are health metrics.
  • 6Log the request as the model saw it, rebuild every request from the log, and check fingerprints and prefixes.
  • 7Observations carry the exit code, never come back empty, say what was cut, and tell the model what to do after a timeout.
  • 8The minimal loop breaks five ways: overflow (Chapters 3 and 4), output flooding (5), false completion (6), destructive actions (7) and lost state across windows (9).

What to do on Monday: copy hx/loop.py, hx/events.py and example_run.py, point the script at a throwaway clone of a repository with one failing test, and set max_usd to 1.00. Run it, then run python -m hx.events runs/session.jsonl and read the requests the model saw, turn by turn. If the last command before the final reply was not a passing test run, add that run to your failure ledger from Chapter 1.

For members: Chapters 3 to 13

Keep reading Harness Engineering from chapter 3

Chapters 3 to 13 cover building, securing, scaling and measuring the harness, with an appendix of harnesses, benchmarks and sources.

The same membership opens all 10 books in full, new ones on release, with code for Agentic SaaS Playbook, OpenClaw Agents, and AgentOps, and shows your fit for every role on the job board.

€14.99 today · renews monthly · cancel anytime
Cancel anytime: you keep access until the end of the month or year you paid for.