Slides · Harness engineering

Guides, sensors and enforcement

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

Diagram: Reading down, a guide steers the agent before it acts, a hook can stop the action as it happens, and a sensor reports afterwards so the...

feedback

Guide
rule or template, before

Agent acts

Hook
can block the call

Sensor
lint, tests, report, after

Diagram summary: Reading down, a guide steers the agent before it acts, a hook can stop the action as it happens, and a sensor reports afterwards so the agent or the team can correct. The dotted line shows sensor findings improving the guides over time. Each control fails alone, so a good harness combines them.

Compare

Guides and sensors

Vocabulary from Böckeler (martinfowler.com, 2 April 2026). The example column is ours.

AspectGuides (feedforward)Sensors (feedback)
Whenbefore the agent actsafter the agent acts
Purposeraise the odds of a good first attemptlet the agent notice and fix its own mistake
Examplesinstruction files, skills, templateslinters, type checkers, tests, an AI review
Fails alone becausenothing checks the rule was followedthe 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.

Source1 Harness engineering for coding agent users

Compare

Computational versus inferential

AspectComputationalInferential
What runs itordinary computea model
Examplestests, linters, type checkers, structural analysisAI code review, LLM as judge
Cost and speedcheap and fastslower and costlier
Predictabilitydeterministicless predictable
Use it forevery changemeaning, 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.

Source1 Harness engineering for coding agent users

Diagram

Check early, check cheaply

Diagram: Reading down, checks run from the cheapest and fastest right after an edit, through commit-time and CI checks, to continuous scans and...

After the edit:
format, lint, types

Before commit:
fast tests, review agent

CI:
full tests, deeper review

Continuous:
drift scans, runtime signals

Diagram summary: Reading down, checks run from the cheapest and fastest right after an edit, through commit-time and CI checks, to continuous scans and runtime signals. Böckeler’s reason for keeping quality left is that the earlier an issue is found, the cheaper it is to fix; fast checks run before integration and expensive ones in the pipeline.

Source1 Harness engineering for coding agent users

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.

