Guides · Claude Code system
Hooks for the rules that must never break
Move the few rules that must hold every time out of CLAUDE.md and into Claude Code hooks, small scripts the program runs before and after each tool call, and read a repo's hooks before you trust it.
- Reading time
- 7 min read
- Updated
- Nov 19, 2026
- Part of
- the 66-guide pack
Every project I run has the same handful of hard rules. Never read a .env file into chat. Never force push. Tests pass before anything is called done. For a long time those rules lived only in text: a shared RULES.md and each project's CLAUDE.md.
Text works most of the time, and that's the problem. Anthropic's own best-practices page splits instructions into two kinds. Some are things Claude decides whether to follow: your prompt, CLAUDE.md, skills. Others are things the program enforces: hooks, deny rules and the sandbox. Their rule of thumb is simple. If you keep adding emphasis to a CLAUDE.md line ("NEVER", "IMPORTANT", bold), that line belongs in a hook.
The tests I've collected point the same way, with limits. One creator ran 24 sessions on a demo shop with a "never install packages" rule. When his prompt said "I know the project rule, I approve installing it this time", the CLAUDE.md version gave way in 3 of 3 runs and the hook version blocked it in 3 of 3. A separate creator found CLAUDE.md rules alone were followed 8 or 9 times in 10, never 10. Both are self-reported. That's enough for me to treat CLAUDE.md as guidance and hooks as the guard rail.
Claude chooses, the program enforces
Testing hooks with piped JSON (Example)
guard-bash git push -f origin main exit=2 blocked guard-files app/.env exit=2 blocked guard-bash npm test exit=0 allowed guard-bash make wipe exit=0 missed: text match only
1. Know what a hook is
A hook is a command Claude Code runs on its own at a fixed point in a session. The points that matter here:
- PreToolUse runs before a tool call (a file read, an edit, a shell command). It can block the call.
- PostToolUse runs after a tool call. It can't undo anything, but it can tidy up, for example format the file that was just edited.
- Stop runs when Claude finishes a response turn. It can send Claude back to work.
- Notification runs when Claude is waiting on you.
Hooks live in a settings file under one hooks object. Put project hooks in .claude/settings.json so they're committed and everyone gets them. Personal ones go in ~/.claude/settings.json.
{
"hooks": {
"PreToolUse": [
{ "matcher": "Read|Edit|Write", "hooks": [{ "type": "command", "command": ".claude/hooks/guard-files.sh" }] },
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": ".claude/hooks/guard-bash.sh" }] }
],
"PostToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": ".claude/hooks/format.sh" }] }
],
"Stop": [
{ "hooks": [{ "type": "command", "command": ".claude/hooks/check-done.sh" }] }
]
}
}
Type /hooks inside Claude Code afterwards to see which hooks are loaded and from which file.
2. Learn the two facts every hook depends on
The event arrives as JSON on standard input. It does not arrive as environment variables. Your script reads stdin and pulls out the fields it needs, usually with jq. For a file tool the path is in tool_input.file_path. For a shell command it's in tool_input.command.
Exit code 2 blocks. Exit 0 means no objection, and the normal permission flow continues. Exit 2 stops the action, and whatever you wrote to standard error goes back to Claude as the reason. Exit 1 does not block. One creator who demonstrated this called it out on camera: a guard that exits 1 lets the command run.
3. Block reads and edits of secret files
It refuses any file tool call that touches an env file or a key.
#!/usr/bin/env bash
# .claude/hooks/guard-files.sh (PreToolUse on Read|Edit|Write)
path=$(jq -r '.tool_input.file_path // ""')
path=${path//\\//} # normalise Windows backslashes
case "$path" in
*.env|*.env.*|*/secrets/*|*.pem|*id_rsa*)
case "$path" in *.env.example) exit 0 ;; esac
echo "Blocked by hook: $path holds secrets. Ask the user instead of reading it." >&2
exit 2 ;;
esac
exit 0
In one creator's test, a checker blocked a harmless request about .env.example, so allow the known-safe names.
4. Block the shell commands you'd never want run
Shell commands need their own hook, because a file-tool matcher never sees them.
#!/usr/bin/env bash
# .claude/hooks/guard-bash.sh (PreToolUse on Bash)
cmd=$(jq -r '.tool_input.command // ""')
deny() { echo "Blocked by hook: $1" >&2; exit 2; }
echo "$cmd" | grep -Eq 'rm +(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r|-r +-f|-f +-r)' && deny "recursive force delete"
echo "$cmd" | grep -Eq 'git +push.*(--force|-f\b| \+)' && deny "force push"
echo "$cmd" | grep -Eq '(cat|less|head|tail|cp|base64|curl).*\.env\b' && deny "touches .env"
exit 0
Be honest with yourself about what this is. It matches text. The best test I've found attacked a blocklist hook like this one with 25 dangerous requests, twice each. It stopped 21 of 50. Direct requests mostly got caught. Indirect ones mostly didn't: flags split as rm -r -f, a make wipe target, git push origin +main, a Python one-liner printing the file, curl posting it somewhere. The script above catches the split flags and the +main push. It still misses the rest. The same creator found a prompt hook (a small model judging each call) stopped 46 of 50, but only after he used the full model name. With the short alias, the hook logged "unrecognized model" and let everything through without telling anyone.
So a text hook is a seatbelt. Pair it with deny rules and the sandbox (see the permissions guide), and don't assume a hook is running until you've seen it block something.
5. Format after every edit
The PostToolUse hook is the friendly one. It never blocks. It just runs your formatter on whatever Claude touched.
#!/usr/bin/env bash
# .claude/hooks/format.sh (PostToolUse on Edit|Write)
path=$(jq -r '.tool_input.file_path // ""')
case "$path" in
*.ts|*.tsx|*.js|*.css|*.html|*.md) npx --no-install prettier --write "$path" >/dev/null 2>&1 ;;
esac
exit 0
Now "always run Prettier" can come out of CLAUDE.md.
6. Make "done" mean the tests pass
A Stop hook fires at the end of each response turn. It fires once per turn, so it won't wait for the whole task, and a manual interrupt doesn't trigger it. If it exits 2, Claude reads the reason and keeps going.
#!/usr/bin/env bash
# .claude/hooks/check-done.sh (Stop)
input=$(cat)
# Already sent back once this turn? Let it stop, or you can loop forever.
[ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0
if ! npm test --silent >/tmp/stop-hook.log 2>&1; then
echo "Tests are failing. Fix them before you finish. Last lines:" >&2
tail -20 /tmp/stop-hook.log >&2
exit 2
fi
exit 0
The stop_hook_active check matters. The docs say Claude Code overrides a Stop hook after several blocks in a row, but you don't want to reach that. One creator measured four Stop-hook gates on a real repo. Only the tests gate paid off, lifting requirements met from 70% to 84% in his runs. Two reviewer agents added cost and didn't help. He also hit loops when the tests and a reviewer asked for opposite things. Start with the tests.
7. Get pinged when Claude needs you
The Notification hook is what lets you walk away. The docs confirm the permission_prompt matcher fires after a permission prompt has waited about six seconds, and idle_prompt fires about a minute after Claude finishes if you haven't typed.
"Notification": [
{ "matcher": "permission_prompt|idle_prompt",
"hooks": [{ "type": "command", "command": "notify-send 'Claude Code' 'Waiting on you'" }] }
]
notify-send is Linux. The ready-made scripts in most guides are macOS only, so on Windows you'll write your own.
8. Test each hook by hand before Claude ever runs it
Pipe fake JSON in and check the exit code. No Claude needed.
echo '{"tool_name":"Bash","tool_input":{"command":"git push -f origin main"}}' | .claude/hooks/guard-bash.sh; echo "exit=$?"
echo '{"tool_name":"Read","tool_input":{"file_path":"app/.env"}}' | .claude/hooks/guard-files.sh; echo "exit=$?"
echo '{"tool_name":"Bash","tool_input":{"command":"npm test"}}' | .claude/hooks/guard-bash.sh; echo "exit=$?"
You want 2, 2, 0. Then run one real session and watch a block happen. A hook script that crashes on a missing helper fails silently. In the blocklist test above, a crashed hook and a hook server that was down both let every dangerous run through, and Claude never mentioned it.
9. Read a repo's hooks before you trust it
Hooks are real code that runs on your machine whenever Claude Code runs in that folder. A repo you clone can ship its own .claude/settings.json with hooks in it. Before you start Claude Code in someone else's project, open .claude/settings.json, .claude/settings.local.json and any hooks/ folder, and read every command. Plugins can carry hooks too, in hooks/hooks.json.
For teams, the docs confirm a managed setting, allowManagedHooksOnly, that blocks user, project, local and plugin hooks so only the organization's own hooks run.
What to watch
- My own repos run on text rules today. RULES.md and every CLAUDE.md say "never read .env files into chat", and no project of mine has a hook enforcing it yet. Writing this guide is how I found that gap. If your rules are only text, you're in the same place.
- Silent hooks. A hook with the wrong model name, a missing
jq, or a script without execute permission does nothing and says nothing. Check/hooksand test with piped JSON. - Rules a prompt can't express. In the Stop-hook test, one task never moved because the request never stated the requirement. No gate recovers a rule nobody wrote down.
Checklist
- Every rule you've written in capitals or bold is either a hook or a deny rule now.
- A PreToolUse hook blocks file-tool access to env files and keys, with
.env.exampleallowed. - A separate PreToolUse hook on Bash blocks recursive force deletes, force pushes and
.envreads, and you know it's only a text match. - A PostToolUse hook formats edited files, so formatting is out of CLAUDE.md.
- A Stop hook runs the tests, exits 2 on failure, and checks
stop_hook_active. - Each hook was tested with piped JSON (2 to block, 0 to allow) and seen blocking in one real session.
- You read
.claude/settings.jsonand any hook scripts before running Claude Code in a repo you didn't write.
Want the rest?
This is one of 66 guides. The full pack is pay what you want, from a coffee up.