Issue 00 · Autumn 2026日本語 · RSS
AgentKoji

Claude Code Hooks in Practice: exit 2 and PreToolUse

Claude Code hooks: exit 2 blocks, other non-zero codes don't. How PreToolUse blocks before a tool runs, and the git commands our first guard let through.

TL;DR

  • Exit 2 blocks; any other non-zero exit code is a non-blocking error and the tool call goes ahead, unless the hook printed valid JSON (a deny still blocks) or sets onFailure: block (v2.1.295+). The docs say to use exit 2 for policy hooks.
  • PreToolUse runs after Claude creates the tool call and before it runs. A hook that exits 2 blocks even when an allow rule matches, but a hook's allow can't override deny or ask rules.
  • Our first regex missed git push origin +main and git -C /repo reset --hard; version 2 catches both. Regex hooks are best-effort, so back them with permission rules.

A rule in CLAUDE.md is a request. A hook is a mechanism. Below we write a PreToolUse hook that stops destructive git commands, find its holes, and fix them. For every hook event and exit code on one page, see the Claude Code hooks reference: every event and exit code on one page. Test environment: Linux, Claude Code 2.1.301, jq 1.7, git 2.47.3, on 2026-10-16. We tested the script by piping the input JSON documented by Anthropic into it; we did not observe it firing inside a live Claude Code session. Doc-sourced statements were rechecked on 2026-10-26.

Exit codes first

From the hooks reference (https://code.claude.com/docs/en/hooks, checked 2026-10-26):

Exit codeEffect on PreToolUse
0Success; a valid JSON permissionDecision on stdout (allow/deny/ask/defer) applies
2Blocks the call; stderr becomes the reason Claude sees
Any other non-zero code, including 1Non-blocking error; the tool call goes ahead. Exception: if stdout is valid JSON, the JSON decides

Exit 2 blocks; any other non-zero exit code is a non-blocking error, and the tool call goes ahead. That covers exit 1 with plain text or no output. If the hook prints JSON that passes validation, that JSON decides, so a deny still blocks. A timed-out hook or a mistyped script path also lets the call through by default. With "onFailure": "block" (v2.1.295+), a failing hook fails closed and blocks. The docs say: “If your hook is meant to enforce a policy, use exit 2” (same source).

PreToolUse: block before the tool runs

PreToolUse runs after Claude creates the tool parameters and before the tool call is processed. It’s the one place a hook can stop a command before it happens (source: https://code.claude.com/docs/en/hooks, checked 2026-10-26).

There are two ways to block:

The other decisions are "allow" (skips the permission prompt, with documented exceptions), "ask" (prompts the user; the reason appears in the prompt) and "defer" (ends the turn so the tool can be resumed later; non-interactive -p mode only). When several PreToolUse hooks disagree, deny beats defer, defer beats ask, and ask beats allow (same source).

Matchers filter on the tool name: Bash, Edit, Write, Read and other built-in tools, or MCP tools as mcp__<server>__<tool>. Edit|Write is an exact list (same source).

How hooks and permission rules interact. A hook that exits 2 stops the tool call before permission rules are evaluated, so it blocks even when an allow rule would let the call through. The reverse doesn’t hold: Claude Code evaluates deny and ask rules regardless of what the hook returns. A matching deny rule blocks, and a matching ask rule still prompts, even when the hook returned "allow" (source: https://code.claude.com/docs/en/permissions, checked 2026-10-26).

A minimal example, from the hooks reference. The matcher narrows to Bash, and if narrows to commands matching rm *:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(rm *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
            "args": []
          }
        ]
      }
    ]
  }
}
#!/bin/bash
# .claude/hooks/block-rm.sh
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked by hook"
    }
  }'
else
  exit 0  # no decision; normal permission flow applies
fi

Make it executable with chmod +x. This is the docs’ example as published; we did not run it for this article. More patterns, each piped through dummy JSON, are in Claude Code PreToolUse Hook Examples, and every event and exit code is in the hooks reference.

Version 1 let two commands through

