Skip to content

Claude 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.

MechanismDeterministic?Best fitExample
CLAUDE.mdAdvisory onlyConventions, architecture context, commands“Use pnpm, never npm”
permissions.denyYes (static pattern)Fixed tool, command prefix, or file path bansDeny Read(./.env), deny Bash(curl *)
Command / HTTP hookYes (computed logic)Checks inspecting payloads, file contents, or repo stateLint edited file; block destructive SQL; gate Stop on tests
Prompt / Agent hookModel-gradedJudgement checks that regex cannot expressVerify 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:

EventFires whenBlocking behaviour
SessionStartSession starts, resumes, clears, or compactsNon-blocking; plain stdout injects live context
UserPromptSubmitUser submits a promptExit 2 blocks and rejects the prompt
PreToolUseBefore a tool executesExit 2 or JSON permissionDecision: "deny" blocks; stderr explains next step
PermissionRequestTool awaits permission decisionDecide via structured JSON output (exit 2 is ignored)
PostToolUseAfter a tool succeedsCannot undo; exit 2 returns stderr to Claude for immediate self-correction
Stop / SubagentStopClaude or subagent finishes a turnExit 2 or JSON {"decision": "block"} forces work to continue
TaskCompletedTask is marked completeExit 2 blocks completion

Four protocol invariants prevent broken gates:

  • Exit 0 succeeds; exit 2 blocks. Any other exit code—including 1 or 127 from 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 block PreToolUse, UserPromptSubmit, and PermissionRequest actions instead of waving them through.
  • Settings permissions.deny always beats a hook’s allow. Precedence across multiple hooks is deny > defer > ask > allow.
  • Matchers are exact unless they contain regex characters. Edit|Write matches 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.

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 pipefail
command -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 ;;
esac

Regex 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 pipefail
retrying=$(jq -r '.stop_hook_active')
[[ -z $(git status --porcelain) ]] && exit 0
if out=$(npm test --silent 2>&1); then exit 0; fi
tail_out=$(tail -n 40 <<<"$out")
if [[ $retrying == "true" ]]; then
jq -nc '{systemMessage: "Tests still fail after one retry. Stopping for human handoff."}'
exit 0
fi
jq -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:

  1. Run JSON fixture tests in CI. Maintain .claude/hooks/test-hooks.sh alongside unit tests: pipe synthetic event payloads into each hook script (using stubbed binaries for fast PostToolUse and Stop checks) and assert exact exit codes and JSON decisions for both allow and deny cases—including known gaps recorded explicitly.
  2. Smoke-test live with debug logging. Launch claude --debug hooks and trigger a blocked action to verify the hook fires, prints its actionable message, and produces zero “hook error” notices.
  3. Audit repo harness hygiene and gate edits via CODEOWNERS. Run npx @wondelai/harness-audit to 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 1 and lets the action through. Only exit 2 or JSON deny blocks. Eliminate exit 1 on block paths, guard missing dependencies like jq with exit 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, keep PreToolUse hooks 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/null and inspect --debug hooks.
  • Path protection has a Bash-shaped gap. Blocking Edit|Write does not stop sed -i in Bash; layer permissions.deny and OS sandboxing (permissions and sandboxing).
  • Stop hook loops or drags every turn. Skip clean working trees, target fast unit or related tests, and escalate to a human when stop_hook_active is true.
  • Emergency kill switch. Set "disableAllHooks": true in local settings for immediate debugging (managed enterprise hooks remain enforced unless disabled in managed policy).

Refer to the official Claude Code hooks reference for all lifecycle events, HTTP/MCP hook schemas, and timeout defaults.

Did this guide help you?

One tap, no sign-in.

not at all a lot