# Hooks URL: https://stevekinney.com/courses/agentic-engineering-playbook/hooks Canonical: https://stevekinney.com/courses/agentic-engineering-playbook/hooks Author: Steve Kinney Language: en-US Modified: 2026-12-03T20:04:32.000Z Description: Hooks run deterministic code at lifecycle events and can block actions. Learn the exit-code contract and how hooks sit relative to permissions. Course: Agentic Engineering Playbook Course URL: https://stevekinney.com/courses/agentic-engineering-playbook --- You wrote "always run the formatter" in `CLAUDE.md`. The agent did it nine times out of ten. The tenth time, it didn't, and you found out in code review. A sentence in an instruction file is a request. A **hook** is code. It runs every time, whether the model remembers or not. Hooks exist in [Claude Code](https://code.claude.com/docs/en/hooks), and [Codex's hooks](https://learn.chatgpt.com/docs/hooks) were modeled on them: same basic contract, with differences in trust, caps, and some events. ## What hooks are A hook runs deterministic code at a _lifecycle event_: a set point in an agent's work, like "a session just started" or "a tool is about to run." It can return feedback at that event. It _cannot_ enforce paths that never pass through it. Hooks are best for "whenever this event happens, do this specific thing." They're usually the wrong choice for "figure out what work needs doing and manage it." Good fits: - Blocking writes to protected branches. - Validating tool inputs. - Formatting an edited file. - Recording a bounded handoff: a short, size-capped note, like a progress file, for the next session to pick up from. - Requiring fresh evidence before completion. A few of the events you'll see throughout this course: - `SessionStart`: A session (one conversation, from launch until you exit) begins. - `PreToolUse`: A tool call, like reading a file or running a shell command, is about to run. The hook can block it. - `PostToolUse`: A tool just ran. Too late to block, but good for feedback and cleanup. - `UserPromptSubmit`: You just submitted a prompt. A hook can add context alongside it, but can't replace it. - `PermissionRequest`: The agent is waiting for you to approve something. - `Stop`: The agent is about to finish a turn (one round of responding, possibly running several tools) and wait for you. - `SubagentStop`: A subagent (a helper agent with fresh context that returns only a final report) is about to finish. There are more, including `TaskCreated`, `TaskCompleted`, and `TeammateIdle` for [agent teams](agent-teams.md), and `PreCompact` and `PostCompact` around compaction. The [hooks reference](https://code.claude.com/docs/en/hooks) lists them all. ## A caveat from someone who's used them Almost every time I've decided to use hooks, I've eventually ripped them out because they were more annoying than helpful. The data disagrees with me a little. When I had agents audit my own sessions, the problems I fixed with a hook or a script _stayed_ fixed, and the ones I fixed with a sentence in `CLAUDE.md` didn't. So here's where I've landed: keep _enforcement_ hooks for the handful of rules that have to hold every single time, and use [The Enforcement Ladder](the-enforcement-ladder.md) to decide which rules those are. Lightweight hooks, like a formatter, a notification, or a context loader, are fine too, because nothing depends on them holding. ## How hooks work The contract is refreshingly boring. The harness sends event JSON to your script on stdin, and your exit code does the talking: - **Exit `0`**: "No objection." That's _not_ the same as approval. Permission rules still get the final say. - **Exit `2`**: Block, where the event supports blocking. Whatever you wrote to stderr goes to Claude, so tell it why. - **Anything else**: A non-blocking error, by default. The action proceeds, so a hook that crashes with exit `1` doesn't stop anything unless you set `"onFailure": "block"` on the hook. [The Enforcement Ladder](the-enforcement-ladder.md) has a story about how that one goes. The other way to block on purpose is to print a JSON decision to stdout and exit `0`. Exit `2` is simpler for a quick block with a message. Use JSON when you want more control, like asking you instead of denying, or having a `PreToolUse` hook rewrite the tool's input with an `updatedInput` field. There's also a safety net for the accidental case. Set `"onFailure": "block"` on a `command`, `http`, or `mcp_tool` hook (Claude Code v2.1.295 or later, v2.1.328 for `mcp_tool`) and a hook that can't start, times out, or exits with anything other than `0` or `2` blocks the action instead of waving it through. It has no effect on `Stop`, `SubagentStop`, `TaskCompleted`, or `TeammateIdle` hooks. Some details that will save you an afternoon: - **Decision fields differ per event**: `PreToolUse` takes `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}}`. `Stop` and `SubagentStop` take `{"decision": "block", "reason": "..."}`. `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. JSON shaped for the wrong event does nothing, silently. - **Not every event can block**: `PostToolUse` can't, because the tool already ran. `SessionStart` can't either. Exiting `2` there doesn't stop the session. - **Matchers only see what they match**: A _matcher_ is the pattern that decides which tool calls trigger a hook. An `Edit|Write` matcher misses writes made through Bash. And `PreToolUse` doesn't fire at all for the shell commands a skill injects while it loads. Those get their own event, `PreSkillShellCommand` (Claude Code v2.1.332 or later). The general filesystem backstop is a repository scan on `Stop`: it detects after the fact and can refuse to let the agent finish until the problem is fixed. - **`FileChanged` reports, it doesn't guard**: It only fires for explicitly watched files and can't block changes. Its matcher registers literal filenames in the working directory, separated by `|`, so `*` registers a file literally named `*`, not every file. For dynamic paths, return absolute `watchPaths` from a `SessionStart`, `CwdChanged`, or `FileChanged` hook and omit the `FileChanged` matcher to handle every watched file. The [FileChanged reference](https://code.claude.com/docs/en/hooks#filechanged) describes how to seed and update that watch list. - **Use `command` handlers for invariants**: A handler is what runs when the hook fires. A `command` handler runs a program you wrote. `prompt` (asks a model), `agent` (runs an agent), `http` (calls a URL), and `mcp_tool` (calls a tool on an MCP server) handlers are fine for advice or a central policy, but they aren't deterministic gates. (An MCP server is a program that adds tools to the harness over the [Model Context Protocol](https://modelcontextprotocol.io/).) - **Injected output is capped**: Each string a hook injects into the model's context tops out at 10,000 characters. Go over, and Claude gets a file path and a preview of the first 2,000 characters instead. Nothing tells it to read the file. ## Configuring hooks Each event holds matcher groups, and each group holds handlers. A command handler has a `type`, a `command`, and a `timeout` in seconds. Most command hooks default to 600 seconds, but `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch` default to 30, `MessageDisplay` defaults to 10, and `SessionEnd` defaults to 1.5 with a shared execution budget. A timeout can cancel the hook before it returns its decision, so check the event in the [hooks reference](https://code.claude.com/docs/en/hooks) and set an explicit timeout that fits the work. Here's a minimal one, under the `hooks` key of `.claude/settings.json`, that runs a script before every `Bash` call: ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/allow-lint.sh", "args": [], "timeout": 10, "onFailure": "block" } ] } ] } } ``` The absolute `${CLAUDE_PROJECT_DIR}` path keeps the hook anchored to the launch project when Claude changes directories or enters a worktree. The JSON input's `cwd` still says where the tool call will run. The empty `args` runs the script directly, with no shell in between to mangle the path. And `onFailure` covers what the script can't: if it's missing or it times out, the call is blocked. Here's a deliberately narrow script: it accepts only the exact command `bun run lint`. Everything else, including malformed event JSON or a missing `jq`, blocks with exit `2`. ```bash #!/bin/bash if ! jq -e -s ' length == 1 and (.[0] | type == "object" and .tool_name == "Bash" and .tool_input.command == "bun run lint") ' >/dev/null; then echo "Blocked: expected one Bash event for exactly bun run lint" >&2 exit 2 fi exit 0 ``` This compares the whole command instead of parsing shell syntax, so `bun run lint && rm -rf x`, leading whitespace, and wrappers all fail. The lint script and the hook still have to be trusted: an exact command runs whatever that script contains. Before installing it, feed the hook valid and malformed events and verify both exits. For ordinary command restrictions, use Claude Code's documented [compound-command matching](https://code.claude.com/docs/en/permissions#compound-commands) instead of a homemade prefix test. A deny rule for `Bash(rm *)` catches `cd /tmp && rm -rf x`, but alternate invocations such as `/bin/rm` still need their own rules. Use sandbox filesystem controls when the boundary is what can be deleted, regardless of command spelling. Hooks can live in a bunch of places: - Settings files: `~/.claude/settings.json` for you across projects, `.claude/settings.json` for the project (committed, so your team gets it), and `.claude/settings.local.json` for you in this project only. - Managed policy (settings an organization pushes to every machine), where `allowManagedHooksOnly` blocks user, project, local, and plugin hooks. The one exception is hooks from plugins the managed settings force-enable. - Skill and agent frontmatter, the YAML block at the top of those files. (See [Configuring Skills](skill-configuration.md) and [Configuring Subagents](subagent-configuration.md).) - A plugin's `hooks/hooks.json`. (A plugin is a bundle of skills, hooks, and agents you install together.) Hooks from all of these are merged, and every matching hook runs in parallel, with no guaranteed order. Define the same handler in more than one settings file and it runs once. Most other settings pick one winner instead: when the same key conflicts across levels, policy wins, then a command-line flag, then local, then project, then user. A few fields worth knowing: - `args`: Runs the command in exec form, with no shell in between, which is safer when inputs contain odd characters. Leave it out when you need pipes or `&&`. - `if`: Filters using permission-rule syntax. It's best-effort, so don't rely on it for a hard allow or deny. - Know when your matcher is a regular expression. A matcher made only of letters, digits, `_`, `-`, spaces, commas, and `|` is an exact match. Add any other character and it becomes an unanchored regular expression: `Edit.*` also matches `NotebookEdit`. Anchor those with `^` and `$`, like `^my-plugin:reviewer$`. MCP tool names are plain, so `mcp__x__y` matches only that tool, a bare `mcp__x` matches nothing, and `mcp__x__.*` matches every tool on the server. ## Hooks and permissions Each side gets the last word on something different. A hook has the last word over _blocking_: exit `2` (or a JSON deny) stops the call even if permission rules would allow it. Permission rules (settings that allow, ask about, or deny specific tool calls) have the last word on _allowing_. So a hook can't grant what a permission rule denies. Permission rules resolve deny first, then ask, then allow, and the first match wins. A deny at any settings level beats every other level, and a `PreToolUse` hook that returns `allow` doesn't bypass a matching deny or ask rule. That makes "allow `Bash`, then block specific commands with a hook" a documented pattern. See the [permissions documentation](https://code.claude.com/docs/en/permissions) for the full rules. > [!NOTE] Mods are the exception > On a machine with no managed settings, no `managed-mcp.json`, and no Team or Enterprise login, an installed [mod](claude-code-mods.md) that handles `tool.check` can approve a call a hook blocked, and some calls a deny rule refuses. Use a permission rule when a plain yes or no on a pattern is enough. Use a hook when the decision depends on what's inside the call.