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.
- What it is
- One neutral registry,
hooks.def.json, with 28 entries over 17 distinct programs.bin/ai-syncrenders 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
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.
| Hook | What it guarantees | Also on |
|---|---|---|
session-start-marker | Writes 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-notice | If another session was active here in the last 15 minutes, says so and has the agent offer a worktree. Silent when alone. | Cu |
env-snapshot | Prints 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-session | Gives 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)
| Hook | What it guarantees | Also on |
|---|---|---|
cam-prompt | Peers' 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.
| Hook | Matcher | What it guarantees | Decision | Also on |
|---|---|---|---|---|
guard-destructive | Bash | Holds data-destroying commands for review: manage.py flush, migrate --fake, DROP TABLE, DELETE with no WHERE, sqlflush, deleting the dev SQLite file. | ask | Cu, Co |
guard-migrations | Bash | Renders 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. | deny | Cu, Co |
guard-shell-status | Bash | Refuses 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 gate | Cu, Co |
peer-session-guard | Bash | While another session is live in this checkout: denies 5 shapes that destroy uncommitted work, asks before 11 checkout-wide ones. | deny / ask | Cu |
cam-lane-guard | Bash | A subagent cannot send, read or answer CAM messages as its parent chat. | deny | |
lane-repeat-guard | all tools | A 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-route | Edit, Write, MultiEdit | Asks 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-spawn | Agent, Task | Records a subagent's start time in the orchestration tracker's ledger. | none | Co |
cam-spawn | Agent, Task | Journals a lane start so its later git calls render as "chat N › agent type". | none | |
cam-spawn-task | spawn_task | Journals the app's background-task spawn so the child chat can claim its parent. | none |
PostToolUse (6) and PostToolUseFailure (2)
| Hook | Matcher | What it guarantees | Also on |
|---|---|---|---|
stamp-tracker | all tools | Keeps 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-failure | Bash | One 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-git | Bash | Peers' new CAM lines beside any shell result that ran git. Declared after git-ops so the write lands before the read. | |
worktree-owner | all tools | Records which session and subagent use each linked worktree, for the cleanup sweep. | |
env-snapshot-worktree | EnterWorktree | Restates the environment facts for the worktree just entered, since SessionStart described the old directory. | |
lane-repeat-guard-edit + -failure | edit tools / all | Bumps a subagent's edit epoch on a successful edit inside its cwd; records each failing call. |
SubagentStart (1) and SubagentStop (1)
| Hook | What it guarantees |
|---|---|
cam-subagent | A lane starts with its own worktree's CAM snapshot and a read cursor of its own. |
worktree-owner-agent-end | Stamps the finished subagent's worktree entries ended. |
SessionEnd (3)
| Hook | What it guarantees | Also on |
|---|---|---|
archive-session | Strips <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-sync | Re-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-end | Stamps 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
| Choice | Used by | Reasoning recorded in the source |
|---|---|---|
| Deny | guard-shell-status, guard-migrations, lane-repeat-guard, cam-lane-guard, the destroy rows of peer-session-guard | The 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. |
| Ask | guard-destructive, claude-md-route, the gate rule in guard-shell-status, the checkout-wide rows of peer-session-guard | The 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 only | everything else | Logging 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-statusare 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-snapshotprints 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-migrationsandguard-shell-statusrun 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
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-sessionalone 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-routewatches edit tools only; a shell write to the global file is a named gap.
Roadmap
| Item | Why it matters | Status |
|---|---|---|
| Make registration safe in a shared checkout | A half-built hook goes live as soon as any peer's session ends | correctness |
| Confirm Cursor runs shell hooks for subagent calls | If not, every shell guard is off for Cursor lanes, which is how the worst incident happened | unverified |
Decide the "pipe then &&" rule | A masked check followed by && commit has committed on a failed check; the detector exists but failed its corpus gate, so it needs an operator call | decision |
| 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-status | A very long command can time out the hook that runs before every shell call | backlog |
Render the async flag in ai-sync | The live settings lost stamp-tracker's async setting, which it needs back | backlog |
Cut cam-session start-up cost | About a second per session and subagent start | backlog |
| Decide which hooks can run on VS Code Copilot | Extends the guards to the editor most likely used at work | planned |
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_caveatrecords 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-syncfor 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.