A hook is a script Claude Code runs at a fixed moment: before a tool runs, after it runs, when a session starts, when it stops. A PreToolUse hook that exits with code 2 refuses the action, and the agent reads your message. That makes hooks the place where a rule stops being a request and becomes a wall.
A wall in the wrong place is worse than no wall. A session that gets refused for nothing either stalls or learns to go around you. So every hook I add starts in warn mode: it logs what it would have blocked and lets the action run. After a week I read the log, fix what fired for nothing, and only then let it block.
This post is what that week found, with a hook you can copy.
What runs on my machine
Twenty-two hooks across seven events:
- Before a tool runs (7): refuse a push to the main branch, guard secrets files, refuse heavy test runs on the laptop, check commands that touch CI and git, warn before reading a very long file, rewrite noisy commands into shorter ones, and tell my status page the session is busy.
- After a tool runs (2): count how much of the context window is used, and scan output for anything that looks like a key.
- Session start (5), prompt submit (3), stop (3), notification (1), session end (1): mostly status lines for my page, a reminder that each session works in its own git worktree, a few that keep my coordinating sessions in step, and a check that a session does not stop with a test result it never read.
Only some of them ever block. The rest say something and get out of the way.
A guard with a warn switch
The pattern is three parts: the rule, a mode file that says warn or block per rule, and a log line for every firing.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "python3 ~/.claude/hooks/guard-env.py" }
]
}
]
}
}
import json
import os
import re
import sys
import time
RULE = "env-files"
MODES = os.path.expanduser("~/.claude/hook-modes.json")
LOG = os.path.expanduser("~/.claude/hook-firings.jsonl")
event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
if not re.search(r"\b(cat|head|tail|less)\b[^|;&]*\.env\b", command):
sys.exit(0)
try:
mode = json.load(open(MODES)).get(RULE, "warn")
except (OSError, ValueError):
mode = "warn"
with open(LOG, "a") as log:
log.write(json.dumps({
"time": time.time(),
"rule": RULE,
"mode": mode,
"session": event.get("session_id"),
"command": command[:300],
}) + "\n")
if mode == "block":
print("This prints a secrets file. List the names only: grep -o '^[A-Za-z_]*=' .env", file=sys.stderr)
sys.exit(2)
hook-modes.json is one line, {"env-files": "warn"}. The hook reads it on every call, so flipping a rule to "block" takes effect on the next command with no restart. Deleting the file puts every rule back to warn. That is the kill switch, and you will want it the first time a blocking rule misfires at night.
Test a hook without Claude Code
A hook reads JSON on standard input, so you can feed it by hand:
echo '{"tool_input": {"command": "cat .env"}}' | python3 ~/.claude/hooks/guard-env.py; echo "exit $?"
echo '{"tool_input": {"command": "git commit -m \"chore(env): tidy\""}}' | python3 ~/.claude/hooks/guard-env.py; echo "exit $?"
Keep a file of these cases next to the hook and run it after every change. Every false alarm you find in the log becomes one more line in that file. Inside Claude Code, /hooks shows what is registered, and claude --debug shows each hook as it runs.
What the warn week found
Over one week the guards fired 2,226 times. I sampled 20 firings per rule and checked each one against what the session was really doing.
A rule that was never right. The rule "quote a commit hash only if this session saw it in command output" fired 307 times. In a sample of 19 I could judge, it caught zero real mistakes. The hashes came from a merge command's output, from another session's report, or from a local branch. It stayed in warn mode. Some rules are better as a sentence in CLAUDE.md than as code.
The secrets guard was right 5 times in 20. It took source code in a folder called keys/ for key files, 28 times. It read env inside a commit message like "chore(env)" as a command. It refused a command that printed only the names of variables. After the fixes it blocked, and the next review still found 7 refusals out of 10 that were for nothing, all of them commands that already masked the value or only counted lines. Those were fixed too. A secrets guard needs more test cases than any other hook, because the safe forms and the unsafe ones look almost the same.
A regex wanted one space. The hook that checks a session read its test result expected one space and lower case. The status line said finished FAILED (exit 1): two spaces, upper case. Four sessions were told they had not read a result they had read.
The advice could not be followed. The heavy-run guard told sessions to wrap docker build in a memory cap. A Docker build runs inside the Docker daemon, not inside the session, so the cap does nothing. Fourteen warnings that no session could satisfy. Docker builds came off the list.
The escape hatch measured a policy, not a bug. A blocking rule can be passed with a comment that gives a reason, and every pass is logged. In 30 hours, 85 sessions passed the "no full test runs on the laptop" rule 361 times. About 200 of them quoted their task description, which told them to re-run their tests. The hook was right. The task template was wrong.
My log had no command text. I logged the rule and the session, not the command. To judge each firing I had to write a script that finds the matching tool call in the session's transcript, within 40 seconds before the firing. It matched 762 of 856. Log the command, cut to a few hundred characters, from day one. If your commands can carry secrets, log a hash and the first word instead.
The rules I keep
- Start in warn mode. Flip one rule at a time, and only after its sample is clean.
- One mode file, read on every call. A kill switch that works without a restart.
- Log every firing with enough to judge it later.
- Every false alarm becomes a test case before the fix.
- Give the session a way through, with a reason, and read the reasons. They tell you which of your instructions are wrong.
- A message that says what to do instead. "Refused" teaches nothing. "List the names only: grep -o '^[A-Za-z_]*=' .env" gets the work done.
The rules these hooks enforce, and the failures behind them, are in My CLAUDE.md, and the failure behind each rule. The shorter hook list is in My AI agent crew.