What are hooks?

Hooks are scripts or handlers that a coding agent runs at fixed points in its loop, such as before a tool call or when a turn ends, whatever the model decides. On the events that can block, a hook stops the action, which a line in CLAUDE.md cannot. Claude Code 2.1.283 documents 33 hook events and Codex 0.157.1 documents 12; Cursor’s hooks can block too.

Last updated
By
Published
In Polish
Hooki
First set up at
Level 4, free guide
Also searched as
agent hooks, Claude Code hooks, lifecycle hooks

$59.99 once for 12 months of access. Nothing renews on its own. 30-day refund on a first purchase.

On this page Why it mattersWhere a hook steps inWhich mechanism fits the ruleTwo hooks, as the guide writes themHow each tool does itQuestions

Why it matters.

A line in CLAUDE.md is advice the model weighs against everything else in its context. A hook is code that runs on every matching event, so a check that must always happen, such as tests before “done”, belongs in one. A hook is a gate only when it exits with code 2 or answers with a JSON deny: exit 1, a crash or a mistyped script path lets the action through.

One rule, written two ways

The same rule, “never force push”: as a line in CLAUDE.md, and as a PreToolUse hook on the Bash tool.

  • Advice the model weighs
  • Code that runs
  • What you can rely on

In CLAUDE.md Advisory

  1. The rule

    Never force push.

    One line in CLAUDE.md, next to everything else the model has read.

  2. The model

    Weighs it against the task

    The guide’s wording: advice the model weighs against everything else in its context.

  3. The command

    git push --force

    Nothing in this lane checks it before it runs.

  4. What you can rely on

    The model’s judgment

    The guide starts from a CLAUDE.md whose rules the agent broke anyway.

As a PreToolUse hook Enforced

  1. The rule

    block-destructive.sh

    A script registered for PreToolUse with the matcher Bash.

  2. The command

    git push --force

    Claude is about to call the Bash tool.

  3. The hook reads it

    Matches the force-push pattern

    It answers with a deny reason, Force push is blocked. Push a new commit instead., which goes to Claude as its next instruction.

  4. What you can rely on

    Blocked, for the spellings it matches

    The guide calls the script a speed bump: rm -r -f and find . -delete get past its patterns, so pair it with permissions.deny rules and the sandbox.

Put each rule in the weakest mechanism that still enforces it. For anything that must never run, the guide adds permissions.deny rules and the sandbox next to the hook. Source: Hooks guide, Claude Code 2.1.283, 2026-10-03.

Where a hook steps in

Claude Code 2.1.283 fires 33 hook events. The five hooks in the guide use these four.

Four Claude Code hook events: when each fires and what exit code 2 does.
EventWhen it firesWhat exit code 2 does
SessionStart The session starts, resumes, clears or compacts Cannot block. Plain stdout on exit 0 becomes context for Claude
PreToolUse Before any tool call Blocks the tool call; stderr goes to Claude as the reason
PostToolUse After a tool call succeeds Cannot undo the call. Shows stderr to Claude, which then fixes it
Stop and SubagentStop Claude or a subagent finishes responding Keeps it working
Exit 1 is not a gate. Any code other than 2 does not block unless valid JSON on stdout makes the decision: Claude Code shows a “hook error” notice and the action goes ahead. WorktreeCreate is the exception, where any non-zero exit aborts worktree creation.

Source: Hooks guide, Claude Code 2.1.283, 2026-10-03.

Which mechanism fits the rule

Put each rule in the weakest mechanism that still enforces it. Stronger ones cost more latency and maintenance, and prompt hooks also cost tokens.

Four ways to state a rule to Claude Code: whether each is enforced, what it suits, an example.
MechanismEnforced?Use it forExample
CLAUDE.md No, advisory Conventions and context the model should know “We use pnpm, not npm.”
Permission rule (permissions.deny) Yes, static pattern A fixed list of tools, commands or paths Deny Bash(curl *), deny Edit(.env)
Command hook Yes, computed Checks that need logic, the file content or the repository state Lint the edited file; block DROP TABLE in any form
Prompt or agent hook Yes, judged by a model Checks that need judgment, not pattern matching “Does the final message cite the test command it ran?”

If a static rule can express the policy, use a permission rule: the official hooks reference calls a handler’s if filter “best-effort” and recommends the permission system for hard allow and deny. Hooks are the right place for anything that checks the result. Source: Hooks guide, Claude Code 2.1.283, 2026-10-03.

Two hooks, as the guide writes them

A PreToolUse hook that denies three destructive spellings, and a Stop hook that refuses to finish while the tests fail. Registered in .claude/settings.json, each runs on every matching event.

Source: Hooks guide, Claude Code 2.1.283, 2026-10-03. Open the guide

