skip to content

Events & Matchers

Hooks fire per session, per turn or per tool call, filtered by matchers on tool names or sources. Asked because PreToolUse versus PostToolUse, or Stop versus SessionEnd, decides whether one can block.

part ofClaude Coderead it →
on this pageshow

explore

questions

6

In Claude Code hooks, how do PreToolUse and PostToolUse differ, and which one can stop Claude from editing a database migration file?

level: juniorimportance: must knowfreq 30%

answer

  1. before versus after the tool runs
  2. one can still say no
  3. the file is already written
  4. failures fire a different event
  5. silence is not approval

basics

~20 s

PreToolUse fires after Claude builds a tool call but before it runs, so it can block the call; PostToolUse fires only after the tool succeeded and cannot undo it. Only a PreToolUse hook can stop a migration edit.

solid answer

~40 s

Both are tool events whose matcher filters on the tool name, such as `Edit|Write`. `PreToolUse` runs after Claude has built the call and before it executes, so it can refuse it: exit 2, or return a `permissionDecision` of `deny`. A guard on `db/migrations/` therefore belongs there. `PostToolUse` runs only after the tool completed successfully, so the file is already on disk; it suits follow-up work such as formatting, linting or telling Claude what a check found, and exit 2 there just shows stderr to Claude. A call that fails fires `PostToolUseFailure` instead. A PreToolUse hook that stays silent approves nothing: the normal permission flow still decides, and a hard guarantee is better expressed as a `permissions.deny` rule.

go deeper

for a junior

Recall the timing: PreToolUse runs before the tool, PostToolUse after it succeeded. Only the first can stop something, so guards go there and formatters go after.

for a middle

Explain the loop order: PreToolUse, then the permission flow, then execution, then PostToolUse or PostToolUseFailure. Show that a silent PreToolUse hook leaves the decision to the permission flow.

for a senior

Name the gaps a guard on Edit|Write leaves: Bash writes, @ references, failed calls. Say when a permissions.deny rule beats a scripted hook and why a deny survives bypassPermissions.

for a principal

Frame hooks as one layer among rules, modes and the sandbox. Argue which rules a team should encode as scripts versus static deny rules, weighing maintenance against coverage.

