08A.4 Harness Engineering: Everything Around the Model

Agents & multimodalLesson 4 of 1514,305 words16 parts
Module 08A · 0 of 15 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

You have built the loop (08A.2), designed tools (08A.6), added memory (08B.2), guarded the agent (08A.14) and met a coding agent (08A.15). This lesson gives the sum of those pieces a name, harness engineering, and teaches the part the earlier lessons did not: how to design everything around the model so that the same model does measurably better work, runs for hours without losing the thread, and keeps working as the models underneath it change.

What you'll learn

  • What a harness is, where the word came from, and how harness engineering differs from prompt engineering and context engineering
  • The twelve components of a real harness, with examples from Claude Code, Codex CLI, Cursor, Devin, Deep Agents and Manus
  • The long-running-agent patterns: initializer agent, progress file, feature list, git checkpoints, and the failure each one fixes
  • The evidence that harness changes move benchmark scores by double-digit points with the model held fixed, and why that evidence needs careful reading
  • The principles practitioners converge on: build to delete, make the repo legible, enforce mechanically, disclose progressively, separate generating from judging
  • A complete, runnable ~130-line harness (loop, path confinement, command allow-list, stop gate, output offloading, log) with real output
  • What the harness looks like for five kinds of agent, and a hardening checklist
  • How to split the harness into six components with seams (tools, context and memory, guardrails and permissions, budgets and stop conditions, tracing, evals), with a runnable piece of each that plugs into the 6.1 harness
  • How to evaluate a harness change: hold the model fixed, change one component, compare on the same tasks and seeds, and report success rate and cost per successful task
  • Which lesson builds each component properly, so you know where to go next

What you don't need

  • API keys. The runnable harness uses a scripted stand-in model, as in 08A.2, and the experiment in Part 15 uses a seeded stand-in that costs nothing.
  • The detail of guardrail taxonomies, sandboxing and the loop itself. They live in 08A.2, 08A.15 and 08A.14; this lesson links instead of repeating.

Setup

Python 3.11+ and the standard library only. Save the sample as mini_harness.py and run it with python mini_harness.py.

bash
uv init harness --bare --python 3.13 && cd harness
# nothing to install: the sample uses only the standard library

Parts 8 to 15 add more files next to mini_harness.py, one per component. The file table is in 8.3. Everything is standard library only and keyless.

Outputs shown under the runnable sample were produced by running it. Vendor numbers are labelled with their source and date; second-hand figures are marked reported.


What you must be able to do after this lesson#

  • Define what a harness is and how it differs from prompt and context engineering
  • Name the main components of a harness and what each one does
  • Run a minimal harness with path confinement, a command allow-list and a stop gate
  • Apply the core harness principles to an agent design
  • Explain why harness changes can move results with the model held fixed
  • Plug a tool registry, a context manager, a permission policy, a meter and a tracer into the loop through seams, and say which lesson builds each one properly
  • Measure a harness change by holding the model fixed, changing one component and reporting success rate and cost per successful task over repeated, paired runs

Why this matters for an AI engineer#

Situation What you need from this lesson
Two teams use the same model and one agent finishes the task while the other loops The harness is the difference; know what to change first
A long task dies at hour two with half the work undocumented The initializer-plus-progress-file pattern and clean-state handoffs
A new model release makes part of your scaffolding useless or harmful The build-to-delete audit
You inherit "the agent keeps doing X" bugs Hashimoto's rule: turn each repeated mistake into a rule or a tool, not a longer prompt
An interviewer asks "what is a harness?" A definition, a component list and one piece of evidence

Common questions this lesson answers#

Question Where
"What is a harness, and is it just a framework?" Part 1
"What goes into one?" Part 2
"How do agents work for hours across context windows?" Part 3
"Does the harness really matter as much as the model?" Part 4
"How do I keep it from rotting?" Part 5
"Show me a small one." Part 6
"How do I split it into parts I can swap and test?" Part 8
"What does each component look like in code?" Parts 9 to 14
"How do I know a harness change actually helped?" Part 15
"Where do I learn each piece properly?" Part 16
"What would it look like for a support or SRE agent?" Part 7

Part 1: What a harness is#

1.1 Agent = Model + Harness#

Vivek Trivedy of LangChain (10 March 2026) put it as an equation: Agent = Model + Harness, where the harness is "every piece of code, configuration, and execution logic that isn't the model itself." Philipp Schmid (5 January 2026) offered an analogy that sticks: the model is the CPU, the context window is RAM, the harness is the operating system, and the agent is the application.

Everything you have built in this module is part of a harness:

Layer Where you built it
The loop that calls the model, runs tools and feeds results back 08A.2
Tool definitions, descriptions and error messages 08A.6
Memory and state across turns and sessions 08B.2
Sub-agents and orchestration 08D.3
Guardrails, permissions, budgets, tracing 08A.14
Repo instructions, edit tools, sandboxing for coding 08A.15

Even a plain chat product is a harness: something has to keep the message history and send it back each turn. The model alone only turns tokens into tokens. It cannot hold durable state, run code, read today's news or set up an environment.

Harness versus framework: a framework (LangGraph, the OpenAI Agents SDK) gives you building blocks. A harness is the assembled, opinionated system: Claude Code is a harness, and the Claude Agent SDK is that same harness exposed as a library ("the same tools, agent loop, and context management that power Claude Code", per its documentation). You can build a harness with a framework or without one.

1.2 Where the word came from#

The older words were scaffold and, from the SWE-agent paper (Yang et al., May 2024), the agent-computer interface: the argument that language-model agents are "a new kind of end user" who need interfaces designed for them, as humans need good UIs. Anthropic's "Building effective agents" (December 2024) said the agent-computer interface deserves "just as much effort" as the human one. "Harness" had long meant an evaluation harness; by late 2025 it was being used for the runtime wrapper too. Anthropic's "Effective harnesses for long-running agents" (26 November 2025) has it in the title. Mitchell Hashimoto's "My AI Adoption Journey" (5 February 2026) names a step "Engineer the Harness", and OpenAI's post "Harness engineering: leveraging Codex in an agent-first world" (February 2026) is widely credited with popularising the discipline's name. (The timeline is a synthesis of these dated posts; no single source claims who coined the term.)

1.3 Prompt, context and harness engineering#

Discipline The question it asks Scope
Prompt engineering How do I word this instruction? One instruction
Context engineering What is the best set of tokens in the window right now? (Anthropic, Sept 2025) Everything the model sees at inference
Harness engineering What should the whole system around the model provide, prevent, measure and correct? Context plus tools, loop, state, permissions, verification and lifecycle

Birgitta Boeckeler of Thoughtworks (April 2026) calls harness engineering "a specific form of context engineering" that focuses on controls, and splits them in two:

  • Guides are feedforward: they steer the agent before it acts (instructions, docs, examples, templates).
  • Sensors are feedback: they observe after it acts and let it self-correct (tests, linters, type checkers, reviewers).

Sensors split again into computational (deterministic, cheap, run on every change: tests, linters) and inferential (an LLM judge or reviewer: richer, slower, less reliable). Feedback alone means the agent repeats mistakes; guidance alone means nothing checks it. A harness needs both.


Part 2: The components#

2.1 Instructions: the system prompt and repo files#

Every coding harness loads a repo instruction file: CLAUDE.md for Claude Code, AGENTS.md for Codex and many others. Codex concatenates files from the Git root down to the working directory, root first so deeper files win, and stops at a 32 KiB cap (project_doc_max_bytes), so a long file is silently truncated. Two rules from practitioners:

  • Hashimoto: every line should address a specific past bad behaviour. If you cannot name the mistake a line prevents, delete it.
  • OpenAI's write-up, reported via a digest because the primary page would not load for our research: keep the file near 100 lines as a table of contents into a structured docs/ tree, because a monolithic file "crowds out task context and goes stale quickly". Whatever the exact numbers, the principle is shared: if knowledge is not discoverable in the repo, it does not exist for the agent.

2.2 Tools#

Anthropic's "Writing tools for agents" (September 2025) is the reference: few high-impact tools rather than many thin ones (schedule_event, not list_users plus list_events plus create_event); namespaced names; return high-signal fields (names, not UUIDs); a response_format of concise or detailed (their example: about 72 versus 206 tokens); pagination and truncation (Claude Code caps tool responses at 25,000 tokens by default); error messages that tell the model what to do next. In "Building effective agents" they describe poka-yoke design: when the model kept making errors with relative paths after changing directory, requiring absolute paths fixed it, and the team "spent more time optimizing tools than the overall prompt".

The strongest version of "fewer tools" is Vercel's d0 text-to-SQL agent (Dec 2025): it went from 17 specialised tools to a bash tool plus one SQL-execution tool over a file-based semantic layer. On five representative queries success rose from 4/5 to 5/5, average time fell from 274.8 s to 77.4 s and tokens by about 37%. Five queries is an anecdote, not a benchmark, but the direction matches what others report: "the model makes better choices when we stop making choices for it."

2.3 The filesystem as memory#

The context window is small and volatile; a disk is large and durable. Harnesses lean on files for four jobs:

  1. Offloading: long tool output is written to a file and only the head and tail stay in context. Cursor's "dynamic context discovery" post (Jan 2026) does this for tool and MCP output, saves chat history to files so the agent can grep what a lossy summary dropped, and loads only tool names and a small amount of static context up front. In an A/B test, runs that called an MCP tool used 46.9% fewer total tokens.
  2. Restorable compression: Manus drops a web page's content but keeps its URL, drops a document but keeps its path, so nothing is lost for good.
  3. Plans and notes: a todo.md the agent rewrites. Manus calls this recitation: pushing the goals to the end of context counters drift over a typical ~50-call task.
  4. Handoff between sessions: Part 3.

2.4 Sub-agents for context isolation#

A sub-agent works in a clean window and returns a condensed report, so the parent's context is not filled with the sub-agent's exploration. Anthropic's research system (June 2025) used a lead Opus 4 with Sonnet 4 sub-agents and beat single-agent Opus 4 by 90.2% on Anthropic's internal research eval, at about 15 times the tokens of a chat (agents alone used about 4 times). Token usage by itself explained about 80% of the variance on BrowseComp. Their failure modes are the ones to design against: spawning many sub-agents for simple queries, endless searching, duplicated work.

2.5 Compaction and resets#

Summarising near the limit (compaction) is lossy; clearing old tool results is its lightest form. A context reset starts a fresh agent with a structured handoff instead of a summary. Claude Code exposes PreCompact and PostCompact hook events, and a PreCompact hook can block compaction. Cursor's answer to lossiness is to keep the full history in searchable files. Cognition reports that Sonnet 4.5 wrote its own CHANGELOG.md/SUMMARY.md notes, but the summaries "weren't comprehensive enough" to replace Devin's own memory system.

2.5b Hooks and middleware#

Hooks run deterministic code at lifecycle points. Claude Code's events include SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStop, TaskCompleted and PreCompact. Exit code 2 blocks: from PreToolUse it blocks the call, from Stop it keeps the agent working. That second behaviour is the stop gate: the agent says it is done, the harness runs the tests, and if they fail the agent is told so and continues. LangChain's Deep Agents ships the same idea as middleware (a pre-completion checklist, a loop detector that counts edits per file, a local-context middleware that maps the working directory at start-up).

2.6 Permissions and sandboxes#

Claude Code's permission tiers (reads free; bash, edits and web fetches ask) sit on top of an OS-level sandbox: bubblewrap on Linux, Seatbelt on macOS. Anthropic's write-up (October 2025) stresses that you need both filesystem and network isolation: without network isolation a compromised agent can send your SSH keys out, without filesystem isolation it can escape the network limit. Sandboxing cut permission prompts by 84% in Anthropic's internal use. For Claude Code on the web, git credentials stay outside the sandbox and a proxy checks the operation (for example, push only to the configured branch) before attaching the token. Codex CLI has three sandbox modes (read-only, workspace-write, full access) plus approval policies. The deep treatment is 08A.14; the harness-level point is that the credential never lives where model-written code runs.

2.7 Skills and MCP#

Skills use progressive disclosure in three levels: the name and description sit in the system prompt, the SKILL.md body loads when relevant, linked files load only when needed, and bundled scripts can run without ever entering context. MCP tool definitions flood the window if loaded eagerly, which is why Cursor and LangChain both load them lazily.

2.8 Verification loops#

A model told to build something will happily declare it done. Anthropic's long-running post found Claude marking features complete after unit tests and curl; prompting it to test through a real browser, as a human user would, improved things markedly (with a limit: the Puppeteer integration could not see native browser alert dialogs). Boeckeler adds that sensors work best when their output is written for an LLM (a linter message that says how to fix the problem) and calls behaviour verification "the elephant in the room": good harnesses for functional behaviour are still to be figured out.

2.9 Stop conditions, checkpoints and observability#

