Slides · Harness engineering
Guides, sensors and enforcement
1 / 27
Guides, sensors and enforcement
How a harness steers an agent before it acts, checks after it acts, and makes the important rules hold even when the model does not cooperate.
By the end you can classify controls as guides or sensors and as computational or inferential, place checks early, use hooks, layer permissions with a sandbox, and keep the builder from being its own grader.
Concept
One rule, three ways to watch it
- A refund rule says: above a set amount, get approval. An agent issues one above the limit anyway.
- The written rule steers the agent before it acts. A nightly report tells you after. A block in the payments system refuses the call as it happens.
- Alone, the rule has nothing checking it, the report comes too late for this refund, and the block gives no guidance.
- A good setup has all three, and you build first the cheapest one that would have caught the mistake.
Diagram
Guide, hook, sensor
Compare
Guides and sensors
Vocabulary from Böckeler (martinfowler.com, 2 April 2026). The example column is ours.
| Aspect | Guides (feedforward) | Sensors (feedback) |
|---|---|---|
| When | before the agent acts | after the agent acts |
| Purpose | raise the odds of a good first attempt | let the agent notice and fix its own mistake |
| Examples | instruction files, skills, templates | linters, type checkers, tests, an AI review |
| Fails alone because | nothing checks the rule was followed | the agent repeats mistakes without guidance |
- The article notes agents with only feedback keep repeating mistakes, and agents with only feedforward never learn whether their rules worked.
Compare
Computational versus inferential
| Aspect | Computational | Inferential |
|---|---|---|
| What runs it | ordinary compute | a model |
| Examples | tests, linters, type checkers, structural analysis | AI code review, LLM as judge |
| Cost and speed | cheap and fast | slower and costlier |
| Predictability | deterministic | less predictable |
| Use it for | every change | meaning, where no deterministic test exists |
Rule of thumb: run computational sensors on every change, spend inferential checks where meaning matters, and treat their verdicts as less certain.
Diagram
Check early, check cheaply
Worked example
Worked example: where the cost lands
Illustrative: an agent makes 30 edits in a task. Lint, format and type check take 5 seconds; the full test suite takes 20 minutes.
| Plan | Calculation | Time spent checking |
|---|---|---|
| Full suite after every edit | 30×20 min | 600 min |
| Fast checks after every edit, full suite once | 30×5 s=2.5 min, plus 20 min | 22.5 min |
- The second plan catches typos and type errors at the edit that caused them, and still runs the expensive check before the work is accepted.
- Run the numbers for your own suite; the shape (cheap often, costly rarely) is the point.
Code
Success is silent, failure is verbose and useful
Illustrative sensor wrapper, run in a scratch script. It prints nothing when the linter finds nothing, and otherwise prints a short list that says the rule and the fix.
Python
def sensor_output(violations, cap=5):
if not violations:
return "" # success adds nothing to context
lines = [f"{v['file']}:{v['line']} {v['rule']}: {v['fix']}"
for v in violations[:cap]]
if len(violations) > cap:
lines.append(f"...and {len(violations) - cap} more; fix these first and re-run.")
return "\n".join(lines)| Input | Output |
|---|---|
| no violations | empty string |
| 120 violations | 6 lines: 5 specific ones, then “…and 115 more” |
| 2 violations | 2 lines, each with rule and fix |
A bare “failed” gives the agent nothing to act on; a message that names the rule and fix lets it self-correct.
Check yourself
Check: slot these in
You have: a secret scanner (3 s), contract tests against a partner API (8 min), a license check of new dependencies (10 s) and an LLM check that a change matches its ticket (about 1 min). Give each a slot and label it computational or inferential.
Answer
Secret scanner: after every edit or before commit, computational; it is fast and a leaked secret is costly. License check: when a dependency changes, before commit, computational. LLM ticket check: before commit or push, inferential, so treat its verdict as advice. Contract tests: in CI, computational but slow and dependent on an outside service, so not after every edit.
Concept
Hooks: code that always runs
- A hook is code the harness runs at defined points in the agent’s lifecycle. Claude Code runs command handlers on events such as before a tool call, after one, when the agent tries to stop, and when a prompt is submitted.
- A rule in a prompt is a suggestion; a hook is a guarantee, because the harness runs it whether or not the model remembers the rule. “Guarantee” has limits: a hook only covers the paths it matches, a crashing hook can fail open, and a stop hook has a continuation cap.
- Contract in the Claude Code docs: a hook that exits with code 2 blocks the action, and the docs state that exit 2 blocks even if the hook also prints JSON that suggests allowing. Other non-zero exit codes do not block by default, so use exit 2 for policy. The docs add an
onFailuresetting (command and HTTP hooks) that makes a failing or timed-out hook block the action; without it, most events carry on. - These are product details that change. Read the current page before relying on a specific event.
Source[2] Hooks reference
Compare
What each hook point can do
From the exit-code table in the Claude Code hooks reference, read 2026-10-23.
| Hook point | Can exit 2 block it? | Effect |
|---|---|---|
| Before a tool call | yes | blocks the call; the error goes back to the agent |
| After a tool call | no | the tool already ran; stderr is shown to the agent as feedback |
| When the agent tries to stop | yes | prevents the stop, so the agent keeps working; after 8 consecutive continuations Claude Code overrides the next block and ends the turn (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises it) |
| When a prompt is submitted | yes | blocks the prompt before it reaches the model |
- The table lists many more events, some of which can block. Check the full list for your version.
Source[2] Hooks reference
Diagram
Hook points along one turn
Source[2] Hooks reference
Code
A before-tool hook, tested, and its limits
A command hook reads a JSON event on stdin, with tool_name and tool_input, and blocks by exiting 2 with a message on stderr. Write and Edit carry file_path; the permissions reference lists notebook_path as the path field for NotebookEdit. The docs say file_path is absolute, so the relative spellings in the table below stand for paths that are resolved against the working directory (they matter only if your own tooling passes them). This sketch protects config/prod/.
Python
def decide(event, project_dir, protected="config/prod"):
ti = event.get("tool_input") or {}
path = ti.get("file_path") or ti.get("notebook_path")
if not path:
return 0, "" # no path: no opinion
full = os.path.realpath(os.path.join(event.get("cwd", project_dir), path))
root = os.path.realpath(os.path.join(project_dir, protected))
hit = full == root or full.startswith(root + os.sep)
p = full
while not hit: # other spellings of the same folder
if os.path.exists(p) and os.path.exists(root) and os.path.samefile(p, root):
hit = True
parent = os.path.dirname(p)
if parent == p: break
p = parent
if not hit and os.path.isfile(full) and os.path.isdir(root):
st = os.stat(full) # hardlink to a protected file
hit = (st.st_dev, st.st_ino) in inodes_under(root) # helper: walk the folder, collect (st_dev, st_ino) pairs
return (2, "Blocked: config/prod/ is protected.") if hit else (0, "")
def main():
try:
code, msg = decide(json.load(sys.stdin), os.environ["CLAUDE_PROJECT_DIR"])
except Exception: # fail closed: a crash must not allow the write
print("Blocked: protection hook failed", file=sys.stderr)
sys.exit(2)
...Test results, run on macOS (case-insensitive filesystem): a first version that resolved the path with realpath and compared the text, a second version that compared with samefile and inodes but resolved only abspath (which lost the symlink handling), and the final version above that does both.
| Path or tool call | Text compare | Stat-only | Final version |
|---|---|---|---|
config/prod/db.yaml, absolute path, new file inside the folder | 2 | 2 | 2 |
| symlink to an existing protected file or folder | 2 | 2 | 2 |
dangling symlink src/dangling pointing at ../config/prod/new.yaml | 2 | 0 (bypass) | 2 |
Config/Prod/db.yaml, config/PROD/new.yaml | 0 (bypass) | 2 | 2 |
hardlink src/hard.yaml to a protected file | 0 (bypass) | 2 | 2 |
notebook_path instead of file_path | 0 (bypass) | 2 | 2 |
config/dev/..., config/production-notes.md, src/app.py | 0 | 0 | 0 |
Bash echo x > config/prod/db.yaml | 0 | 0 | 0 (not caught) |
Crash cases, run as a real subprocess:
| Situation | Unwrapped hook | Final version |
|---|---|---|
protected folder missing, samefile raises FileNotFoundError | unhandled error (exit 1 is a non-blocking error: the action goes ahead) | handled; writes into the folder, spelled exactly as configured, still exit 2 (a different-case spelling of a folder that does not exist yet is not caught) |
| invalid JSON on stdin | unhandled error, action goes ahead | exit 2 |
tool_input is null | AttributeError, action goes ahead | no path, exit 0 |
Claude Code 2.1.295 and later also offers "onFailure": "block" on command hooks, which blocks when the hook itself fails. Case-insensitive behaviour depends on the filesystem; only macOS was tested.
What actually holds. The hooks reference says a PostToolUse hook matching Edit|Write does not run when a Bash command rewrites the file (the hook only sees Bash’s command string), and FileChanged runs after the change and cannot block it. It also says the if filter is best-effort, so use the permission system rather than a hook to enforce a hard allow or deny. So the dependable controls are two:
- A permission deny rule such as
Edit(config/prod/**). The permissions reference says path rules are checked againstEditandReadrules only, so Write and NotebookEdit rules never match; anEditdeny rule covers the edit tools, and it also covers file commands Claude Code recognises in Bash and Bash redirections, but not a script that opens the file itself. - A sandbox
denyWriteentry for the shell. The sandbox covers shell commands only; Read, Edit and Write follow permission rules instead.
The hook is the early, friendly message on top.
Sources[2] Hooks reference[3] Configure permissions[4] Sandboxing
Check yourself
Check: the lint hook runs after the edit
A hook that runs after every file edit exits 2 when lint fails. A teammate says this means a bad edit is rolled back, so the file on disk is always clean. Is that right? What does the agent actually get?
Answer
No. The tool had already run when the after-hook fired, and exit 2 there only shows the hook’s stderr to the agent. The bad edit stays on disk until the agent fixes it, which is why the message should state the rule and the fix.
Concept
Architecture as a constraint
- “Keep the layers separate” in an instruction file is a guide. A structural test that fails when a lower layer imports a higher one is a computational sensor.
- InfoQ (21 February 2026), summarising OpenAI’s report, describes dependencies flowing one way through fixed layers, with structural tests checking compliance and linters and CI checking that design documents stay consistent. That is a secondary account.
- The transferable idea: enforce the invariants (the boundaries that must hold) and leave implementation free.
- Put the fix in the error message so the agent can repair itself. When a document is not enough, promote the rule into code.
Source[5] OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development
Compare
Permission tiers
A design aid, not a standard.
| Tier | Example | Policy |
|---|---|---|
| Read-only | read files, search | allow |
| Reversible write | edit workspace files, make a branch | allow inside the sandbox |
| Costly or external | network calls, installs, spending, sending email | allow-list or approve each use |
| Destructive or irreversible | delete data, deploy, force-push, pay | explicit human approval |
Approvals cost attention, which the next slide shows.
Worked example
Approval fatigue and boundaries
Anthropic (20 October 2025) warns that constant approval clicks lead to approval fatigue, where people stop scrutinising what they approve. Its answer: set boundaries so the agent can work freely inside them. In its internal usage, it reports that sandboxing reduced permission prompts by 84 percent.
Illustrative arithmetic (the 84 percent is Anthropic’s internal figure, not a rate you will necessarily see): a session that raised 50 prompts would raise about 50×(1−0.84)=8.
- Fewer prompts means each remaining one is more likely to be read.
- The remaining prompts should be the ones that matter: the costly and destructive tiers.
Source[6] Beyond permission prompts: making Claude Code more secure and autonomous
Diagram
A sandbox needs both walls
Source[6] Beyond permission prompts: making Claude Code more secure and autonomous
Concept
More layers
- No secrets inside the sandbox; limits on CPU, memory and time; a separate working copy or container per task so parallel agents cannot collide.
- Fail closed when identity or scope is missing. Microsoft’s file-access documentation describes scoped access that refuses to fall back to the shared store.
- Defence in depth means a failure of one layer (a missed prompt rule, a missed hook) is caught by another.
Source[7] Agent Harness
Concept
The lethal trifecta
Simon Willison (16 June 2025) names three capabilities that are dangerous together.
- Access to private data.
- Exposure to untrusted content.
- The ability to communicate externally.
- An agent with all three can be tricked by the untrusted content into sending the private data out.
- His advice: avoid the combination entirely. He also quotes the Design Patterns for Securing LLM Agents against Prompt Injections paper: once an agent has ingested untrusted input, it must be constrained so that input cannot trigger consequential actions.
- He is skeptical of relying on prompt instructions or vendor guardrail products as the control.
- In a harness: remove one leg by design, separate agents by trust level, give each tool a least-privilege credential, and require approval where data crosses a boundary.
Source[8] The lethal trifecta for AI agents: private data, untrusted content, and external communication
Check yourself
Check: is a reply an exit?
A support agent reads incoming tickets written by anyone, can look up the customer’s order history, and can post a reply on the ticket. It has no other network access. Does it hold all three legs of the trifecta? What would you change?
Answer
Yes. Tickets are untrusted content, order history is private data, and the reply is an outbound channel to whoever wrote the ticket, so injected text could make it put another customer’s data in the reply. Remove a leg: have the agent draft replies for a human to send, limit the data it can reach to the ticket author’s own orders, or both. A prompt line saying “never reveal other customers’ data” is not a control.
Diagram
The builder is not the only grader
Concept
Where verification is still weak
Böckeler splits what you can regulate into three categories.
- Maintainability (duplication, complexity, coverage, style): the easiest; computational sensors cover much of it.
- Architecture fitness (performance and logging standards, boundaries): checkable with fitness-style tests.
- Behaviour (does the software do the right thing): the hardest. Common practice is a functional spec plus an AI-generated test suite that is green, and she says that “puts a lot of faith into the AI-generated tests”, which she considers “not good enough yet”.
- So a green suite with decent coverage is not full confidence: add coverage and mutation checks where you can, and keep manual testing for critical paths.
- Her open questions include whether a sensor that never fires means quality or blindness.
Check yourself
Check: is CI independent?
The agent can push branches. CI runs .github/workflows/test.yml from the branch it pushed, and the workflow file is in the same repository the agent can edit. A reviewer calls CI “the independent grader”. What is wrong, and what is the fix?
Answer
The agent can change the workflow, for example to skip tests, so CI is only independent in name. Run the required checks from a definition the agent cannot edit (for example a protected branch’s workflow or a separate required-checks configuration), keep tests and the pass list in protected paths, and have a human or separate evaluator review changes to those paths. The exact setting names depend on your CI provider.
Summary
Recap
- A guide steers before, a sensor observes after; use both. Run computational checks on every change and inferential ones where meaning matters.
- Check early and cheaply. Success is silent, failure is short and says the fix.
- A prompt rule is a suggestion; a hook is a guarantee. Before-tool hooks can block, after-tool hooks cannot undo, a stop hook can refuse “done” (up to a cap of consecutive continuations).
- Tier permissions, sandbox both files and network, keep credentials out, fail closed, and break the lethal trifecta by removing a leg.
- Do not let the builder be the only grader, protect the success criteria, and remember behaviour checks are the weak spot.
References
References & Sources (1 of 2)
Harness engineering for coding agent users (opens in a new tab)
Birgitta Böckeler2026Article
https://martinfowler.com/articles/harness-engineering.html
Used for The guide and sensor vocabulary, computational versus inferential controls, keep-quality-left timing, the three regulation categories and the weakness of behaviour checks.
Hooks reference (opens in a new tab)
Anthropic (Claude Code docs)2026Documentation
https://code.claude.com/docs/en/hooks
Used for Hook events, the exit-code 2 blocking contract, and which events can or cannot block.
Configure permissions (opens in a new tab)
Anthropic (Claude Code docs)2026Documentation
https://code.claude.com/docs/en/permissions
Used for Edit and Read path deny rules, which tools they cover, notebook_path for NotebookEdit, and the limit that they do not stop a script writing files itself.
Sandboxing (opens in a new tab)
Anthropic (Claude Code docs)2026Documentation
https://code.claude.com/docs/en/sandboxing
Used for The sandbox covers shell commands only, and file tools follow permission rules instead.
Leela Kumili2026Article
https://www.infoq.com/news/2026/02/openai-harness-engineering-codex
Used for A secondary account of layered architecture enforced by structural tests, linters and CI.
References
References & Sources (2 of 2)
Beyond permission prompts: making Claude Code more secure and autonomous (opens in a new tab)
David Dworken, Oliver Weller-Davies2025Article
https://www.anthropic.com/engineering/claude-code-sandboxing
Used for Approval fatigue, the internal 84 percent prompt reduction, the need for both filesystem and network isolation, and keeping credentials outside the sandbox.
Agent Harness (opens in a new tab)
Microsoft Learn (Agent Framework)2026Documentation
https://learn.microsoft.com/en-us/agent-framework/concepts/harness
Used for Scoped file access that fails closed when no session or scope is available.
Simon Willison2025Article
https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
Used for The three legs of the lethal trifecta and the advice to avoid the combination rather than rely on prompts or guardrail products.
Keys: ← → move, Home End first and last, F full screen.