PlanCalculationTime spent checking
Full suite after every edit30×20 min30 \times 20\ \text{min}600 min
Fast checks after every edit, full suite once30×5 s=2.5 min30 \times 5\ \text{s} = 2.5\ \text{min}, plus 20 min22.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)
InputOutput
no violationsempty string
120 violations6 lines: 5 specific ones, then “…and 115 more”
2 violations2 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 onFailure setting (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.

Source2 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 pointCan exit 2 block it?Effect
Before a tool callyesblocks the call; the error goes back to the agent
After a tool callnothe tool already ran; stderr is shown to the agent as feedback
When the agent tries to stopyesprevents 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 submittedyesblocks 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.

Source2 Hooks reference

Diagram

Hook points along one turn

Diagram: Reading down, a hook on prompt submission can block the prompt, a hook before the tool call can block the call, and a hook after the call...

Prompt submitted
hook can block

Model proposes a call

Before the call
hook can block

Tool runs

After the call
feedback only

Agent tries to stop
hook can refuse

Diagram summary: Reading down, a hook on prompt submission can block the prompt, a hook before the tool call can block the call, and a hook after the call can only send feedback because the tool already ran. A hook at the stop point can refuse “done”, for example while tests are failing.

Source2 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 callText compareStat-onlyFinal version
config/prod/db.yaml, absolute path, new file inside the folder222
symlink to an existing protected file or folder222
dangling symlink src/dangling pointing at ../config/prod/new.yaml20 (bypass)2
Config/Prod/db.yaml, config/PROD/new.yaml0 (bypass)22
hardlink src/hard.yaml to a protected file0 (bypass)22
notebook_path instead of file_path0 (bypass)22
config/dev/..., config/production-notes.md, src/app.py000
Bash echo x > config/prod/db.yaml000 (not caught)

Crash cases, run as a real subprocess:

SituationUnwrapped hookFinal version
protected folder missing, samefile raises FileNotFoundErrorunhandled 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 stdinunhandled error, action goes aheadexit 2
tool_input is nullAttributeError, action goes aheadno 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:

  1. A permission deny rule such as Edit(config/prod/**). The permissions reference says path rules are checked against Edit and Read rules only, so Write and NotebookEdit rules never match; an Edit deny 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.
  2. A sandbox denyWrite entry 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.

Sources2 Hooks reference3 Configure permissions4 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.

Source5 OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development

Compare

Permission tiers

A design aid, not a standard.

TierExamplePolicy
Read-onlyread files, searchallow
Reversible writeedit workspace files, make a branchallow inside the sandbox
Costly or externalnetwork calls, installs, spending, sending emailallow-list or approve each use
Destructive or irreversibledelete data, deploy, force-push, payexplicit 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)=850 \times (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.

Source6 Beyond permission prompts: making Claude Code more secure and autonomous

Diagram

A sandbox needs both walls

Diagram: Reading down, the agent works inside a filesystem boundary and a network boundary.

missing: can escape,
reach the network

missing: can send
files out

Agent

Filesystem isolation

Network isolation

Free to work inside,
fewer prompts

Risk

Risk

Diagram summary: Reading down, the agent works inside a filesystem boundary and a network boundary. Anthropic says effective sandboxing requires both: without network isolation a compromised agent could send out sensitive files, and without filesystem isolation it could escape the sandbox and reach the network. For credentials, its web version keeps them outside the sandbox and uses a proxy that checks the request and attaches the real token.

Source6 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.

Source7 Agent Harness

Concept

The lethal trifecta

Simon Willison (16 June 2025) names three capabilities that are dangerous together.

  1. Access to private data.
  2. Exposure to untrusted content.
  3. 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.

Source8 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

Diagram: Reading down, the agent that wrote the work does not approve it.

Builder agent
writes the change

Deterministic checks
tests, lint, types

Separate evaluator
for judgment

Protected criteria
builder cannot edit

Accept

Diagram summary: Reading down, the agent that wrote the work does not approve it. Deterministic checks run first, a separate evaluator handles judgment calls, and the success criteria (tests and the pass list) sit where the builder cannot rewrite them. Protecting them with permissions or a hook is stronger than telling the agent in a prompt not to touch them.

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.

Source1 Harness engineering for coding agent users

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)

  1. Harness engineering for coding agent users (opens in a new tab)

    Birgitta Böckeler2026Article

    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.

  2. Hooks reference (opens in a new tab)

    Anthropic (Claude Code docs)2026Documentation

    Used for Hook events, the exit-code 2 blocking contract, and which events can or cannot block.

  3. Configure permissions (opens in a new tab)

    Anthropic (Claude Code docs)2026Documentation

    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.

  4. Sandboxing (opens in a new tab)

    Anthropic (Claude Code docs)2026Documentation

    Used for The sandbox covers shell commands only, and file tools follow permission rules instead.

  5. OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development (opens in a new tab)

    Leela Kumili2026Article

    Used for A secondary account of layered architecture enforced by structural tests, linters and CI.

References

References & Sources (2 of 2)

  1. Beyond permission prompts: making Claude Code more secure and autonomous (opens in a new tab)

    David Dworken, Oliver Weller-Davies2025Article

    Used for Approval fatigue, the internal 84 percent prompt reduction, the need for both filesystem and network isolation, and keeping credentials outside the sandbox.

  2. Agent Harness (opens in a new tab)

    Microsoft Learn (Agent Framework)2026Documentation

    Used for Scoped file access that fails closed when no session or scope is available.

  3. The lethal trifecta for AI agents: private data, untrusted content, and external communication (opens in a new tab)

    Simon Willison2025Article

    Used for The three legs of the lethal trifecta and the advice to avoid the combination rather than rely on prompts or guardrail products.