AI · Topic 5 · Exam domains D1 · D2 · D5

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.

D1 · D2 · D5 loop, configuration, reliability 3 animated diagrams 17 offline tests behind the code ≈ 80 min read

1. What is a harness?

The one-line definitionAgent = Model + Harness. The model is the engine. The harness is everything else that makes it a car you can trust on a road: steering (the loop), fuel (context), controls (tools), brakes (permissions and budgets), dashboard (traces), and inspection (verification and evals).
checks fail → feedback, keep working tool_use allowed result: capped, redacted, logged Task user / trigger Context builder prompt · memory · cache Model proposes actions Verifier tests · checks Done Policy gate hooks · permissions Executor sandboxed tools
Only the orange box is the model. Every blue box is harness code you own. A denied call at the gate goes back to the model as an error result, so it can choose another way.

Why harness engineering matters

2. Anatomy of a harness

ComponentJobIn Claude CodeIn your own harness
Control loopCall the model, dispatch tools, decide when to stopThe agent loop, max_turns, interruptswhile loop on stop_reason, or the SDK tool runner
Context assemblyBuild what the model sees each turnSystem prompt + CLAUDE.md + history + tool resultsFrozen system prompt, append-only messages
Context managementStay within the window and keep it high-signalAuto-compact, /compact, /clear, subagentsServer-side compaction, context editing, output caps
ToolsWhat the agent can doRead, Edit, Bash, Grep, WebFetch, MCP serversYour functions, MCP, Anthropic tools
PermissionsWhat it may do without askingsettings.json allow/ask/deny, permission modesPolicy per tool and risk level
HooksDeterministic code at lifecycle eventsPreToolUse, PostToolUse, Stop, SessionStart…Pre/post callbacks around every tool
SandboxContain the blast radiusFilesystem and network sandboxing, devcontainersContainers, read-only mounts, egress allowlists
MemoryPersist knowledge across sessionsCLAUDE.md hierarchy, auto-memoryFiles, memory tool, progress notes
VerificationProve the work is right before accepting itTests via Bash, Stop hooks, reviewer subagentsChecks run on end_turn
ObservabilitySee what happened and what it costTranscripts, OpenTelemetry metrics, cost reportsJSONL 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

ConcernGood practice
Stop conditionsFinish on end_turn after verification; stop on refusal; continue on max_tokens (or raise it); resend on pause_turn (server tools).
BudgetsCap 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 offA 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.
RetriesThe 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 detectionNotice the same tool called with the same arguments repeatedly, and intervene (a message, or a stop).
Streaming & long turnsStream 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.

cached prefix (cheap, fast) tools system prompt edited! CLAUDE.md turn 1 turn 2 turn 3 new turn stable: set once per session grows every turn, append-only ① Each request re-sends everything; the unchanged prefix is read from cache. ② Append-only: on the next request the cached prefix grows to include the new turn. ③ Editing the system prompt mid-session breaks the prefix: everything after it is uncached.
The green bar is the cache hit. Appending keeps it long; editing anything earlier cuts it at the edit.

Rules for the context builder

  1. Freeze the prefixTools in a deterministic order, a system prompt with no timestamps or request IDs, and memory files loaded once per session.
  2. 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).
  3. 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.
  4. 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.
  5. 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})
Game · Prompt caching

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 eventFiresTypical use
PreToolUseBefore a tool runsBlock dangerous commands; validate arguments; enforce branch policies
PostToolUseAfter a tool succeedsAuto-format edited files; run linters; log
UserPromptSubmitWhen the user sends a promptAdd context; block prompts containing secrets
Stop / SubagentStopWhen the agent wants to finishRefuse to stop until tests pass
SessionStart / PreCompactSession start; before compactionLoad 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)
🎯 Exam lens: prompt vs hook"Claude must always run the formatter after editing" → a 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.
Game · Permissions

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.

.claude/settings.json (the example from this section)
"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.

Game · Hooks & guarantees

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.