.claude/hooks/block-destructive.sh (PreToolUse, matcher "Bash")
#!/usr/bin/env bash
# .claude/hooks/block-destructive.sh (PreToolUse, matcher "Bash")
set -euo pipefail
# Fail closed: without jq this gate cannot read the command, so block.
command -v jq >/dev/null || { echo "jq is missing; install it before running Bash." >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')

deny() {
  jq -nc --arg r "$1" '{hookSpecificOutput: {hookEventName: "PreToolUse",
    permissionDecision: "deny", permissionDecisionReason: $r}}'
  exit 0
}

shopt -s nocasematch
rm_rf='(^|[;&|[:space:]])rm[[:space:]]+-[a-z]*(rf|fr)'
sql_drop='(drop|truncate)[[:space:]]+(table|database|schema)'
force_push='git[[:space:]]+push.*(--force|[[:space:]]-f([[:space:]]|$))'

[[ $cmd =~ $rm_rf ]]      && deny "rm -rf is blocked. Delete the specific files by path."
[[ $cmd =~ $sql_drop ]]   && deny "Destructive SQL is blocked. Write a migration and stop for review."
[[ $cmd =~ $force_push ]] && deny "Force push is blocked. Push a new commit instead."
exit 0
.claude/hooks/tests-before-stop.sh (Stop)
#!/usr/bin/env bash
# .claude/hooks/tests-before-stop.sh (Stop)
set -uo pipefail
retrying=$(jq -r '.stop_hook_active')

# Nothing changed in the working tree: nothing to verify.
[[ -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 a human."}'
  exit 0
fi
jq -nc --arg r "The test suite fails. Fix it before you finish. Last 40 lines:
$tail_out" '{decision: "block", reason: $r}'
The first hook is a speed bump, not a boundary. rm -r -f, rm --recursive --force and find . -delete all get past these patterns. Pattern matching catches the common spellings, not every one, so pair it with permissions.deny rules and the sandbox for anything that must never run.

The full guide comes with the Toolkit.

Buy the Toolkit

$59.99 once for 12 months of access. Nothing renews on its own. 30-day refund on a first purchase.

How each tool does it.

Cursor, Claude Code and Codex each name this their own way. Each note carries the date it was checked.

Cursor

Hooks are spawned processes that exchange JSON over stdio, and they can observe, block or modify behaviour. Cursor’s hooks page lists events such as preToolUse, beforeShellExecution and afterFileEdit (checked 2026-10-12); the config file was not re-verified.

Cross-tool hooks guide (Cursor docs), 2026-08-28

Claude Code

33 hook events in 2.1.283; handlers can be shell commands, HTTP endpoints, MCP tools, prompts or agents. Exit code 2 blocks a PreToolUse call.

Hooks merge across ~/.claude/settings.json, .claude/settings.json, .claude/settings.local.json, managed policy settings, plugins and skill or subagent frontmatter, and none replaces another. Open /hooks in a session to see which hooks loaded and from which file.

Hooks guide, Claude Code 2.1.283, 2026-10-03

Codex

12 hook events; a hook needs persisted trust before it runs.

A fresh CI runner has no trust yet, so check that the hook’s output appears in the job log. --dangerously-bypass-hook-trust skips the check and belongs only in automation that already vets the hook source.

Feature matrix, Codex 0.157.1, 2026-09-26

Questions about hooks.

What are hooks used for?

Five jobs recur: block destructive shell commands, protect paths the agent must not edit, format and lint every edit, refuse to stop while the tests fail, and seed each session with live context such as the branch and the last CI result. The first four are gates; the fifth only adds context.

Which exit code blocks an action?

Exit code 2, on the events that can block. Any other code, including 1, does not block unless valid JSON on stdout makes the decision: Claude Code shows a hook error notice and the action goes ahead. WorktreeCreate is the exception, where any non-zero exit aborts worktree creation.

Do Codex and Cursor have hooks?

Yes, with different events and output formats. Codex documents 12 events and runs a project hook only after you trust it in /hooks. Cursor’s hooks exchange JSON over stdio and can block; its hooks page lists events such as preToolUse, beforeShellExecution and afterFileEdit (checked 2026-10-12), so check the full list before you port a script.

Is one hook enough to stop rm -rf?

No. A pattern-matching PreToolUse hook is a speed bump: rm -r -f, rm --recursive --force and find . -delete get past its patterns. Pair it with permissions.deny rules and the sandbox for anything that must never run.

Does this page answer your questions?

One tap, no sign-in.

not at all fully

Read the guides in the same words.

Open every guide with the Toolkit. Each term is defined once here, and the guides use it the same way.

$59.99 once for 12 months of access. Nothing renews on its own. 30-day refund on a first purchase.