Blog

Claude Code hooks: every event, with examples to copy

What hooks are, all 33 events, where to configure them, how exit codes and JSON output steer Claude, and four example hooks to adapt.

Alex Mercer

Claude Code hooks are commands, HTTP calls, MCP tool calls, prompts or subagents that Claude Code runs automatically at set points in a session: before a tool call, after it, when Claude finishes responding, and 30 more events. You define them in a settings file, they fire every time their event happens, and their exit code or JSON output can block the action, send Claude feedback, or add context.

That makes hooks the place for rules that must hold every time. A line in CLAUDE.md is context that Claude reads and interprets. A hook is code that Claude Code runs on its own, so the action happens whether or not the model thinks of it. Anthropic's hooks guide calls this deterministic control.

Hook events and settings here follow Anthropic's docs as of Oct 12, 2026. If you're setting up Claude Code for a team, start with our practical guide to using Claude Code.

How a Claude Code hook works

Every hook has three layers:

  1. Event: the moment it fires, such as PreToolUse or Stop.

  2. Matcher: a filter on when it fires, such as "only the Bash tool".

  3. Handlers: what runs when the event and matcher line up.

Handlers come in five types:

  • command runs a shell command. It receives the event as JSON on stdin and answers through its exit code, stdout and stderr.

  • http sends the same JSON as a POST request and reads the response body.

  • mcp_tool calls a tool on an MCP server you've configured.

  • prompt sends the input to a Claude model, which returns a decision as JSON. Use it for checks that need judgment.

  • agent starts a subagent that can read files before it decides. Anthropic marks agent hooks as experimental.

Per Anthropic's features overview, a hook adds nothing to Claude's context unless it returns output, so a formatter that runs after every edit costs no context. For instructions that never change, a line in CLAUDE.md is simpler than a script; our guide to CLAUDE.md and AGENTS.md covers how those files load.

Every Claude Code hook event

Anthropic's hooks reference lists 33 events as of Oct 12, 2026. A few run once per session (SessionStart, SessionEnd), a few once per turn (UserPromptSubmit, Stop, StopFailure), and PreToolUse and PostToolUse run on every tool call. "Can block" means exit code 2, or a blocking JSON decision, stops the action.

Event

When it fires

Can block?

SessionStart

A session starts or resumes

No

Setup

Claude Code starts with --init-only, or with --init or --maintenance in -p mode

No

InstructionsLoaded

