Projects Blog Tools Music Contact
← All Posts
Tech September 7, 2026

Claude Code Hooks in Production: The Security Gate That Asked 752 Times and Learned Nothing

By: Evgeny Padezhnov

Illustration for: Claude Code Hooks in Production: The Security Gate That Asked 752 Times and Learned Nothing

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:

  1. In headless mode (claude -p) hooks from .claude/settings.json do not fire. You pass them per invocation: claude -p … --settings '{"hooks":{"PreToolUse":[…]}}'. Verified on CLI 2.1.162.
  2. Only allow and deny are safe headless. ask bypasses deny rules when nobody is there to answer.
  3. 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:

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:

  1. Existence ≠ content. ls, stat, test, find, wc enumerate; they do not read.
  2. Our own source is not a secret. A path under /root/projects with a code extension stays code; real carriers (.env, .pem, .key, id_rsa, .pgpass) are named explicitly.
  3. A table name in a reading SQL is not a secret file — but a query against the secrets table itself still is.
  4. sudo is a wrapper, not an action. The pipeline already runs as root; judge the inner command. sudo -u stays with the owner.
  5. 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.
  6. 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:

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

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


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.

✦ Squeeze AI
  1. Гейт спроектирован fail-closed по механике (deny/timeout по умолчанию), но как процесс он не работал: за три месяца 752 запроса дали лишь 18 реальных решений человека, остальные 734 протухли по таймауту — то есть де-факто система работала на отказ, а не на обучение.
  2. 734 таймаута обернулись примерно 57 часами простоя агентов, и каждый такой эпизод заканчивался отказом — ценой безопасности стала не гибкость, а тупое зависание конвейера.
  3. Изначальная политика судила по словам в команде (vocabulary-based), из-за чего похожие по риску действия классифицировались по-разному; решение — судить по фактическому доступу/обратимости операции, а не по лексике команды.
  4. Три технические ловушки хуков Claude Code стоили автору по дню каждая: в headless-режиме (`claude -p`) хуки из settings.json не срабатывают и их нужно передавать явно через `--settings`; решение `ask` небезопасно без живого человека; хук может держать вызов до таймаута, и по умолчанию таймаут завершает вызов отказом.
  5. Осознанный компромисс архитектуры: если сам скрипт гейта падает — вызов разрешается (чтобы баг в гейте не парализовал весь конвейер), но все содержательные решения по риску обязаны fail-closed.

Powered by B1KEY