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.
- 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.
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
-
The rule
Never force push.One line in
CLAUDE.md, next to everything else the model has read. -
The model
Weighs it against the task
The guide’s wording: advice the model weighs against everything else in its context.
-
The command
git push --forceNothing in this lane checks it before it runs.
-
What you can rely on
The model’s judgment
The guide starts from a
CLAUDE.mdwhose rules the agent broke anyway.
As a PreToolUse hook Enforced
-
The rule
block-destructive.shA script registered for
PreToolUsewith the matcherBash. -
The command
git push --forceClaude is about to call the Bash tool.
-
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. -
What you can rely on
Blocked, for the spellings it matches
The guide calls the script a speed bump:
rm -r -fandfind . -deleteget past its patterns, so pair it withpermissions.denyrules and the sandbox.
Where a hook steps in
Claude Code 2.1.283 fires 33 hook events. The five hooks in the guide use these four.
| Event | When it fires | What 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 |
WorktreeCreate is the exception, where any non-zero exit aborts worktree creation.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.
| Mechanism | Enforced? | Use it for | Example |
|---|---|---|---|
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?” |
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
#!/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
#!/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}'
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.
Keep reading.
The guides that go deeper, and the terms and comparisons next to this one.
In the docs
Does this page answer your questions?
One tap, no sign-in.
What are you here for?
What is holding you back?
How does it read?
Thanks. If you left an email, Michał will reply.
Answering your questions?
One tap each. Close whenever you like.
no sign-in
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.
Michał replies, not a bot. The address is used for this reply only.