pass fail errors → next prompt Agent actsedits code Verifytests · lint · types Doneverified result Feedbackfailing test output
Two failed checks feed their error output back to the agent; on the third attempt the light turns green and only then does the run finish.
VerifierStrengthWatch out for
Rules / code (tests, linters, type-checkers, schema validation)Fast, cheap, objectiveOnly as good as the tests; agents may "fix" tests instead of code, so protect test files
Visual (screenshots of UI)Catches layout and rendering bugsNeeds 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 reviewThe final authority for high-stakes changesSlow; 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)
⚠️ TrapA 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 featureWhere in the code
Bounded loop & budgetsBudget, while not self.budget.exhausted()
Warn before the endappended role: "system" message at 3 turns left
Permissions (allow / ask / deny)Policy.decide per risk level + deny patterns
Deterministic guardrailspre_hooks (e.g. protect_main_branch)
Output hygienepost_hooks (redaction) + max_result_chars cap
Errors as informationevery failure becomes is_error: true, never an exception
Caching & compactioncache_control on the system block; server-side compact_20260112
Append-only transcriptonly messages.append(...), never edits
Verification before doneverify() on end_turn; failures re-enter as feedback
Observabilitytrace() → 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())
⚠️ A subtle ordering ruleTools listed in 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 modeBehaviour
defaultAsk for anything not allowed by rules
acceptEditsAuto-approve file edits; still ask for other risky tools
planRead-only exploration and planning; no changes
dontAskNever prompt: anything not pre-approved is denied
autoA classifier approves low-risk calls and escalates the rest
bypassPermissionsNo 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:

  1. Initializer sessionSets up the project, writes a structured feature list (all items "failing"), an init.sh to start the app, and a progress file, then makes the first git commit.
  2. 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.
  3. One feature at a timePick the highest-priority failing item, implement it, and verify it end to end.
  4. 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
💡 Why JSON for the feature list?Structured files are harder for the model to "accidentally" rewrite than prose, and easy for the harness to check (e.g. a hook that rejects edits removing items).

10. Observability: you can't fix what you can't see

SignalWhy it mattersSource
Full transcript / trace per runDebugging starts by reading what the agent saw and didJSONL events, SDK message stream, Claude Code transcripts
Tokens in/out, cache read/writeCost and cache healthresponse.usage
Cost per completed taskThe real unit economics (a cheap call that needs 5 retries isn't cheap)Sum per run ÷ successes
Turns per task, tool error rateSpot confusing tools and loopsTrace events
Permission denials, hook blocksPolicy too tight, or agent misbehavingHarness 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.

  1. Collect tasksReal requests with a checkable outcome (tests that must pass, expected fields, a rubric). Start with 20–50; grow from production failures.
  2. Grade automaticallyCode checks first; LLM judges with a rubric for fuzzy quality; humans to calibrate the judges.
  3. Run each task several timesAgents are stochastic. One run tells you little.
  4. Change one thing at a timeAn ablation shows which harness component actually moved the score.
  5. 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,
    }
🎯 pass@k vs pass^kpass@k: at least one of k tries succeeds. That's fine when a human picks the best attempt. pass^k: all k tries succeed. That's what matters for an unattended agent that runs every day. A harness with 60% per-try success has pass@3 ≈ 94% but pass^3 ≈ 22%.

12. Anti-patterns checklist

Anti-patternDo instead
Safety rules only in the promptPermissions + hooks + sandbox; the prompt explains why
Timestamps or per-request data in the system promptFrozen prefix; volatile data in the latest message
Editing or deleting earlier messagesAppend-only; server-side compaction and context editing; role: "system" messages for new instructions
Raising exceptions on tool failureis_error results with actionable text
Unbounded loopsTurn, token, dollar, and time budgets, plus a warning before the cut-off
Accepting "done" at face valueVerification on end_turn; Stop hooks
Dumping whole files or results into contextCaps, pagination, just-in-time reads, subagents
Judging changes from one lucky runRepeated trials; pass^k; ablations
bypassPermissions on a laptop with real credentialsOnly in disposable, network-restricted sandboxes
Game · Anti-patterns

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

1 · Your team requires that every edited file is auto-formatted. What's the most reliable implementation in Claude Code?
B. Hooks are deterministic and run every time. Instructions are followed most of the time, which isn't a guarantee.
2 · Cache reads stay at zero across requests in a long session. Most likely cause?
C. Caching is a prefix match. Any byte change invalidates everything after it, so a changing system prompt or tool order silently kills the cache.
3 · Mid-session, you need to tell the agent "the deploy freeze is now active." What's the best harness technique?
A. Appending keeps the cached prefix (and thinking blocks) valid and carries operator authority. Editing or deleting history breaks both.
4 · A Stop hook runs tests and exits 2 on failure. Users report the agent sometimes never stops. Fix?
D. The hook should block once and then let the agent stop (reporting the failure) rather than loop indefinitely.
5 · In the Agent SDK you added "Write" to allowed_tools and wrote a can_use_tool callback to block writes outside the repo. Writes outside the repo still happen. Why?
B. Remove Write from allowed_tools (or enforce the rule in a PreToolUse hook, which runs regardless).
6 · An agent passes a task 60% of the time per run. For an unattended nightly job, which metric best reflects the risk?
C. Consistency matters when no human picks the best attempt. pass^k measures reliability; pass@k measures "can it ever do it".
7 · A multi-day build agent keeps redoing finished work in each new session. Best harness fix?
A. New sessions start with no memory, so the harness must make the environment carry the state.
8 · Which change belongs in the harness rather than the model prompt?
D. Output caps and redaction must happen every time, before the model sees the data, so they're code. The others are guidance.