Harness engineering: the system around the model
The model proposes; the harness disposes. A harness is all the code and configuration around an LLM: the loop that calls it, the context it sees, the tools it may use, the permissions that gate them, the checks that verify its work, and the traces that tell you what happened. With the same model, the harness often decides whether an agent is a toy or a teammate. This page builds one up, from concepts to a tested ~200-line implementation.
1. What is a harness?
Why harness engineering matters
- The same model gives very different results in different harnesses. Agent benchmark scores depend heavily on the scaffold: the tools offered, how errors are reported, and when the agent is allowed to stop.
- Reliability lives in the harness. Budgets, approvals, sandboxes, and verification are code. The model can't promise them.
- Cost and latency live in the harness. Caching, context hygiene, and model routing are harness decisions.
- Harnesses are what you can change today. You can't retrain the model, but you can ship a better harness this afternoon.
2. Anatomy of a harness
| Component | Job | In Claude Code | In your own harness |
|---|---|---|---|
| Control loop | Call the model, dispatch tools, decide when to stop | The agent loop, max_turns, interrupts | while loop on stop_reason, or the SDK tool runner |
| Context assembly | Build what the model sees each turn | System prompt + CLAUDE.md + history + tool results | Frozen system prompt, append-only messages |
| Context management | Stay within the window and keep it high-signal | Auto-compact, /compact, /clear, subagents | Server-side compaction, context editing, output caps |
| Tools | What the agent can do | Read, Edit, Bash, Grep, WebFetch, MCP servers | Your functions, MCP, Anthropic tools |
| Permissions | What it may do without asking | settings.json allow/ask/deny, permission modes | Policy per tool and risk level |
| Hooks | Deterministic code at lifecycle events | PreToolUse, PostToolUse, Stop, SessionStart… | Pre/post callbacks around every tool |
| Sandbox | Contain the blast radius | Filesystem and network sandboxing, devcontainers | Containers, read-only mounts, egress allowlists |
| Memory | Persist knowledge across sessions | CLAUDE.md hierarchy, auto-memory | Files, memory tool, progress notes |
| Verification | Prove the work is right before accepting it | Tests via Bash, Stop hooks, reviewer subagents | Checks run on end_turn |
| Observability | See what happened and what it cost | Transcripts, OpenTelemetry metrics, cost reports | JSONL traces, token and cache metrics |
Claude Code is itself a harness, and the Claude Agent SDK sells exactly that harness as a library. If you are building on the raw Messages API, every row above is yours to write. Sections 3–8 show how.
3. The control loop: when to call, continue, and stop
| Concern | Good practice |
|---|---|
| Stop conditions | Finish on end_turn after verification; stop on refusal; continue on max_tokens (or raise it); resend on pause_turn (server tools). |
| Budgets | Cap turns, output tokens, dollars, and wall-clock time. All are hard stops in code. A model-visible task budget (beta task_budget) lets the model pace itself instead of being cut off. |
| Warn before cutting off | A few turns before the limit, append a short instruction ("3 turns left, wrap up") so the run ends with a summary instead of mid-edit. |
| Retries | The SDKs already retry 408/409/429/5xx and connection errors with backoff (2 retries by default). Add your own retry only around tools, and only for idempotent ones. |
| Loop detection | Notice the same tool called with the same arguments repeatedly, and intervene (a message, or a stop). |
| Streaming & long turns | Stream large outputs to avoid HTTP timeouts. Show progress, and let users interrupt. |
4. Context assembly, caching and append-only transcripts
Every request re-sends the whole conversation, and the API processes it as one long prefix: tools → system → messages. Prompt caching makes the unchanged part of that prefix cheap and fast. That leads to the most important context rule in harness engineering: keep the past byte-for-byte stable and only append.
Rules for the context builder
- Freeze the prefixTools in a deterministic order, a system prompt with no timestamps or request IDs, and memory files loaded once per session.
- Append, never rewriteDon't edit or delete earlier messages. Beyond caching, newer models bind their thinking blocks to the exact conversation that produced them. Editing history invalidates them (and new API accounts get a 400 for it).
- Mid-session instructions as messagesTo change instructions, append a
{"role": "system", …}message instead of editing the top-level system prompt. It preserves the cache and carries operator authority. - Shrink with server-side toolsUse API compaction (
compact_20260112) or context editing (clear_tool_uses_20250919) rather than hand-rewriting history. Cap tool output before it is appended. - MeasureLog
usage.cache_read_input_tokens. If it stays at zero, something in your prefix changes every request.
"""Cache-friendly request layout: stable things first, growing things last, never edit the past."""
import anthropic
from my_tools import TOOLS as MY_TOOLS # your tool definitions
client = anthropic.Anthropic()
SYSTEM_PROMPT = open("SYSTEM.md").read() # frozen for the whole session: no timestamps!
TOOLS = sorted(MY_TOOLS, key=lambda t: t["name"]) # deterministic order on every request
messages = [] # append-only transcript
def turn(user_text: str):
messages.append({"role": "user", "content": user_text})
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=TOOLS, # 1. rendered first
system=[{"type": "text", "text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}}], # 2. breakpoint: tools + system
cache_control={"type": "ephemeral"}, # 3. auto-cache the growing tail
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
u = response.usage
print(f"cache read={u.cache_read_input_tokens} written={u.cache_creation_input_tokens} "
f"uncached={u.input_tokens}") # watch your hit rate
return response
def add_instruction(text: str):
"""Mid-session instruction WITHOUT editing the system prompt (keeps the cache valid)."""
messages.append({"role": "system", "content": text})
Keep the bookmark
Everyday picture: a bookmark in a long book. You can pick up instantly where you left off, as long as nobody changes the earlier pages. Change one word on page 3 and you must re-read from page 3. The API caches the prompt prefix (tools → system → messages) the same way.
Each card is a change to how the harness builds the next request. Will the long, cached history stay warm? After you answer, the bar shows what's read from cache (green) and what has to be processed again (orange).
5. Permissions, hooks and sandboxing
Safety in a harness is layered, so no single mistake is catastrophic.
1 · Prompt
Tells the model the rules. Soft: it guides most behaviour, but it can be forgotten or overridden by injected text.
2 · Permissions
Allow / ask / deny per tool or command pattern, checked by code before execution.
3 · Hooks
Your scripts run at lifecycle events and can block, modify, or add context. Deterministic.
4 · Sandbox
Even if everything above fails, the process can't reach what it isn't given: files, network, credentials.
Claude Code: permissions and hooks in .claude/settings.json
{
"permissions": {
"allow": ["Read", "Grep", "Glob", "Bash(npm test:*)", "Bash(git diff:*)", "Bash(git status)"],
"ask": ["Bash(git push:*)", "WebFetch"],
"deny": ["Read(./.env)", "Read(./secrets/**)", "Bash(curl:*)"]
},
"hooks": {
"PreToolUse": [
{ "matcher": "Bash",
"hooks": [{ "type": "command", "command": "python3 .claude/hooks/block_dangerous.py" }] }
],
"PostToolUse": [
{ "matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }] }
],
"Stop": [
{ "hooks": [{ "type": "command", "command": "python3 .claude/hooks/stop_until_tests_pass.py" }] }
]
}
}
| Hook event | Fires | Typical use |
|---|---|---|
PreToolUse | Before a tool runs | Block dangerous commands; validate arguments; enforce branch policies |
PostToolUse | After a tool succeeds | Auto-format edited files; run linters; log |
UserPromptSubmit | When the user sends a prompt | Add context; block prompts containing secrets |
Stop / SubagentStop | When the agent wants to finish | Refuse to stop until tests pass |
SessionStart / PreCompact | Session start; before compaction | Load project state; save notes before history is summarised |
A command hook receives the event as JSON on stdin. Exit 0 lets it proceed. Exit 2 blocks it, and stderr is fed back to Claude so it can adapt:
#!/usr/bin/env python3
"""Claude Code PreToolUse hook: block destructive shell commands.
Claude Code sends the pending tool call as JSON on stdin.
Exit 0 = allow. Exit 2 = block; stderr is shown to Claude so it can choose another way.
"""
import json
import re
import sys
DANGEROUS = [
r"\brm\s+-rf\s+(/|~|\$HOME)",
r"\bgit\s+push\b.*--force",
r"\bDROP\s+(TABLE|DATABASE)\b",
r"\bcurl\b[^|]*\|\s*(ba|z)?sh\b",
]
event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
for pattern in DANGEROUS:
if re.search(pattern, command, re.IGNORECASE):
print(f"Blocked by policy: '{command}' matches {pattern}. Use a safer alternative.",
file=sys.stderr)
sys.exit(2)
sys.exit(0)
PostToolUse hook, not a CLAUDE.md line. "Never touch .env" → a deny permission rule plus a sandbox, not just an instruction. Instructions are for judgment; hooks and permissions are for guarantees.The security desk
Everyday picture: a building's security desk. The guard checks the banned list first, then the “call upstairs before letting them in” list, then the guest list. Anyone on no list gets the building's default treatment. Claude Code checks permission rules in exactly that order.
Claude wants to run each tool call below. Using the rules, decide what happens.
"allow": ["Read", "Grep", "Glob", "Bash(npm test:*)", "Bash(git diff:*)", "Bash(git status)"], "ask": ["Bash(git push:*)", "WebFetch"], "deny": ["Read(./.env)", "Read(./secrets/**)", "Bash(curl:*)"]
Rules are checked deny → ask → allow; the first matching category decides. Anything unmatched falls back to the permission mode. Here that's the default mode, where Claude asks you.
Handbook, badge or alarm?
Everyday picture: rules for a new employee. The handbook (the prompt) guides their judgment. The badge reader (permissions) decides which doors open. Automatic checklists (hooks) run at set moments, every time. And the building's walls (the sandbox) stop anyone reaching what they shouldn't, even if everything else fails.
Pick the mechanism that best fits each requirement. Instructions are for judgment; hooks and permissions are for guarantees.
6. Verification: don't accept "done" without proof
The highest-leverage thing a harness can do is give the agent a way to check its own work, and refuse to finish until the check passes. Models are good at fixing a failure they can see.
| Verifier | Strength | Watch out for |
|---|---|---|
| Rules / code (tests, linters, type-checkers, schema validation) | Fast, cheap, objective | Only as good as the tests; agents may "fix" tests instead of code, so protect test files |
| Visual (screenshots of UI) | Catches layout and rendering bugs | Needs a browser tool and a clear spec |
| LLM as judge (a separate reviewer with a rubric) | Handles fuzzy quality (tone, completeness) | Costs tokens; calibrate against human grades |
| Human review | The final authority for high-stakes changes | Slow; save it for what matters |
In Claude Code, a Stop hook turns this into policy. Exit 2 blocks the stop and hands the failure output back to Claude:
#!/usr/bin/env python3
"""Claude Code Stop hook: the agent may not finish while the tests fail.
Exit 2 blocks the stop and feeds stderr back to Claude, so it keeps working.
"""
import json
import subprocess
import sys
event = json.load(sys.stdin)
if event.get("stop_hook_active"): # we already sent it back once: don't loop forever
sys.exit(0)
tests = subprocess.run(["npm", "test", "--silent"], capture_output=True, text=True)
if tests.returncode != 0:
print("Tests are failing. Fix them before finishing:\n" + (tests.stdout + tests.stderr)[-2000:],
file=sys.stderr)
sys.exit(2)
sys.exit(0)
Stop hook that always blocks creates an endless loop. Check stop_hook_active (as above), or count attempts and give up after N.7. Build it: a complete mini harness (tested)
Everything above in one file, on the raw Messages API. It's small enough to read in ten minutes, and it is covered by offline tests with a scripted fake client: the deny pattern, the pre-hook block, a human "no", secret redaction, a failed-then-passed verification, the budget warning, and the trace are all exercised.
"""A small but complete agent harness.
The model only proposes actions. Everything in this file is the harness: loop control,
budgets, permissions, hooks, context hygiene, verification and tracing.
"""
import json
import re
import subprocess
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
import anthropic
MODEL = "claude-opus-5-5"
@dataclass
class Tool:
name: str
description: str
input_schema: dict
fn: Callable[..., str]
risk: str = "read" # read | write | exec
def spec(self) -> dict:
return {"name": self.name, "description": self.description, "input_schema": self.input_schema}
@dataclass
class Policy:
"""Permission rules: deny patterns first, then a default per risk level."""
read: str = "allow"
write: str = "ask"
exec: str = "ask"
deny_patterns: tuple[str, ...] = ("rm -rf", "git push --force", "| sh", ".env")
def decide(self, tool: Tool, args: dict) -> str:
blob = json.dumps(args)
if any(p in blob for p in self.deny_patterns):
return "deny"
return getattr(self, tool.risk)
@dataclass
class Budget:
max_turns: int = 30
max_output_tokens: int = 300_000
turns: int = 0
output_tokens: int = 0
def charge(self, usage) -> None:
self.turns += 1
self.output_tokens += usage.output_tokens
@property
def turns_left(self) -> int:
return self.max_turns - self.turns
def exhausted(self) -> bool:
return self.turns_left <= 0 or self.output_tokens >= self.max_output_tokens
PreHook = Callable[[str, dict], Optional[str]] # return a reason to block, or None
PostHook = Callable[[str, dict, str], str] # may rewrite the output (e.g. redact)
def ask_human(name: str, args: dict) -> bool:
return input(f"Allow {name} {json.dumps(args)[:200]}? [y/N] ").strip().lower() == "y"
@dataclass
class Harness:
tools: list[Tool]
system: str
client: anthropic.Anthropic = field(default_factory=anthropic.Anthropic)
policy: Policy = field(default_factory=Policy)
budget: Budget = field(default_factory=Budget)
approve: Callable[[str, dict], bool] = ask_human
pre_hooks: list[PreHook] = field(default_factory=list)
post_hooks: list[PostHook] = field(default_factory=list)
verify: Optional[Callable[[], Optional[str]]] = None # failure text, or None when OK
max_result_chars: int = 10_000
trace_path: Path = Path("trace.jsonl")
# -- observability ---------------------------------------------------------------
def trace(self, event: str, **data) -> None:
with self.trace_path.open("a") as f:
f.write(json.dumps({"ts": time.time(), "event": event, **data}, default=str) + "\n")
# -- one model call: stable prefix for caching, server-side compaction -------------
def call_model(self, messages: list):
return self.client.beta.messages.create(
model=MODEL,
max_tokens=16000,
betas=["compact-2026-01-12"],
context_management={"edits": [{"type": "compact_20260112"}]},
system=[{"type": "text", "text": self.system,
"cache_control": {"type": "ephemeral"}}], # caches tools + system
tools=[t.spec() for t in self.tools], # same order on every call
messages=messages,
)
# -- one tool call: hooks -> permission -> execute -> post-process -----------------
def run_tool(self, block) -> dict:
def result(text: str, error: bool = False) -> dict:
self.trace("tool", name=block.name, error=error, chars=len(text))
return {"type": "tool_result", "tool_use_id": block.id, "content": text, "is_error": error}
tool = next((t for t in self.tools if t.name == block.name), None)
if tool is None:
return result(f"Unknown tool '{block.name}'.", error=True)
for hook in self.pre_hooks: # deterministic guardrails
reason = hook(block.name, block.input)
if reason:
return result(f"Blocked by policy: {reason}", error=True)
decision = self.policy.decide(tool, block.input)
if decision == "deny" or (decision == "ask" and not self.approve(block.name, block.input)):
return result(f"Permission denied for {block.name}. Try a different approach.", error=True)
try:
output = tool.fn(**block.input)
except Exception as exc: # errors become information
return result(f"{type(exc).__name__}: {exc}", error=True)
for hook in self.post_hooks:
output = hook(block.name, block.input, output)
if len(output) > self.max_result_chars: # context hygiene
cut = len(output) - self.max_result_chars
output = output[: self.max_result_chars] + f"\n[... {cut} more chars not shown]"
return result(output)
# -- the loop ----------------------------------------------------------------------
def run(self, task: str) -> str:
messages: list = [{"role": "user", "content": task}]
self.trace("start", task=task)
while not self.budget.exhausted():
response = self.call_model(messages)
self.budget.charge(response.usage)
self.trace("model", stop_reason=response.stop_reason,
output_tokens=response.usage.output_tokens)
messages.append({"role": "assistant", "content": response.content}) # append-only
if response.stop_reason == "tool_use":
calls = [b for b in response.content if b.type == "tool_use"]
messages.append({"role": "user", "content": [self.run_tool(b) for b in calls]})
if self.budget.turns_left == 3: # warn instead of cutting off
messages.append({"role": "system",
"content": "3 turns left. Finish the current step and summarise."})
continue
if response.stop_reason == "max_tokens":
messages.append({"role": "user", "content": "Continue exactly where you stopped."})
continue
if response.stop_reason == "refusal":
self.trace("refusal")
return "The model declined this task."
failure = self.verify() if self.verify else None # end_turn: check before accepting
if failure is None:
self.trace("done", turns=self.budget.turns)
return "".join(b.text for b in response.content if b.type == "text")
self.trace("verify_failed", details=failure[:500])
messages.append({"role": "user",
"content": f"Verification failed. Fix this before finishing:\n{failure}"})
self.trace("budget_exhausted", turns=self.budget.turns)
return "Stopped: budget exhausted."
# ---- wiring it up -------------------------------------------------------------------
def read_file(path: str) -> str:
return Path(path).read_text()
def write_file(path: str, content: str) -> str:
Path(path).write_text(content)
return f"Wrote {len(content)} chars to {path}"
def run_command(command: str) -> str:
p = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=120)
return f"exit={p.returncode}\n{p.stdout}{p.stderr}"
def tests_pass() -> Optional[str]:
p = subprocess.run(["pytest", "-q"], capture_output=True, text=True)
return None if p.returncode == 0 else (p.stdout + p.stderr)[-3000:]
def protect_main_branch(name: str, args: dict) -> Optional[str]:
if name == "run_command" and re.search(r"git (commit|push).*\bmain\b", args.get("command", "")):
return "Never commit or push to main. Create a feature branch."
return None
def redact_secrets(name: str, args: dict, output: str) -> str:
return re.sub(r"sk-[A-Za-z0-9_-]{20,}", "[REDACTED]", output)
PATH = {"type": "string", "description": "Path relative to the repo root."}
TOOLS = [
Tool("read_file", "Read a UTF-8 text file.",
{"type": "object", "properties": {"path": PATH}, "required": ["path"]}, read_file, "read"),
Tool("write_file", "Create or overwrite a file with the given content.",
{"type": "object", "properties": {"path": PATH, "content": {"type": "string"}},
"required": ["path", "content"]}, write_file, "write"),
Tool("run_command", "Run a shell command in the repo (120 s timeout). Returns exit code and output.",
{"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]},
run_command, "exec"),
]
if __name__ == "__main__":
harness = Harness(
tools=TOOLS,
system="You are a careful coding agent. Make the smallest change that makes the tests pass.",
pre_hooks=[protect_main_branch],
post_hooks=[redact_secrets],
verify=tests_pass,
)
print(harness.run("The test test_parse_date is failing. Find the cause and fix it."))
| Harness feature | Where in the code |
|---|---|
| Bounded loop & budgets | Budget, while not self.budget.exhausted() |
| Warn before the end | appended role: "system" message at 3 turns left |
| Permissions (allow / ask / deny) | Policy.decide per risk level + deny patterns |
| Deterministic guardrails | pre_hooks (e.g. protect_main_branch) |
| Output hygiene | post_hooks (redaction) + max_result_chars cap |
| Errors as information | every failure becomes is_error: true, never an exception |
| Caching & compaction | cache_control on the system block; server-side compact_20260112 |
| Append-only transcript | only messages.append(...), never edits |
| Verification before done | verify() on end_turn; failures re-enter as feedback |
| Observability | trace() → trace.jsonl |
8. Or rent the harness: the Claude Agent SDK
The Agent SDK gives you Claude Code's harness (built-in tools, loop, compaction, subagents, sessions) and lets you plug in your own policy as Python callbacks:
"""The same guardrails, programmatically, with the Claude Agent SDK."""
import asyncio
from claude_agent_sdk import (ClaudeAgentOptions, HookMatcher, PermissionResultAllow,
PermissionResultDeny, ResultMessage, query)
async def block_dangerous(input_data, tool_use_id, context):
"""PreToolUse hook: runs before every Bash call, can deny it."""
command = input_data["tool_input"].get("command", "")
if "rm -rf" in command or "--force" in command:
return {"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Destructive command blocked by policy.",
}}
return {}
async def can_use_tool(tool_name, tool_input, context):
"""Called for tools that are NOT pre-approved in allowed_tools."""
if tool_name in ("Write", "Edit") and not tool_input.get("file_path", "").startswith("/repo/"):
return PermissionResultDeny(message="Only files inside /repo may be changed.")
return PermissionResultAllow()
options = ClaudeAgentOptions(
cwd="/repo",
allowed_tools=["Read", "Grep", "Glob", "Bash"], # pre-approved; never reach can_use_tool
can_use_tool=can_use_tool, # decides Write/Edit
hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_dangerous])]},
max_turns=40,
max_budget_usd=3.00,
)
async def main() -> None:
async for message in query(prompt="Upgrade the date library and fix what breaks.", options=options):
if isinstance(message, ResultMessage):
print(message.subtype, message.num_turns, message.total_cost_usd)
if __name__ == "__main__":
asyncio.run(main())
allowed_tools are pre-approved: they never reach your can_use_tool callback. Put a tool there only if you never want to inspect its calls. Hooks still run for pre-approved tools, which is why the dangerous-command check above is a PreToolUse hook.| Permission mode | Behaviour |
|---|---|
default | Ask for anything not allowed by rules |
acceptEdits | Auto-approve file edits; still ask for other risky tools |
plan | Read-only exploration and planning; no changes |
dontAsk | Never prompt: anything not pre-approved is denied |
auto | A classifier approves low-risk calls and escalates the rest |
bypassPermissions | No checks at all. Only inside a disposable sandbox |
9. Long-running agents: work that spans many context windows
Some jobs (building an app, a large migration) can't finish in one context window. Each new session starts with no memory, so the harness must make the environment carry the state:
- Initializer sessionSets up the project, writes a structured feature list (all items "failing"), an
init.shto start the app, and a progress file, then makes the first git commit. - Each working session starts by orientingRead the progress file and git log, run
init.sh, and run a smoke test to confirm nothing is broken before starting. - One feature at a timePick the highest-priority failing item, implement it, and verify it end to end.
- Leave a clean stateMark the item passing only after verification, commit with a descriptive message, and update the progress notes for the next session.
# features.json (the agent may only flip "passes"; never delete or edit tests)
[{"id": "auth-01", "description": "User can sign up with email", "passes": true},
{"id": "auth-02", "description": "Password reset email is sent", "passes": false}]
# progress.md (written at the end of every session)
## Session 14
- Done: auth-01 (signup), verified in browser; commit 3f2a91c
- Next: auth-02. Mail sender stub exists in src/mail.ts
- Gotcha: run `npm run db:reset` before e2e tests
10. Observability: you can't fix what you can't see
| Signal | Why it matters | Source |
|---|---|---|
| Full transcript / trace per run | Debugging starts by reading what the agent saw and did | JSONL events, SDK message stream, Claude Code transcripts |
| Tokens in/out, cache read/write | Cost and cache health | response.usage |
| Cost per completed task | The real unit economics (a cheap call that needs 5 retries isn't cheap) | Sum per run ÷ successes |
| Turns per task, tool error rate | Spot confusing tools and loops | Trace events |
| Permission denials, hook blocks | Policy too tight, or agent misbehaving | Harness logs; ResultMessage.permission_denials in the SDK |
Claude Code can export usage metrics via OpenTelemetry, so teams can track usage and cost in their existing dashboards.
11. Evaluating a harness
Every harness change (new tool description, different compaction threshold, new hook) can help one task and hurt another. Treat the harness like any other software: a fixed task set, automatic graders, and a number you track.
- Collect tasksReal requests with a checkable outcome (tests that must pass, expected fields, a rubric). Start with 20–50; grow from production failures.
- Grade automaticallyCode checks first; LLM judges with a rubric for fuzzy quality; humans to calibrate the judges.
- Run each task several timesAgents are stochastic. One run tells you little.
- Change one thing at a timeAn ablation shows which harness component actually moved the score.
- Read transcripts of failuresThe fix is usually visible: a misleading tool description, a missing error message, a context flood.
"""Measuring an agent harness: run every task k times, report pass@k AND pass^k."""
from math import comb
from statistics import mean
def pass_at_k(n: int, c: int, k: int) -> float:
"""P(at least one of k attempts succeeds), from n trials with c successes."""
if n - c < k:
return 1.0
return 1 - comb(n - c, k) / comb(n, k)
def pass_hat_k(n: int, c: int, k: int) -> float:
"""P(ALL k attempts succeed): the reliability number users actually feel."""
return comb(c, k) / comb(n, k)
def evaluate(tasks: list[dict], run_agent, grade, trials: int = 5, k: int = 3) -> dict:
per_task = []
for task in tasks:
successes = sum(bool(grade(task, run_agent(task["prompt"]))) for _ in range(trials))
per_task.append({"id": task["id"], "successes": successes})
return {
f"pass@{k}": mean(pass_at_k(trials, t["successes"], k) for t in per_task),
f"pass^{k}": mean(pass_hat_k(trials, t["successes"], k) for t in per_task),
"per_task": per_task,
}
12. Anti-patterns checklist
| Anti-pattern | Do instead |
|---|---|
| Safety rules only in the prompt | Permissions + hooks + sandbox; the prompt explains why |
| Timestamps or per-request data in the system prompt | Frozen prefix; volatile data in the latest message |
| Editing or deleting earlier messages | Append-only; server-side compaction and context editing; role: "system" messages for new instructions |
| Raising exceptions on tool failure | is_error results with actionable text |
| Unbounded loops | Turn, token, dollar, and time budgets, plus a warning before the cut-off |
| Accepting "done" at face value | Verification on end_turn; Stop hooks |
| Dumping whole files or results into context | Caps, pagination, just-in-time reads, subagents |
| Judging changes from one lucky run | Repeated trials; pass^k; ablations |
bypassPermissions on a laptop with real credentials | Only in disposable, network-restricted sandboxes |
Building inspection
Everyday picture: a building inspection. Before anyone moves in, an inspector walks through and flags the violations, and leaves alone the parts that are built to code. Here's a design review of a team's harness.
Self-check quiz
Score: 0 / 0 answered
Stop hook runs tests and exits 2 on failure. Users report the agent sometimes never stops. Fix?"Write" to allowed_tools and wrote a can_use_tool callback to block writes outside the repo. Writes outside the repo still happen. Why?Write from allowed_tools (or enforce the rule in a PreToolUse hook, which runs regardless).