A CLAUDE.md or .claude/rules/*.md file loads into context

No

UserPromptSubmit

You submit a prompt, before Claude processes it

Yes, rejects the prompt

UserPromptExpansion

A command you typed expands into a prompt

Yes, blocks the expansion

PreToolUse

Before a tool call runs

Yes, blocks the call

PermissionRequest

A tool call needs a permission decision

Through JSON only (allow or deny)

PermissionDenied

Auto mode denies a tool call

No (JSON can allow a retry)

PostToolUse

After a tool call succeeds

No, but stderr reaches Claude

PostToolUseFailure

After a tool call fails

No, but stderr reaches Claude

PostToolBatch

After a batch of parallel tool calls resolves, before the next model call

Yes, stops the loop

Notification

Claude Code sends a notification

No

MessageDisplay

While Claude's message text is displayed

No (can change the displayed text)

SubagentStart

A subagent is spawned

No

SubagentStop

A subagent finishes

Yes, keeps it working

TaskCreated

A task is created with TaskCreate

Yes, cancels the task

TaskCompleted

A task is being marked complete

Yes, keeps it open

TeammateIdle

An agent team teammate is about to go idle

Yes, keeps it working

Stop

Claude finishes responding

Yes, keeps Claude working

StopFailure

A turn ends because of an API error

No

PreCompact

Before context compaction

Yes

PostCompact

After compaction completes

No

PreModelSwitch

Before a model switch you or a client requested

Yes

PostModelSwitch

After the session's model changes

No

ConfigChange

A configuration file changes during the session

Yes, except policy settings

CwdChanged

The working directory changes

No

DirectoryAdded

A directory is added with /add-dir or the SDK

No

FileChanged

A file you told it to watch changes on disk

No

WorktreeCreate

A worktree is created; the hook replaces the default git behavior

Yes, any non-zero exit fails it

WorktreeRemove

A worktree is removed

Yes, a non-zero exit fails the removal

Elicitation

An MCP server asks for user input during a tool call

Yes, denies the request

ElicitationResult

After you answer an MCP elicitation, before the answer goes back

Yes

SessionEnd

The session ends

No

Matchers filter on a different field for each event. Tool events match the tool name, such as Bash, Edit|Write or mcp__github__.*. SessionStart matches how the session began (startup, resume, clear, compact or fork). SubagentStart and SubagentStop match the subagent's name, and Notification matches the notification type, such as permission_prompt or idle_prompt. UserPromptSubmit, Stop, PostToolBatch, TeammateIdle, TaskCreated, TaskCompleted, WorktreeCreate, WorktreeRemove, MessageDisplay and CwdChanged don't take a matcher and fire every time.

Where hooks are configured

Hooks live in JSON settings files and a few other places, including plugins and skills. Where you put one sets its scope:

Location

Scope

Shared with the team?

~/.claude/settings.json

All your projects

No, local to your machine

.claude/settings.json

One project

Yes, commit it to the repo

.claude/settings.local.json

One project

No, Claude Code gitignores it when it saves a setting there

Managed policy settings

Whole organization

Yes, set by admins

A plugin's hooks/hooks.json

While the plugin is enabled

Yes, ships with the plugin

Skill frontmatter

Rest of the session once the skill is invoked

Yes, in the skill file

Subagent frontmatter

While that subagent runs

Yes, in the subagent file

A few rules about how these combine:

  • Hooks from every level merge. A project hook doesn't replace a user hook, and a handler defined in two settings files runs once.

  • Claude Code normally picks up edits to settings files on its own, and /hooks lists every hook and where it came from.

  • To pause all hooks, set "disableAllHooks": true. There is no switch for one hook, and only managed settings can turn off managed hooks.

  • Cloud sessions don't read your local ~/.claude/settings.json.

  • Settings, managed and plugin hooks also run inside subagents, with agent_id and agent_type in the input. A subagent's own frontmatter hooks run only while it's active; our subagents guide uses one to keep a reviewer read-only.

The shape of a hook entry

Each event name is a key inside one hooks object. Under it sits a list of matcher groups, and each group holds a list of handlers. This one, from Anthropic's reference, runs a lint script after Claude writes or edits a file:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/lint-check.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/lint-check.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/lint-check.sh"
          }
        ]
      }
    ]
  }
}

If your settings file already has a hooks key, add new events as siblings inside it rather than a second hooks object.

Matchers and the if field

  • "*", "" or no matcher at all matches everything.

  • A matcher made only of letters, digits, _, -, spaces, commas and | is an exact match or a list of them, so Edit|Write matches either tool.

  • Anything else is a JavaScript regular expression, and it isn't anchored: Edit.* also matches NotebookEdit. Write ^Edit$ when you need a whole-name match.

  • Matchers are case-sensitive. MCP tools are named mcp__<server>__<tool>, so mcp__memory__.* matches every tool from the memory server.

On tool events you can narrow further with the if field. It takes one permission rule, such as "Bash(git *)" or "Edit(*.ts)", and the handler only spawns when the tool call matches. For Bash, each subcommand is checked, so Bash(git *) fires on npm test && git push. Anthropic calls if best-effort and recommends permission rules, not hooks, for a hard allow or deny.

Pointing at scripts

Use ${CLAUDE_PROJECT_DIR} for the project root, or ${CLAUDE_PLUGIN_ROOT} inside a plugin. Anthropic recommends setting args (an argument list, even an empty one) whenever a command uses one of these placeholders: Claude Code then runs the executable directly with no shell, each argument is passed as is, and paths with spaces need no quoting. The examples below also use timeout, in seconds (600 by default for command hooks on most events), and statusMessage, the spinner text while the hook runs.

What a hook receives

A command hook gets one JSON object on stdin. The common fields are:

  • session_id and prompt_id

  • transcript_path, the path to the conversation file

  • cwd, the directory Claude is working in

  • permission_mode, such as default, plan, acceptEdits or auto (most events)

  • hook_event_name

  • agent_id and agent_type, when the hook fires inside a subagent

Each event adds its own fields. A PreToolUse hook for a Bash call receives something like this:

{
  "session_id": "abc123",
  "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
  "cwd": "/home/user/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  },
  "tool_use_id": "toolu_01ABC123..."
}
{
  "session_id": "abc123",
  "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
  "cwd": "/home/user/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  },
  "tool_use_id": "toolu_01ABC123..."
}
{
  "session_id": "abc123",
  "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
  "cwd": "/home/user/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  },
  "tool_use_id": "toolu_01ABC123..."
}

For scripts that read this input:

  • For Write, Edit and Read, tool_input.file_path is always absolute. Claude Code expands ~ and relative paths first, so a path check can't be dodged with a different spelling.

  • Stop hooks get stop_hook_active, which is true when Claude is already continuing because a Stop hook blocked it, and last_assistant_message, the text of Claude's final reply. Read that rather than the transcript file, which is written asynchronously and can lag.

How exit codes and output control Claude

The exit code is the simplest signal:

Exit code

Meaning

What Claude Code does

0

Success

Proceeds and reads any JSON on stdout. Plain stdout goes to the debug log, except on UserPromptSubmit, UserPromptExpansion, SessionStart and PostModelSwitch, where Claude gets it as context

2

Block

On events that can block, stops the action. The message is your stderr, or your JSON's reason; for a blocked tool call or Stop, Claude reads it

Anything else

Non-blocking error (most events)

Proceeds and shows a hook error notice with the first line of stderr

On most events, exit code 1, the usual Unix failure code, doesn't block, so a policy hook should exit 2. And a hook that can't start, because the path is wrong or the script isn't executable, also lands in the non-blocking bucket. A typo in settings.json quietly turns your gate off, so watch for a hook error notice the first time a new hook runs. On Claude Code v2.1.295 or later, setting "onFailure": "block" on a command or HTTP hook makes a hook that can't start, times out or exits with an unexpected code block the action instead; it has no effect on Stop hooks.

JSON output for finer control

When block-or-allow isn't enough, exit 0 and print a JSON object on stdout. Pick one approach per hook: exit codes alone, or exit 0 plus JSON. On events that can block, exit 2 wins even if your JSON says allow.

  • Universal fields work on most events. "continue": false stops Claude entirely and shows the user stopReason, and systemMessage shows the user a warning.

  • decision and reason let events such as UserPromptSubmit, PostToolUse, Stop and SubagentStop block or send feedback. The only value for decision is "block".

  • hookSpecificOutput carries richer control and needs a hookEventName. On PreToolUse it holds permissionDecision (allow, deny, ask or defer) with a permissionDecisionReason, and updatedInput can rewrite the tool's arguments. On several events it can hold additionalContext, text Claude reads as a system reminder.

This denies a tool call and tells Claude why:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Database writes are not allowed"
  }
}

Write additionalContext as plain facts ("This repo uses bun test"), not as commands. Anthropic notes that text framed as system instructions can trip Claude's prompt-injection defenses. Each additionalContext, systemMessage and plain stdout value is capped at 10,000 characters.

Hooks also sit above permission modes. A PreToolUse hook that returns deny blocks the tool even in bypassPermissions mode, but one that returns allow can't override a deny rule in your settings.

Four example Claude Code hooks

These are examples to adapt. The first two follow Anthropic's guide; the test gate and review hook are our own, so try each one in a scratch repo before you rely on it. Each goes in .claude/settings.json, so the whole team gets it. The scripts parse JSON with jq, so install it first. Save scripts under .claude/hooks/ and run chmod +x on them, or they fail without blocking anything.

1. Format every file Claude edits

A PostToolUse hook with an Edit|Write matcher runs after each file edit. This one, from Anthropic's guide, passes the edited path to Prettier:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ]
  }
}

When it works, you see nothing in the conversation; the file is just formatted. Swap in the formatter your project uses. PostToolUse can't undo the edit, and the matcher only sees the Edit and Write tools. To catch a specific file however it changes, including a Bash rewrite, use a FileChanged hook.

2. Block edits to sensitive files

A PreToolUse hook runs before the edit, so it can stop it. This script, adapted from Anthropic's guide, exits 2 when the target path matches a protected pattern, and Claude gets the message as feedback. Unlike the original, it fails closed: without jq, it blocks the edit.

#!/bin/bash
# Example: .claude/hooks/protect-files.sh
INPUT=$(cat)

# Fail closed: without jq this guard can't read the path.
command -v jq >/dev/null || { echo "protect-files.sh needs jq to check paths" >&2; exit 2; }

FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Normalize Windows backslashes so the patterns match
FILE_PATH="${FILE_PATH//\\//}"

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0
#!/bin/bash
# Example: .claude/hooks/protect-files.sh
INPUT=$(cat)

# Fail closed: without jq this guard can't read the path.
command -v jq >/dev/null || { echo "protect-files.sh needs jq to check paths" >&2; exit 2; }

FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Normalize Windows backslashes so the patterns match
FILE_PATH="${FILE_PATH//\\//}"

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0
#!/bin/bash
# Example: .claude/hooks/protect-files.sh
INPUT=$(cat)

# Fail closed: without jq this guard can't read the path.
command -v jq >/dev/null || { echo "protect-files.sh needs jq to check paths" >&2; exit 2; }

FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Normalize Windows backslashes so the patterns match
FILE_PATH="${FILE_PATH//\\//}"

PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh",
            "args": []
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh",
            "args": []
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh",
            "args": []
          }
        ]
      }
    ]
  }
}

The check is a substring match, so .env also covers .env.local and .env.example. Adjust the list for your repo. Like the formatter, it only sees Edit and Write. To keep Claude's file tools from reading a file, add a Read deny rule such as Read(./.env) to permissions.deny in your settings.

3. Run tests before Claude stops

Stop fires when Claude finishes responding. Exit 2 from a Stop hook keeps Claude working and hands it your stderr as the reason. That gives you a test gate: if tests fail, Claude fixes them before handing the turn back to you.

#!/bin/bash
# Example: .claude/hooks/test-gate.sh
INPUT=$(cat)

# Without jq the loop guard below can't work, so let Claude stop.
command -v jq >/dev/null || exit 0

CWD=$(jq -r '.cwd' <<<"$INPUT")
ROOT=$(git -C "$CWD" rev-parse --show-toplevel 2>/dev/null) || exit 0
cd "$ROOT" || exit 0

# Stop fires after every response. Skip the run when nothing has changed.
[ -z "$(git status --porcelain)" ] && exit 0

if OUTPUT=$(npm test 2>&1); then
  exit 0
fi

# Claude already had one retry. Let it stop, and warn the user.
if [ "$(jq -r '.stop_hook_active' <<<"$INPUT")" = "true" ]; then
  jq -nc '{systemMessage: "Tests still fail after one retry. Check them before you merge."}'
  exit 0
fi

{
  echo "Tests are failing. Fix them before you finish. Last 40 lines:"
  tail -n 40 <<<"$OUTPUT"
} >&2
exit 2
#!/bin/bash
# Example: .claude/hooks/test-gate.sh
INPUT=$(cat)

# Without jq the loop guard below can't work, so let Claude stop.
command -v jq >/dev/null || exit 0

CWD=$(jq -r '.cwd' <<<"$INPUT")
ROOT=$(git -C "$CWD" rev-parse --show-toplevel 2>/dev/null) || exit 0
cd "$ROOT" || exit 0

# Stop fires after every response. Skip the run when nothing has changed.
[ -z "$(git status --porcelain)" ] && exit 0

if OUTPUT=$(npm test 2>&1); then
  exit 0
fi

# Claude already had one retry. Let it stop, and warn the user.
if [ "$(jq -r '.stop_hook_active' <<<"$INPUT")" = "true" ]; then
  jq -nc '{systemMessage: "Tests still fail after one retry. Check them before you merge."}'
  exit 0
fi

{
  echo "Tests are failing. Fix them before you finish. Last 40 lines:"
  tail -n 40 <<<"$OUTPUT"
} >&2
exit 2
#!/bin/bash
# Example: .claude/hooks/test-gate.sh
INPUT=$(cat)

# Without jq the loop guard below can't work, so let Claude stop.
command -v jq >/dev/null || exit 0

CWD=$(jq -r '.cwd' <<<"$INPUT")
ROOT=$(git -C "$CWD" rev-parse --show-toplevel 2>/dev/null) || exit 0
cd "$ROOT" || exit 0

# Stop fires after every response. Skip the run when nothing has changed.
[ -z "$(git status --porcelain)" ] && exit 0

if OUTPUT=$(npm test 2>&1); then
  exit 0
fi

# Claude already had one retry. Let it stop, and warn the user.
if [ "$(jq -r '.stop_hook_active' <<<"$INPUT")" = "true" ]; then
  jq -nc '{systemMessage: "Tests still fail after one retry. Check them before you merge."}'
  exit 0
fi

{
  echo "Tests are failing. Fix them before you finish. Last 40 lines:"
  tail -n 40 <<<"$OUTPUT"
} >&2
exit 2
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/test-gate.sh",
            "args": [],
            "timeout": 300,
            "statusMessage": "Running tests before Claude finishes"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/test-gate.sh",
            "args": [],
            "timeout": 300,
            "statusMessage": "Running tests before Claude finishes"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/test-gate.sh",
            "args": [],
            "timeout": 300,
            "statusMessage": "Running tests before Claude finishes"
          }
        ]
      }
    ]
  }
}

Replace npm test with your test command. How it behaves:

  • Stop fires after every response, not only at the end of a task, so the script skips the run when the working tree is clean.

  • The first failure blocks and sends Claude the last 40 lines of output. If tests still fail at the next stop, stop_hook_active is true, so the script lets Claude stop and warns you through systemMessage instead of looping. Claude Code also ends the turn itself after Stop hooks block eight times in a row with no tool call in between.

  • It fails safe: without jq or outside a git repo it lets Claude stop, and if the suite runs past the hook's timeout, Claude Code cancels the hook and the turn ends as if nothing blocked.

4. Review the diff before every commit

Claude Code wrote 78.1% of the AI-written code that cubic reviewed in the latest full week, according to Bug Bench. That share covers code reviewed by cubic, not the whole market. A PreToolUse hook on git commit puts a review in front of each commit Claude makes, while Claude still has the context to fix what it finds.

This example calls cubic's CLI as its docs describe it. On macOS or Linux, install it with curl -fsSL https://cubic.dev/install | bash, then run cubic once in your repo to sign in. cubic review --json reviews uncommitted changes and returns one JSON object with an issues array.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(git commit *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/review-before-commit.sh",
            "args": [],
            "statusMessage": "Reviewing changes before commit"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(git commit *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/review-before-commit.sh",
            "args": [],
            "statusMessage": "Reviewing changes before commit"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(git commit *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/review-before-commit.sh",
            "args": [],
            "statusMessage": "Reviewing changes before commit"
          }
        ]
      }
    ]
  }
}
#!/bin/bash
# Example: .claude/hooks/review-before-commit.sh
INPUT=$(cat)
COMMAND=$(jq -r '.tool_input.command // empty' <<<"$INPUT")

# The if filter is best-effort, so check the command here too.
[[ "$COMMAND" == *"git commit"* ]] || exit 0

REPORT=$(cubic review --json 2>/dev/null)
COUNT=$(jq '.issues | length' <<<"$REPORT" 2>/dev/null)

# Block only on a positive issue count. Anything else fails open.
if [[ "$COUNT" =~ ^[1-9][0-9]*$ ]]; then
  {
    echo "Review found $COUNT issue(s) in the uncommitted changes."
    echo "Fix them, then commit again. If you think a finding is wrong, stop and ask the user instead of committing."
    jq '.issues' <<<"$REPORT"
  } >&2
  exit 2
fi

exit 0
#!/bin/bash
# Example: .claude/hooks/review-before-commit.sh
INPUT=$(cat)
COMMAND=$(jq -r '.tool_input.command // empty' <<<"$INPUT")

# The if filter is best-effort, so check the command here too.
[[ "$COMMAND" == *"git commit"* ]] || exit 0

REPORT=$(cubic review --json 2>/dev/null)
COUNT=$(jq '.issues | length' <<<"$REPORT" 2>/dev/null)

# Block only on a positive issue count. Anything else fails open.
if [[ "$COUNT" =~ ^[1-9][0-9]*$ ]]; then
  {
    echo "Review found $COUNT issue(s) in the uncommitted changes."
    echo "Fix them, then commit again. If you think a finding is wrong, stop and ask the user instead of committing."
    jq '.issues' <<<"$REPORT"
  } >&2
  exit 2
fi

exit 0
#!/bin/bash
# Example: .claude/hooks/review-before-commit.sh
INPUT=$(cat)
COMMAND=$(jq -r '.tool_input.command // empty' <<<"$INPUT")

# The if filter is best-effort, so check the command here too.
[[ "$COMMAND" == *"git commit"* ]] || exit 0

REPORT=$(cubic review --json 2>/dev/null)
COUNT=$(jq '.issues | length' <<<"$REPORT" 2>/dev/null)

# Block only on a positive issue count. Anything else fails open.
if [[ "$COUNT" =~ ^[1-9][0-9]*$ ]]; then
  {
    echo "Review found $COUNT issue(s) in the uncommitted changes."
    echo "Fix them, then commit again. If you think a finding is wrong, stop and ask the user instead of committing."
    jq '.issues' <<<"$REPORT"
  } >&2
  exit 2
fi

exit 0

The wrapper exists because the CLI exits with code 1 when it reports findings, and Claude Code treats exit code 1 from a hook as a non-blocking error, so every commit would go through. The script exits 2 instead, which blocks the commit and hands Claude the findings. How it handles trouble:

  • It fails open. If jq or the CLI is missing, or the review errors out, the commit goes ahead. Add an exit 2 for an empty report if you'd rather fail closed.

  • Command hooks time out after 600 seconds by default, and a timed-out PreToolUse hook doesn't block. Raise timeout if your reviews take longer.

  • The message tells Claude to stop and ask you when it disagrees with a finding, so a disputed finding doesn't turn into a loop.

With another review tool, keep the wrapper and swap the command: exit 2 with the findings on stderr when the commit should wait.

A local review is a first pass. cubic's docs recommend its GitHub pull request review as the final one, since that review uses a different model and pipeline and may find issues the CLI misses. Our guide to AI code review covers where each step fits, and a pre-review safety gate for AI-generated code covers gating agent output. For the whole loop in Claude Code, from a local review to fixing pull request comments, see our Claude Code review guide.

Security: hooks run with your permissions

Command hooks run with your full user permissions. They can read, change or delete anything your account can, so review every hook before you add it, especially one from a repo you didn't write.

Workspace trust adds a guard in interactive sessions: Claude Code holds back hooks from settings files until you accept the trust dialog for the folder. A claude -p or Agent SDK session treats the folder as trusted, so hooks committed in a repo's .claude/settings.json run without asking. Before you script claude -p over someone else's repository, read its .claude/ settings, or turn hooks off for that run with --settings '{"disableAllHooks": true}'.

Anthropic's checklist for hook scripts: validate input, quote shell variables ("$VAR"), reject paths that contain .., use absolute paths, and skip sensitive files such as .env and keys.

Debugging a hook that doesn't fire

  • Run /hooks and check that the hook is listed under the right event.

  • Check the matcher. Matchers are case-sensitive.

  • Run the script by hand with sample input: echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh; echo $?

  • If your JSON output has no effect, look for a shell profile that prints text on startup. Anything printed before the { makes Claude Code treat the whole output as plain text.

  • Start Claude Code with claude --debug-file /tmp/claude.log to log which hooks matched, their exit codes and their output, or run /debug to turn logging on mid-session.

FAQ

Which exit code blocks an action in a Claude Code hook?

Exit code 2. On events that can block, such as PreToolUse, UserPromptSubmit and Stop, it stops the action, and for a tool call or Stop, Claude gets your stderr as the reason. On most events, exit code 1 and other non-zero codes are non-blocking errors, so the action goes ahead. You can also block by exiting 0 with a JSON decision, such as "permissionDecision": "deny" on PreToolUse.

What is the difference between hooks and mods in Claude Code?

The hooks in this guide are configured in settings. A mod is a plugin that registers hooks as JavaScript functions, which Claude Code calls in its own process, and it can also draw in the interface. Both work side by side, but a mod that handles tool.check can approve a call your PreToolUse hook blocked, unless that hook lives in managed settings.

How do I get a notification when Claude Code needs input?

Add a Notification hook to ~/.claude/settings.json. On macOS, Anthropic's guide uses the command osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'. Use a matcher such as permission_prompt or idle_prompt to limit which notifications trigger it. For a terminal notification that also works in tmux, return the escape sequence in the terminalSequence JSON field instead of writing to /dev/tty.

Table of contents