Hooks and guards

Twenty-eight hook registrations turn rules an agent kept forgetting into checks that run whether it remembers or not. They fire on session start, every prompt, before and after every tool call, around subagents, and at session end.

  • Harness engineering
  • Agent guardrails
  • Context engineering
  • Agent observability
What it is
One neutral registry, hooks.def.json, with 28 entries over 17 distinct programs. bin/ai-sync renders it into each tool's own hook config: all 28 for Claude Code, 10 for Cursor, 8 for Copilot CLI.
What it isn't
A sandbox. Every guard pattern-matches one tool call's payload, and almost all of them fail open. A determined or unlucky command shape can get past. They are there to catch the mistakes agents actually make, and each one names the incident it came from.
Why it exists
Rules in prose kept recurring while loaded. One shell-status mistake was in the global prompt and still showed up 52 times in 3,439 real shell calls, against 34 uses of the correct form. A hook that denies the command costs one round trip and no operator attention.

Why a hook beats a prose rule

The harness thesis puts every rule on an enforcement ladder: global prompt line, skill text, printed context, gate script, tool-call hook, then a test in pre-push or CI. Each rung costs more to build and is harder to skip. A prompt line can be skipped by not following it. A PreToolUse hook cannot, because the call is denied or held for the operator before it runs.

The ladder is not academic. docs/lessons-status.json today records 168 lessons, of which 34 name something that enforces them. The rest are prose, some because nothing mechanical can see them ("read the file before prescribing a fix") and some because nobody has built the guard yet. Several of those 34 are hooks on this page; others are tests and gate scripts.

Two habits came out of building them. A hook sees one command, while a test sees every file, so "no hook can see it" does not mean "nothing can check it". And a guard is proven by making it fire on the payload the tool really sends: the shell guards were registered for Cursor for three weeks while reading an empty command, because Cursor's payload has a different shape (see Shared-checkout safety).

The lifecycle

SessionStart 4 · facts in UserPromptSubmit 1 · peer delta PreToolUse 10 · guards tool runs Bash, Edit, … PostToolUse 6 + 2 on failure SessionEnd 3 · archive deny or ask reason to agent Subagent Start 1 · Stop 1 next tool call guard fires Agent tool
Most of the weight sits around the tool call. Eighteen of the 28 registrations fire before or after a tool runs, counting the two failure twins. A single shell call passes through 6 hooks before it runs and 4 after, which is why hook start-up time is a real cost.

The catalog

28 registrations over 17 programs: several scripts are registered more than once, one entry per event they need. git-ops, for example, needs a PostToolUseFailure twin because a shell call that exits non-zero never fires PostToolUse, and the failed push is the git operation most worth logging. The "Also on" column is where ai-sync renders the same entry for Cursor (Cu) or Copilot CLI (Co).

SessionStart (4)

Order is load-bearing here: each later hook reads what an earlier one wrote.

HookWhat it guaranteesAlso on
session-start-markerWrites this session's start marker (session id, start sha, worktree) in the worktree. Wrap-up and both peer hooks build on it.Cu, Co
peer-session-noticeIf another session was active here in the last 15 minutes, says so and has the agent offer a worktree. Silent when alone.Cu
env-snapshotPrints facts the agent would otherwise assume: hooks dir, linked-worktree parent, last fetch age, venv interpreter and editable roots, env file names (never contents), compose project, ref-guard state. Read-only, capped at 1,500 characters and a 3-second budget.Cu
cam-sessionGives the chat a number and title, links a spawned chat to its parent, and shows who is live plus each peer's latest CAM line.

UserPromptSubmit (1)

HookWhat it guaranteesAlso on
cam-promptPeers' new journal lines since this chat last read, as factual context. Prints nothing when the project is quiet.

PreToolUse (10)

The only event that can stop a call. Seven of these entries can return a deny or an ask; the other three only record.