## Where the two events sit in the agentic loop Claude Code **hooks** are handlers you register on named lifecycle points of the agent: a session starting, a prompt being submitted, a tool call, a turn ending. They are not git hooks: they fire on what the agent does, not on `git commit` or `git push`. Inside the agentic loop, every tool call passes two hook points: 1. Claude produces a tool call, for example `Edit` with a `file_path` and the replacement text. 2. **`PreToolUse`** fires. The call has not run yet. 3. The permission flow decides (rules, mode, maybe a prompt to you); `PermissionRequest` fires only if a dialog would be shown. 4. The tool executes. 5. **`PostToolUse`** fires if it succeeded, or **`PostToolUseFailure`** if it threw an error. Both tool events filter on the **tool name** through the group's `matcher`: `Edit|Write`, `Bash`, `mcp__github__.*` and so on. ## What each event can do | | `PreToolUse` | `PostToolUse` | |---|---|---| | When | Before the call runs | After a successful call | | Can block? | Yes: the tool call never runs | No: the tool already ran | | Exit 2 means | Block; stderr goes to Claude as the denial reason | Stderr is shown to Claude; nothing is undone | | Typical use | Guards, input rewriting, asking the user | Formatting, linting, logging, feedback | | Fires on failure? | n/a | No, `PostToolUseFailure` does | The exact output fields each event honours, and how several hooks' answers combine, are the subject of the hook input and output contract; for choosing the event, the column that matters is **can block**. ## The migration guard, worked through A team rule "Claude must never edit anything under `db/migrations/`" needs the refusal to happen **before** the write: - Register on `PreToolUse` with matcher `Edit|Write`, and either let the script inspect `tool_input.file_path` or narrow each handler with an `if` such as `Edit(**/migrations/**)`. - The script exits 2 with a message on stderr, or prints a `deny` decision; Claude sees the reason and can change approach. - On `PostToolUse` the same script would run after the migration is already rewritten. It could complain to Claude, but the damage is done; `PostToolUse` can even replace what Claude sees of the result, yet the files written stay written. A `PreToolUse` deny is honoured in every permission mode, including `bypassPermissions`, which is why it works as a policy layer. The reverse does not hold: a hook that exits 0 with no output reports **no decision**, and the call continues through the normal permission flow. For a rule that needs no script at all, a `permissions.deny` rule on `Edit` is the simpler and stronger layer; how those rules are written belongs to the permission-rules material. ## Why not `PermissionRequest` `PermissionRequest` also matches on the tool name and can deny, so it looks like an alternative. It is not one for a guard. It fires only when Claude Code is about to show you a permission dialog, or would otherwise auto-deny a call that cannot prompt. If edits are already allowed, for example in `acceptEdits` mode or through an allow rule, no dialog appears and the hook never runs. `PreToolUse` runs before every tool call, whether or not the call needs permission, which is exactly the coverage a guard needs. ## Edges that catch people out - **Other tools write files too.** An `Edit|Write` matcher never sees `sed -i` or a redirect run through `Bash`. Match `Bash` as well and inspect the command, or accept the gap. - **`@` references bypass tool events.** A file you mention with `@` in a prompt is inserted without any tool call, so no `PreToolUse` fires, not even one matching `Read`. - **Failures are separate.** A guard that also logs outcomes must register on `PostToolUseFailure` to see failed calls; `PostToolUse` fires only on success. - **Watching a file is a third option.** `FileChanged` fires on any change to a watched file, whatever wrote it, but only after the change and with no decision control, so it observes rather than guards. ## Rule of thumb If the hook's job is to **prevent**, it belongs on an event that fires before the action and can block: `PreToolUse` for tool calls. If its job is to **react**, such as formatting what was written or reporting what a linter found, `PostToolUse` is right, and its inability to block is irrelevant.

  • Claude changed a migration with `sed -i` through Bash and your `Edit|Write` PreToolUse guard never fired. Why?
    The matcher filters on the tool name, and that call was a `Bash` tool call, not `Edit` or `Write`. Add `Bash` to the matcher and have the script inspect `tool_input.command`, accepting that parsing shell text is best-effort. For a guarantee at the operating-system level, the sandbox with that path denied for writes is the layer, a separate subject.
  • Can a PostToolUse hook still get Claude to fix what it just wrote?
    Yes. The tool already ran, but the hook can feed back: exit 2 puts its stderr in front of Claude, and a JSON block decision or `additionalContext` adds text next to the tool result. Claude reads it before its next step and can repair the file. What it cannot do is prevent or roll back the write itself.

  • A PostToolUse hook that exits 2 rolls the edit back.
  • A PreToolUse hook that exits 0 approves the tool call.
  • PostToolUse also fires when the tool call fails.
  • An Edit|Write matcher catches every way Claude can change a file.
  • PreToolUse hooks are skipped in bypassPermissions mode.
open as a page

Why does a Claude Code PreToolUse hook with matcher `mcp__github` never fire, and how do Claude Code matchers choose exact or regex matching?

level: middleimportance: should knowfreq 12%

basics

~10 s

A matcher of only letters, digits, underscores, hyphens, spaces, commas and pipes is compared exactly, so mcp__github matches no tool. Any other character makes it an unanchored regex; use mcp__github__.*.

open as a page

Which Claude Code hook events fit four rules: block migration edits, add ticket context to prompts, notify when Claude waits, and restore context after compaction?

level: middleimportance: should knowfreq 16%

basics

~10 s

Migration guard: PreToolUse on Edit|Write. Ticket context: UserPromptSubmit. Waiting alert: Notification matched on permission_prompt or idle_prompt. Post-compaction context: SessionStart with the compact matcher, whose stdout reaches Claude.

open as a page

Where can Claude Code hooks be declared, and what happens when user settings, project settings and a plugin all define hooks for one event?

level: middleimportance: should knowfreq 11%

basics

~20 s

Hooks live in user, project, local and managed settings, a plugin's hooks/hooks.json, and skill or subagent frontmatter. They merge rather than override: every matching hook from every source runs, in parallel, and /hooks shows each one's source.

open as a page

In Claude Code, how do the Stop, SubagentStop, StopFailure and SessionEnd hook events differ, and which of them can keep Claude working?

level: seniorimportance: should knowfreq 10%

basics

~20 s

Stop fires each time the main agent finishes responding and can block, keeping Claude working; SubagentStop does so for a subagent. StopFailure replaces Stop on API errors, observe-only. SessionEnd fires at session close and cannot block.

open as a page

In Claude Code, how does a hook handler's `if` field differ from its group's `matcher`, and why is `if` not an enforcement boundary?

level: seniorimportance: nice to knowfreq 6%

basics

~20 s

The matcher filters a group by tool name; if filters one handler by tool and arguments in permission-rule syntax, such as Bash(git *). It works only on tool events and is best-effort: a spawn filter, not policy.

open as a page