Budgets and step limits are in 08A.2. Beyond them: a stop gate (2.5b), a time-budget warning injected near the limit, and effort-scaling rules in the prompt (Anthropic's research system: a simple fact lookup gets one agent and 3 to 10 tool calls). Checkpoints are usually git commits. Anthropic's Managed Agents design (April 2026) goes further and keeps an append-only session log outside the harness, so a crashed harness can be replaced and resumed from the last event. Observability and trajectories are also the dataset: Schmid's line is "the harness is the dataset."

2.10 A product snapshot#

Product Notable harness choices
Claude Code CLAUDE.md, skills, sub-agents, about 30 hook events, tiered permissions plus OS sandbox, MCP, auto-compaction, 25,000-token tool-result cap; the same engine is exposed as the Agent SDK
Codex CLI AGENTS.md chain with a 32 KiB cap, three sandbox modes, approval policies and command rules, an App Server protocol so one harness drives CLI, IDE and web
Cursor Everything long goes to files; skills and MCP tools are discovered lazily
Devin Rebuilt for Sonnet 4.5; reminders at both ends of the prompt to counter context anxiety; its own memory system
Deep Agents write_todos, a virtual filesystem, task sub-agents, summarisation, AGENTS.md, skills, middleware
Manus Cache-first design, logit masking to constrain tools without changing the prompt, filesystem memory, todo recitation, failed actions kept in context

Manus's single most useful number for harness designers: its cached input on Claude Sonnet cost $0.30 per million tokens against $3 uncached, and its agent runs at roughly 100 input tokens per output token, so it calls the KV-cache hit rate "the single most important metric for a production-stage agent". The rule that follows is to keep the prefix stable, make context append-only, serialise deterministically and never add or remove tools mid-task. Lesson 11B.4 covers why, and 11B.2 covers what it does to the bill.


Part 3: Harnesses for long-running work#

Deep-dive

A single context window ends. A task that takes hours or days spans many windows, and each new session starts with no memory, like "engineers working shifts without handoff notes". Justin Young's post for Anthropic (26 November 2025) describes the pattern that fixed this, and it is worth knowing in detail because every serious long-running harness resembles it.

3.1 The two failure modes#

  1. One-shotting: the agent tries to build everything at once, runs out of context mid-feature and leaves half-implemented, undocumented work.
  2. Premature completion: a later session looks around, sees progress, and declares the job done.

Compaction alone did not fix either: even a strong model looping across windows on a high-level prompt did not produce a production-quality app.

3.2 The initializer and the coding agent#

The harness uses one agent, one system prompt and one set of tools, with a different first prompt in the first session:

  • The initializer agent (session 1 only) sets up the environment: an init.sh that starts the dev server and runs a basic end-to-end check; a claude-progress.txt log; a feature list as JSON with every feature marked "passes": false; and an initial git commit.
  • The coding agent (every later session) works one feature at a time and ends each session in a clean, mergeable, documented state with a descriptive git commit and an updated progress file.

The feature list is JSON on purpose: models were less likely to overwrite it than a Markdown file. Agents may change only the passes field, and the prompt is blunt about it ("It is unacceptable to remove or edit tests because this could lead to missing or buggy functionality").

Each coding session opens with a startup routine: print the working directory; read the git log and the progress file; read the feature list and pick the highest-priority unfinished item; run init.sh and the basic end-to-end test to catch a broken state before adding to it.

json
{
  "features": [
    {"id": 1, "category": "functional", "description": "User can start a new chat", "steps": ["open app", "click New chat", "see empty thread"], "passes": false},
    {"id": 2, "category": "functional", "description": "Sending a message shows a reply", "steps": ["type hi", "press Enter", "see assistant reply"], "passes": false}
  ]
}

(illustrative shape; the post describes the idea, not this exact schema)

Failure Harness fix
Declares victory too early Structured feature list; one feature at a time
Leaves bugs or undocumented progress Git repo, progress notes, end every session with a commit
Marks features done without testing Verify through the browser before flipping passes
Wastes time working out how to run the app init.sh

3.3 Generator and evaluator#

A follow-up from Anthropic Labs (Prithvi Rajasekaran, 24 March 2026) adds two findings. First, context anxiety: Sonnet 4.5 wrapped work up early as it approached its perceived limit. Cognition independently called it "the first model we've seen that is aware of its own context window", observed it consistently underestimating its remaining tokens, and found that enabling the 1M-token beta but capping use at 200k made it behave normally. Context resets fixed it at the cost of complexity and latency. Second, self-evaluation bias: agents rate their own work too kindly, so a separate, skeptical evaluator (using Playwright, with a hard threshold per criterion) and an agreed "sprint contract" (what done means and how it will be checked) work better than self-review.

Their cost numbers show why you should add harness only when it earns its keep. A retro game maker with Opus 4.5 took 20 minutes and $9 solo and the core gameplay was broken; the full planner-generator-evaluator harness took 6 hours and $200 (over 20 times the cost) and was playable. With Opus 4.6 and a simplified harness a digital audio workstation took about 4 hours and $124.70. The context resets were dropped when Opus 4.5 largely stopped showing context anxiety, and the sprint construct was dropped with Opus 4.6.

3.4 Loops#

The Ralph loop (LangChain's term): a hook intercepts the model's attempt to exit and re-injects the original prompt in a fresh context, with state carried in the filesystem. It is the crudest long-running harness and sometimes enough. Its cousin, the loop detector, counts repeats (the same call three times, the same file edited many times) and tells the agent to rethink.


Part 4: The evidence, and how to read it#

Deep-dive
Result Controlled? What it shows
LangChain Deep Agents on Terminal-Bench 2.0 (89 tasks): 52.8% to 66.5% with the model (gpt-5.2-codex) fixed; changes were a plan-build-verify-fix prompt, a pre-completion checklist, local-context mapping, time budgets, loop detection and a reasoning "sandwich" (Trivedy, 17 Feb 2026) Yes: model fixed, harness changed +13.7 points from harness alone. Maximum reasoning everywhere scored 53.9% (timeouts) against 63.6% at high, so more reasoning is not simply better
Audit of 254 SWE-bench submissions (Liu et al., Sept 2026; not re-run) No: observational Within one model, scaffolds differ by up to 29.8 points, while the whole top 30 leaderboard spans 8.8 points
Epoch AI on SWE-bench Verified (2025) No, and Epoch says so Claude 3.7 Sonnet 62.3% to 70.2% with custom scaffolding; scaffold choice can move results "by up to 20%"
Meta-Harness (Lee, Khattab, Finn et al., 30 Mar 2026) Yes: automated search over harness code +7.7 points over a state-of-the-art context-management system on a text-classification task with 4 times fewer context tokens; +4.7 points on average across five held-out models on 200 IMO-level problems
Anthropic tool-description refinement (2025) Partly Description changes alone reached state of the art on SWE-bench Verified for Claude 3.5 Sonnet; a tool-testing agent that rewrote descriptions cut later task time by 40%

Reported, not verified against the live leaderboard: a blog compiled Opus 4.6 Terminal-Bench 2.0 scores by harness (Claude Code at 58.0%, other harnesses from 62.9% to 81.8%). Treat those as indicative only.

How to read it honestly. The controlled results (the first and fourth rows) are the strong evidence. The observational ones suggest the effect is large but confound the scaffold with everything else. None of it says the harness matters more than the model: model upgrades still move scores, and some harness gains will be absorbed into future models. A fair claim: for a fixed model, harness changes are worth several to roughly 20 or more points on agentic benchmarks, which is often larger than the gap between neighbouring models. There is also a trap in the other direction: models are post-trained against their vendor's own harness, so the best harness for a task is not automatically the one a model shipped with.


Part 5: Principles#

  1. Build to delete. Every component encodes an assumption about what the model cannot do alone. Stress-test each assumption on every new model. The context resets above died with a model upgrade; Vercel deleted 80% of its tools and improved; Manus rebuilt its framework several times (its own post says four). Schmid: "If you over-engineer the control flow, the next model update will break your system."
  2. Fix mistakes by engineering, not by nagging. Hashimoto's rule: when an agent errs, either add a line to the instruction file that addresses exactly that behaviour or build a real tool for it (a script that takes the screenshot, a filtered test runner), and tell the agent the tool exists.
  3. Make the environment legible. The agent can only use what it can see: put the knowledge in the repo, make the app bootable per worktree, expose logs and metrics to the agent. The long-running artifacts (init.sh, progress file, feature list) are legibility tools.
  4. Enforce invariants mechanically. Prefer a structural test or a linter whose message says how to fix the problem over a sentence in a prompt. Reported from OpenAI's write-up: layered architecture enforced by custom lints, and validation at boundaries rather than inside implementations.
  5. Fight entropy. Agent-written code drifts. OpenAI's team reportedly spent a fifth of its time cleaning up "AI slop" by hand before encoding golden principles and running recurring background agents that scan for drift and open small refactor PRs. Whatever your numbers, schedule the cleanup.
  6. Disclose progressively. Names first, details on demand: skills, MCP tool folders, a table-of-contents instruction file, just-in-time retrieval by path or query.
  7. Prefer fewer, better tools. Start from a general tool (bash, file read and edit) and add specialised ones only where traces show a need.
  8. Separate generating from judging. Use an independent evaluator for subjective work, and tests for objective work.
  9. Keep credentials out of the sandbox. A proxy or vault attaches them outside the place where model-written code runs.
  10. Design for the cache. Stable prefix, append-only context, deterministic serialisation (11B.4).
  11. Start simple. Anthropic's advice since 2024: find the simplest solution and add complexity only when it demonstrably helps; frameworks can hide the prompts and responses you most need to see.
  12. Harnessability varies. Typed code, clear module boundaries and good tests make controls cheaper (Boeckeler); legacy code needs the harness most and is the hardest to build it for.

Part 6: A minimal harness you can run#

The sample is one file of about 130 lines. It has: a budgeted loop; an instruction-file loader with a byte cap; a tool registry; path confinement; a command allow-list with shell=False, a timeout and a scrubbed environment; actionable error messages that stay in context; a stop gate that runs the tests before the agent may finish; oversized-output offloading; repeat detection; and an append-only JSONL log. The model is a scripted stand-in that makes four mistakes on purpose: it reads outside the workspace, tries to finish before fixing the bug, runs rm -rf, and only then does the work.

6.1 mini_harness.py#

python
"""mini_harness.py - a minimal agent harness: loop, tools, permissions, hooks, context, log."""
import json, subprocess, sys, tempfile, time
from pathlib import Path

# ---- 1. config and budgets -------------------------------------------------
MAX_STEPS = 12
MAX_TOOL_CHARS = 2000            # per-tool-result cap before offloading to a file
AGENTS_MD_MAX_BYTES = 32 * 1024  # silently truncating is a bug; we cut and say so
BASH_ALLOW = {("python", "-m", "unittest"), ("ls",), ("cat",)}  # argv prefixes

# ---- 2. context loader: AGENTS.md from repo root down to cwd ---------------
def load_instructions(root: Path) -> str:
    f = root / "AGENTS.md"
    if not f.exists():
        return ""
    raw = f.read_bytes()[:AGENTS_MD_MAX_BYTES].decode("utf-8", "replace")
    return "# Repo instructions\n" + raw

# ---- 3. permission layer: confine paths, allow-list commands ----------------
class Denied(Exception):
    pass

def confine(root: Path, rel: str) -> Path:
    p = (root / rel).resolve()
    if not p.is_relative_to(root.resolve()):
        raise Denied(f"path {rel!r} is outside the workspace; use a path inside it")
    return p

# ---- 4. tool registry ------------------------------------------------------
TOOLS = {}
def tool(fn):
    TOOLS[fn.__name__] = fn
    return fn

@tool
def read_file(root, path):
    return confine(root, path).read_text()

@tool
def edit_file(root, path, old, new):
    p = confine(root, path)
    text = p.read_text()
    if text.count(old) != 1:
        raise Denied(f"'old' must match exactly once; it matched {text.count(old)} times")
    p.write_text(text.replace(old, new))
    return "edited"

@tool
def bash(root, argv):
    if not any(tuple(argv[: len(a)]) == a for a in BASH_ALLOW):
        raise Denied(f"command {argv!r} is not allowed; allowed prefixes: {sorted(BASH_ALLOW)}")
    run_argv = [sys.executable if argv[0] == "python" else argv[0]] + argv[1:]   # "python" may not be on PATH
    r = subprocess.run(run_argv, cwd=root, capture_output=True, text=True, timeout=20, shell=False,
                       env={"PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"})  # scrubbed env; no stale .pyc
    return f"exit={r.returncode}\n{r.stdout}{r.stderr}"

# ---- 5. hooks ---------------------------------------------------------------
def on_stop_gate(root):
    """Pre-completion check: the agent may only finish if the tests pass."""
    out = bash(root, ["python", "-m", "unittest"])
    return out.startswith("exit=0"), out

# ---- 6. context manager: offload oversized output, keep head and tail -------
def fit(result: str, root: Path, step: int) -> str:
    if len(result) <= MAX_TOOL_CHARS:
        return result
    spill = root / ".harness" / f"step{step}.txt"
    spill.parent.mkdir(exist_ok=True)
    spill.write_text(result)
    half = MAX_TOOL_CHARS // 2
    return f"{result[:half]}\n...[{len(result) - MAX_TOOL_CHARS} chars cut; full output in {spill.relative_to(root)}]...\n{result[-half:]}"

# ---- 7. the loop ------------------------------------------------------------
def run(model, root: Path, task: str, log: Path):
    messages = [{"role": "system", "content": "You are a coding agent.\n" + load_instructions(root)},
                {"role": "user", "content": task}]
    seen_calls = {}
    for step in range(1, MAX_STEPS + 1):
        reply = model(messages)                       # {"tool": name, "args": {...}} or {"final": text}
        messages.append({"role": "assistant", "content": json.dumps(reply)})
        if "final" in reply:
            ok, detail = on_stop_gate(root)
            _log(log, step, "stop_gate", ok)
            if ok:
                return reply["final"], step
            messages.append({"role": "user", "content": f"Not done: tests fail.\n{fit(detail, root, step)}"})
            continue
        key = json.dumps(reply, sort_keys=True)
        seen_calls[key] = seen_calls.get(key, 0) + 1
        if seen_calls[key] >= 3:
            messages.append({"role": "user", "content": "You repeated this call 3 times. Change approach."})
            continue
        t0 = time.time()
        try:
            out = TOOLS[reply["tool"]](root, **reply["args"])
            err = False
        except (Denied, KeyError, TypeError, FileNotFoundError) as e:
            out, err = f"ERROR: {e}", True            # actionable, and kept in context
        messages.append({"role": "tool", "content": fit(out, root, step)})
        _log(log, step, reply["tool"], not err, round(time.time() - t0, 3))
    return "STOPPED: step budget exhausted", MAX_STEPS

def _log(log, step, what, ok, secs=None):
    with log.open("a") as f:
        f.write(json.dumps({"step": step, "event": what, "ok": ok, "secs": secs}) + "\n")

# ---- demo: a scripted stand-in model, so no API key is needed ---------------
def make_scripted_model():
    script = iter([
        {"tool": "read_file", "args": {"path": "calc.py"}},
        {"tool": "read_file", "args": {"path": "../secrets.txt"}},          # tries to escape
        {"final": "I think it is fixed."},                                   # premature: gate will refuse
        {"tool": "edit_file", "args": {"path": "calc.py", "old": "a - b", "new": "a + b"}},
        {"tool": "bash", "args": {"argv": ["rm", "-rf", "."]}},             # not on the allow-list
        {"tool": "bash", "args": {"argv": ["python", "-m", "unittest"]}},
        {"final": "Fixed add(): it subtracted. Tests pass."},
    ])
    return lambda messages: next(script)

if __name__ == "__main__":
    work = Path(tempfile.mkdtemp())
    (work / "AGENTS.md").write_text("Run `python -m unittest` before you finish.\n")
    (work / "calc.py").write_text("def add(a, b):\n    return a - b\n")
    (work / "test_calc.py").write_text(
        "import unittest\nfrom calc import add\n\nclass T(unittest.TestCase):\n"
        "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n")
    log = work / "run.jsonl"
    answer, steps = run(make_scripted_model(), work, "add() is wrong; fix it.", log)
    print("answer:", answer, "| steps:", steps)
    for line in log.read_text().splitlines():
        print(line)

Real output (the temporary directory differs on each run):

text
answer: Fixed add(): it subtracted. Tests pass. | steps: 7
{"step": 1, "event": "read_file", "ok": true, "secs": 0.0}
{"step": 2, "event": "read_file", "ok": false, "secs": 0.0}
{"step": 3, "event": "stop_gate", "ok": false, "secs": null}
{"step": 4, "event": "edit_file", "ok": true, "secs": 0.0}
{"step": 5, "event": "bash", "ok": false, "secs": 0.0}
{"step": 6, "event": "bash", "ok": true, "secs": 0.031}
{"step": 7, "event": "stop_gate", "ok": true, "secs": null}

Read the log as the harness's view of the run: step 2 was the escape attempt (denied with an error the model can act on), step 3 was the premature "done" (refused by the gate), step 5 was rm -rf (not on the allow-list), and only step 7 let the agent finish.

6.2 A bug this sample taught us#

While writing it, the final gate kept failing even though the file was fixed. The edit changed a - b to a + b: same file size, same second, so Python's cached bytecode (__pycache__) looked fresh and the old code ran. The fix is the PYTHONDONTWRITEBYTECODE=1 in the scrubbed environment. It is a good example of a harness-level bug: nothing was wrong with the model or the tool logic, and an environment detail made the gate lie. Your sensors need to be as trustworthy as the thing they check.

6.3 What the sample leaves out#

Gap Add
Real model Replace model(messages) with a provider call (08A.2); keep the tool-call format identical
Real isolation Run the whole thing in a container or OS sandbox; shell=False and an allow-list are a first layer, not a sandbox
Compaction Summarise the middle when tokens pass a threshold; keep system prompt, plan and last turns
Sub-agents A task tool that starts the same loop with a fresh message list and returns one report
Git checkpoints git add -A && git commit after each verified step; resume from the log
Approvals A callback for risky tools (08A.14's policy layer)

Parts 8 to 14 close most of these gaps in toy form, one component at a time: the seams and a loop that ends with a named reason (Part 8), a tool registry with validation (Part 9), a context view and notes (Part 10), a permission policy with an approval tier (Part 11), a four-way meter (Part 12) and a tracer (Part 13). Real isolation, real compaction, sub-agents and git checkpoints stay out, and Part 16 says where each is built.

6.4 Hardening checklist#

  • Budgets: steps, wall time, tokens and cost per run and per day; a kill switch.
  • Execution: no shell=True; argv allow-list; timeouts; pinned working directory; scrubbed environment; network off or a proxy allow-list; symlink-safe path confinement; credentials outside the sandbox.
  • Permissions: approval tiers for destructive or external actions; deny unknown tools; validate arguments against a schema.
  • Injection: treat tool, file and web content as data (08A.14).
  • Gates: tests and linters before "done"; no editing tests to pass; an independent evaluator for subjective work.
  • Loops: identical-call detection, per-file edit counters, escalate to re-planning.
  • Context: offload big outputs, compact before the limit, keep failed actions in context, keep the prefix stable, restate the plan near the end.
  • Durability: append-only log, idempotent tools, resume from the last event, atomic writes, clean-state handoffs.
  • Observability: per-step trace with latency, tokens, cost and error; keep trajectories for evals.
  • Evals: about 20 realistic tasks with verifiable end states; change one harness component, hold the model fixed, re-run (LangChain's method). Part 15 runs that method end to end.
  • Delete audit: for each component, write the model weakness it assumes; re-test on each new model.

Part 7: Use cases#

Reference

The first row follows published harnesses. The others are design syntheses built on the same pieces; no primary source was researched for them, so treat them as starting points.

Agent Tools Context and memory Verification Permissions Stop and handoff
Coding read, edit, grep, bash, todo, sub-agents, browser Instruction file as a table of contents, repo map, outputs offloaded to files Tests, linters, structural tests, browser checks, reviewer agent Workspace-write sandbox, network allow-list, git credentials in a proxy Tests pass plus commit; progress file and feature list for long runs
Research search, fetch, note-taking, parallel sub-agents Plan saved to memory; sub-agents write to files and return references Citation check, LLM judge on accuracy, citations, completeness, sources Read-only, web allow-list Effort-scaling rules; resume from checkpoint
Support KB search, read-only account tools, policy-gated write tools (refund, update), hand-off to a human Session memory; policy documents retrieved just in time; concise tool outputs Policy validators on every write tool, output guardrails, confirmation before irreversible steps Per-customer scoping, approval tiers for money-moving actions Escalate on low confidence or loops with a ticket summary
Data analysis SQL, sandboxed Python, file reads of schema and semantic-layer docs Semantic layer as files Row-count and sanity checks, EXPLAIN or dry run, reproduce the headline number Read-only database role, query timeouts, no network Answer plus the query plus the assumptions
Ops and SRE Read-only logs, metrics and traces; runbook skills; cloud CLI Runbooks as skills; an incident timeline file Hypothesis, then evidence from telemetry; confirm the fix in metrics Read-only by default; privileged actions need human approval and short-lived credentials; audit log Page a human when unsure; rollback plan mandatory

Worked example: the support agent's harness#

Take the support row. The model is not the hard part. The harness decides: which tools are read-only (order lookup) and which move money (refund); that every refund call passes a validator (amount under a limit, order belongs to the authenticated customer, not already refunded); that the customer's ID is bound by the harness, not chosen by the model; that three failed attempts or a low-confidence answer hands over to a human with a summary; and that every action is logged for audit. Swap the model and none of those controls change. That is what "the harness is the product" means.


Part 8: From one file to a harness with seams#

Part 6 gave you one file that does everything. That is right for starting and wrong for growing: with the loop, permissions, context trimming and logging tangled together, you cannot change one without risking the others, or measure what one change did. This part cuts the harness into components with clean joints, called seams, so each component of Part 2 can be swapped, tested and measured on its own.

8.1 Six components and the seam for each#

# Component What it decides Seam in the loop Built in
1 Tools What the agent can do, and what a failure tells it tools (a registry) Part 9
2 Context and memory What the model sees on this turn prepare and instructions Part 10
3 Guardrails and permissions What the agent may do check (called before every tool) Part 11
4 Budgets and stop conditions When the run must end, and why meter (before and after every model call) Part 12
5 Tracing What happened, step by step tracer (one span per step) Part 13
6 Evals Whether a change made the harness better outside the loop: a suite that runs it Parts 14 and 15

The stop gate from 6.1 belongs to two components at once (a check the agent cannot argue with, and a stop condition), so it gets its own seam, gate.

8.2 kit.py: the same loop with the seams drawn in#

kit.py imports mini_harness.py (the file from 6.1, unchanged) and reuses its Denied, confine, fit, bash and on_stop_gate. It adds a Components record that holds one plug per seam, and a run() function that is the 6.1 loop rewritten to call the plugs. It also fixes two gaps in 6.1: a gate that keeps refusing now ends the run (gate_failed), and repeated identical calls now end the run after two nudges (stagnation) instead of nudging until the step budget runs out.

Save it next to mini_harness.py.

python
"""kit.py - mini_harness.py with seams: every component is a plug you can swap."""
import json
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Callable

import mini_harness as mh                 # Denied, confine, fit, load_instructions, on_stop_gate, TOOLS

PRICE_IN, PRICE_OUT = 3.00, 15.00         # made-up demo prices, USD per million tokens

def tokens(text: str) -> int:
    return max(1, len(text) // 4)         # crude estimate: about 4 characters per token

class _NoSpan:
    def set(self, **attrs): pass

class NullTracer:                         # component 5 plugs in here
    @contextmanager
    def span(self, name, **attrs):
        yield _NoSpan()

class StepMeter:                          # component 4 plugs in here; this one only counts steps
    def __init__(self, max_steps=12):
        self.max_steps, self.steps = max_steps, 0
    def before(self):                     # None to go on, or a stop reason
        return "step_budget" if self.steps >= self.max_steps else None
    def after(self, sent, reply, span):
        self.steps += 1
    def warning(self):                    # text to show the model, or None
        return None

@dataclass
class Components:
    tools: dict                           # name -> function(root, **args)          (1 tools)
    prepare: Callable                     # messages -> messages the model sees      (2 context)
    check: Callable                       # (name, args) -> None, or raises Denied   (3 permissions)
    meter: object                         # before(), after(), warning()             (4 budgets)
    tracer: object                        # span(name, **attrs)                      (5 tracing)
    gate: Callable | None                 # root -> (ok, detail), or None            (completion check)
    instructions: Callable = mh.load_instructions   # root -> text for the system prompt (2 context)

def default_components() -> Components:
    return Components(tools=dict(mh.TOOLS), prepare=lambda m: m, check=lambda name, args: None,
                      meter=StepMeter(12), tracer=NullTracer(), gate=mh.on_stop_gate)

@dataclass
class Result:
    status: str                           # "done" or a stop reason
    answer: str
    steps: int
    messages: list

def run(model, root: Path, task: str, c: Components, system="You are a coding agent.") -> Result:
    with c.tracer.span("agent.run") as top:
        result = _loop(model, root, task, c, system)
        top.set(outcome=result.status, steps=result.steps)
    return result

def _loop(model, root, task, c, system):
    messages = [{"role": "system", "content": system + "\n" + c.instructions(root)},
                {"role": "user", "content": task}]
    seen, nudges, refusals, step, warned = {}, 0, 0, 0, False
    while True:
        why = c.meter.before()
        if why:
            return Result(why, "", step, messages)
        step += 1
        sent = c.prepare(messages)
        with c.tracer.span("model", step=step, **{"gen_ai.operation.name": "chat"}) as sp:
            reply = model(sent)
            c.meter.after(sent, reply, sp)
        messages.append({"role": "assistant", "content": json.dumps(reply)})
        if "final" in reply:
            if c.gate is None:
                return Result("done", reply["final"], step, messages)
            with c.tracer.span("gate", step=step) as sp:
                ok, detail = c.gate(root)
                sp.set(ok=ok)
            if ok:
                return Result("done", reply["final"], step, messages)
            refusals += 1
            if refusals >= 3:
                return Result("gate_failed", reply["final"], step, messages)
            messages.append({"role": "user", "content": f"Not done: tests fail.\n{mh.fit(detail, root, step)}"})
            continue
        key = json.dumps(reply, sort_keys=True)
        seen[key] = seen.get(key, 0) + 1
        if seen[key] >= 3:
            nudges += 1
            if nudges > 2:
                return Result("stagnation", "", step, messages)
            messages.append({"role": "user", "content": "You repeated this call 3 times. Change approach."})
            continue
        name = reply.get("tool")
        with c.tracer.span("tool", step=step, **{"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name}) as sp:
            try:
                c.check(name, reply.get("args", {}))
                out, ok = c.tools[name](root, **reply.get("args", {})), True
            except (mh.Denied, KeyError, TypeError, FileNotFoundError) as e:
                out, ok = f"ERROR: {e}", False
            sp.set(ok=ok, result_chars=len(out))
        messages.append({"role": "tool", "content": mh.fit(out, root, step)})
        note = c.meter.warning()
        if note and not warned:
            warned = True
            messages.append({"role": "user", "content": note})

if __name__ == "__main__":
    import tempfile
    work = Path(tempfile.mkdtemp())
    (work / "AGENTS.md").write_text("Run `python -m unittest` before you finish.\n")
    (work / "calc.py").write_text("def add(a, b):\n    return a - b\n")
    (work / "test_calc.py").write_text(
        "import unittest\nfrom calc import add\n\nclass T(unittest.TestCase):\n"
        "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n")
    r = run(mh.make_scripted_model(), work, "add() is wrong; fix it.", default_components())
    print("status:", r.status, "| steps:", r.steps, "| answer:", r.answer)

Real output. It is the same scripted run as 6.1, now through the seams, and it takes the same seven steps:

text
status: done | steps: 7 | answer: Fixed add(): it subtracted. Tests pass.

Three things to notice:

  • Defaults reproduce Part 6. default_components() plugs in the 6.1 pieces: mh.TOOLS, a prepare that changes nothing, a check that allows everything, a step-only meter, no tracing.
  • run() returns a Result with a named status: done, step_budget, stagnation or gate_failed (Part 12 adds more). A run must never end silently (08A.3, 1.3).
  • Tool errors are caught in one place and become ERROR: ... text for the model. That is why the wording of an error matters (Part 9).

8.3 Where each piece goes#

From here on, each Part adds one file next to kit.py. Every file imports the one before it, so the program grows by one component at a time:

File Adds Run it with
tools_kit.py (Part 9) Tool specs, argument validation, two error styles, a new list_files tool python tools_kit.py
context_kit.py (Part 10) A loader that says when it cuts, old-result clearing, notes python context_kit.py
policy_kit.py (Part 11) An allow, ask or deny policy with a decision log python policy_kit.py
meter_kit.py (Part 12) A meter for steps, tokens, money and time python meter_kit.py
trace_kit.py (Part 13) A span recorder and a trace viewer python trace_kit.py
test_components.py, evals_kit.py (Part 14) Component tests, a ten-task suite, a stand-in model, an end-state grader python test_components.py, python evals_kit.py
experiment.py (Part 15) Change one component, compare, report success and cost python experiment.py

All of it is standard library only, runs offline and costs nothing. The model in every demo is scripted or a seeded stand-in, as in Part 6.


Part 9: Component 1, tools#

9.1 What it is and why the harness needs it#

A model can only produce text. A tool is how that text becomes an action: the model writes {"tool": "edit_file", ...}, the harness checks it, runs the real function and writes the result back. The tool layer is the agent's whole reach into the world, and where most day-to-day failures happen: a wrong argument name, a missing path, an edit that matches twice.

The harness needs four things from this layer:

  1. A contract. Each tool has a name, a description the model reads, and typed parameters. That text is part of every request, so it is a prompt you maintain (08A.6, Part 1).
  2. Validation before running. Check the arguments against the contract and refuse bad calls with a precise message. The model made the mistake, not the file system.
  3. Errors the model can act on. A failed call is the cheapest moment to steer the agent. "edit failed" leaves it guessing. "The text matched 2 times, include more surrounding lines" tells it the next move (08A.6, 3.4).
  4. Bounded results. A tool that can return a million lines will, one day. Cut the result and say how much was cut (08A.7, Part 6).

Part 2.2 has the evidence for few, high-signal tools; this part gives you the mechanics.

9.2 tools_kit.py#

The file defines a ToolSpec (name, description, parameters, a risk class that Part 11 will read, and the function), four tools, a validator, a renderer that produces the text the model reads, and a registry whose errors come in two styles: terse (only what failed) and helpful (what failed, the detail, and the next step). The two styles exist so that Part 15 can change only the error wording and measure what it does.

python
"""tools_kit.py - component 1: tool specs, argument validation, errors the model can act on."""
from dataclasses import dataclass
from typing import Callable

import mini_harness as mh

class ToolError(mh.Denied):
    """A tool failure with three parts: what failed, the detail, and what to do next."""
    def __init__(self, short, detail, hint):
        super().__init__(f"{short}: {detail}. {hint[0].upper() + hint[1:]}.")
        self.short = short

@dataclass
class ToolSpec:
    name: str
    description: str
    params: dict          # name -> (type, required, meaning)
    risk: str             # "read", "write" or "exec" (the permission layer reads this)
    fn: Callable

# ---- the tools themselves ----------------------------------------------------
def read_file(root, path):
    return mh.confine(root, path).read_text()

def list_files(root, path=".", limit=20):
    base, top = mh.confine(root, path), root.resolve()      # compare resolved paths with resolved paths
    names = sorted(str(p.relative_to(top)) for p in base.rglob("*")
                   if p.is_file() and ".harness" not in p.parts and "__pycache__" not in p.parts)
    if len(names) <= limit:
        return "\n".join(names) or "(empty)"
    return "\n".join(names[:limit]) + f"\n...[{len(names) - limit} more files; pass a larger limit or a narrower path]"

def edit_file(root, path, old, new):
    p = mh.confine(root, path)
    text = p.read_text()
    n = text.count(old)
    if n != 1:
        hint = ("include more surrounding lines in 'old' so it matches exactly once" if n > 1
                else "copy 'old' from the file exactly, including spaces and line breaks")
        raise ToolError("edit failed", f"'old' matched {n} times", hint)
    p.write_text(text.replace(old, new))
    return "edited"

SPECS = [
    ToolSpec("read_file", "Return the text of one file inside the workspace.",
             {"path": ("string", True, "file path relative to the workspace root")}, "read", read_file),
    ToolSpec("list_files", "List files under a folder, at most `limit` names; says how many were cut.",
             {"path": ("string", False, "folder, default '.'"), "limit": ("integer", False, "default 20")},
             "read", list_files),
    ToolSpec("edit_file", "Replace one exact piece of text in a file. 'old' must match exactly once.",
             {"path": ("string", True, "file path"), "old": ("string", True, "text to replace"),
              "new": ("string", True, "replacement text")}, "write", edit_file),
    ToolSpec("bash", "Run one allow-listed command as an argv list (no shell). Returns exit code and output.",
             {"argv": ("array", True, "for example ['python', '-m', 'unittest']")}, "exec", mh.bash),
]

# ---- validation, rendering and the registry ------------------------------------
PYTYPES = {"string": str, "integer": int, "array": list}

def validate(spec: ToolSpec, args: dict):
    for k in args:
        if k not in spec.params:
            raise ToolError("invalid call", f"unknown argument {k!r}", f"valid arguments: {', '.join(spec.params)}")
    for k, (typ, required, _) in spec.params.items():
        if k not in args:
            if required:
                raise ToolError("invalid call", f"missing argument {k!r}", f"required arguments for {spec.name}: {', '.join(p for p, v in spec.params.items() if v[1])}")
            continue
        ok = isinstance(args[k], PYTYPES[typ]) and not isinstance(args[k], bool)
        if not ok:
            raise ToolError("invalid call", f"{k!r} must be {typ}, got {type(args[k]).__name__}", "fix the type and call again")

def render_docs(specs) -> str:
    """What the model reads about the tools. This text is part of every request."""
    lines = []
    for s in specs:
        sig = ", ".join(f"{k}: {t}{'' if req else '?'}" for k, (t, req, _) in s.params.items())
        lines.append(f"- {s.name}({sig}): {s.description}")
    return "# Tools\n" + "\n".join(lines)

class Registry(dict):
    def __init__(self, style, *a):
        super().__init__(*a)
        self.style = style
    def __missing__(self, name):
        e = ToolError("unknown tool", repr(name), f"available tools: {', '.join(sorted(self))}")
        raise mh.Denied(e.short if self.style == "terse" else str(e))

def make_tools(specs=SPECS, style="helpful") -> Registry:
    """style='terse' gives the model only the short error; 'helpful' adds the detail and the next step."""
    def wrap(spec):
        def call(root, **args):
            try:
                validate(spec, args)
                return spec.fn(root, **args)
            except ToolError as e:
                raise mh.Denied(e.short if style == "terse" else str(e))
        return call
    return Registry(style, {s.name: wrap(s) for s in specs})

if __name__ == "__main__":
    import tempfile
    from pathlib import Path
    from kit import tokens
    docs = render_docs(SPECS)
    print(docs, f"\n[{len(docs)} characters, about {tokens(docs)} tokens, sent with every request]\n", sep="")
    work = Path(tempfile.mkdtemp())
    (work / "calc.py").write_text("def add(a, b):\n    return a - b\n\ndef diff(a, b):\n    return a - b\n")
    for n in range(4):
        (work / f"extra{n}.txt").write_text("x")
    calls = [("list_files", {"limit": 3}), ("edit_file", {"path": "calc.py", "old": "a - b", "new": "a + b"}),
             ("edit_file", {"path": "calc.py", "old": "a * b", "new": "a + b"}), ("read_file", {"file": "calc.py"}),
             ("read_file", {}), ("list_files", {"limit": "3"}), ("grep", {"pattern": "add"})]
    for style in ("terse", "helpful"):
        print(f"--- style = {style}")
        tools = make_tools(style=style)
        for name, args in calls:
            try:
                out = tools[name](work, **args)
            except mh.Denied as e:
                out = f"ERROR: {e}"
            print(f"{name} {args}\n    {out!r}")

Real output:

text
# Tools
- read_file(path: string): Return the text of one file inside the workspace.
- list_files(path: string?, limit: integer?): List files under a folder, at most `limit` names; says how many were cut.
- edit_file(path: string, old: string, new: string): Replace one exact piece of text in a file. 'old' must match exactly once.
- bash(argv: array): Run one allow-listed command as an argv list (no shell). Returns exit code and output.
[439 characters, about 109 tokens, sent with every request]

--- style = terse
list_files {'limit': 3}
    'calc.py\nextra0.txt\nextra1.txt\n...[2 more files; pass a larger limit or a narrower path]'
edit_file {'path': 'calc.py', 'old': 'a - b', 'new': 'a + b'}
    'ERROR: edit failed'
edit_file {'path': 'calc.py', 'old': 'a * b', 'new': 'a + b'}
    'ERROR: edit failed'
read_file {'file': 'calc.py'}
    'ERROR: invalid call'
read_file {}
    'ERROR: invalid call'
list_files {'limit': '3'}
    'ERROR: invalid call'
grep {'pattern': 'add'}
    'ERROR: unknown tool'
--- style = helpful
list_files {'limit': 3}
    'calc.py\nextra0.txt\nextra1.txt\n...[2 more files; pass a larger limit or a narrower path]'
edit_file {'path': 'calc.py', 'old': 'a - b', 'new': 'a + b'}
    "ERROR: edit failed: 'old' matched 2 times. Include more surrounding lines in 'old' so it matches exactly once."
edit_file {'path': 'calc.py', 'old': 'a * b', 'new': 'a + b'}
    "ERROR: edit failed: 'old' matched 0 times. Copy 'old' from the file exactly, including spaces and line breaks."
read_file {'file': 'calc.py'}
    "ERROR: invalid call: unknown argument 'file'. Valid arguments: path."
read_file {}
    "ERROR: invalid call: missing argument 'path'. Required arguments for read_file: path."
list_files {'limit': '3'}
    "ERROR: invalid call: 'limit' must be integer, got str. Fix the type and call again."
grep {'pattern': 'add'}
    "ERROR: unknown tool: 'grep'. Available tools: bash, edit_file, list_files, read_file."

9.3 What the run shows#

  • The tool docs are not free. Four tools cost about 109 tokens, sent with every request. Fifty tools would cost well over a thousand tokens on every step. That is why 08E.4 and Part 2.7 talk about loading tool definitions lazily.
  • list_files cuts and says so. ...[2 more files; pass a larger limit or a narrower path] is a truncation marker. Without the marker the model believes it saw everything.
  • The same failure, two messages. Under terse, the model learns only that the edit failed. Under helpful, it learns that old matched twice and what to change. For a model that does read and follow messages, that is the difference between one retry and a loop.
  • Every validation failure names the fix. An unknown argument lists the valid ones, a missing argument lists the required ones, a wrong type says which type was expected.
  • A bug the sample taught us. The first list_files crashed on macOS: /var is a symlink to /private/var, so the resolved path was not inside the unresolved root. Same class as 6.2: compare resolved paths with resolved paths.

9.4 Where to go for depth#

You will build this properly in two lessons. 08A.6 covers names, descriptions, granularity, result design and measuring tools. 08A.7 covers the border: read and write tools, idempotency keys, validating input and results, untrusted results. For tools that come from MCP servers, see 08E.2.


Part 10: Component 2, context and memory#

10.1 What it is and why the harness needs it#

The model has no memory between calls. Everything it "knows" is the list of messages you send, which has a size limit and a price. In an agent loop the list grows by two messages per step and tool results are big: a run that reads six files has six files in the window whether or not the model still needs them.

So the harness needs a context manager: code that decides on every turn what the model sees. It has four jobs:

  1. Load the standing instructions (the repo's AGENTS.md or CLAUDE.md) and say loudly if it had to cut them.
  2. Keep the window small by clearing old tool results first, because they are the biggest and the most replaceable.
  3. Keep the goal in sight by restating notes at the end of the context (Manus calls this recitation, Part 2.3).
  4. Never destroy the record. The model sees a view; the full history stays intact for the log, for resuming and for audits.

10.2 context_kit.py#

The file has a loader that appends a visible notice when it cuts, a function clear_old_results that returns a trimmed copy of the history, a note tool that appends a line to .harness/notes.md, a recite function that puts the notes at the very end of the view, and make_prepare, which combines them into the prepare plug from Part 8.

python
"""context_kit.py - component 2: what the model sees. Clear old tool results, restate notes, say when you cut."""
from pathlib import Path

import mini_harness as mh
from tools_kit import ToolSpec

CLEARED = "[tool result cleared: {n} chars. Call the tool again if you need it.]"

def load_instructions(root: Path, max_bytes=mh.AGENTS_MD_MAX_BYTES) -> str:
    f = root / "AGENTS.md"
    if not f.exists():
        return ""
    raw = f.read_bytes()
    text = raw[:max_bytes].decode("utf-8", "replace")
    if len(raw) > max_bytes:                      # 6.1 cut silently; say so
        text += f"\n[AGENTS.md cut at {max_bytes} bytes; {len(raw) - max_bytes} bytes were not loaded]"
    return "# Repo instructions\n" + text

def clear_old_results(messages, budget_chars, keep_last=4):
    """Return a VIEW that fits the budget. Old tool results go first; the history itself is never changed."""
    view = [dict(m) for m in messages]
    size = lambda: sum(len(m["content"]) for m in view)
    for m in view[:-keep_last]:                   # oldest first; the newest messages stay whole
        if size() <= budget_chars:
            break
        if m["role"] == "tool" and not m["content"].startswith("[tool result cleared"):
            m["content"] = CLEARED.format(n=len(m["content"]))
    return view

NOTES = ".harness/notes.md"

def note(root, text):
    p = root / NOTES
    p.parent.mkdir(exist_ok=True)
    with p.open("a") as f:
        f.write(f"- {text}\n")
    return "noted"

NOTE_SPEC = ToolSpec("note", "Save one short fact you will need later. Notes are shown to you again at the end of every turn.",
                     {"text": ("string", True, "one line")}, "write", note)

def recite(root: Path, view):
    """Put the notes at the END of the context, where the model attends most (recitation)."""
    p = root / NOTES
    if p.exists():
        view = view + [{"role": "user", "content": "Your notes so far:\n" + p.read_text()}]
    return view

def make_prepare(root: Path, budget_chars=6000, keep_last=4):
    return lambda messages: recite(root, clear_old_results(messages, budget_chars, keep_last))

if __name__ == "__main__":
    import tempfile
    work = Path(tempfile.mkdtemp())
    (work / "AGENTS.md").write_text("Run the tests before you finish.\n" * 1200)      # about 39 KB
    old, new = mh.load_instructions(work), load_instructions(work)
    print(f"6.1 loader: {len(old)} chars, ends with: {old[-40:]!r}")
    print(f"new loader: {len(new)} chars, ends with: {new[-70:]!r}\n")

    history = [{"role": "system", "content": "You are a coding agent. " + "x" * 1100},
               {"role": "user", "content": "Fix the failing test in the billing module."}]
    for i in range(1, 7):
        history.append({"role": "assistant", "content": '{"tool": "read_file", "args": {"path": "module%d.py"}}' % i})
        history.append({"role": "tool", "content": f"contents of module{i}.py " + "y" * 1700})
    note(work, "the failing test is test_invoice_total in billing/test_invoice.py")
    view = make_prepare(work, budget_chars=6000, keep_last=4)(history)
    print("msg role       full  view")
    for i, (a, b) in enumerate(zip(history + [None], view)):
        full = len(a["content"]) if a else 0
        print(f"{i:>3} {b['role']:<9} {full:>5} {len(b['content']):>5}  {b['content'][:44]!r}")
    print(f"total: {sum(len(m['content']) for m in history)} chars in history, {sum(len(m['content']) for m in view)} chars sent")
    print("history unchanged:", all(not m["content"].startswith("[tool result cleared") for m in history))

Real output:

text
6.1 loader: 32788 chars, ends with: 'finish.\nRun the tests before you finish.'
new loader: 32847 chars, ends with: 'you finish.\n[AGENTS.md cut at 32768 bytes; 6832 bytes were not loaded]'

msg role       full  view
  0 system     1124  1124  'You are a coding agent. xxxxxxxxxxxxxxxxxxxx'
  1 user         43    43  'Fix the failing test in the billing module.'
  2 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
  3 tool       1723    70  '[tool result cleared: 1723 chars. Call the t'
  4 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
  5 tool       1723    70  '[tool result cleared: 1723 chars. Call the t'
  6 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
  7 tool       1723    70  '[tool result cleared: 1723 chars. Call the t'
  8 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
  9 tool       1723    70  '[tool result cleared: 1723 chars. Call the t'
 10 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
 11 tool       1723  1723  'contents of module5.py yyyyyyyyyyyyyyyyyyyyy'
 12 assistant    53    53  '{"tool": "read_file", "args": {"path": "modu'
 13 tool       1723  1723  'contents of module6.py yyyyyyyyyyyyyyyyyyyyy'
 14 user          0    87  'Your notes so far:\n- the failing test is tes'
total: 11823 chars in history, 5298 chars sent
history unchanged: True

10.3 What the run shows#

  • The 6.1 loader cut silently. Its own comment says "we cut and say so", but the code only cuts. With a 39 KB AGENTS.md, the old loader returns 32,788 characters ending mid-list and the model has no idea 6,832 bytes are missing. The new loader ends with [AGENTS.md cut at 32768 bytes; 6832 bytes were not loaded]. This is the 2.1 warning made concrete: a long instruction file is silently truncated unless you add the notice yourself.
  • Clearing is a view, not an edit. Six tool results of 1,723 characters each were in the history. Four of the older ones became a 70-character placeholder, the two newest stayed whole, the system prompt and the task were never touched, and the last line proves the history is unchanged. The model sent 5,298 characters instead of 11,823.
  • The placeholder says how to get the result back, and the notes come last. That is restorable compression and recitation from 2.3.

10.4 Where to go for depth#

Selecting and ordering context for one call is 04.6; long conversations are 04.7. The agent-level versions of this part (tool-result clearing, summaries, provider-side compaction, files and git as memory, sub-context isolation) are 08B.3. Notes, long-term memory, write policies and memory safety are 08B.2 and 08B.4.


Part 11: Component 3, guardrails and permissions#

11.1 What it is and why the harness needs it#

A guardrail is a rule the agent cannot talk its way past. A permission is the form of it that answers "may this agent do this action, here, now?". The harness needs them because the model is the one part you cannot fully predict, and a tool call is a real action.

Two ideas keep this layer simple.

  • Decide outside the model. The check is ordinary code that runs before the tool, on the arguments the model produced. A sentence in the prompt ("never edit the tests") is a request. A line of code that refuses the edit is a control. Part 5 of this lesson says the same thing: enforce mechanically.
  • Three outcomes, not two. Allow (safe, just do it), deny (never, tell the model why) and ask (a person decides). Without the third outcome you are forced to choose between an agent that is too timid to be useful and one that is too free to be safe.

Layer the checks. In the sample below the policy allows read_file on ../secrets.txt (reading is read-only) and the path confinement from Part 6 still refuses it inside the tool. Two layers ask two questions: "is this kind of action allowed?" and "is this target inside the box?".

11.2 policy_kit.py#

The Policy class is the check plug from Part 8. It reads each tool's risk class from the ToolSpec of Part 9 (read, write or exec), applies a short list of rules, appends every decision to a log, and raises Denied for anything not allowed. The model sees the reason, which is what lets it change course. The "ask" tier calls an approve function; in the demo that function is a scripted person who says yes once and no once.

python
"""policy_kit.py - component 3: one place that decides allow, ask or deny, and records why."""
import os
from pathlib import Path

import mini_harness as mh
from tools_kit import SPECS

class Policy:
    ALLOW_EXEC = [("python", "-m", "unittest")]              # run with no questions
    ASK_EXEC = [("ls",), ("cat",)]                           # in the tool's allow-list, but a person says yes first
    def __init__(self, root: Path, approve=lambda name, args: False, specs=SPECS):
        self.root, self.approve, self.risk = root, approve, {s.name: s.risk for s in specs}
        self.log = []                                        # (tool, summary, decision, reason)
    def __call__(self, name, args):                          # the "check" seam: return, or raise Denied
        decision, reason = self._decide(name, args)
        self.log.append((name, args.get("path") or " ".join(args.get("argv", [])), decision, reason))
        if decision == "deny":
            raise mh.Denied(f"{reason}. This action is not available to you.")
    def _decide(self, name, args):
        risk = self.risk.get(name)
        if risk is None:
            return "deny", "unknown tool"
        if risk == "read":
            return "allow", "read-only"
        if risk == "write":
            base = Path(str(args.get("path", ""))).name
            if base.startswith("test_") or "tests" in Path(str(args.get("path", ""))).parts:
                return "deny", "tests are read-only: fix the code, not the test"
            return "allow", "write inside the workspace"
        argv = tuple(args.get("argv", []))                   # risk == "exec"
        if any(argv[: len(p)] == p for p in self.ALLOW_EXEC):
            return "allow", "allow-listed command"
        if any(argv[: len(p)] == p for p in self.ASK_EXEC):
            ok = self.approve(name, args)
            return ("allow", "approved by a person") if ok else ("deny", "a person declined")
        return "deny", "command is not on any list"

if __name__ == "__main__":
    import tempfile
    from kit import default_components, run
    from tools_kit import make_tools

    work = Path(tempfile.mkdtemp())
    (work / "calc.py").write_text("def add(a, b):\n    return a - b\n")
    (work / "test_calc.py").write_text("import unittest\nfrom calc import add\n\nclass T(unittest.TestCase):\n"
                                       "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n")
    answers = iter([True, False])                            # the scripted person: yes to the first question, no to the second
    policy = Policy(work, approve=lambda name, args: next(answers))
    c = default_components()
    c.tools, c.check = make_tools(), policy
    script = iter([
        {"tool": "edit_file", "args": {"path": "test_calc.py", "old": "5", "new": "-1"}},   # make the test pass the cheap way
        {"tool": "read_file", "args": {"path": "../secrets.txt"}},
        {"tool": "bash", "args": {"argv": ["rm", "-rf", "."]}},
        {"tool": "bash", "args": {"argv": ["ls"]}},
        {"tool": "bash", "args": {"argv": ["cat", ".env"]}},
        {"tool": "edit_file", "args": {"path": "calc.py", "old": "a - b", "new": "a + b"}},
        {"tool": "bash", "args": {"argv": ["python", "-m", "unittest"]}},
        {"final": "Fixed add()."},
    ])
    r = run(lambda messages: next(script), work, "add() is wrong; fix it.", c)
    print(f"{'tool':<10} {'target':<22} {'decision':<8} reason")
    for row in policy.log:
        print(f"{row[0]:<10} {row[1]:<22} {row[2]:<8} {row[3]}")
    print("\nrun:", r.status, "in", r.steps, "steps")
    print("test file unchanged:", "5" in (work / "test_calc.py").read_text())

    os.environ["FAKE_API_KEY"] = "sk-demo-not-a-real-key"
    mh.BASH_ALLOW.add(("printenv",))                         # demo only: a tool that shows the environment
    print("\nparent sees the key:", "FAKE_API_KEY" in os.environ)
    print("child process sees: ", mh.bash(work, ["printenv"]).replace("\n", " | "))

Real output:

text
tool       target                 decision reason
edit_file  test_calc.py           deny     tests are read-only: fix the code, not the test
read_file  ../secrets.txt         allow    read-only
bash       rm -rf .               deny     command is not on any list
bash       ls                     allow    approved by a person
bash       cat .env               deny     a person declined
edit_file  calc.py                allow    write inside the workspace
bash       python -m unittest     allow    allow-listed command

run: done in 8 steps
test file unchanged: True

parent sees the key: True
child process sees:  exit=0 | PATH=/usr/bin:/bin | PYTHONDONTWRITEBYTECODE=1 | 

11.3 What the run shows#

  • Exercise 1 of this lesson, solved with a rule. The first call edits test_calc.py to make the failing test pass the cheap way. The policy refuses it, and the last line shows the test file is unchanged. A prompt line can be ignored; this cannot.
  • The log is the audit trail. Seven rows: what was asked, what the policy decided, and why.
  • "Ask" is a person in the loop. ls was approved, cat .env declined. Both are on the tool's own allow-list, so the policy is stricter than the tool. 08A.12 covers approval gates.
  • Credentials stay out of the child process. The parent holds a fake key; the command the agent runs sees only PATH and PYTHONDONTWRITEBYTECODE. Code the model writes cannot read what was never put there (principle 9).
  • Refusals cost steps. Four of the eight steps ended in a refusal (the test edit, the secret path, rm -rf and cat .env). Every control has a price in steps and tokens, which matters in Part 15: measure it.

11.4 What real harnesses expose#

Checked against the official documentation on 2 December 2026:

  • Claude Agent SDK (Python). ClaudeAgentOptions has allowed_tools (tools to auto-approve without prompting), disallowed_tools (tools to deny; a scoped rule such as "Bash(rm *)" leaves the tool available and denies matching calls in every permission mode, including bypassPermissions), permission_mode (default, acceptEdits, plan, dontAsk, bypassPermissions and auto) and hooks. Source: Claude Agent SDK Python reference.
  • Claude Code hooks. A PreToolUse hook that exits with code 2 blocks the tool call, and the hook's standard error is the message shown to Claude. A Stop hook that exits with code 2 prevents Claude from stopping, which is the stop gate of 2.5b. Source: Claude Code hooks reference.

The mapping to this lesson: disallowed_tools is the deny list, allowed_tools is the allow list, the permission mode sets what happens to everything on neither list (prompt, deny, or auto-accept edits), and a PreToolUse hook is a check plug. The shapes are the same as the ones you just built.

11.5 Where to go for depth#

You will build this properly in 08A.5: least privilege and scoped credentials (Part 3), secrets (Part 4), approval gates (Part 5), sandboxing (Part 6) and all seven controls in one dispatcher (Part 8). 12.6 extends it to excessive agency, risk tiers and approvals (2.5), sandbox choices, MCP and multi-agent security. 08A.7 covers tool-level controls.


Part 12: Component 4, budgets and stop conditions#

12.1 What it is and why the harness needs it#

An agent loop is while True with a model in the middle. It finishes, crashes, or never stops and the bill grows. The harness owns the third case: the provider cannot know that your loop has spent enough, taken too long or started going in circles.

A good stop layer has four properties:

  1. Several limits, one idea. Steps, tokens, money and time are all "how much have we used?", so one meter can track them.
  2. A name for every ending: done, step_budget, token_budget, cost_budget, deadline, stagnation, gate_failed (08A.3, 1.3). A run that ends silently cannot be debugged or evaluated.
  3. A warning before the wall. One message at 80% used lets the model wrap up instead of being cut off mid-edit.
  4. A limit per run and a limit per team. This part is the per-run layer. Team limits live in a gateway or platform (11B.6, 11B.7).

12.2 meter_kit.py#

Meter extends the step counter of Part 8. before() is called before every model call and returns the name of any limit that is used up. after() is called after every call; it estimates tokens (about four characters each, so an estimate, not a bill) and prices them with the made-up demo rates from kit.py. warning() produces the 80% notice. The demo runs the same loop under six different limits, with a fake clock so the deadline result is the same on every machine.

python
"""meter_kit.py - component 4: one meter for steps, tokens, money and time, with a named stop reason."""
import json
import time

from kit import StepMeter, tokens, PRICE_IN, PRICE_OUT

class Meter(StepMeter):
    def __init__(self, max_steps=12, max_tokens=None, max_cost=None, max_seconds=None, now=time.monotonic, warn_at=0.8):
        super().__init__(max_steps)
        self.max_tokens, self.max_cost, self.max_seconds = max_tokens, max_cost, max_seconds
        self.now, self.t0, self.warn_at = now, now(), warn_at
        self.tokens_in = self.tokens_out = 0
    @property
    def cost(self):
        return (self.tokens_in * PRICE_IN + self.tokens_out * PRICE_OUT) / 1_000_000
    def _used(self):                                   # fraction of each limit used so far
        used = {"step_budget": self.steps / self.max_steps}
        if self.max_tokens:  used["token_budget"] = (self.tokens_in + self.tokens_out) / self.max_tokens
        if self.max_cost:    used["cost_budget"] = self.cost / self.max_cost
        if self.max_seconds: used["deadline"] = (self.now() - self.t0) / self.max_seconds
        return used
    def before(self):                                  # checked BEFORE every model call
        for reason, frac in self._used().items():
            if frac >= 1:
                return reason
        return None
    def after(self, sent, reply, span):                # called AFTER every model call
        self.steps += 1
        a, b = sum(tokens(m["content"]) for m in sent), tokens(json.dumps(reply))
        self.tokens_in, self.tokens_out = self.tokens_in + a, self.tokens_out + b
        span.set(**{"gen_ai.usage.input_tokens": a, "gen_ai.usage.output_tokens": b})
    def warning(self):                                 # one warning when any limit is 80% used
        worst = max(self._used().items(), key=lambda kv: kv[1])
        if worst[1] >= self.warn_at:
            return f"Budget notice: {worst[1]:.0%} of the {worst[0].replace('_', ' ')} is used. Finish soon and say what is left."
        return None
    def usage(self):
        return {"steps": self.steps, "tokens": self.tokens_in + self.tokens_out, "cost_usd": round(self.cost, 5)}

if __name__ == "__main__":
    import itertools, tempfile
    from pathlib import Path
    import mini_harness as mh
    from kit import default_components, run
    from tools_kit import make_tools

    def wanderer():                                    # never finishes, never repeats a call
        n = itertools.count(1)
        return lambda messages: {"tool": "list_files", "args": {"limit": next(n)}}
    def repeater():                                    # never finishes, repeats one call
        return lambda messages: {"tool": "read_file", "args": {"path": "calc.py"}}
    def finisher():
        script = iter([{"tool": "read_file", "args": {"path": "calc.py"}},
                       {"tool": "edit_file", "args": {"path": "calc.py", "old": "a - b", "new": "a + b"}},
                       {"final": "Fixed."}])
        return lambda messages: next(script)

    cases = [("finishes", finisher, {"max_steps": 12}),
             ("12 steps", wanderer, {"max_steps": 12}),
             ("600 tokens", wanderer, {"max_tokens": 600}),
             ("$0.004", wanderer, {"max_cost": 0.004}),
             ("30 seconds", wanderer, {"max_seconds": 30}),
             ("same call", repeater, {"max_steps": 12})]
    print(f"{'limit':<13} {'stop reason':<12} {'steps':>5} {'tokens':>7} {'cost':>9}  warning shown to the model")
    for label, make_model, limits in cases:
        work = Path(tempfile.mkdtemp())
        (work / "calc.py").write_text("def add(a, b):\n    return a - b\n")
        (work / "test_calc.py").write_text("import unittest\nfrom calc import add\n\nclass T(unittest.TestCase):\n"
                                           "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n")
        clock = itertools.count(0, 4.0)                # a fake clock: every look at it is 4 seconds later
        meter = Meter(now=lambda: float(next(clock)), **limits)
        c = default_components()
        c.tools, c.meter = make_tools(), meter
        r = run(make_model(), work, "Fix add().", c)
        warned = any(m["content"].startswith("Budget notice") for m in r.messages)
        u = meter.usage()
        print(f"{label:<13} {r.status:<12} {u['steps']:>5} {u['tokens']:>7} ${u['cost_usd']:>8.5f}  {'yes' if warned else 'no'}")

Real output:

text
limit         stop reason  steps  tokens      cost  warning shown to the model
finishes      done             3     121 $ 0.00080  no
12 steps      step_budget     12    1445 $ 0.00592  yes
600 tokens    token_budget     8     697 $ 0.00315  yes
$0.004        cost_budget     10    1029 $ 0.00441  yes
30 seconds    deadline         4     224 $ 0.00120  yes
same call     stagnation       5     312 $ 0.00166  no

12.3 What the run shows#

  • Each limit stops the run with its own name. Six runs, six different endings: done, step_budget, token_budget, cost_budget, deadline and stagnation. A dashboard that counts stop reasons tells you more than one that counts failures.
  • The call that crosses the limit still happens. The token limit was 600 and the run ended at 697: the check is before a call and the last call took it over. Real limits keep a reserve (08A.3, 3.4).
  • The warning appears when it can still help. It fired in all four runs that hit a budget. It did not fire in the run that finished early, or in the one stopped for repeating itself (that run never got near a limit; the loop detector caught it).
  • Stagnation is not a budget. The same call run used five steps and a sliver of its budget. It was busy but not progressing. 08A.3, Part 5 has four detectors.
  • Tokens grow faster than steps. Each step re-sends the whole history, so the total grows roughly with the square of the steps. That is why Part 10 exists.

12.4 What real harnesses expose#

Checked against the official documentation on 2 December 2026:

  • OpenAI Agents SDK. Runner.run takes a max_turns limit; if the run exceeds it, the SDK raises MaxTurnsExceeded. All Runner entry points also accept error_handlers, keyed by error kind with "max_turns" as one of the keys, so you can return a controlled final output instead of ending with an error. Source: Running agents.
  • Claude Agent SDK (Python). ClaudeAgentOptions has max_turns and max_budget_usd. The budget stops the query when the client-side cost estimate reaches the value, and the documentation warns that the estimate can pass it, so you should leave headroom. Source: Claude Agent SDK Python reference.

Both match the pattern above: a limit on turns, one on money, a named way to stop, and the honest note that an estimate is not an invoice.

12.5 Where to go for depth#

You will build this properly in 08A.3: the gauge, reserve and soft-limit meter (Part 3), deadlines that truly cancel (Part 4), four stagnation detectors (Part 5) and partial results (Part 6). The base loop's budgets are 08A.2, 3.3 and 3.4. Team budgets and kill switches are 11B.6 and 11B.7; 08A.5, Part 7 treats budgets as security. A run that must survive a crash, not only stop, is 08C.3.


Part 13: Component 5, tracing#

13.1 What it is and why the harness needs it#

When an agent fails, the answer to "why?" is not in the final message. It is in step four, where it read the wrong file, or step seven, where a permission check refused a command. If the harness did not write those steps down as they happened, you cannot get them back.

A trace is the record of one run. It is made of spans: one per unit of work, with a start time, a duration, a status and a few attributes. Spans nest: the whole run is one span, and each model call, tool call and gate check is a child. That is enough to answer the first three questions every incident asks: what happened, in what order, and where did the time and tokens go?

Three rules for a trace in an agent harness:

  1. Record shape, not content. Tool names, token counts, durations, status and result sizes are safe and useful. Raw prompts, tool arguments and results often hold personal data or secrets. The default is not to store them; storing content is an opt-in, with redaction (03.12, Part 5, 11A.1, Part 7).
  2. Use shared names. The kit.py loop already tags spans with gen_ai.operation.name (chat or execute_tool) and gen_ai.tool.name, and the meter writes gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Those are OpenTelemetry's GenAI attribute names (11A.1, 3.8), so a real exporter can take these spans later without renaming anything.
  3. Never let tracing break the run. A trace that throws an exception takes the agent down with it. The class of the exception is recorded, never its message.

13.2 trace_kit.py#

Tracer is the tracer plug from Part 8. span() is a context manager that stacks spans (so children know their parent), times them, records the exception class on failure, redacts anything that looks like an API key, and appends one JSON line per finished span. show() reads the file back and prints it as an indented tree.

python
"""trace_kit.py - component 5: one span per model call, tool call and gate check, as JSON lines."""
import json
import re
import time
from contextlib import contextmanager
from pathlib import Path

SECRET = re.compile(r"sk-[A-Za-z0-9_-]{8,}")           # never write keys into a trace

class Span:
    def __init__(self, tracer, name, attrs):
        self.t, self.name, self.attrs = tracer, name, dict(attrs)
    def set(self, **attrs):
        self.attrs.update(attrs)

class Tracer:
    def __init__(self, path: Path, trace_id="run-1", clock=time.perf_counter):
        self.path, self.trace_id, self.clock, self.stack, self.n = path, trace_id, clock, [], 0
        self.t0 = clock()
    @contextmanager
    def span(self, name, **attrs):
        self.n += 1
        sp = Span(self, name, attrs)
        sid, parent, start = self.n, (self.stack[-1] if self.stack else None), self.clock()
        self.stack.append(sid)
        status = "ok"
        try:
            yield sp
        except Exception as e:
            status = f"error:{type(e).__name__}"           # the class only, never the message
            raise
        finally:
            self.stack.pop()
            row = {"trace": self.trace_id, "span": sid, "parent": parent, "name": name,
                   "start": round(start - self.t0, 3), "secs": round(self.clock() - start, 3), "status": status,
                   **{k: SECRET.sub("[redacted]", v) if isinstance(v, str) else v for k, v in sp.attrs.items()}}
            with self.path.open("a") as f:
                f.write(json.dumps(row) + "\n")

def show(path: Path):
    rows = sorted((json.loads(l) for l in path.read_text().splitlines()), key=lambda r: r["span"])   # span ids grow, so this is parent-first
    depth = {None: -1}
    for r in rows:
        depth[r["span"]] = depth[r["parent"]] + 1
        d = depth[r["span"]]
        if r["name"] == "model":
            detail = f'{r["gen_ai.usage.input_tokens"]} in / {r["gen_ai.usage.output_tokens"]} out'
        elif r["name"] == "tool":
            detail = r["gen_ai.tool.name"] + ("" if r["ok"] else "  <- failed")
        elif r["name"] == "gate":
            detail = "passed" if r["ok"] else "refused"
        else:
            detail = f'outcome={r["outcome"]}'
        print(f'{"  " * d}{r["name"]:<{12 - 2 * d}} {r["secs"]:>6.3f}s  {detail}')
    return rows

if __name__ == "__main__":
    import tempfile
    import mini_harness as mh
    from kit import default_components, run
    from meter_kit import Meter
    from policy_kit import Policy
    from tools_kit import make_tools

    work = Path(tempfile.mkdtemp())
    (work / "calc.py").write_text("def add(a, b):\n    return a - b\n")
    (work / "test_calc.py").write_text("import unittest\nfrom calc import add\n\nclass T(unittest.TestCase):\n"
                                       "    def test_add(self):\n        self.assertEqual(add(2, 3), 5)\n")
    log = work / "trace.jsonl"
    c = default_components()
    c.tools, c.check, c.meter, c.tracer = make_tools(), Policy(work), Meter(), Tracer(log)
    c.tracer.t0 = c.tracer.clock()
    script = iter([{"tool": "read_file", "args": {"path": "calc.py"}},
                   {"tool": "edit_file", "args": {"path": "calc.py", "old": "a - b", "new": "a + b"}},
                   {"tool": "bash", "args": {"argv": ["rm", "-rf", "."]}},
                   {"tool": "bash", "args": {"argv": ["python", "-m", "unittest"]}},
                   {"final": "Fixed add()."}])
    r = run(lambda m: next(script), work, "Fix add().", c)
    rows = show(log)
    slow = max((x for x in rows if x["name"] == "tool"), key=lambda x: x["secs"])
    print(f"\n{len(rows)} spans | {sum(x.get('gen_ai.usage.input_tokens', 0) for x in rows)} input tokens "
          f"| failed tools: {[x['gen_ai.tool.name'] for x in rows if x['name'] == 'tool' and not x['ok']]} "
          f"| slowest tool: {slow['gen_ai.tool.name']} ({slow['secs']}s)")
    print("first line of the file:", open(log).readline().strip()[:150])
    with c.tracer.span("demo", error_text="auth failed for key sk-demo-abcdef123456"):
        pass
    print("a secret in an attribute:", log.read_text().splitlines()[-1][-95:])

Real output (the durations differ on every run; the shape does not):

text
agent.run     0.068s  outcome=done
  model       0.000s  8 in / 12 out
  tool        0.000s  read_file
  model       0.000s  28 in / 20 out
  tool        0.000s  edit_file
  model       0.000s  49 in / 13 out
  tool        0.000s  bash  <- failed
  model       0.000s  79 in / 16 out
  tool        0.033s  bash
  model       0.000s  121 in / 6 out
  gate        0.033s  passed

11 spans | 285 input tokens | failed tools: ['bash'] | slowest tool: bash (0.033s)
first line of the file: {"trace": "run-1", "span": 2, "parent": 1, "name": "model", "start": 0.0, "secs": 0.0, "status": "ok", "step": 1, "gen_ai.operation.name": "chat", "ge
a secret in an attribute: ", "start": 0.068, "secs": 0.0, "status": "ok", "error_text": "auth failed for key [redacted]"}

13.3 What the run shows#

  • The trace tells the story without the transcript. Five model calls, four tool calls and one gate check. The third tool span is marked <- failed: that is the rm -rf the policy refused. You can find it without reading a line of the conversation.
  • Tokens grow step by step. 8, 28, 49, 79, 121 input tokens: the history is re-sent every time. Summing the column gives the 285 in the summary line, which is the input of the whole run.
  • Where the time went. Only the bash call that ran the tests and the gate that ran them again took measurable time (about 0.03 s each). In a real agent the model spans dominate.
  • Children are written before parents. A span is written when it finishes, so the root is the last line of the file; show() sorts by span number to put parents first.
  • Secrets never reach the file. The last line shows an attribute holding an API key written as [redacted].

13.4 What real harnesses expose#

Checked against the official documentation on 2 December 2026: the OpenAI Agents SDK has tracing enabled by default. It wraps each agent run in an agent_span(), each LLM generation in a generation_span(), each function tool call in a function_span(), each guardrail in a guardrail_span() and each handoff in a handoff_span(). You can switch it off with the environment variable OPENAI_AGENTS_DISABLE_TRACING=1, with set_tracing_disabled(True), or per run with RunConfig.tracing_disabled. Source: Tracing. The span kinds are close to the ones in the tree above: run, model, tool and a checking step.

13.5 Where to go for depth#

You will build this properly in two places. 03.12 is the plain-Python recorder. 11A.1 is the full treatment: the OpenTelemetry GenAI conventions, a mini tracer with OTel-shaped spans (3.9), the safe exporter, platforms and debugging. 11A.4 turns production traces into eval datasets, the bridge to Part 14; latency and dashboards are 11A.3.


Part 14: Component 6, evals#

14.1 What it is and why the harness needs it#

Every other component makes a promise: the policy blocks bad actions, the context manager keeps what matters, the meter stops runaways. An eval is how you find out whether the promise holds, and whether the last change helped or hurt. Without one, harness work is guesswork with confidence. Every change in this lesson (a new error message, a stricter permission, a smaller context budget) can fix one case and break another, and nothing throws an error when it does.

A harness needs checks at three levels:

Level Question Needs a model? Runs
Component tests Does this one part do what it says? (path confinement, the policy table, the clearing rule, the meter) No On every save
Task evals Does the whole harness, with a model, finish realistic tasks? Yes (here: a stand-in) Before every harness change ships
Regression gate Did the change make any case that passed before fail now? Yes In CI, as a pass or fail

Part 14 builds the first two. Part 15 uses them to evaluate a change. The regression gate is the same compare() idea as 03.13, Part 5, and 10A.8 wires it into CI.

14.2 Level one: tests for the parts, with no model#

Most harness bugs are ordinary code bugs, so test them like code: no model, no network, no cost. These four tests pin down behaviour from Parts 6 to 12.

python
"""test_components.py - deterministic tests for the harness parts. No model, no network, no cost."""
import tempfile
import unittest
from pathlib import Path

import mini_harness as mh
from meter_kit import Meter
from policy_kit import Policy
from tools_kit import make_tools

class Parts(unittest.TestCase):
    def setUp(self):
        self.root = Path(tempfile.mkdtemp())
        (self.root / "mod.py").write_text("x = 1\nx = 1\n")

    def test_confine_blocks_escape_and_symlink(self):
        (self.root / "link").symlink_to("/etc")
        for bad in ("../x", "/etc/passwd", "link/hosts"):
            with self.assertRaises(mh.Denied):
                mh.confine(self.root, bad)

    def test_helpful_error_says_what_to_do(self):
        tools = make_tools(style="helpful")
        with self.assertRaisesRegex(mh.Denied, "surrounding"):
            tools["edit_file"](self.root, path="mod.py", old="x = 1", new="x = 2")

    def test_policy_protects_tests_and_unknown_commands(self):
        p = Policy(self.root)
        with self.assertRaises(mh.Denied):
            p("edit_file", {"path": "test_mod.py", "old": "a", "new": "b"})
        with self.assertRaises(mh.Denied):
            p("bash", {"argv": ["curl", "example.com"]})
        p("bash", {"argv": ["python", "-m", "unittest"]})            # allowed: no exception

    def test_meter_names_the_limit_that_stopped_the_run(self):
        m = Meter(max_steps=5, max_tokens=50)
        class S:                                                      # a span stand-in
            def set(self, **a): pass
        m.after([{"content": "x" * 400}], {"final": "ok"}, S())
        self.assertEqual(m.before(), "token_budget")

if __name__ == "__main__":
    unittest.main(verbosity=2)

Real output:

text
test_confine_blocks_escape_and_symlink (__main__.Parts.test_confine_blocks_escape_and_symlink) ... ok
test_helpful_error_says_what_to_do (__main__.Parts.test_helpful_error_says_what_to_do) ... ok
test_meter_names_the_limit_that_stopped_the_run (__main__.Parts.test_meter_names_the_limit_that_stopped_the_run) ... ok
test_policy_protects_tests_and_unknown_commands (__main__.Parts.test_policy_protects_tests_and_unknown_commands) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

These do not ask "does the agent behave well". They ask whether confinement rejects ../x, an absolute path and a symlink that points outside, whether the helpful error holds the word that tells the model what to do, whether the policy refuses tests and unknown commands, and whether the meter names the limit. Everything else leans on those controls.

14.3 Level two: a task suite, a stand-in model, an end-state grader#

evals_kit.py is the evaluation side of the harness. It has four parts.

  1. Ten tasks. Each is a tiny repository with a bug and a test. Five have a bug that appears once. Five hide the same buggy text in a twin function, so a vague edit_file call matches twice and fails.
  2. A stand-in model (StubModel): a seeded program with fixed weaknesses. It sometimes makes a vague first edit, says "done" before testing, or makes a subtly wrong first fix, and it reacts to an error by following a hint or by repeating itself. It reads the harness's messages, so a better harness can change what it does. The weaknesses are drawn once per task and seed, so every harness variant faces the same model. That is how "hold the model fixed" works with no real model.
  3. An end-state grader. After the run it runs the tests itself and checks the test file is unchanged. It trusts neither the agent's "done" nor the harness's gate (10A.7, 5.5 covers broken graders and reward hacking).
  4. The numbers. summarize() gives success rate, a 95% Wilson interval, cost per run, cost per successful task and the stop reasons. compare() pairs two runs by task and seed and lists what was fixed and what regressed, using the vocabulary of 03.13.
python
"""evals_kit.py - component 6: a task suite, a fixed stand-in model, an end-state grader and a report."""
import json
import math
import random
import shutil
import subprocess
import sys
import tempfile
from collections import Counter
from pathlib import Path

import mini_harness as mh
from context_kit import load_instructions, make_prepare
from kit import default_components, run
from meter_kit import Meter
from policy_kit import Policy
from tools_kit import SPECS, make_tools, render_docs

# ---- 1. the tasks: ten tiny bugs, each with a test; the last five hide the bug in a twin function -------
PLAIN = [("add", "a, b", "a - b", "a + b", "a * b", "add(2, 3)", "5"),
         ("mul", "a, b", "a + b", "a * b", "a - b", "mul(3, 4)", "12"),
         ("square", "n", "n * 2", "n * n", "n + 2", "square(5)", "25"),
         ("is_even", "n", "n % 2 == 1", "n % 2 == 0", "n % 2 == 2", "is_even(4)", "True"),
         ("last", "items", "items[1]", "items[-1]", "items[0]", "last([1, 2, 3])", "3")]
TWINS = [("plus", "minus", "a, b", "a - b", "a + b", "a * b", "plus(2, 3)", "5", "minus(5, 3)", "2"),
         ("times", "over", "a, b", "a / b", "a * b", "a - b", "times(3, 4)", "12", "over(8, 2)", "4"),
         ("inc", "dec", "n", "n - 1", "n + 1", "n * 1", "inc(4)", "5", "dec(4)", "3"),
         ("double", "half", "n", "n // 2", "n * 2", "n + 2", "double(4)", "8", "half(4)", "2"),
         ("upper", "lower", "s", "s.lower()", "s.upper()", "s.title()", "upper('ab')", "'AB'", "lower('AB')", "'ab'")]

def make_tasks():
    tasks = []
    for fn, params, bad, good, wrong, call, want in PLAIN:
        code = f"def {fn}({params}):\n    return {bad}\n"
        test = f"import unittest\nfrom mod import {fn}\n\nclass T(unittest.TestCase):\n    def test_{fn}(self):\n        self.assertEqual({call}, {want})\n"
        tasks.append(dict(id=fn, files={"mod.py": code, "test_mod.py": test}, prompt=f"{fn}() is wrong; fix it.",
                          bad=bad, good=good, wrong=wrong, wide=f"def {fn}({params}):\n    return {bad}", ambiguous=False))
    for fn, other, params, bad, good, wrong, call, want, call2, want2 in TWINS:
        code = f"def {fn}({params}):\n    return {bad}\n\n\ndef {other}({params}):\n    return {bad}\n"
        test = (f"import unittest\nfrom mod import {fn}, {other}\n\nclass T(unittest.TestCase):\n"
                f"    def test_{fn}(self):\n        self.assertEqual({call}, {want})\n"
                f"    def test_{other}(self):\n        self.assertEqual({call2}, {want2})\n")
        tasks.append(dict(id=fn, files={"mod.py": code, "test_mod.py": test}, prompt=f"{fn}() is wrong; fix it.",
                          bad=bad, good=good, wrong=wrong, wide=f"def {fn}({params}):\n    return {bad}", ambiguous=True))
    return tasks

# ---- 2. the model: a seeded stand-in with weaknesses, the SAME for every harness variant ----------------
class StubModel:
    """Weaknesses (drawn once per task and seed): vague first edit, 'done' before testing, a wrong first fix,
    and what it does after an unhelpful error. It reads the harness's messages, so the harness can change what it does."""
    def __init__(self, task, seed):
        r = random.Random(f"{task['id']}/{seed}")
        self.t = task
        self.narrow = task["ambiguous"] and r.random() < 0.8     # first edit does not say which function
        self.rush = r.random() < 0.35                            # says "done" before running the tests
        self.wrong_first = r.random() < 0.30                     # the first fix is subtly wrong
        self.stubborn = r.random() < 0.75                        # after an unhelpful error, repeats the call
        self.follows_hint = r.random() < 0.90                    # after a helpful error, follows the hint
        self.mode, self.last_call, self.corrected = "read", None, False
    def _edit(self, old, new):
        self.last_call = {"tool": "edit_file", "args": {"path": "mod.py", "old": old, "new": new}}
        return self.last_call
    def __call__(self, messages):
        t, last = self.t, messages[-1]["content"]
        if self.mode == "read":
            self.mode = "edit"
            return {"tool": "read_file", "args": {"path": "mod.py"}}
        if self.mode == "edit":
            self.mode = "after_edit"
            expr = t["wrong"] if self.wrong_first else t["good"]
            old = t["bad"] if self.narrow else t["wide"]
            return self._edit(old, old.replace(t["bad"], expr))
        if self.mode == "after_edit":
            if last.startswith("ERROR"):
                if "surrounding" in last and self.follows_hint:  # the error said what to do, and the model did it
                    expr = t["wrong"] if self.wrong_first else t["good"]
                    return self._edit(t["wide"], t["wide"].replace(t["bad"], expr))
                if self.stubborn:
                    return self.last_call
                self.mode = "finish"
                return {"final": "I could not apply the edit."}
            self.mode = "check"
            return {"final": "Fixed."} if self.rush else {"tool": "bash", "args": {"argv": ["python", "-m", "unittest"]}}
        if self.mode == "check":
            if last.startswith("exit=0"):
                return {"final": "Fixed. Tests pass."}
            if self.wrong_first and not self.corrected:          # tests (or the gate) said it fails: fix the wrong fix
                self.corrected = True
                wrong_text = t["wide"].replace(t["bad"], t["wrong"])
                return self._edit(wrong_text, t["wide"].replace(t["bad"], t["good"]))
            if last.startswith("edited"):
                return {"tool": "bash", "args": {"argv": ["python", "-m", "unittest"]}}
        return {"final": "Done."}

# ---- 3. one run, graded by the END STATE (not by what the agent says) --------------------------------
def build(root, cfg):
    c = default_components()
    c.tools = make_tools(SPECS, style=cfg.get("errors", "helpful"))
    c.instructions = load_instructions
    c.check = Policy(root)
    c.meter = Meter(max_steps=cfg.get("max_steps", 12))
    c.gate = mh.on_stop_gate if cfg.get("gate", True) else None
    if cfg.get("compact_budget"):
        c.prepare = make_prepare(root, cfg["compact_budget"])
    return c

def grade(root, task):
    """Pass only if the tests pass AND the test file is untouched. Independent of the harness's own gate."""
    if (root / "test_mod.py").read_text() != task["files"]["test_mod.py"]:
        return False
    r = subprocess.run([sys.executable, "-m", "unittest"], cwd=root, capture_output=True, text=True, timeout=20,
                       env={"PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"})
    return r.returncode == 0

def run_one(task, seed, cfg):
    root = Path(tempfile.mkdtemp())
    try:
        for name, text in task["files"].items():
            (root / name).write_text(text)
        c = build(root, cfg)
        res = run(StubModel(task, seed), root, task["prompt"], c, system="You are a coding agent.\n" + render_docs(SPECS))
        u = c.meter.usage()
        return {"task": task["id"], "seed": seed, "passed": grade(root, task), "status": res.status,
                "steps": u["steps"], "tokens": u["tokens"], "cost_usd": u["cost_usd"]}
    finally:
        shutil.rmtree(root)

def run_suite(cfg, tasks, seeds, log=None):
    rows = [run_one(t, s, cfg) for t in tasks for s in seeds]
    if log:
        log.write_text("".join(json.dumps({"config": cfg, **r}) + "\n" for r in rows))
    return rows

# ---- 4. numbers ---------------------------------------------------------------------------------------
def wilson(k, n, z=1.96):
    if n == 0:
        return (0.0, 0.0)
    p, d = k / n, 1 + z * z / n
    mid = (p + z * z / (2 * n)) / d
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (mid - half, mid + half)

def summarize(rows):
    n, k = len(rows), sum(r["passed"] for r in rows)
    spend = sum(r["cost_usd"] for r in rows)
    lo, hi = wilson(k, n)
    return {"runs": n, "passed": k, "rate": k / n, "ci": (lo, hi), "cost_per_run": spend / n,
            "cost_per_success": spend / k if k else float("inf"), "steps": sum(r["steps"] for r in rows) / n,
            "stops": Counter(r["status"] for r in rows)}

def compare(old_rows, new_rows):
    """Pair the runs by (task, seed). The model draws are the same in both, so each pair is a fair comparison."""
    old = {(r["task"], r["seed"]): r for r in old_rows}
    new = {(r["task"], r["seed"]): r for r in new_rows}
    fixed = [k for k in new if k in old and not old[k]["passed"] and new[k]["passed"]]
    regressed = [k for k in new if k in old and old[k]["passed"] and not new[k]["passed"]]
    n = len(fixed) + len(regressed)                                # exact McNemar test on the pairs that changed
    p = min(1.0, 2 * sum(math.comb(n, i) for i in range(min(len(fixed), len(regressed)) + 1)) / 2 ** n) if n else 1.0
    return {"fixed": fixed, "regressed": regressed, "p": p}

if __name__ == "__main__":
    tasks = make_tasks()
    rows = run_suite({"errors": "terse", "gate": True}, tasks, seeds=[0])
    print(f"{'task':<9} {'passed':<7} {'stop':<12} {'steps':>5} {'cost':>9}")
    for r in rows:
        print(f"{r['task']:<9} {str(r['passed']):<7} {r['status']:<12} {r['steps']:>5} ${r['cost_usd']:>8.5f}")
    s = summarize(rows)
    print(f"\n{s['passed']}/{s['runs']} passed, cost per run ${s['cost_per_run']:.5f}, cost per success ${s['cost_per_success']:.5f}")

Real output of the demo at the bottom (one run of each task, with terse errors and the gate on):

text
task      passed  stop         steps      cost
add       True    done             4 $ 0.00298
mul       True    done             4 $ 0.00298
square    True    done             4 $ 0.00299
is_even   True    done             4 $ 0.00307
last      True    done             4 $ 0.00307
plus      True    done             3 $ 0.00213
times     True    done             4 $ 0.00310
inc       False   gate_failed      7 $ 0.00651
double    True    done             4 $ 0.00309
upper     False   gate_failed      5 $ 0.00462

8/10 passed, cost per run $0.00345, cost per success $0.00432

14.4 What the run shows#

  • Two tasks failed, and the table says how. inc and upper are twin-function tasks: the stand-in made a vague first edit, got ERROR: edit failed, and the gate refused its "done" three times (gate_failed).
  • The failed runs are the expensive ones. inc cost $0.00651 and upper $0.00462; passing tasks cost $0.002 to $0.003. Cost per run is $0.00345, but cost per successful task is $0.00432: the eight successes pay for the two failures.
  • Ten tasks and one run each is a demo, not a measurement. Part 15 repeats the suite with ten seeds per task.
  • This is evalkit in shape, not in import. 03.13 grades a prompt and a text answer. An agent run needs a workspace and an end-state grader, so this file keeps the same parts (case, grader, pass rate, JSONL row, compare() with regressed and fixed) in agent form. The full agent harness is 10A.7, Part 10, and the DeepEval route for the same job is 10B.2 and 10B.5.

14.5 Where to go for depth#

You will build this properly in 10A.7: task design (Part 2), outcome graders (Part 3), trajectory metrics (Part 4), intervals and pass^k (Part 5) and cost (Part 6). Framework tooling is Module 10B: DeepEval (10B.2 to 10B.5) and Inspect (10B.14, 10B.16). Evaluating context and memory is 10A.11.


Part 15: Evaluating a harness change#

Part 4 reported controlled results: LangChain moved a score from 52.8% to 66.5% with the model fixed. This part shows you how to produce that kind of result for your own harness. The method fits in one sentence: hold the model fixed, change one component, run the same tasks the same number of times, and report success rate and cost per successful task.

15.1 The experiment#

experiment.py runs five arms, each of ten tasks times ten seeds (100 runs):

Arm What changes Why it is there
baseline nothing: terse tool errors, gate on, 12 steps The reference
A/A nothing, but a different ten seeds Measures noise: how far apart two identical harnesses land
helpful tool errors component 1 only: the error wording of Part 9 A change that should matter
stop gate off component 4 and 3 only: remove the completion check A change that should hurt quality
compaction at 2,000 characters component 2 only: the context budget of Part 10 A change this dataset may not be able to see

Everything else is identical: the same ten tasks, the same stand-in model draws (seed by seed), the same policy, the same meter, the same grader. Expect it to take a few minutes: 500 runs, each starting a few small test processes.

python
"""experiment.py - hold the model fixed, change ONE component, compare on the same tasks and seeds."""
from evals_kit import make_tasks, run_suite, summarize, compare

TASKS, SEEDS, OTHER_SEEDS = make_tasks(), list(range(10)), list(range(10, 20))
BASE = {"errors": "terse", "gate": True, "max_steps": 12}

ARMS = [("baseline", BASE, SEEDS),
        ("A/A: baseline, new seeds", BASE, OTHER_SEEDS),
        ("change: helpful tool errors", {**BASE, "errors": "helpful"}, SEEDS),
        ("change: stop gate off", {**BASE, "gate": False}, SEEDS),
        ("change: compaction at 2,000 chars", {**BASE, "compact_budget": 2000}, SEEDS)]

results = {name: run_suite(cfg, TASKS, seeds) for name, cfg, seeds in ARMS}
print(f"{'arm':<36} {'success':>8} {'95% interval':>14} {'$/run':>9} {'$/success':>10} {'steps':>6}")
for name, rows in results.items():
    s = summarize(rows)
    print(f"{name:<36} {s['rate']:>8.0%} {s['ci'][0]:>7.0%}-{s['ci'][1]:<5.0%} {s['cost_per_run']:>9.5f} {s['cost_per_success']:>10.5f} {s['steps']:>6.1f}")
print("\nhow the runs ended:")
for name, rows in results.items():
    print(f"  {name:<36} {dict(summarize(rows)['stops'])}")
print("\npaired against the baseline (same task and seed):")
for name in list(results)[2:]:
    c = compare(results["baseline"], results[name])
    print(f"  {name:<36} fixed {len(c['fixed']):>2}  regressed {len(c['regressed']):>2}  p = {c['p']:.4f}")

Real output (deterministic: the same seeds give the same numbers):

text
arm                                   success   95% interval     $/run  $/success  steps
baseline                                  61%     51%-70%     0.00528    0.00865    5.5
A/A: baseline, new seeds                  60%     50%-69%     0.00496    0.00827    5.2
change: helpful tool errors               94%     88%-97%     0.00446    0.00475    4.9
change: stop gate off                     55%     45%-64%     0.00373    0.00679    4.5
change: compaction at 2,000 chars         61%     51%-70%     0.00524    0.00859    5.5

how the runs ended:
  baseline                             {'done': 61, 'gate_failed': 39}
  A/A: baseline, new seeds             {'done': 60, 'gate_failed': 40}
  change: helpful tool errors          {'done': 94, 'gate_failed': 6}
  change: stop gate off                {'done': 100}
  change: compaction at 2,000 chars    {'done': 61, 'gate_failed': 39}

paired against the baseline (same task and seed):
  change: helpful tool errors          fixed 33  regressed  0  p = 0.0000
  change: stop gate off                fixed  0  regressed  6  p = 0.0312
  change: compaction at 2,000 chars    fixed  0  regressed  0  p = 1.0000

15.2 Reading the table#

Read it in this order. It is the order that keeps you from fooling yourself.

1. Noise first, with the A/A row. The baseline scored 61% and the same harness on new seeds scored 60%, each with an interval of about 51% to 70%. A difference of a few points between arms means nothing here. It is the most useful row, and the one most people skip.

2. The helpful errors arm is a real result. Success went from 61% to 94%. The intervals (51 to 70, against 88 to 97) do not overlap, and the paired view agrees: of the 100 task and seed pairs, 33 were fixed and none regressed, p below 0.0001. Cost per run fell 15% ($0.00528 to $0.00446), but cost per successful task fell 45% ($0.00865 to $0.00475): 39 baseline runs ended gate_failed after burning steps on a failing call, and the successes pay for them. Cost per run flatters an unreliable harness (10A.7, 5.6).

3. The gate-off arm is a trap, and the paired view catches it. Without the gate, success fell from 61% to 55%, but the two intervals (51 to 70 and 45 to 64) overlap almost completely. Read unpaired, that looks like noise. The paired comparison says otherwise: 6 pairs regressed, none was fixed, and an exact paired test gives p = 0.031. It is also the arm with the best-looking cost: $0.00373 per run and $0.00679 per success, both lower than the baseline. And look at how the runs ended: all 100 said done. The agent reported success every time, and 45 of those were wrong. Without an end-state grader that does not trust the agent, this change would have looked like a pure saving.

4. The compaction arm looks like nothing, because here it is nothing. Zero fixed, zero regressed, cost per run within 1%. In these tiny tasks the context rarely passes 2,000 characters, so the clearing rule almost never fires. That does not show compaction is useless; it shows this dataset cannot see it. To evaluate a context change you need tasks that fill the window.

15.3 What this experiment cannot tell you#

  • The size of the effect. The 33-point gain follows from the numbers in StubModel. With a real model it might be 5 points or 30. What carries over is the method and the shape of the conclusions (cost per success falls more than cost per run, a removed gate looks cheap, a no-op looks like zero).
  • Interactions. If two components might help each other, add the arm that combines them after measuring each alone.
  • Generalisation. Ten small Python fixes say nothing about a research or support agent; each kind needs its own tasks (Part 7).

15.4 The discipline#

  1. One change at a time. Two changes in one arm give a number you cannot attribute.
  2. Hold the model fixed. Same model, version and settings. With a real model, record the model name and date: a provider can update a model under the same name.
  3. Same dataset, same seeds, paired comparison. Pairing turns "the intervals overlap" into "6 regressions and no fixes".
  4. Repeat the runs, and run an A/A. One run per task is an anecdote; an A/A arm shows how wide the noise is on your dataset.
  5. Report success rate and cost per successful task together. A trade (more success at higher cost, or the reverse) should be stated as a trade.
  6. Grade the end state, independently. Run the tests yourself, check they were not edited, never score "the agent said it worked".
  7. Read the stop reasons. They explain why a number moved; the rate alone does not.
  8. Check the dataset can see the component. If a change that should matter shows nothing, the tasks may not exercise it.
  9. Record the configuration with every run. run_suite writes the config into each JSONL row.
  10. Re-run on every model upgrade. The build-to-delete audit of Part 5 is this experiment run again.

15.5 Where to go for depth#

You will build this properly in 10A.7 (cost per successful task in 5.6, the evalkit agent harness in Part 10), 10A.8 (repeats and a CI regression gate), 10B.2 (the same job in DeepEval), 11B.8 (what an eval run costs with a real model) and 11C.2 (shipping a harness change behind evals). New tasks come from production traces: 11A.4.


Part 16: Where each piece goes next#

Reference

This lesson is a hub: it names the pieces, builds a toy of each so you can see how they fit, and sends you to the lessons that own the depth. The table is the map. "Toy" means what you built in Parts 8 to 15; "real" means the lesson where you build it properly.

Component Toy in this lesson You build the real thing in Then you use it in
Loop and stop reasons kit.run, Part 8 08A.2, 08A.3 08C (plans, replanning, checkpoint and resume)
Tools tools_kit.py, Part 9 08A.6, 08A.7 08E (MCP servers, A2A, tool selection at scale)
Context and memory context_kit.py, Part 10 04.6, 08B.3, 08B.2 08B.4, 08B.5
Guardrails and permissions policy_kit.py, Part 11 08A.5, 12.6 08A.12 (approval gates), 14A.6 (policy as code)
Budgets and stop conditions meter_kit.py, Part 12 08A.3 11B.6, 11B.7
Tracing trace_kit.py, Part 13 03.12, 11A.1 11A.2, 11A.3
Evals evals_kit.py, Parts 14 and 15 10A.7, 10B 10A.8, 11C.2
Sub-agents the task tool idea in 6.3 08A.11, 08D
Frameworks that package this the snapshot in 2.10 08F.1, 08F.2, 08F.3

Common misconceptions#

Misconception Reality
"The harness is just the framework." A framework supplies parts; the harness is the assembled system, including prompts, tools, permissions and checks.
"A better model makes the harness unnecessary." It makes some of it unnecessary (context resets were), and other parts become more valuable. Audit; do not assume.
"More tools make a more capable agent." Often the opposite. Vercel's agent improved after deleting most of its tools; Anthropic's guidance is few, high-impact tools.
"Put the rules in a longer prompt." A recurring mistake deserves a lint, a test or a tool; a prompt line is the weakest control.
"The agent will tell you when it's done." Agents declare victory early and rate their own work kindly. Gate completion on a check they cannot argue with.
"Harness beats model." The evidence says harness changes are worth double-digit points for a fixed model; it does not say they outweigh model upgrades.
"shell=False and an allow-list is a sandbox." It is a first layer. Real isolation is OS or container level, with network control.
"A harness change that raises the pass rate is an improvement." Not until you have checked cost per successful task, the stop reasons and the paired regressions on the same cases (Part 15).
"If a change shows no effect, that component does not matter." The dataset may not exercise it. Compaction did nothing on tiny tasks (15.2); that says something about the tasks first.
"Lower cost per run means a cheaper harness." A harness that stops checking its work is cheaper per run and worse per success. Compare cost per successful task.

Key takeaways#

  • Agent = Model + Harness. The harness is everything except the weights: loop, tools, context, memory, permissions, verification and lifecycle.
  • Harness engineering is context engineering plus controls: guides before the action, sensors after it.
  • Long-running work needs state outside the window: an initializer, a progress file, a feature list and git commits, with a startup routine in every session.
  • Gate completion with a check the agent cannot argue with; separate generating from judging for subjective work.
  • Fix repeated mistakes with tools, tests and lints rather than longer prompts.
  • Controlled results show double-digit gains from harness changes with the model fixed; observational leaderboards suggest more but confound everything.
  • Build to delete: write down the model weakness each component assumes and re-test it on every model.
  • Draw seams between components (tools, context and memory, permissions, budgets, tracing, evals) so each can be swapped, tested alone and measured.
  • Evaluate a harness change by holding the model fixed, changing one component, and comparing the same tasks and seeds, reporting success rate and cost per successful task, with an A/A run for noise.
  • Grade the end state, not the agent's claim, and keep the grader independent of the harness's own gate.

Terms introduced in this lesson#

Term One-line definition
Harness engineering Designing everything around a model (context, tools, loop, state, permissions, checks) so the same model performs better and more reliably
Guide (feedforward control) A control that steers an agent before it acts: instructions, docs, templates
Sensor (feedback control) A control that observes after the agent acts so it can self-correct: tests, linters, reviewers
Stop gate A hook that runs when the agent says it is done and sends it back to work if a check fails
Context anxiety A model wrapping work up early because it believes it is near its context limit
Context reset Starting a fresh agent with a structured handoff instead of summarising the old context
Initializer agent The first session of a long-running harness, which sets up the environment, progress file and feature list
Progress file A running log the agent updates so the next session can resume
Ralph loop A hook that re-injects the original prompt in a fresh context when the agent tries to exit
Recitation Rewriting the plan at the end of context to keep goals in the model's recent attention
Build to delete Treating each harness component as an assumption about model weakness and removing it when it stops being true
Component (of a harness) One replaceable part with a small interface: tools, context and memory, guardrails and permissions, budgets and stop conditions, tracing or evals
Seam A joint in the harness where a component plugs in, so it can be swapped, tested or measured alone
Risk class A label on a tool (read, write or exec) that the permission layer uses to decide
Permission tier The three outcomes of a permission check: allow, ask (a person decides) or deny
Context view The copy of the history the model actually sees on one turn; the full history is kept unchanged
Tool-result clearing Replacing old tool results with a short placeholder that says how to get them back
Meter One counter for steps, tokens, money and time that names the limit that ended a run
Stop reason The name of how a run ended: done, step_budget, token_budget, cost_budget, deadline, stagnation or gate_failed
End-state grader A check that runs after the agent finishes and looks at the result (for example, the tests), not at what the agent said
A/A run Running the same harness twice on different seeds to measure noise
Paired comparison Comparing two arms task by task and seed by seed, listing what was fixed and what regressed
Cost per successful task Total spend on all runs, failed ones included, divided by the number of successes

Exercises#

  1. Gate it (6.1): change the scripted model so its first final message is followed by a call that edits test_calc.py to make the test pass. What would you add to the harness to stop that, and where does the feature-list prompt wording in Part 3 address it?
  2. Offload (6.1): make MAX_TOOL_CHARS small and have the script call bash with ls. Read the file under .harness/. What does the model see in its context, and what does it have to do to get the rest?
  3. Loop detector (6.1): write a model that issues the same read_file call every step. At which step does the harness intervene, and what does it say?
  4. Escape attempts (6.1): try read_file with ./../x, a symlink inside the workspace pointing outside it, and an absolute path. Which are denied, and why does resolve() matter?
  5. Delete audit (Part 5): list five components of your own agent (or of the harness in 6.1). For each, write the model weakness it assumes and a cheap test that would show whether it is still needed.
  6. Sensors (1.3): classify as guide or sensor, and computational or inferential: a pre-commit hook; AGENTS.md; an LLM code-review agent; a type checker; a skill file.
  7. Feature list (3.2): write a ten-item feature list for a to-do app and the startup routine prompt a coding agent would follow each session.
  8. Use case (Part 7): pick one row and write its stop gate: what check, what failure message, what the agent is told to do next.
  9. A second check (Part 8): write a check plug that refuses any edit_file whose new text is more than 2,000 characters. Plug it in beside Policy and add a test to test_components.py.
  10. A new tool (Part 9): add a grep tool to SPECS. Which risk class does it get, which arguments are required, and what should its error say when the pattern matches nothing?
  11. Pairs (Part 10): change clear_old_results to drop whole assistant and tool pairs instead of replacing the tool text. Why can that break a provider API, and where does 08B.3, 2.2 explain it?
  12. Read the trace (Part 13): run trace_kit.py and answer from trace.jsonl alone: which step was refused, how many input tokens did step 4 use, and what took the longest?
  13. Make compaction visible (Part 15): add three tasks whose mod.py is 3,000 characters long, set compact_budget to 1,500 and re-run the compaction arm. Does it now fix or regress anything?
  14. A fair test (15.4): a colleague changed the system prompt and two tool descriptions together and reports "+8 points on 20 runs". Which rules of the discipline does that break, and what would you run instead?

Check yourself#

  1. State the "Agent = Model + Harness" equation and give three things that belong to the harness.
  2. How does harness engineering differ from context engineering?
  3. What is the difference between a guide and a sensor? Give an example of each.
  4. Why does the long-running pattern use an initializer session and a progress file?
  5. Why is the feature list JSON, and what may the coding agent change in it?
  6. What is context anxiety, and which two fixes were reported?
  7. Why is a separate evaluator better than asking the agent to check its own work?
  8. What is the strongest controlled evidence that harness changes matter, and why is the SWE-bench audit weaker?
  9. Why does Hashimoto prefer a tool or a lint over a longer prompt?
  10. What does "build to delete" mean in practice?
  11. Why does the minimal harness pass PYTHONDONTWRITEBYTECODE=1?
  12. Why must credentials stay outside the sandbox where model code runs?
  13. What is a seam, and why do you need seams to evaluate a harness change?
  14. Why does "include more surrounding lines" beat "edit failed" as a tool error?
  15. Why is clearing old tool results done on a view and not on the history?
  16. Name the three outcomes of a permission check and give an example of each.
  17. Why run an A/A arm?
  18. Why is cost per successful task a better number than cost per run?
  19. In Part 15, why did removing the gate look like a saving, and what exposed it?

Further resources#

Framework facts in 11.4, 12.4 and 13.4 were checked against the official documentation on 2 December 2026. Not verified against primary sources: the OpenAI "Harness engineering" post could not be loaded during research, so figures attributed to it come from secondary summaries; the Opus 4.6 per-harness scores come from one blog.


← 08A.3: Loop Control, Budgets and Stagnation Detection in the Raw Loop | Module 08A overview | 08A.5: Required Agent Security →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close