Claude Code Hooks in Production: The Security Gate That Asked 752 Times and Learned Nothing
By: Evgeny Padezhnov
Claude Code Hooks in Production: The Security Gate That Asked 752 Times and Learned Nothing
A case study, not a tutorial. Every number below comes from our own database and git history; the judgement calls are mine.
We run a fleet of autonomous Claude Code agents on one Linux box: they fix bugs, deploy static sites, write content, rotate proxies, and touch a production Postgres. In June 2026 I built a PreToolUse hook to stop them from doing anything irreversible without a human. Three months later I measured what it had actually done. The short version: 752 requests for approval, 18 human decisions, 734 timeouts, zero learned rules — and about 57 hours of agents frozen, all of them ending in a refusal.
This is the story of that hook: how it works, why it failed as a process while succeeding as a mechanism, and what fixed it.
I did not build this after an incident, and that matters. I built it on 7 June, three days after this box came back from a backup — the previous machine had died and the whole fleet was re-materialised on a new one. What I had, on a freshly re-assembled server, was a set of agents that could run shell commands, overwrite files and reach a production Postgres, and no place to read what would stop them. Every risky moment was being resolved silently: some calls went through, some the model refused on its own, and no policy existed anywhere outside the model's judgement. The thing I could not live with was not a near-miss. It was being unable to answer the question "what, specifically, stops it?"
How a Claude Code hook actually gates a tool call
Claude Code fires PreToolUse before every tool invocation — every Bash, Write, Edit. A hook is a script that receives the call on stdin and answers on stdout:
{"session_id":"…","cwd":"/root/projects/x","permission_mode":"…","tool_name":"Bash","tool_input":{"command":"git push --force"}}
and must print
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"outward-facing, irreversible"}}
Three details cost me a day each, so here they are up front:
- In headless mode (
claude -p) hooks from.claude/settings.jsondo not fire. You pass them per invocation:claude -p … --settings '{"hooks":{"PreToolUse":[…]}}'. Verified on CLI 2.1.162. - Only
allowanddenyare safe headless.askbypasses deny rules when nobody is there to answer. - The hook may block up to its timeout (default 600 s); on timeout the tool call is denied. We set ours to 280 s, below the 300 s hook limit, so a hung decision fails cleanly instead of hanging the agent forever.
One deliberate trade-off: if the gate script itself crashes, the call is allowed. A bug in the gate must not brick the whole pipeline. Every real decision path fails closed.
The decision engine: rules first, a strong model second, a human last
The gate (agents/security-gate/, 1 463 lines across policy.js, gate.js, triage.js, arbiter.js, 225 unit tests across seven suites) decides in three tiers:
- Deterministic allow — read-only commands, writes inside
/root/projects, read-only pipes. - Deterministic deny —
rm -rf /,dd of=/dev/*, fork bombs,curl | sh, writes outside the project tree,DROP/TRUNCATE, secret exfiltration. - Escalate to the owner — deploys,
pm2/systemctlrestarts, new packages, deletions, shared DB tables, secrets,git push. - Grey zone → an arbiter model. Anything the rules cannot classify goes to a strong model with one instruction: reversible — decide yourself; irreversible or outward-facing — escalate. On any parse error or timeout the arbiter returns
escalaterather thanallow.
The grey zone goes to the most expensive model available, and that was a deliberate trade against the cheap option. The arbiter only ever sees calls the deterministic rules could not classify — by construction the hardest ones, and the ones where a wrong allow is the kind you cannot take back. It runs a few hundred times a month, not a few hundred thousand. Buying judgement at the exact point where the rules ran out is the cheapest safety in the whole system; saving money there would mean saving it only on the decisions that matter.
Escalation is a Telegram card. The hook inserts a row into approval_requests; a control-bus tick (every 4 s) sends the card with three buttons — approve once, deny, approve for this project from now on; the hook polls the row until it is decided or the 280 s run out. The per-project approval was supposed to write a narrow rule into approval_rules, so the same command would not ask again.
That was the design. Here is what the database says happened.
Three months of data
Between 7 June and 3 September 2026 the gate escalated 752 tool calls (approval_requests, counted 6 Sep).
| Outcome | Count |
|---|---|
| Expired (280 s timeout → deny) | 734 |
| Approved by a human | 13 |
| Denied by a human | 5 |
Sixteen of the eighteen human decisions happened on 7 and 8 June, the first two days the gate was live; the remaining two are a single denial on 23 June and another on 21 July. In August I answered 0 of 189 cards. approval_rules — the learning table — has zero rows: every approval was one-shot, the per-project button was not pressed once, so the same command asked again the next day.
Multiply it out: 734 timeouts × 280 s ≈ 57 hours of agents standing still, each one ending in a refusal. "Ask a human" had become, in practice, "freeze for 4.7 minutes, then say no."
By category:
| Category | Requests |
|---|---|
db_secrets |
231 |
gray (arbiter could not decide) |
203 |
dangerous (catch-all) |
133 |
prod_system |
84 |
pkg_net_delete |
67 |
supply_chain |
33 |
git_push |
1 |
The arbiter itself sent 204 of the 752 up to the human; 195 of those also expired.
I answered 16 cards in the first two days and then stopped, and "the human got lazy" is the wrong lesson to draw from it. Every card authorised one command, one time: all 18 of my decisions carry the scope once, and approval_rules — the table that was supposed to hold everything I had taught the gate — is empty. So each answer bought four minutes of progress and nothing that would apply tomorrow. Meanwhile the largest category of what I was being asked about was commands in the shape of ls .env | wc -l. A queue that is mostly noise and never learns is a queue you stop opening. Day three is the honest life expectancy of any human-in-the-loop design that does not pay the human back.
What the numbers exposed
The biggest category, db_secrets (231), was almost entirely commands that did not touch a secret's value at all: ls .env | wc -l, select … from secrets where secrets is a table name in a read-only query, the string vault inside the path of our own source file. The rule was matching words (.env, secrets, vault) in the command text, not access to secret content.
A word-matching gate produces two failure modes at once: it cries wolf on ls, and — because the human learns to ignore it — it also stops being a gate.
The fix: judge by access, not by vocabulary (1 September)
Commit d4b06fe re-drew the axis. The six rules, from decision record #151:
- Existence ≠ content.
ls,stat,test,find,wcenumerate; they do not read. - Our own source is not a secret. A path under
/root/projectswith a code extension stays code; real carriers (.env,.pem,.key,id_rsa,.pgpass) are named explicitly. - A table name in a reading SQL is not a secret file — but a query against the
secretstable itself still is. sudois a wrapper, not an action. The pipeline already runs as root; judge the inner command.sudo -ustays with the owner.- The agent's own memory (
~/.claude/**/memory) is not "a write outside the tree". The CLI's own configuration still escalates — it could remove the gate. - Reading a secret → the arbiter. Writing a secret → the owner. Exfiltration outward stays a hard deny.
Replayed against every historical request (scripts/gate-replay.js --diff, the 752-request corpus as it stood on 1 September), owner escalations fell from 397 to 199. Nothing moved out of deny. Two holes closed along the way — one mine, one older:
- My first version treated any quoted body containing
selectas a SQL string. Withnode -e "…"the whole program sits in quotes, and a genuinefs.readFileSync('/root/…/.env')vanished with it. Caught by a test on the historical corpus. - The path pattern had no wildcards, so
find /root -name '*.pem' -exec cat {} \;passed as a read — one command that reads every private key on the box.
Two smaller commits sit around it: a repeated, already-decided call no longer opens a new card or freezes the agent (5a5c085), and cards can no longer wait forever — 47 were found hanging (8006fce).
What I would tell someone building this
- Measure the process, not the mechanism. The mechanism worked from day one: the hook fired, deny was honoured, force-push was blocked. The process — a human in the loop — died in 48 hours, and nobody noticed for three months because the failure mode looked like safety.
- A timeout that denies is still a decision. 734 of them. If a human will not answer within N seconds, decide what the default should be for that category and make it explicit.
- Match access, not words. Lexical rules are cheap to write and expensive to live with.
- Keep a replay harness. Every policy change since September is judged by rerunning the whole historical corpus, not by reading the diff.
Would I build it again: yes, and the mechanism unchanged — the hook, the deterministic tiers, fail-closed on every real decision path. What changes is the shape of the human's role. The barrier becomes a notification for everything reversible, so that the arbiter decides and I read about it afterwards, and the categories that genuinely need me keep the barrier and get an immediate answer instead of a 280-second wait that ends in a refusal nobody chose. A gate is not measured by how often it asks. It is measured by whether the answers it gets are real ones.
Since 1 October 2026 this kind of gate can also ship as a mod: TypeScript that runs inside the agent. Claude Code Mods Explained compares hooks, mods, skills and MCP. Your First Claude Code Mod in 20 Minutes builds a small gate in four files. Before installing someone else's mod, read this security checklist.
Where the pieces live
agents/security-gate/policy.js— deterministic tiers (768 lines)agents/security-gate/gate.js— hook entry point, escalation, polling (391)agents/security-gate/triage.js— three-axis classifier (224)agents/security-gate/arbiter.js— model prompt and fail-to-escalate (80)scripts/gate-replay.js,scripts/gate-smoke.js— replay and live smoke checks- tests: 225 across seven suites, green on 7 September 2026, all on real commands from the corpus
FAQ
Can a Claude Code hook block a command?
Yes. A PreToolUse hook that returns "permissionDecision":"deny" stops the tool call before it runs. PostToolUse fires after the fact and can only report back.
Do hooks in settings.json work with claude -p?
Not in our tests (CLI 2.1.162). Pass them per invocation with --settings.
What happens if the hook times out? The tool call is denied. Set the hook's own timeout below the CLI's limit so the denial is clean.
Should the hook ever default to allow? Only when the gate itself crashes — so a bug in your gate cannot stop the whole pipeline. Every real decision path should fail closed.
Information is accurate as of the publication date. Terms, prices, and regulations may change — verify with relevant professionals.