← Back to Guides · AUTOMATION
Claude Code Hooks in Production: The Advisory vs Deterministic Rule Nobody Explains
Short answer: CLAUDE.md is advisory — it's text the model reads and can deprioritize once a session fills up with tool output, a long diff, or a dozen file reads. A hook is deterministic — it's a shell command the harness runs on a lifecycle event (PreToolUse, PostToolUse, Stop) no matter how full the context window is or how the model is "feeling" about the task. Every 2026 guide to Claude Code hooks explains the event names; almost none say out loud that this is the actual reason hooks exist — not convenience, but the fact that a rule in a markdown file is a request, and a hook is an enforcement.
If you already know hooks exist and just want working JSON, skip to the three copy-paste hooks below. If you want the fuller 15-hook catalog with exit-code mechanics, see 15 Claude Code Hooks That Actually Prevent Mistakes; for the destructive-command and secrets categories specifically, see our original hooks examples post. For a ranked, ROI-ordered list that adds async: true hooks and more safety gates, see 20 Claude Code Hooks Examples That Actually Ship in Production.
Why CLAUDE.md rules get ignored under context pressure
CLAUDE.md gets loaded into the model's context at session start, same as any other instruction. That's the whole mechanism — there's no separate enforcement layer checking the model's output against it. Which means a rule like "never commit .env" or "always run tests before marking a task done" survives exactly as well as any other piece of text survives a long session: well at the start, worse as the context fills with tool results, file contents, and back-and-forth.
This isn't a Claude-specific flaw. It's true of any instruction given to a model that has to balance it against everything else in the window. A 400-line CLAUDE.md with 30 rules competes for attention with the actual diff the model is looking at, the error message it's debugging, and the five files it just read to understand a function. The rule doesn't disappear, but its weight relative to immediate task pressure drops. That's why teams report the same rule being followed reliably in a short session and skipped in a long one — the rule didn't change, the context around it did.
The practical tell: if a rule is something you'd never accept "the agent forgot" as an excuse for — secrets in a commit, a destructive migration, skipping tests before a merge — it shouldn't be a rule at all. It should be a hook, because a hook has no attention budget to run out of.
The deterministic alternative: PreToolUse, PostToolUse, and Stop hooks
A hook is a shell command registered in .claude/settings.json against a lifecycle event. The harness runs it every time that event fires — not "when the model remembers to," every time. Three events cover most of what a CLAUDE.md rule is trying (and failing) to guarantee:
PreToolUsefires before a tool call executes, with the tool name and its input as JSON on stdin. This is the only event where exiting with status2blocks the action outright — the tool call never happens. This is where a CLAUDE.md rule like "never write to.env" belongs instead, because aPreToolUsehook can refuse the write; a rule can only hope the model remembers.PostToolUsefires after a tool call completes, with the input and result both available. It can't undo the action, but exiting2here surfaces an error back to the model as the reason the turn didn't silently continue — useful for "format this file" or "run the nearest test" style rules that are really post-conditions, not pre-conditions.Stopfires when a turn ends. It's the natural home for "don't consider this task done until X passes" — a rule that's really a gate on finishing, not on any single tool call.
The distinction that matters when choosing between these three: can the thing you want to enforce be checked before an action (block it), only after an action (verify and flag it), or only at the end of a turn (gate completion)? That answer tells you which event to hook, not just that you should hook something.
3 copy-paste hooks: lint-on-write, test-on-commit, secret-scan
All three merge into the top-level hooks key of .claude/settings.json. If you already have hooks configured for other events or tools, merge the arrays — don't overwrite the file.
1. Lint-on-write (PostToolUse, blocks the turn on failure)
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.ts|*.tsx) npx eslint \"$f\" --max-warnings=0 || { echo \"Lint failed on $f\" >&2; exit 2; };; esac"
}
]
}
]
}
}
This is the CLAUDE.md rule "always lint your changes" turned into something that can't be skipped. The edit already happened by the time this fires, so it can't block the write itself — but exiting 2 stops the turn from moving on with a broken file, and feeds the lint error back to the model as the stated reason.
2. Test-on-commit (PreToolUse, blocks the commit itself)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "cmd=$(jq -r '.tool_input.command'); case \"$cmd\" in *'git commit'*) npm test --silent || { echo 'Tests failing — commit blocked' >&2; exit 2; };; esac"
}
]
}
]
}
}
This one is the stronger case for a hook over a rule: "run tests before committing" is a rule every CLAUDE.md in a serious repo already has, and it's exactly the kind of rule that gets skipped under context pressure near the end of a long task when the model is eager to wrap up. Hooked to PreToolUse on Bash, the commit simply never executes if npm test fails — there's no version of this where the model "forgot."
3. Secret-scan (PreToolUse, blocks writes containing likely credentials)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.content // .tool_input.new_string // \"\"' | grep -qE '(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)' && { echo 'Blocked: possible secret in write' >&2; exit 2; } || true"
}
]
}
]
}
}
This pattern-matches AWS access keys, OpenAI/Anthropic-style sk- tokens, and PEM private key headers against the content of any write before it happens. It's intentionally narrow — a handful of high-confidence patterns, not a general secrets scanner — because a hook that's too aggressive about false positives will get disabled by a frustrated user, which defeats the entire point of making enforcement non-negotiable. Pair it with a real scanner (gitleaks, trufflehog) in CI as the backstop; this hook is the fast, local tripwire.
Converting an existing CLAUDE.md rule into a hook
If you're staring at a CLAUDE.md with 20+ rules, the conversion test is simple: for each rule, ask "would I accept 'the model forgot' as a reason this happened?" If no, it's a hook candidate. Then check whether the thing it's guarding is tied to a specific tool action (Edit, Write, Bash) or a session-level moment (Stop, Notification) — that tells you which event to wire it to. Rules that are genuinely about judgment ("prefer composition over inheritance," "keep functions under 40 lines as a guideline") should stay rules, because there's no deterministic check for taste. Rules that are really gates ("never," "always," "must") are the ones worth hooking.
AgenticKit's hooks builder tool generates the .claude/settings.json JSON for common presets — pick the event and the pattern (format-on-save, block-destructive-bash, protect-secrets), and it outputs the config instead of you hand-writing the jq pipeline. If you're running Cursor alongside Claude Code, the same builder also outputs .cursor/hooks.json, which uses a different event vocabulary (beforeShellExecution, beforeMCPExecution, afterFileEdit) for the same advisory-vs-deterministic split — see Cursor Rules vs Skills vs Commands vs Hooks for how that maps across the two tools.
FAQ
Is CLAUDE.md useless, then? No — it's the right place for context the model needs to reason well (architecture, conventions, what a function is for) and for judgment calls that don't reduce to a yes/no check. It's the wrong place for anything where "the model skipped it" is an unacceptable outcome.
Do hooks replace CLAUDE.md rules entirely? No, they cover a different job. A hook can block a git commit with failing tests; it can't explain to the model why your repo's auth pattern works the way it does. Use both — hooks for the non-negotiables, CLAUDE.md for everything else.
What happens if a PostToolUse hook exits 2? The action already ran (the file is already written), but the turn doesn't continue silently — the harness surfaces the hook's stderr back to the model as the reason, which typically triggers a fix-and-retry rather than letting the broken state stand.
Can a hook be bypassed by the model? Not through normal tool use — the harness runs the hook command itself, outside the model's control, so there's no prompt-level way around it. The only bypass is a human editing .claude/settings.json to remove or weaken the hook.
Which event should I use if I want to stop a bad commit before it happens? PreToolUse with a matcher on Bash, inspecting .tool_input.command for git commit — see the test-on-commit hook above. PostToolUse is too late; the commit will have already landed.
Sources
- smartscope.blog, Claude Code Advanced Best Practices: Hooks, Subagents & Context Management (referenced, not quoted)
- wmedia.es, Claude Code hooks practical guide (referenced, not quoted)
Written by Rakshit Yadav. Published 2026-10-31, last updated 2026-10-31.
Related Tools & Agents
Build your hooks.json visually
Pick an event and a preset, then download a hooks file instead of hand-writing the JSON.
Open the hooks builder →