Claude Code hooks: guardrails, gates, and live context
PLClaude Code hooks are deterministic handlers (shell commands, HTTP endpoints, MCP tools, prompts, or agents) attached to lifecycle events including PreToolUse, PostToolUse, SessionStart, and Stop. Unlike advisory CLAUDE.md instructions, hooks execute on every matching event so repositories block unsafe commands, protect files, lint every edit, and prevent completion while tests fail.
Your CLAUDE.md says “never edit merged migrations” and “run the tests before finishing”, and last week the agent broke both rules anyway. Context instructions compete with everything else in the prompt window; hooks execute as code every single time. This guide is for developers and tech leads who own .claude/settings.json and want enforceable repository invariants.
Choosing between CLAUDE.md, permissions, and hooks
Section titled “Choosing between CLAUDE.md, permissions, and hooks”Always place a rule in the simplest mechanism that reliably enforces it. Heavier layers add latency, maintenance, or extra model calls.
| Mechanism | Deterministic? | Best fit | Example |
|---|---|---|---|
CLAUDE.md | Advisory only | Conventions, architecture context, commands | “Use pnpm, never npm” |
permissions.deny | Yes (static pattern) | Fixed tool, command prefix, or file path bans | Deny Read(./.env), deny Bash(curl *) |
| Command / HTTP hook | Yes (computed logic) | Checks inspecting payloads, file contents, or repo state | Lint edited file; block destructive SQL; gate Stop on tests |
| Prompt / Agent hook | Model-graded | Judgement checks that regex cannot express | Verify final reply cites the exact command and output |
Use static permission rules whenever a fixed pattern suffices—the official hooks reference treats hook if filters as best-effort optimisations and relies on the permission engine for hard bans (permissions and sandboxing). For cross-tool setups spanning Claude Code, Codex, and Cursor, read agent hooks as deterministic guardrails.
Lifecycle events and the exit-code contract
Section titled “Lifecycle events and the exit-code contract”Hooks merge across user, project (.claude/settings.json), local, managed policy, plugin, and skill/subagent scopes. Core events used in production repositories:
| Event | Fires when | Blocking behaviour |
|---|---|---|
SessionStart | Session starts, resumes, clears, or compacts | Non-blocking; plain stdout injects live context |
UserPromptSubmit | User submits a prompt | Exit 2 blocks and rejects the prompt |
PreToolUse | Before a tool executes | Exit 2 or JSON permissionDecision: "deny" blocks; stderr explains next step |
PermissionRequest | Tool awaits permission decision | Decide via structured JSON output (exit 2 is ignored) |
PostToolUse | After a tool succeeds | Cannot undo; exit 2 returns stderr to Claude for immediate self-correction |
Stop / SubagentStop | Claude or subagent finishes a turn | Exit 2 or JSON {"decision": "block"} forces work to continue |
TaskCompleted | Task is marked complete | Exit 2 blocks completion |
Four protocol invariants prevent broken gates:
- Exit
0succeeds; exit2blocks. Any other exit code—including1or127from a missing binary or mistyped script path—fails open by default, letting the action proceed after a brief warning. - Set
"onFailure": "block"on security-critical command or HTTP hooks. Failing closed ensures that timeouts, missing scripts, malformed JSON, or non-2xx HTTP errors blockPreToolUse,UserPromptSubmit, andPermissionRequestactions instead of waving them through. - Settings
permissions.denyalways beats a hook’sallow. Precedence across multiple hooks isdeny>defer>ask>allow. - Matchers are exact unless they contain regex characters.
Edit|Writematches only those two tools;mcp__github__.*uses regex to match every tool on that server. Reference scripts via${CLAUDE_PROJECT_DIR}in exec form ("args": []) so working-directory changes never break paths.
Check the official Claude Code hooks documentation for the full event catalogue and JSON schemas.
Four high-leverage hook patterns
Section titled “Four high-leverage hook patterns”Commit hook scripts under .claude/hooks/, mark them executable, and register them in .claude/settings.json. Keep PreToolUse scripts fast, local, and free of network calls.
1. PreToolUse: protect critical paths and destructive commands
Section titled “1. PreToolUse: protect critical paths and destructive commands”Write deny messages as the exact next instruction Claude should follow:
#!/usr/bin/env bash# .claude/hooks/protect-paths.sh (PreToolUse, matcher "Edit|Write")set -euo pipefailcommand -v jq >/dev/null || { echo "jq is required to verify path policy." >&2; exit 2; }file=$(jq -r '.tool_input.file_path // empty')rel=${file#"$CLAUDE_PROJECT_DIR"/}
case "$rel" in db/migrations/*|.env|.env.*|tests/acceptance/*) echo "Protected path: $rel. Describe the required change in your reply for human review." >&2 exit 2 ;;esacRegex command hooks catch common mistakes (rm -rf, git push --force, DROP TABLE), yet shell indirection (sh -c, split flags, sed -i) can bypass pattern matching. Treat PreToolUse scripts as speed bumps backed by permissions.deny and OS sandboxing (protecting the oracle).
2. PostToolUse: format and lint every edited file
Section titled “2. PostToolUse: format and lint every edited file”Run your formatter and linter on the touched file; exit 2 with the first ~40 lines of lint errors on stderr so Claude repairs violations immediately before moving on.
3. Stop: refuse completion on failing tests (with loop protection)
Section titled “3. Stop: refuse completion on failing tests (with loop protection)”Always inspect stop_hook_active so a failing suite gets one structured retry before escalating cleanly to a human instead of burning turns in a loop:
#!/usr/bin/env bash# .claude/hooks/tests-before-stop.sh (Stop)set -uo pipefailretrying=$(jq -r '.stop_hook_active')[[ -z $(git status --porcelain) ]] && exit 0
if out=$(npm test --silent 2>&1); then exit 0; fitail_out=$(tail -n 40 <<<"$out")
if [[ $retrying == "true" ]]; then jq -nc '{systemMessage: "Tests still fail after one retry. Stopping for human handoff."}' exit 0fijq -nc --arg r "Test suite failed. Fix implementation before finishing:$tail_out" '{decision: "block", reason: $r}'4. SessionStart: inject live repository state
Section titled “4. SessionStart: inject live repository state”Print changing facts (current branch, dirty file count, latest CI status) on SessionStart with matcher "startup|resume|compact" so live state survives compaction while static rules remain in CLAUDE.md. Register all four in .claude/settings.json:
{ "hooks": { "SessionStart": [ { "matcher": "startup|resume|compact", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/session-context.sh", "args": [] }] } ], "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh", "args": [], "onFailure": "block" }] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format-and-lint.sh", "args": [], "timeout": 60 }] } ], "Stop": [ { "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tests-before-stop.sh", "args": [], "timeout": 180 }] } ] }}When a rule requires judgement rather than deterministic scripting—such as verifying that a final message actually cites the verification command and result—attach a "type": "prompt" hook to Stop or SubagentStop (keep prompt hooks off per-tool events to avoid extra model latency). For slower type checks that should not block edits, use asynchronous background hooks (async or asyncRewake) locally and keep synchronous gates in CI.
Proving every hook works without reading regexes
Section titled “Proving every hook works without reading regexes”Hooks guard production code and require their own automated tests:
- Run JSON fixture tests in CI. Maintain
.claude/hooks/test-hooks.shalongside unit tests: pipe synthetic event payloads into each hook script (using stubbed binaries for fastPostToolUseandStopchecks) and assert exact exit codes and JSON decisions for both allow and deny cases—including known gaps recorded explicitly. - Smoke-test live with debug logging. Launch
claude --debug hooksand trigger a blocked action to verify the hook fires, prints its actionable message, and produces zero “hook error” notices. - Audit repo harness hygiene and gate edits via
CODEOWNERS. Runnpx @wondelai/harness-auditto confirm deterministic hooks and protected paths are wired properly (Harness Audit), and require tech-lead review on.claude/settings.json,.claude/hooks/, and.github/.
Hook security in CI and untrusted repositories
Section titled “Hook security in CI and untrusted repositories”Command hooks execute with full local user privileges. Interactive sessions hold back repository hooks until you accept workspace trust, whereas headless claude -p and SDK sessions execute committed repository hooks immediately without a trust prompt.
Never run claude -p inside an untrusted checkout (such as a fork pull request or unreviewed repo) while API keys or deployment secrets exist in the environment. Isolate untrusted runs with --bare --setting-sources "" --strict-mcp-config, keep trusted scripts on the default branch, and enforce allowManagedHooksOnly in organization-wide managed settings when only admin-approved hooks may execute (managed policy and agent threat model).
When Claude Code hooks fail silently or loop
Section titled “When Claude Code hooks fail silently or loop”- Hook exits
1and lets the action through. Only exit2or JSONdenyblocks. Eliminateexit 1on block paths, guard missing dependencies likejqwithexit 2, and set"onFailure": "block". - Mistyped path or timeout silently disables a gate. Use
${CLAUDE_PROJECT_DIR}in exec form ("args": []), test the exact configured paths in CI fixtures, keepPreToolUsehooks fast and local, and enable"onFailure": "block". - JSON decision is ignored. Extra stdout before
{forces plain-text fallback. Redirect helper output to stderr or/dev/nulland inspect--debug hooks. - Path protection has a Bash-shaped gap. Blocking
Edit|Writedoes not stopsed -iin Bash; layerpermissions.denyand OS sandboxing (permissions and sandboxing). Stophook loops or drags every turn. Skip clean working trees, target fast unit or related tests, and escalate to a human whenstop_hook_activeistrue.- Emergency kill switch. Set
"disableAllHooks": truein local settings for immediate debugging (managed enterprise hooks remain enforced unless disabled in managed policy).
Official docs and next steps
Section titled “Official docs and next steps”Refer to the official Claude Code hooks reference for all lifecycle events, HTTP/MCP hook schemas, and timeout defaults.
- Agent hooks across tools: register equivalent guardrails in Claude Code, Codex, and Cursor.
- Custom subagents: attach frontmatter hooks scoped to a single specialist’s run.
- Automated code reviews: layer independent diff reviews after local hook gates pass.
- Managed policy: enforce
allowManagedHooksOnlyand organization-wide security floors.
Did this guide help you?
One tap, no sign-in.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in