HookMatcherWhat it guaranteesDecisionAlso on
guard-destructiveBashHolds data-destroying commands for review: manage.py flush, migrate --fake, DROP TABLE, DELETE with no WHERE, sqlflush, deleting the dev SQLite file.askCu, Co
guard-migrationsBashRenders an Alembic migration offline and reads the SQL it would run. Upgrades that drop or retype columns or tables, and downgrades to base, are refused. No-op outside an Alembic project; defers to a project's own guard.denyCu, Co
guard-shell-statusBashRefuses shell shapes whose output lies: $? read through a pass-through pipe, an || fallback that can never run, an exported private git index that outlives its command, and in zsh, unsplit multi-word variables, $VAR: history modifiers and assignments to tied parameters like path. A commit chained after a gate with ; instead of && gets an ask.deny; ask for the gateCu, Co
peer-session-guardBashWhile another session is live in this checkout: denies 5 shapes that destroy uncommitted work, asks before 11 checkout-wide ones.deny / askCu
cam-lane-guardBashA subagent cannot send, read or answer CAM messages as its parent chat.deny
lane-repeat-guardall toolsA subagent's identical call that has already failed 3 times is refused on the 4th. Any change to the call is a new call, and a successful edit resets the count, so a red-green TDD loop is not caught.deny
claude-md-routeEdit, Write, MultiEditAsks before an edit-tool write to the global instruction file, which loads into every session in every repo, and hands the agent the routing order for where a rule belongs instead.ask
stamp-tracker-spawnAgent, TaskRecords a subagent's start time in the orchestration tracker's ledger.noneCo
cam-spawnAgent, TaskJournals a lane start so its later git calls render as "chat N › agent type".none
cam-spawn-taskspawn_taskJournals the app's background-task spawn so the child chat can claim its parent.none

PostToolUse (6) and PostToolUseFailure (2)

HookMatcherWhat it guaranteesAlso on
stamp-trackerall toolsKeeps an orchestration run's tracker.json honest: bumps updated on every write, stamps each subagent's start and end, and records which sessions drove the run. All three used to depend on the orchestrator remembering; one run shipped with 8 of 8 agents unstamped.Cu, Co
git-ops + git-ops-failureBashOne JSON line per git invocation, failures included. The shell line is tokenized the way the shell would, so git inside a commit message or heredoc is not counted. Feeds the git timeline page.
cam-prompt-gitBashPeers' new CAM lines beside any shell result that ran git. Declared after git-ops so the write lands before the read.
worktree-ownerall toolsRecords which session and subagent use each linked worktree, for the cleanup sweep.
env-snapshot-worktreeEnterWorktreeRestates the environment facts for the worktree just entered, since SessionStart described the old directory.
lane-repeat-guard-edit + -failureedit tools / allBumps a subagent's edit epoch on a successful edit inside its cwd; records each failing call.

SubagentStart (1) and SubagentStop (1)

HookWhat it guarantees
cam-subagentA lane starts with its own worktree's CAM snapshot and a read cursor of its own.
worktree-owner-agent-endStamps the finished subagent's worktree entries ended.

SessionEnd (3)

HookWhat it guaranteesAlso on
archive-sessionStrips <private>…</private> spans from the transcript with redact-private.py, then hands it to the repo's own archive script. If redaction fails, nothing is archived.Cu, Co
ai-syncRe-renders links and hook configs for every tool and commits changed harness files. Skips the commit while another session is live.Cu, Co
worktree-owner-endStamps every worktree entry of this session, its agents included, ended.

Fail open or fail closed

Almost everything here fails open: a crash, an unreadable payload or a timeout prints {} and exits 0. These hooks run before every tool call in every session on the machine, and a guard that crashed closed would stop all work at once. Every Cursor entry is rendered with failClosed: false for the same reason. The cost is that a broken guard is silent, which is why each has a regression suite and why the start-up snapshot reports a missing or stale ref guard.

The one hook that fails closed is privacy. redact-private.py writes nothing if it cannot sanitize the transcript, and the archive step is then skipped. Losing one session's archive is cheap; shipping text the operator marked private to object storage is not.

A second, quieter choice: a guard that has no opinion prints {}, never an explicit allow. An allow would approve every command the guard merely failed to understand, including one in a payload shape it cannot parse, and would override any other guard's decision.

Deny or ask

ChoiceUsed byReasoning recorded in the source
Denyguard-shell-status, guard-migrations, lane-repeat-guard, cam-lane-guard, the destroy rows of peer-session-guardThe fix is mechanical, and the reason reaches the agent. guard-migrations denies because an ask may be auto-approved under a bypass-permissions mode. peer-session-guard denies what no reflog can recover: an ask is one click from it.
Askguard-destructive, claude-md-route, the gate rule in guard-shell-status, the checkout-wide rows of peer-session-guardThe command is sometimes right and only the operator knows when. claude-md-route asks because context added by a PreToolUse hook arrives beside the tool result, after the write already happened.
Record onlyeverything elseLogging and context hooks never print a decision, so they cannot interfere with a guard.