#!/usr/bin/env bash
# .claude/hooks/git-guard.sh (PreToolUse, matcher: Bash) v1
cmd=$(jq -r '.tool_input.command // ""')
if printf '%s' "$cmd" | grep -Eq 'git +(push +(-f|--force)|reset +--hard|clean +-[a-z]*f|branch +-D)'; then
  jq -n --arg c "$cmd" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:("destructive git: "+$c)}}'
fi
exit 0

git push --force and npm test && git reset --hard HEAD~1 got ask. Two passed with no decision: git push origin +main (a + refspec is a force push) and git -C /repo reset --hard (an option between git and the subcommand).

Version 2 and results

g='git( +-C +[^ ]+)*'
grep -Eq "$g +(push( +[^ ]+)* +(-f|--force[a-z-]*|\+[^ ]+)|reset +--hard|clean +-[a-z]*f|branch +-D)"
Inputv2
git statusno decision
git push origin mainno decision
git push origin +mainask
git -C /repo reset --hardask
git push --force-with-leaseask
git branch -d topicno decision
git branch -D topicask

Regexes never cover everything. The docs call if filtering best-effort and point to permission rules for hard allow/deny (source: https://code.claude.com/docs/en/hooks, checked 2026-10-26). See Permission Design for AI Agents.

Matchers

Letters, digits, _, -, spaces, , and | mean exact match; any other character makes it a regex. Edit.* also matches NotebookEdit; use ^Edit$ for an exact match (source: https://code.claude.com/docs/en/hooks, checked 2026-10-26).

Matchers also accept MCP tool names (mcp__<server>__<tool>); for the server side, see MCP Servers 101 and Five Design Rules.

Don’t let the model judge

Our hooks decide on exit codes, git counts and regexes only. Through model generation upgrades, not one hook needed editing. We measured an LLM-judged Stop hook per category: two of three either blocked wrongly or caught nothing, so we cut it to one category.

One rule we kept: verify “done” with a Stop hook.

Injected context must earn its place

One hook added about 450 characters to every prompt. It reported “unknown” on every first prompt, so it did nothing. We removed it.

Session-start files bloat the same way: agent memory design.

Check reality after a reject

More than once, when the commit-message hook rejected a commit, lint-staged’s stash was not restored and edits vanished without showing in git status. Now: git status after a reject, git show --stat HEAD after a commit.

Promote only what recurs

Stop-hook blocks go to a jsonl log. Weekly, failures seen three or more times get promoted to a hook or lint rule, at most three per week, so the hooks don’t become a maintenance burden of their own.

For cutting the prose rules themselves, see Trim Your CLAUDE.md.

Copy-paste PreToolUse scripts are collected in Claude Code PreToolUse Hook Examples, and a checklist for hooks that never fire is in Claude Code Hooks Not Working?. For the other events, see PostToolUse: Format and Test on Edit, UserPromptSubmit Hook Examples and Stop Hook: Verify Before It Stops.

Every hook event, exit code and JSON field is listed on one page in the Claude Code hooks reference.

Codex CLI has its own hooks with a different config format and a trust step; see Codex CLI Hooks.

Summary

FAQ

Are Claude Code hooks better than CLAUDE.md rules?
A rule in CLAUDE.md is a request; a hook is a mechanism. Regex hooks are still best-effort, so the docs point to permission rules for a hard allow or deny.
How do I test a Claude Code hook?
Pipe the input JSON documented by Anthropic into the script and check what it decides. Doing that, we found our first git guard let git push origin +main and git -C /repo reset --hard through.
Does a PreToolUse hook override permission rules?
Only in one direction. A hook that exits 2 stops the call before permission rules are evaluated, even when an allow rule matches. A hook that returns allow doesn't bypass rules: a matching deny still blocks and a matching ask still prompts.
Does the Edit.* matcher also match NotebookEdit?
Yes. A matcher with only letters, digits, _, -, spaces, commas and | is an exact match; any other character makes it a regex, so Edit.* matches NotebookEdit. Use ^Edit$ for an exact match.
Should a Claude Code hook ask the model to decide?
Our hooks decide on exit codes, git counts and regexes only, and none needed editing across model upgrades. When we measured an LLM-judged Stop hook, two of three categories blocked wrongly or caught nothing.