AI engineering practices it demonstrates

  • Mechanical enforcement over instruction. A rule that recurs while loaded moves down the ladder into a hook or a test.
  • Measure before you deny. New deny rules in guard-shell-status are run against the real transcript corpus first, and every hit is hand-classified. A detector that failed that gate ships with its tests but stays unwired.
  • Refusals are written for the model: each one quotes the offending fragment and names the exact replacement command.
  • Context engineering at session start. env-snapshot prints facts and never advice, under a hard character cap, so the agent stops guessing at its environment.
  • Subagents get narrower rights than their parent: no CAM messaging, and a cap on repeating a failing call.
  • One registry, several agent tools. A neutral definition rendered per tool, with each tool's real payload shape tested.
  • Privacy is enforced at a choke point: redaction runs once, before any copy or upload, so every consumer sees the redacted text.

Benefits

  • Corrections cost a round trip, not the operator's attention. A denied command comes back with its fix, and the corrected form is not flagged again.
  • Failures that used to be silent, like a pipe that makes a failed test run look green, become visible at the moment they would have been made.
  • guard-destructive, guard-migrations and guard-shell-status run unchanged under Claude Code, Cursor and Copilot CLI, through one payload reader.
  • Logging hooks give a record of agent git activity and orchestration timing that no agent has to remember to write.

Limits

Where it loses

A hook sees one tool call's text. It cannot see a variable set in an earlier call, a file edited through the shell instead of an edit tool, or a command wrapped in a form its regex does not expect, and when it crashes it says nothing. Each guard is a running contest with shell syntax: guard-shell-status alone is 995 lines and has more than two dozen open board items for false positives and misses.

  • Registering is going live. The registry is synced into every tool's settings by the next session to end, so a hook is live within minutes of being committed. It has to be finished and reviewed before that commit, not after.
  • Latency on every call. Six hook processes run before every shell call and four after. cam-session alone takes about a second at session start.
  • Uneven coverage. Cursor gets 10 of the 28 entries and Copilot 8. Whether Cursor runs shell hooks for its subagents' calls is unverified. Copilot turns an ask into a deny when running non-interactively.
  • Guard cost is unmeasured. False positives are filed, but nobody has counted how often a guard blocked correct work.
  • claude-md-route watches edit tools only; a shell write to the global file is a named gap.

Roadmap

ItemWhy it mattersStatus
Make registration safe in a shared checkoutA half-built hook goes live as soon as any peer's session endscorrectness
Confirm Cursor runs shell hooks for subagent callsIf not, every shell guard is off for Cursor lanes, which is how the worst incident happenedunverified
Decide the "pipe then &&" ruleA masked check followed by && commit has committed on a failed check; the detector exists but failed its corpus gate, so it needs an operator calldecision
Ask on "silence means none found"2>/dev/null | grep or | wc used as an existence check reads a usage error as "nothing there"backlog
Quadratic quoting pass in guard-shell-statusA very long command can time out the hook that runs before every shell callbacklog
Render the async flag in ai-syncThe live settings lost stamp-tracker's async setting, which it needs backbacklog
Cut cam-session start-up costAbout a second per session and subagent startbacklog
Decide which hooks can run on VS Code CopilotExtends the guards to the editor most likely used at workplanned

Sources

  • hooks.def.json: 28 entries, 17 distinct programs, events counted by script (PreToolUse 10, PostToolUse 6, SessionStart 4, SessionEnd 3, PostToolUseFailure 2, one each for UserPromptSubmit, SubagentStart, SubagentStop); Cursor 10, Copilot 8. Its _copilot_caveat records the live Copilot CLI checks.
  • hooks/guard-destructive.sh, hooks/guard-migrations.sh, hooks/guard-shell-status.py (995 lines; corpus numbers in its docstring), hooks/peer-session-guard.py, hooks/cam-lane-guard.py, hooks/lane-repeat-guard.py (THRESHOLD = 3), hooks/claude-md-route.py.
  • hooks/env-snapshot.py (OUTPUT_CAP = 1500, TOTAL_BUDGET = 3.0), hooks/session-start-marker.py, hooks/stamp-tracker.py, hooks/git-ops.py, hooks/worktree-owner.py, hooks/archive-session.sh, hooks/redact-private.py, hooks/hook_io.py.
  • hooks/tests/: 30 test files; bin/ai-sync for rendering.
  • docs/workflow/harness-thesis.md: the enforcement ladder. docs/lessons-status.json: 168 lessons, 35 enforced, derived on 2026-10-08.
  • Task board: open items for registration safety, Cursor subagent hooks, the pipe rules, hook latency and Copilot support.

Facts as of 2026-10-08. Counts derived from hooks.def.json and source on that date. The README's figure of 28 counts registrations, not scripts.