Automate actions with hooks
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -644,7 +644,13 @@
#### Filter by tool name and arguments with the `if` field
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together. Add a pattern in parentheses, such as `Bash(git *)`, after these tool names:
+
+ * **`Bash`, `PowerShell`, [`Monitor`](</docs/en/hooks#match-monitor-commands>)**: matches the command
+ * **`Read`, `Edit`, `Write`, `NotebookEdit`**: matches the file path. To cover `Edit` and `Write`, use two handlers: `"Edit(*.ts)"` and `"Write(*.ts)"`
+ * **`Grep`, `Glob`**: matches the call’s `pattern` argument
+
+For other tools, use the tool’s full name alone and check the input in your script. The following configuration runs a hook when Claude uses `git` commands:
{
"hooks": {
@@ -673,7 +679,7 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-When Claude Code can’t split the Bash input into subcommands, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.
+When Claude Code can’t split the Bash input into subcommands, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.
`if` only works on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`, and `PreSkillShellCommand`. If you add it on any other event, the hook doesn’t run.
@@ -691,13 +697,13 @@
[Skill](</docs/en/skills>) frontmatter| See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
[Subagent](</docs/en/sub-agents>) frontmatter| While that subagent is running| Yes, defined in the subagent file
-Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse your configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
## Prompt-based hooks
For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON:
- * `"ok": true`: the action proceeds
+ * `"ok": true`: Claude Code handles the action as it would without this hook, so permission prompts still apply
* `"ok": false`: what happens depends on the event:
* `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working, unless the response also sets `"impossible": true` to mark the condition as one that can never be satisfied, in which case Claude Code allows the stop and the turn ends
* `PreToolUse`: the tool call is denied; by default the turn ends and the deny `reason` appears in the chat as a warning line. Set `continueOnBlock: true` on the hook to instead return the `reason` to Claude as the tool error, so it can adjust and continue
@@ -727,7 +733,7 @@
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
-When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the `"ok"` / `"reason"` response format with a longer default timeout of 60 seconds and up to 50 tool-use turns. They don’t support the prompt-hook `impossible` field. On `ok: false`, Claude Code handles an agent hook the way it handles a prompt hook with `continueOnBlock: true` on the same event, so on `PreToolUse` and `PostToolUse` the turn continues; agent hooks have no `continueOnBlock` field. See [agent hook configuration](</docs/en/hooks#agent-hook-configuration>) for the fields, including the `$ARGUMENTS` placeholder that Claude Code replaces with the hook’s JSON input. This example verifies that tests pass before allowing Claude to stop:
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the `"ok"` / `"reason"` response format and run for up to 50 tool-use turns. They don’t support the prompt-hook `impossible` field. On `ok: false`, Claude Code handles an agent hook the way it handles a prompt hook with `continueOnBlock: true` on the same event, so on `PreToolUse` and `PostToolUse` the turn continues; agent hooks have no `continueOnBlock` field. This example verifies that tests pass before allowing Claude to stop, and uses the `$ARGUMENTS` placeholder to insert the hook’s JSON input into the prompt:
{
"hooks": {
@@ -787,7 +793,7 @@
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
* `command`, `http`, `mcp_tool`: 10 minutes. Claude Code lowers this default to 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch` hooks, and to 10 seconds for `MessageDisplay`.
* `prompt`: 30 seconds.
- * `agent`: 60 seconds.
+ * `agent`: 60 seconds, or 30 on `UserPromptSubmit`.
* [`SessionEnd`](</docs/en/hooks#sessionend>) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.
* `PostToolUse` hooks can’t undo actions since the tool has already executed.
* [`PermissionRequest`](</docs/en/hooks#permissionrequest>) hooks fire when Claude Code is about to ask you for permission. In a [`-p` run](</docs/en/headless>) with no [permission host](</docs/en/headless#turn-off-permission-prompts-in-unattended-runs>), outside [`dontAsk` mode](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>), a call that would prompt you is denied unless something approves it, such as one of these hooks.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -749,7 +749,7 @@
## HTTP hooks
-Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic, such as a team’s shared audit service. The configuration below posts every successful tool call to a local logging service:
+Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic, such as a team’s shared audit service. The configuration below sends [`PostToolUse`](</docs/en/hooks#posttooluse>) events to an audit service, authenticating with a token from the `MY_TOKEN` environment variable:
{
"hooks": {
@@ -758,7 +758,7 @@
"hooks": [
{
"type": "http",
- "url": "http://localhost:8080/hooks/tool-use",
+ "url": "https://hooks.example.com/tool-use",
"headers": {
"Authorization": "Bearer $MY_TOKEN"
},
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -389,6 +389,7 @@
`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts
`UserPromptSubmit`| When a prompt is submitted, before Claude processes it. Also fires on [turns Claude Code starts on its own](</docs/en/hooks#userpromptsubmit>)
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
+`PreSkillShellCommand`| Before a skill’s [injected shell command](</docs/en/skills#inject-dynamic-context>) runs. Can block the command
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a tool call needs a permission decision
`PermissionDenied`| When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict
@@ -576,6 +577,7 @@
`ElicitationResult`| MCP server name| same values as `Elicitation`
`FileChanged`| literal filenames to watch (see [FileChanged](</docs/en/hooks#filechanged>))| `.envrc|.env`
`UserPromptExpansion`| command name| your skill or command names
+`PreSkillShellCommand`| tool that runs the command| `Bash`, `PowerShell`
`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `MessageDisplay`| no matcher support| always fires on every occurrence
The tabs below show a few more matchers on different event types.
@@ -671,7 +673,9 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-When Claude Code can’t split the Bash input into subcommands, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+When Claude Code can’t split the Bash input into subcommands, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.
+
+`if` only works on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`, and `PreSkillShellCommand`. If you add it on any other event, the hook doesn’t run.
### Configure hook location
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -786,7 +786,7 @@
* `agent`: 60 seconds.
* [`SessionEnd`](</docs/en/hooks#sessionend>) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.
* `PostToolUse` hooks can’t undo actions since the tool has already executed.
- * [`PermissionRequest`](</docs/en/hooks#permissionrequest>) hooks fire when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, they still run outside [`dontAsk` mode](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>), and a call that no hook decides and nothing else can answer is denied.
+ * [`PermissionRequest`](</docs/en/hooks#permissionrequest>) hooks fire when Claude Code is about to ask you for permission. In a [`-p` run](</docs/en/headless>) with no [permission host](</docs/en/headless#turn-off-permission-prompts-in-unattended-runs>), outside [`dontAsk` mode](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>), a call that would prompt you is denied unless something approves it, such as one of these hooks.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
* When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s input, Claude Code doesn’t merge the rewrites or guarantee which rewrite the tool runs with. Avoid having more than one hook rewrite the same tool’s input.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -642,7 +642,7 @@
#### Filter by tool name and arguments with the `if` field
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
{
"hooks": {
@@ -684,7 +684,7 @@
`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins/overview>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
-[Skill](</docs/en/skills>) frontmatter| The rest of the session once the skill is invoked. See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
+[Skill](</docs/en/skills>) frontmatter| See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
[Subagent](</docs/en/sub-agents>) frontmatter| While that subagent is running| Yes, defined in the subagent file
Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -570,7 +570,7 @@
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
-`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, `unknown`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -497,10 +497,8 @@
* **Exit 0** : if you exit 0 from a `PreToolUse` hook, the tool call still goes through the normal [permission flow](</docs/en/permissions>), because exit 0 doesn’t approve it. For `UserPromptSubmit`, `UserPromptExpansion`, `SessionStart`, and `PostModelSwitch` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
* **Exit 2** : write a reason to stderr. Depending on the event, Claude receives it as feedback so it can adjust, the user sees it, or no message appears, as with `ConfigChange` and `Elicitation`. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
- * **Any other exit code** : for the per-event exceptions, such as `WorktreeCreate` failing on any nonzero exit, see [Exit code output](</docs/en/hooks#exit-code-output>). On other events, unless the hook is one whose failure blocks the action, find your case by what your hook printed to stdout:
- * A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error.
- * A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: the action proceeds as a non-blocking error. Check the `<hook name> hook error` notice for the validation or parse message.
- * Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
+
+To look up the outcome for a combination of exit code and stdout on an event such as `PreToolUse`, see [Exit code output](</docs/en/hooks#exit-code-output>). Check the same section for events with their own exit code rules, such as `WorktreeCreate`.
#### Structured JSON output
@@ -582,13 +580,13 @@
The tabs below show a few more matchers on different event types.
- * Log every Bash command
+ * Log successful Bash commands
* Match MCP tools
* Clean up on session end
-Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts only the command string, which `>>` appends to the log file:
+Match only `Bash` tool calls and log each successful command to a file. The `PostToolUse` event fires after a command succeeds, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts only the command string, which `>>` appends to the log file:
{
"hooks": {
@@ -673,7 +671,7 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-When Claude Code can’t determine which commands the Bash input runs, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+When Claude Code can’t split the Bash input into subcommands, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
### Configure hook location
@@ -747,7 +745,7 @@
## HTTP hooks
-Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team. This example posts every tool use to a local logging service:
+Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic, such as a team’s shared audit service. The configuration below posts every successful tool call to a local logging service:
{
"hooks": {
@@ -886,9 +884,9 @@
* **Success** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback.
* To confirm the hook ran, check for its effect, like a reformatted file
* **Blocking error** : on most events you see the message that came with the block, for example `Blocked: rm commands are not allowed`. On a few events, such as `ConfigChange` and `Elicitation`, you see no message. [Exit code 2](</docs/en/hooks#exit-code-2>) covers where the message comes from.
- * **Non-blocking error** : you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr after `Failed with non-blocking status code:`, or a JSON validation or parse message. The action went ahead.
-
-To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details, including hook exit codes, stdout, and stderr, read the [debug log](</docs/en/hooks#debug-hooks>). Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+ * **Non-blocking error** : a `<hook name> hook error` notice with `Failed with non-blocking status code:` means your hook didn’t stop the action. You don’t see this notice when a command hook on an event such as `Notification` fails.
+
+To look up the outcome for a combination of exit code and stdout on an event such as `PreToolUse`, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. Check the same section for events with their own exit code rules, such as `WorktreeCreate`. For execution details, read the [debug log](</docs/en/hooks#debug-hooks>). Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
## Learn more
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -190,7 +190,7 @@
### Block edits to protected files
-Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.
+Stop Claude’s `Edit` and `Write` tools from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.
1
@@ -253,6 +253,8 @@
Test the hook
Ask Claude to add a comment to your `.env` file. Claude Code blocks the edit before it runs and passes the script’s `Blocked:` message to Claude as feedback.
+
+Claude can still change the protected files with shell commands. To block some of those commands, add an [`Edit` deny rule](</docs/en/permissions#what-read-and-edit-rules-cover>) per path under `permissions.deny` in `.claude/settings.json`, like `Edit(/.env)` for the project root’s `.env`. Even with those rules, Claude can change `.env` in other ways. To limit which files commands can write to, see [Configure sandboxing](</docs/en/sandboxing#configure-sandboxing>).
### Re-inject context after compaction
@@ -769,7 +771,7 @@
Your endpoint responds with a JSON body in the same [output format](</docs/en/hooks#json-output>) as command hooks, and Claude Code also checks the response status:
* **2xx status** : to block a tool call, return the appropriate `hookSpecificOutput` fields in the body.
- * **Any other status, or the request fails** : Claude Code reports a [non-blocking error](</docs/en/hooks#exit-code-output>) and lets the action continue. To make a failed endpoint block the action, set [`onFailure: "block"`](</docs/en/hooks#block-the-action-when-a-hook-fails>) on the hook.
+ * **Any other status, or the request fails** : Claude Code reports a [non-blocking error](</docs/en/hooks#exit-code-output>) and lets the action continue, unless the hook is one [whose failure blocks the action](</docs/en/hooks#block-the-action-when-a-hook-fails>). To make a failed endpoint block the action, set [`onFailure: "block"`](</docs/en/hooks#block-the-action-when-a-hook-fails>) on the hook.
Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
Show diff (435 lines)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -2,11 +2,7 @@
This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
-##
-
-
-
-Set up your first hook
+## Set up your first hook
To create a hook, add a `hooks` block to a settings file. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.
@@ -39,7 +35,7 @@
"PostToolUse": [
{
"matcher": "Edit|Write",
- "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
+ "hooks": [{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" }]
}
],
"Notification": [
@@ -65,19 +61,11 @@
Press `Esc` to return to the CLI. Press `Shift+Tab` until the status bar shows `⏸ manual mode on`, ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
-##
-
-
-
-What you can automate
+## What you can automate
Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
-###
-
-
-
-Get notified when Claude needs input
+### Get notified when Claude needs input
Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
@@ -176,11 +164,7 @@
Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. The `auth_storage_failure` matcher requires v2.1.288 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`.
-###
-
-
-
-Auto-format code after edits
+### Auto-format code after edits
Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.org/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
@@ -192,7 +176,7 @@
"hooks": [
{
"type": "command",
- "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
+ "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
@@ -204,11 +188,7 @@
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
-###
-
-
-
-Block edits to protected files
+### Block edits to protected files
Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.
@@ -274,11 +254,7 @@
Ask Claude to add a comment to your `.env` file. Claude Code blocks the edit before it runs and passes the script’s `Blocked:` message to Claude as feedback.
-###
-
-
-
-Re-inject context after compaction
+### Re-inject context after compaction
When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Claude Code adds plain text your command writes to stdout to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:
@@ -300,13 +276,9 @@
You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](</docs/en/memory>) instead. For environment variables, see [`CLAUDE_ENV_FILE`](</docs/en/hooks#persist-environment-variables>) in the reference.
-###
-
-
-
-Audit configuration changes
-
-Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each change to an audit log. Add this to `~/.claude/settings.json`:
+### Audit configuration changes
+
+Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each event to an audit log. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -326,11 +298,7 @@
The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema. To confirm the hook records changes, edit a settings file in another editor while a session is running, then open `~/claude-config-audit.log`: the hook appends one JSON line per change with the timestamp, source, and file path.
-###
-
-
-
-Reload environment when directory or files change
+### Reload environment when directory or files change
Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool doesn’t pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
@@ -379,11 +347,7 @@
See the [CwdChanged](</docs/en/hooks#cwdchanged>) and [FileChanged](</docs/en/hooks#filechanged>) reference entries for input schemas, `watchPaths` output, and `CLAUDE_ENV_FILE` details.
-###
-
-
-
-Auto-approve specific permission prompts
+### Auto-approve specific permission prompts
Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. Claude Code runs `PermissionRequest` hooks when it’s about to ask you for permission, and if your hook returns `"behavior": "allow"`, Claude Code answers the request on your behalf. For a tool that [requires user interaction](</docs/en/hooks#allow-with-updatedinput>), such as `ExitPlanMode`, the allow also needs `updatedInput`, or Claude Code ignores it and still shows the prompt. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
@@ -413,11 +377,7 @@
Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every tool permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields.
-##
-
-
-
-How hooks work
+## How hooks work
Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs the matching hooks in parallel; see [Hook handler fields](</docs/en/hooks#hook-handler-fields>) for how duplicate handlers are treated. The table below shows each event and when it triggers:
@@ -464,11 +424,7 @@
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
* `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks.
-###
-
-
-
-Combine results from multiple hooks
+### Combine results from multiple hooks
When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` doesn’t stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer applies, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
@@ -494,19 +450,11 @@
When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny takes precedence, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
-###
-
-
-
-Read input and return output
+### Read input and return output
Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script’s stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code.
-####
-
-
-
-Hook input
+#### Hook input
Every event includes common fields like `session_id`, a unique ID for the session, and `cwd`, the working directory when the event fired, but each event type adds different data. When Claude runs a Bash command, a `PreToolUse` hook receives these fields on stdin:
@@ -528,11 +476,7 @@
Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, `compact`, or `fork`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
-####
-
-
-
-Hook output
+#### Hook output
Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. The following `PreToolUse` hook blocks a command:
@@ -556,11 +500,7 @@
* A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: the action proceeds as a non-blocking error. Check the `<hook name> hook error` notice for the validation or parse message.
* Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
-####
-
-
-
-Structured JSON output
+#### Structured JSON output
Exit codes only let you block or stay silent. For more control, exit 0 and print a JSON object to stdout instead.
@@ -594,11 +534,7 @@
See [UserPromptSubmit decision control](</docs/en/hooks#userpromptsubmit-decision-control>) for the full output shape, including blocking prompts and setting the session title. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks.
-###
-
-
-
-Filter hooks with matchers
+### Filter hooks with matchers
Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits, not after every tool call, add a matcher to your `PostToolUse` hook:
@@ -704,11 +640,7 @@
}
}
-####
-
-
-
-Filter by tool name and arguments with the `if` field
+#### Filter by tool name and arguments with the `if` field
The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
@@ -741,11 +673,7 @@
When Claude Code can’t determine which commands the Bash input runs, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
-###
-
-
-
-Configure hook location
+### Configure hook location
Where you add a hook determines its scope:
@@ -761,11 +689,7 @@
Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
-##
-
-
-
-Prompt-based hooks
+## Prompt-based hooks
For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON:
@@ -795,11 +719,7 @@
For full configuration options, see [Prompt-based hooks](</docs/en/hooks#prompt-based-hooks>) in the reference.
-##
-
-
-
-Agent-based hooks
+## Agent-based hooks
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
@@ -823,11 +743,7 @@
Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase. For full configuration options, see [Agent-based hooks](</docs/en/hooks#agent-based-hooks>) in the reference.
-##
-
-
-
-HTTP hooks
+## HTTP hooks
Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team. This example posts every tool use to a local logging service:
@@ -857,17 +773,9 @@
Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
-##
-
-
-
-Limitations and troubleshooting
-
-###
-
-
-
-Limitations
+## Limitations and troubleshooting
+
+### Limitations
Keep these constraints in mind when designing hooks:
@@ -882,11 +790,7 @@
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
* When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s input, Claude Code doesn’t merge the rewrites or guarantee which rewrite the tool runs with. Avoid having more than one hook rewrite the same tool’s input.
-###
-
-
-
-Hooks and permission modes
+### Hooks and permission modes
With a hook in a settings file or a plugin’s `hooks/hooks.json` you can’t loosen restrictions past what permission rules allow, and a hook’s `"deny"` holds in every permission mode:
@@ -900,11 +804,7 @@
Your machine might lack [managed settings](</docs/en/settings#check-what-your-organization-enforces>) and a [`managed-mcp.json` file](</docs/en/managed-mcp#deploy-managed-mcp-json>), and your session might not use [`/login` credentials](</docs/en/authentication#authentication-precedence>) for a Team or Enterprise plan. In that setup, a [mod](</docs/en/plugins/mods/overview>) can approve a call your `PreToolUse` hook blocked. A session that runs on an API key or a long-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/authentication#generate-a-long-lived-token>) instead isn’t using that login, even when that login is stored.In plan mode, a mod can approve such a blocked call only when it’s read-only, so not a file edit. For the cases where a mod’s approval doesn’t get past your rules and hooks, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>).
-###
-
-
-
-Hook not firing
+### Hook not firing
The hook is configured but never executes.
@@ -913,11 +813,7 @@
* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
* Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission; see the limitations for the non-interactive cases
-###
-
-
-
-Hook error in output
+### Hook error in output
You see a message like “PreToolUse hook error: …” in the transcript.
@@ -932,11 +828,7 @@
* If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. If it shows a JSON parse message, the stdout looked like a JSON object but wasn’t valid JSON. Both happen even on exit 0. To fix a parse failure, build the payload with a JSON encoder such as `jq` instead of string concatenation, so quotes and backslashes inside values are escaped. The reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section covers the exit-code and JSON combinations
* If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
-###
-
-
-
-`/hooks` shows no hooks configured
+### `/hooks` shows no hooks configured
You edited a settings file but the hooks don’t appear in the menu.
@@ -945,11 +837,7 @@
* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks
* If the menu shows `Only hooks from managed settings run here`, your organization has set [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>). Hooks in your user, project, and local settings files don’t run and aren’t listed
-###
-
-
-
-Stop hook hits the block cap
+### Stop hook hits the block cap
Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row with no tool call from Claude in between. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
@@ -962,22 +850,14 @@
If your hook legitimately needs more than eight iterations to converge, raise the cap with [`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`](</docs/en/env-vars>).
-###
-
-
-
-Hook JSON has no effect
+### Hook JSON has no effect
Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. Check which cause applies:
* **Extra output before the JSON** : something else writes to stdout first, usually an unconditional `echo` in your shell profile, so the output no longer starts with `{`. See Shell profile output before the JSON.
* **A field at the wrong level** : compare each field’s placement against the [JSON output](</docs/en/hooks#json-output>) format. For example, `permissionDecision` belongs inside `hookSpecificOutput`, not at the top level. See Fields at the wrong level.
-####
-
-
-
-Shell profile output before the JSON
+#### Shell profile output before the JSON
Hooks run in non-interactive shells, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile, and anything the profile prints reaches stdout ahead of your hook’s JSON:
@@ -993,19 +873,11 @@
The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.
-####
-
-
-
-Fields at the wrong level
+#### Fields at the wrong level
When your hook returns `permissionDecision` or `additionalContext` at the top level instead of inside `hookSpecificOutput`, the JSON still parses, and Claude Code ignores the misplaced fields without reporting an error. To see which fields it ignored, start Claude Code with `claude --debug` and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook JSON output had unrecognized keys`.
-###
-
-
-
-Check what a hook did
+### Check what a hook did
Press `Ctrl+O` to open the transcript view and look for the hook’s outcome:
@@ -1016,11 +888,7 @@
To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details, including hook exit codes, stdout, and stderr, read the [debug log](</docs/en/hooks#debug-hooks>). Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
-##
-
-
-
-Learn more
+## Learn more
* [Hooks reference](</docs/en/hooks>): full event schemas, JSON output format, async hooks, and MCP tool hooks
* [Security considerations](</docs/en/hooks#security-considerations>): review before deploying hooks in shared or production environments
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -898,7 +898,7 @@
In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), if your `PreToolUse` hook returns `"allow"` for a file edit, you get the same prompt, block, or approval the edit would get with no hook. To lift this limit on hook approvals, [approve the plan](</docs/en/permission-modes#review-and-approve-a-plan>) or switch to another permission mode.
* **`"deny"` in every permission mode**: a hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. `PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. This lets you enforce policy that users can’t bypass by changing their permission mode.
-If your machine has no [managed settings](</docs/en/settings#check-what-your-organization-enforces>) and your session doesn’t use [`/login` credentials](</docs/en/authentication#authentication-precedence>) for a Team or Enterprise plan, a [mod](</docs/en/plugins/mods/overview>) can approve a call your `PreToolUse` hook blocked. A session that runs on an API key or a long-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/authentication#generate-a-long-lived-token>) instead isn’t using that login, even when that login is stored.In plan mode, a mod can approve such a blocked call only when it’s read-only, so not a file edit. For the cases where a mod’s approval doesn’t get past your rules and hooks, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>).
+Your machine might lack [managed settings](</docs/en/settings#check-what-your-organization-enforces>) and a [`managed-mcp.json` file](</docs/en/managed-mcp#deploy-managed-mcp-json>), and your session might not use [`/login` credentials](</docs/en/authentication#authentication-precedence>) for a Team or Enterprise plan. In that setup, a [mod](</docs/en/plugins/mods/overview>) can approve a call your `PreToolUse` hook blocked. A session that runs on an API key or a long-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/authentication#generate-a-long-lived-token>) instead isn’t using that login, even when that login is stored.In plan mode, a mod can approve such a blocked call only when it’s read-only, so not a file edit. For the cases where a mod’s approval doesn’t get past your rules and hooks, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -385,7 +385,7 @@
Auto-approve specific permission prompts
-Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. Claude Code runs `PermissionRequest` hooks when it’s about to ask you for permission, and if your hook returns `"behavior": "allow"`, Claude Code answers the request on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
+Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. Claude Code runs `PermissionRequest` hooks when it’s about to ask you for permission, and if your hook returns `"behavior": "allow"`, Claude Code answers the request on your behalf. For a tool that [requires user interaction](</docs/en/hooks#allow-with-updatedinput>), such as `ExitPlanMode`, the allow also needs `updatedInput`, or Claude Code ignores it and still shows the prompt. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -395,7 +395,7 @@
"hooks": [
{
"type": "command",
- "command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"
+ "command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input}}}'"
}
]
}
@@ -407,19 +407,9 @@
`bypassPermissions` only applies if you started the session with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in [user, `--settings`, or managed settings](</docs/en/settings-reference#permissions-defaultmode>). It doesn’t apply if bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>), or if you started the session in [restricted mode](</docs/en/cli-reference#cli-flags>).Claude Code never saves it as `defaultMode`.
-To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
-
- {
- "hookSpecificOutput": {
- "hookEventName": "PermissionRequest",
- "decision": {
- "behavior": "allow",
- "updatedPermissions": [
- { "type": "setMode", "mode": "acceptEdits", "destination": "session" }
- ]
- }
- }
- }
+To switch the session to `acceptEdits`, replace the `command` line in that hook with this one:
+
+ "command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input, updatedPermissions: [{type: \"setMode\", mode: \"acceptEdits\", destination: \"session\"}]}}}'"
Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every tool permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -155,13 +155,14 @@
This command opens a dialog box rather than a notification in the corner of your screen, so the dialog can open behind your terminal window. Test the command directly in PowerShell first.If you run Claude Code inside WSL, `powershell.exe` must be available on your `PATH` through Windows interop.
-The empty `matcher` fires on all notification types. To fire only on specific events, set it to one of these values:
+The empty `matcher` fires on all notification types. To fire only on specific events, set it to a notification type, such as one of these:
Matcher| Fires when
---|---
`permission_prompt`| Claude needs you to approve a tool use or a sandboxed command’s [network request](</docs/en/sandboxing#network-isolation>), and the prompt has waited about six seconds
`idle_prompt`| Claude finished responding about 60 seconds ago and you haven’t typed since
`auth_success`| Authentication completes
+`auth_storage_failure`| Your sign-in completes, but Claude Code can’t save the new credentials to its [credential storage](</docs/en/authentication#credential-management>). Fires in place of `auth_success`
`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about six seconds
`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds
`elicitation_complete`| An MCP server reports that a [URL-mode elicitation](</docs/en/hooks#elicitation-input>) is complete
@@ -173,7 +174,7 @@
`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
`plugin_notification`| A [mod](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) raises a notification with `$.ui.notify`. The hook’s `title` is the mod’s name unless the mod set one
-Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`.
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. The `auth_storage_failure` matcher requires v2.1.288 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`.
###
@@ -636,7 +637,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`, `plugin_notification`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `auth_storage_failure`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`, `plugin_notification`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`PreModelSwitch`, `PostModelSwitch`| canonical name of the model the session switches to, as described under [PreModelSwitch](</docs/en/hooks#premodelswitch>)| `claude-opus-5`, `claude-opus-4-6|claude-opus-5`, `.*opus.*`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -589,6 +589,7 @@
* Reads from [network paths](</docs/en/permissions#network-paths>)
* MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Calls to [tools an Agent SDK app marks `always_ask`](</docs/en/agent-sdk/custom-tools#require-approval-for-specific-tools>), unless the [permission mode approves the call](</docs/en/agent-sdk/typescript#permission-modes-that-can-approve-an-always_ask-call>)
* Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>). A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning it ends the turn with the tool call preserved, so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
@@ -901,6 +902,7 @@
* **What still holds over`"allow"`**: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for:
* Reads from [network paths](</docs/en/permissions#network-paths>)
* MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Calls to [tools an Agent SDK app marks `always_ask`](</docs/en/agent-sdk/custom-tools#require-approval-for-specific-tools>), unless the [permission mode approves the call](</docs/en/agent-sdk/typescript#permission-modes-that-can-approve-an-always_ask-call>)
* Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), if your `PreToolUse` hook returns `"allow"` for a file edit, you get the same prompt, block, or approval the edit would get with no hook. To lift this limit on hook approvals, [approve the plan](</docs/en/permission-modes#review-and-approve-a-plan>) or switch to another permission mode.
* **`"deny"` in every permission mode**: a hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. `PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. This lets you enforce policy that users can’t bypass by changing their permission mode.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -888,7 +888,7 @@
* `PostToolUse` hooks can’t undo actions since the tool has already executed.
* [`PermissionRequest`](</docs/en/hooks#permissionrequest>) hooks fire when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, they still run outside [`dontAsk` mode](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>), and a call that no hook decides and nothing else can answer is denied.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
- * When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
+ * When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s input, Claude Code doesn’t merge the rewrites or guarantee which rewrite the tool runs with. Avoid having more than one hook rewrite the same tool’s input.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -916,6 +916,7 @@
The hook is configured but never executes.
* Run `/hooks` and confirm the hook appears under the correct event
+ * For a hook in a skill’s frontmatter, invoke the skill or ask Claude to, then run `/hooks` again. `/hooks` doesn’t list hooks from a skill that hasn’t been invoked in the session. If `/hooks` still doesn’t list the hook, check for other causes, such as [frontmatter that didn’t parse](</docs/en/skills#skill-not-triggering>) or one of the [limits on skill hooks](</docs/en/hooks#limits-on-skill-hooks>)
* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
* Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission; see the limitations for the non-interactive cases
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -171,6 +171,7 @@
`quota_auto_resume_fired`| Claude Code continues your task after a claude.ai usage limit paused it: at the reset, or sooner when something you do in Claude Code during the wait, such as adding usage credits, upgrading your plan, or switching models, makes usage available again, with the [model-setting exception](</docs/en/interactive-mode#wait-for-a-usage-limit-to-reset>)
`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
+`plugin_notification`| A [mod](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) raises a notification with `$.ui.notify`. The hook’s `title` is the mod’s name unless the mod set one
Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`.
@@ -590,7 +591,7 @@
* MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
* Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
-For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>). A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
+For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>). A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning it ends the turn with the tool call preserved, so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
{
"hookSpecificOutput": {
@@ -634,7 +635,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`, `plugin_notification`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`PreModelSwitch`, `PostModelSwitch`| canonical name of the model the session switches to, as described under [PreModelSwitch](</docs/en/hooks#premodelswitch>)| `claude-opus-5`, `claude-opus-4-6|claude-opus-5`, `.*opus.*`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -427,7 +427,7 @@
How hooks work
-Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs all matching hooks in parallel; see [Hook handler fields](</docs/en/hooks#hook-handler-fields>) for how duplicate handlers are treated. The table below shows each event and when it triggers:
+Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs the matching hooks in parallel; see [Hook handler fields](</docs/en/hooks#hook-handler-fields>) for how duplicate handlers are treated. The table below shows each event and when it triggers:
Event| When it fires
---|---
@@ -555,15 +555,13 @@
exit 0 # exit 0 = no decision; the normal permission flow applies
-The exit code determines what happens next:
-
- * **Exit 0** : your hook reports no objection through its exit code.
- * For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies.
- * For `UserPromptSubmit`, `UserPromptExpansion`, `SessionStart`, and `PostModelSwitch` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
- * **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
- * **Any other exit code** : for most events, the action proceeds as a [non-blocking error](</docs/en/hooks#exit-code-output>), unless the hook is one [whose failure blocks the action](</docs/en/hooks#block-the-action-when-a-hook-fails>) or its JSON output passes validation:
- * A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
- * A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: a non-blocking error; the notice carries the validation or parse message.
+With an exit code besides 0 and 2 and no valid JSON output, the action proceeds on most events, unless the hook is one [whose failure blocks the action](</docs/en/hooks#block-the-action-when-a-hook-fails>). A hook with `onFailure` set to `"block"` is one example. Exit 0 to report no objection, or exit 2 to block the action:
+
+ * **Exit 0** : if you exit 0 from a `PreToolUse` hook, the tool call still goes through the normal [permission flow](</docs/en/permissions>), because exit 0 doesn’t approve it. For `UserPromptSubmit`, `UserPromptExpansion`, `SessionStart`, and `PostModelSwitch` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
+ * **Exit 2** : write a reason to stderr. Depending on the event, Claude receives it as feedback so it can adjust, the user sees it, or no message appears, as with `ConfigChange` and `Elicitation`. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Any other exit code** : for the per-event exceptions, such as `WorktreeCreate` failing on any nonzero exit, see [Exit code output](</docs/en/hooks#exit-code-output>). On other events, unless the hook is one whose failure blocks the action, find your case by what your hook printed to stdout:
+ * A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error.
+ * A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: the action proceeds as a non-blocking error. Check the `<hook name> hook error` notice for the validation or parse message.
* Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
####
@@ -586,17 +584,13 @@
}
}
-With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. On `PreToolUse`, Claude Code handles each `permissionDecision` value as follows:
-
- * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for:
- * Reads from [network paths](</docs/en/permissions#network-paths>)
- * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
- * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
-For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>).
- * `"deny"`: cancel the tool call and send the reason to Claude
- * `"ask"`: show the permission prompt to the user as normal
-
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
+With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. On `PreToolUse`, you can also return `"ask"` to show the user the normal permission prompt, or `"allow"` to skip the interactive permission prompt. With `"allow"`, deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for:
+
+ * Reads from [network paths](</docs/en/permissions#network-paths>)
+ * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+
+For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>). A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
{
"hookSpecificOutput": {
@@ -785,7 +779,7 @@
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
* `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working, unless the response also sets `"impossible": true` to mark the condition as one that can never be satisfied, in which case Claude Code allows the stop and the turn ends
- * `PreToolUse`: the tool call is denied; by default the turn ends and the deny `reason` appears in the chat as a warning line. Set `continueOnBlock: true` on the hook to instead return the `reason` to Claude as the tool error, so it can adjust and continue. Before v2.1.210, the deny `reason` was returned to Claude as the tool error and the turn continued
+ * `PreToolUse`: the tool call is denied; by default the turn ends and the deny `reason` appears in the chat as a warning line. Set `continueOnBlock: true` on the hook to instead return the `reason` to Claude as the tool error, so it can adjust and continue
* `PostToolUse`: by default the turn ends and the `reason` appears in the chat as a warning line. Set `continueOnBlock: true` to feed the `reason` back to Claude and continue the turn instead
* `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line
@@ -901,13 +895,16 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for:
-
- * Reads from [network paths](</docs/en/permissions#network-paths>)
- * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
- * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
-
-In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), if your `PreToolUse` hook returns `"allow"` for a file edit, you get the same prompt, block, or approval the edit would get with no hook. To lift this limit on hook approvals, [approve the plan](</docs/en/permission-modes#review-and-approve-a-plan>) or switch to another permission mode. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. In plan mode, the mod can approve such a call when it’s read-only, but not a file edit or another call that isn’t read-only. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
+With a hook in a settings file or a plugin’s `hooks/hooks.json` you can’t loosen restrictions past what permission rules allow, and a hook’s `"deny"` holds in every permission mode:
+
+ * **What still holds over`"allow"`**: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for:
+ * Reads from [network paths](</docs/en/permissions#network-paths>)
+ * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), if your `PreToolUse` hook returns `"allow"` for a file edit, you get the same prompt, block, or approval the edit would get with no hook. To lift this limit on hook approvals, [approve the plan](</docs/en/permission-modes#review-and-approve-a-plan>) or switch to another permission mode.
+ * **`"deny"` in every permission mode**: a hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. `PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. This lets you enforce policy that users can’t bypass by changing their permission mode.
+
+If your machine has no [managed settings](</docs/en/settings#check-what-your-organization-enforces>) and your session doesn’t use [`/login` credentials](</docs/en/authentication#authentication-precedence>) for a Team or Enterprise plan, a [mod](</docs/en/plugins/mods/overview>) can approve a call your `PreToolUse` hook blocked. A session that runs on an API key or a long-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/authentication#generate-a-long-lived-token>) instead isn’t using that login, even when that login is stored.In plan mode, a mod can approve such a blocked call only when it’s read-only, so not a file edit. For the cases where a mod’s approval doesn’t get past your rules and hooks, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -561,7 +561,7 @@
* For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies.
* For `UserPromptSubmit`, `UserPromptExpansion`, `SessionStart`, and `PostModelSwitch` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
* **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
- * **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
+ * **Any other exit code** : for most events, the action proceeds as a [non-blocking error](</docs/en/hooks#exit-code-output>), unless the hook is one [whose failure blocks the action](</docs/en/hooks#block-the-action-when-a-hook-fails>) or its JSON output passes validation:
* A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
* A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: a non-blocking error; the notice carries the validation or parse message.
* Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
@@ -588,7 +588,11 @@
With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. On `PreToolUse`, Claude Code handles each `permissionDecision` value as follows:
- * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for reads from [network paths](</docs/en/permissions#network-paths>), for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+ * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for:
+ * Reads from [network paths](</docs/en/permissions#network-paths>)
+ * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+For what `"allow"` does in plan mode, see [Hook approvals in plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>).
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
@@ -897,7 +901,13 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for reads from [network paths](</docs/en/permissions#network-paths>), for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
+`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for:
+
+ * Reads from [network paths](</docs/en/permissions#network-paths>)
+ * MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+
+In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), if your `PreToolUse` hook returns `"allow"` for a file edit, you get the same prompt, block, or approval the edit would get with no hook. To lift this limit on hook approvals, [approve the plan](</docs/en/permission-modes#review-and-approve-a-plan>) or switch to another permission mode. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. In plan mode, the mod can approve such a call when it’s read-only, but not a file edit or another call that isn’t read-only. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
###
@@ -926,6 +936,7 @@
* If you see “command not found”, use absolute paths or `${CLAUDE_PROJECT_DIR}` to reference scripts. To avoid shell quoting entirely, add `"args": []` to switch to [exec form](</docs/en/hooks#exec-form-and-shell-form>), which spawns the script directly without a shell
* If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing
+ * If the message includes `blocking because Git Bash wasn't found`, you’re on Windows, Claude Code didn’t find Git Bash, and the failed or timed-out hook blocked the tool call. See [Failed hooks on Windows without Git Bash](</docs/en/hooks#failed-hooks-on-windows-without-git-bash>) for the fixes
* If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. If it shows a JSON parse message, the stdout looked like a JSON object but wasn’t valid JSON. Both happen even on exit 0. To fix a parse failure, build the payload with a JSON encoder such as `jq` instead of string concatenation, so quotes and backslashes inside values are escaped. The reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section covers the exit-code and JSON combinations
* If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -588,7 +588,7 @@
With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. On `PreToolUse`, Claude Code handles each `permissionDecision` value as follows:
- * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
+ * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for reads from [network paths](</docs/en/permissions#network-paths>), for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
@@ -897,7 +897,7 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
+`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for reads from [network paths](</docs/en/permissions#network-paths>), for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
###
@@ -967,22 +967,36 @@
Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. Check which cause applies:
- * **Extra output before the JSON** : something else writes to stdout first, usually an unconditional `echo` in your shell profile, so the output no longer starts with `{` and Claude Code doesn’t parse it as JSON. The cause and fix follow this list.
- * **A field at the wrong level** : compare each field’s placement against the [JSON output](</docs/en/hooks#json-output>) format. For example, `permissionDecision` belongs inside `hookSpecificOutput`, not at the top level.
-
-When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+ * **Extra output before the JSON** : something else writes to stdout first, usually an unconditional `echo` in your shell profile, so the output no longer starts with `{`. See Shell profile output before the JSON.
+ * **A field at the wrong level** : compare each field’s placement against the [JSON output](</docs/en/hooks#json-output>) format. For example, `permissionDecision` belongs inside `hookSpecificOutput`, not at the top level. See Fields at the wrong level.
+
+####
+
+
+
+Shell profile output before the JSON
+
+Hooks run in non-interactive shells, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile, and anything the profile prints reaches stdout ahead of your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
-The combined output no longer starts with `{`, so Claude Code treats all of stdout as plain text and ignores the JSON. On exit 0 nothing is reported in the transcript; the parse attempt is recorded only in the [debug log](</docs/en/hooks#debug-hooks>). To fix this, wrap echo statements in your shell profile so they only run in interactive shells:
+Unless the hook is [async](</docs/en/hooks#how-async-hooks-execute>), Claude Code reads output that doesn’t start with `{` as plain text, so your JSON is ignored. Because the hook exited 0, the transcript shows no error either. To check for this cause, start Claude Code with `claude --debug`, trigger the hook, and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook output does not start with {`. To fix it, wrap the `echo` statements in your profile so they run only in interactive shells:
# In ~/.zshrc or ~/.bashrc
if [[ $- == *i* ]]; then
echo "Shell ready"
fi
-The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped. When your hook returns `permissionDecision` or `additionalContext` at the top level instead of inside `hookSpecificOutput`, the JSON still parses, and Claude Code ignores the misplaced fields without reporting an error. To see which fields it ignored, start Claude Code with `claude --debug` and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook JSON output had unrecognized keys`.
+The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.
+
+####
+
+
+
+Fields at the wrong level
+
+When your hook returns `permissionDecision` or `additionalContext` at the top level instead of inside `hookSpecificOutput`, the JSON still parses, and Claude Code ignores the misplaced fields without reporting an error. To see which fields it ignored, start Claude Code with `claude --debug` and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook JSON output had unrecognized keys`.
###
@@ -997,7 +1011,7 @@
* **Blocking error** : on most events you see the message that came with the block, for example `Blocked: rm commands are not allowed`. On a few events, such as `ConfigChange` and `Elicitation`, you see no message. [Exit code 2](</docs/en/hooks#exit-code-2>) covers where the message comes from.
* **Non-blocking error** : you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr after `Failed with non-blocking status code:`, or a JSON validation or parse message. The action went ahead.
-To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details including hook exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details, including hook exit codes, stdout, and stderr, read the [debug log](</docs/en/hooks#debug-hooks>). Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -198,7 +198,7 @@
}
}
-To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques. To reformat a specific file however it changes, including when a `Bash` command rewrites it, use a [FileChanged](</docs/en/hooks#filechanged>) hook instead.
+To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Check what a hook did. To reformat a specific file however it changes, including when a `Bash` command rewrites it, use a [FileChanged](</docs/en/hooks#filechanged>) hook instead.
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
@@ -859,7 +859,12 @@
}
}
-The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone can’t block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
+Your endpoint responds with a JSON body in the same [output format](</docs/en/hooks#json-output>) as command hooks, and Claude Code also checks the response status:
+
+ * **2xx status** : to block a tool call, return the appropriate `hookSpecificOutput` fields in the body.
+ * **Any other status, or the request fails** : Claude Code reports a [non-blocking error](</docs/en/hooks#exit-code-output>) and lets the action continue. To make a failed endpoint block the action, set [`onFailure: "block"`](</docs/en/hooks#block-the-action-when-a-hook-fails>) on the hook.
+
+Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
##
@@ -983,16 +988,16 @@
-Debug techniques
-
-Press `Ctrl+O` to open the transcript view to check the outcome of a hook run:
-
- * **Successful run** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback.
- * To confirm a hook ran, check for its effect, like a reformatted file, or turn on debug logging as described below and trigger the hook again
- * **Blocking error** : on most events you see the hook’s feedback. When the hook’s JSON made a blocking decision, the feedback is the reason from that decision; otherwise it is the hook’s stderr. On a few events, such as `ConfigChange` and `Elicitation`, a block surfaces no message.
- * **Non-blocking error** : the action proceeded, and you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr prefixed with `Failed with non-blocking status code:`, or a JSON validation or parse message.
-
-Which exit-code and JSON combinations produce each outcome, including the per-event exceptions, is defined in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+Check what a hook did
+
+Press `Ctrl+O` to open the transcript view and look for the hook’s outcome:
+
+ * **Success** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback.
+ * To confirm the hook ran, check for its effect, like a reformatted file
+ * **Blocking error** : on most events you see the message that came with the block, for example `Blocked: rm commands are not allowed`. On a few events, such as `ConfigChange` and `Elicitation`, you see no message. [Exit code 2](</docs/en/hooks#exit-code-2>) covers where the message comes from.
+ * **Non-blocking error** : you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr after `Failed with non-blocking status code:`, or a JSON validation or parse message. The action went ahead.
+
+To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details including hook exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -456,7 +456,7 @@
`DirectoryAdded`| When a working directory is added mid-session via `/add-dir` or the SDK `register_repo_root` control request
`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
-`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
+`WorktreeRemove`| When a worktree that a `WorktreeCreate` hook created is being removed
`PreCompact`| Before context compaction
`PostCompact`| After context compaction completes
`PreModelSwitch`| Before Claude Code applies a model switch that you or a client requested. Can block the switch
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -943,7 +943,7 @@
Stop hook hits the block cap
-Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
+Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row with no tool call from Claude in between. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
#!/bin/bash
INPUT=$(cat)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -433,7 +433,7 @@
---|---
`SessionStart`| When a session begins or resumes
`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts
-`UserPromptSubmit`| When you submit a prompt, before Claude processes it
+`UserPromptSubmit`| When a prompt is submitted, before Claude processes it. Also fires on [turns Claude Code starts on its own](</docs/en/hooks#userpromptsubmit>)
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a tool call needs a permission decision
@@ -882,9 +882,7 @@
* `agent`: 60 seconds.
* [`SessionEnd`](</docs/en/hooks#sessionend>) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.
* `PostToolUse` hooks can’t undo actions since the tool has already executed.
- * `PermissionRequest` hooks fire when Claude Code is about to ask you for permission.
- * In [non-interactive mode](</docs/en/headless>) with the `-p` flag, that prompt only exists when the Agent SDK’s [`canUseTool` callback](</docs/en/agent-sdk/permissions>) supplies it. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks for automated permission decisions instead.
- * Background subagents can’t show a prompt in non-interactive mode. Claude Code still runs the hooks for their tool calls, and if no hook returns a decision, it denies the call. In an interactive session, background subagent prompts surface in your main session and the hooks fire as usual.
+ * [`PermissionRequest`](</docs/en/hooks#permissionrequest>) hooks fire when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, they still run outside [`dontAsk` mode](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>), and a call that no hook decides and nothing else can answer is denied.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
* When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -57,7 +57,7 @@
Verify the configuration
-Type `/hooks` to open the hooks browser. You’ll see a list of all available hook events, with a count next to each event that has hooks configured. Select `Notification` to confirm your new hook appears in the list. Selecting the hook shows its details: the event, matcher, type, source file, and command.
+Type `/hooks` at the Claude Code prompt to open the hooks browser. Your new hook appears in the list under `Notification`.
3
@@ -65,8 +65,6 @@
Press `Esc` to return to the CLI. Press `Shift+Tab` until the status bar shows `⏸ manual mode on`, ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
-The `/hooks` menu is read-only. To add, modify, or remove hooks, edit your settings JSON directly or ask Claude to make the change.
-
##
@@ -107,7 +105,7 @@
If no notification appears
-`osascript` routes notifications through the built-in Script Editor app. If Script Editor doesn’t have notification permission, the command fails silently, and macOS won’t prompt you to grant it. Run this in Terminal once to make Script Editor appear in your notification settings:
+`osascript` routes notifications through the built-in Script Editor app. If Script Editor doesn’t have notification permission, the command fails silently, and macOS won’t prompt you to grant it.Run this in Terminal once to make Script Editor appear in your notification settings:
osascript -e 'display notification "test"'
@@ -155,7 +153,7 @@
If no dialog appears
-This command opens a dialog box rather than a notification in the corner of your screen, so the dialog can open behind your terminal window. Test the command directly in PowerShell first. If you run Claude Code inside WSL, `powershell.exe` must be available on your `PATH` through Windows interop.
+This command opens a dialog box rather than a notification in the corner of your screen, so the dialog can open behind your terminal window. Test the command directly in PowerShell first.If you run Claude Code inside WSL, `powershell.exe` must be available on your `PATH` through Windows interop.
The empty `matcher` fires on all notification types. To fire only on specific events, set it to one of these values:
@@ -174,7 +172,7 @@
`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
-Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`.
###
@@ -896,7 +894,7 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks in settings files and in a plugin’s `hooks/hooks.json` can tighten restrictions but not loosen them past what permission rules allow. A [mod](</docs/en/plugins/mods/overview>) you install that handles `tool.check` can approve a call that your `PreToolUse` hook blocked, unless the hook is in managed settings. [Extend permissions with hooks](</docs/en/permissions#extend-permissions-with-hooks>) lists which rules hold over a mod.
###
@@ -939,6 +937,7 @@
* File edits are normally picked up automatically. If they haven’t appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.
* Verify your JSON is valid: trailing commas and comments aren’t allowed
* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks
+ * If the menu shows `Only hooks from managed settings run here`, your organization has set [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>). Hooks in your user, project, and local settings files don’t run and aren’t listed
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -168,7 +168,7 @@
`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds
`elicitation_complete`| An MCP server reports that a [URL-mode elicitation](</docs/en/hooks#elicitation-input>) is complete
`elicitation_response`| An MCP elicitation response is sent back to the server
-`agent_needs_input`| A background session starts waiting on your input while [agent view](</docs/en/agent-view>) is open, or the current session asks you an [agent team teammate’s terminal setup question](</docs/en/agent-teams#choose-a-display-mode>) and you haven’t typed for about six seconds
+`agent_needs_input`| A background session starts waiting on your input while [agent view](</docs/en/agent-view>) is open. Also fires when a terminal session shows you an [agent team teammate’s terminal setup question](</docs/en/agent-teams#choose-a-display-mode>) or auto mode’s notice about [classifier request charges](</docs/en/auto-mode-classifier-billing>) and you haven’t typed for about six seconds
`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
`quota_auto_resume_fired`| Claude Code continues your task after a claude.ai usage limit paused it: at the reset, or sooner when something you do in Claude Code during the wait, such as adding usage credits, upgrading your plan, or switching models, makes usage available again, with the [model-setting exception](</docs/en/interactive-mode#wait-for-a-usage-limit-to-reset>)
`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -778,7 +778,7 @@
Prompt-based hooks
-For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model, Haiku by default, to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON:
+For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON:
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -470,7 +470,7 @@
Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Four other types are available:
* `"type": "http"`: POST event data to a URL. See HTTP hooks.
- * `"type": "mcp_tool"`: call a tool on an already-connected MCP server. See [MCP tool hooks](</docs/en/hooks#mcp-tool-hook-fields>).
+ * `"type": "mcp_tool"`: call a tool on a configured MCP server. See [MCP tool hooks](</docs/en/hooks#mcp-tool-hook-fields>).
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
* `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks.
@@ -877,7 +877,7 @@
Keep these constraints in mind when designing hooks:
- * Command hooks communicate through stdout, stderr, and exit codes only. They can’t trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
+ * Command hooks communicate through stdout, stderr, and exit codes only. They can’t trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a [system reminder](</docs/en/glossary#system-reminder>) that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
* `command`, `http`, `mcp_tool`: 10 minutes. Claude Code lowers this default to 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch` hooks, and to 10 seconds for `MessageDisplay`.
* `prompt`: 30 seconds.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -1,4 +1,4 @@
-Hooks are user-defined shell commands. Claude Code runs them at specific points in its lifecycle, which gives you deterministic control: certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
+Hooks are user-defined shell commands. Claude Code runs them at specific points in its lifecycle, which gives you deterministic control: certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins/overview>) for packaging extensions to share across projects.
This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
@@ -626,7 +626,7 @@
}
}
-The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. On Claude Code v2.1.191 or later, a comma separates alternatives the same way, so `"Edit, Write"` is equivalent. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
+The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. A comma separates alternatives the same way, so `"Edit, Write"` is equivalent. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
Claude can also create or modify files by running shell commands. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash|PowerShell` and have your script list modified and untracked files with `git status --porcelain`. The [PowerShell hook input section](</docs/en/hooks#powershell>) explains why matching `Bash` alone is not enough. To run a hook when a specific file changes on disk, whatever wrote it, use a [FileChanged](</docs/en/hooks#filechanged>) hook.
@@ -766,7 +766,7 @@
`.claude/settings.json`| Single project| Yes, can be committed to the repo
`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
Managed policy settings| Organization-wide| Yes, admin-controlled
-[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
+[Plugin](</docs/en/plugins/overview>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) frontmatter| The rest of the session once the skill is invoked. See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
[Subagent](</docs/en/sub-agents>) frontmatter| While that subagent is running| Yes, defined in the subagent file
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -963,7 +963,12 @@
Hook JSON has no effect
-Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. Check which cause applies:
+
+ * **Extra output before the JSON** : something else writes to stdout first, usually an unconditional `echo` in your shell profile, so the output no longer starts with `{` and Claude Code doesn’t parse it as JSON. The cause and fix follow this list.
+ * **A field at the wrong level** : compare each field’s placement against the [JSON output](</docs/en/hooks#json-output>) format. For example, `permissionDecision` belongs inside `hookSpecificOutput`, not at the top level.
+
+When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
@@ -975,7 +980,7 @@
echo "Shell ready"
fi
-The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.
+The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped. When your hook returns `permissionDecision` or `additionalContext` at the top level instead of inside `hookSpecificOutput`, the JSON still parses, and Claude Code ignores the misplaced fields without reporting an error. To see which fields it ignored, start Claude Code with `claude --debug` and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook JSON output had unrecognized keys`.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -645,7 +645,7 @@
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
-`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -405,7 +405,7 @@
When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it can’t clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
-`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>) or by starting the session in [restricted mode](</docs/en/cli-reference#cli-flags>). It is never persisted as `defaultMode`.
+`bypassPermissions` only applies if you started the session with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in [user, `--settings`, or managed settings](</docs/en/settings-reference#permissions-defaultmode>). It doesn’t apply if bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>), or if you started the session in [restricted mode](</docs/en/cli-reference#cli-flags>).Claude Code never saves it as `defaultMode`.
To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -645,7 +645,7 @@
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
-`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -168,13 +168,13 @@
`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds
`elicitation_complete`| An MCP server reports that a [URL-mode elicitation](</docs/en/hooks#elicitation-input>) is complete
`elicitation_response`| An MCP elicitation response is sent back to the server
-`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
+`agent_needs_input`| A background session starts waiting on your input while [agent view](</docs/en/agent-view>) is open, or the current session asks you an [agent team teammate’s terminal setup question](</docs/en/agent-teams#choose-a-display-mode>) and you haven’t typed for about six seconds
`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
`quota_auto_resume_fired`| Claude Code continues your task after a claude.ai usage limit paused it: at the reset, or sooner when something you do in Claude Code during the wait, such as adding usage credits, upgrading your plan, or switching models, makes usage available again, with the [model-setting exception](</docs/en/interactive-mode#wait-for-a-usage-limit-to-reset>)
`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
-Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -461,6 +461,8 @@
`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
`PreCompact`| Before context compaction
`PostCompact`| After context compaction completes
+`PreModelSwitch`| Before Claude Code applies a model switch that you or a client requested. Can block the switch
+`PostModelSwitch`| After the session’s model changes, including changes Claude Code makes on its own, such as restoring the model when you resume a session
`Elicitation`| When an MCP server requests user input during a tool call
`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
`SessionEnd`| When a session terminates
@@ -557,7 +559,9 @@
The exit code determines what happens next:
- * **Exit 0** : the hook reports no objection through its exit code. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
+ * **Exit 0** : your hook reports no objection through its exit code.
+ * For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies.
+ * For `UserPromptSubmit`, `UserPromptExpansion`, `SessionStart`, and `PostModelSwitch` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
* **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
* A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
@@ -584,13 +588,13 @@
}
}
-With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`:
+With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. On `PreToolUse`, Claude Code handles each `permissionDecision` value as follows:
* `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. A `PreModelSwitch` hook returns the same `permissionDecision` field: `"allow"` lets a model switch proceed, and `"deny"` cancels it. `"ask"` has you confirm the switch when you run `/model` in an interactive session; everywhere else, Claude Code treats `"ask"` as a refusal. See [PreModelSwitch decision control](</docs/en/hooks#premodelswitch-decision-control>). Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
{
"hookSpecificOutput": {
@@ -637,6 +641,7 @@
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
+`PreModelSwitch`, `PostModelSwitch`| canonical name of the model the session switches to, as described under [PreModelSwitch](</docs/en/hooks#premodelswitch>)| `claude-opus-5`, `claude-opus-4-6|claude-opus-5`, `.*opus.*`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
@@ -874,7 +879,7 @@
* Command hooks communicate through stdout, stderr, and exit codes only. They can’t trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
- * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.
+ * `command`, `http`, `mcp_tool`: 10 minutes. Claude Code lowers this default to 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch` hooks, and to 10 seconds for `MessageDisplay`.
* `prompt`: 30 seconds.
* `agent`: 60 seconds.
* [`SessionEnd`](</docs/en/hooks#sessionend>) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -561,7 +561,7 @@
* **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
* A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
- * A parsed object that fails schema validation: a non-blocking error; the notice carries the validation message.
+ * A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: a non-blocking error; the notice carries the validation or parse message.
* Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
####
@@ -745,7 +745,7 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+When Claude Code can’t determine which commands the Bash input runs, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
@@ -920,7 +920,7 @@
* If you see “command not found”, use absolute paths or `${CLAUDE_PROJECT_DIR}` to reference scripts. To avoid shell quoting entirely, add `"args": []` to switch to [exec form](</docs/en/hooks#exec-form-and-shell-form>), which spawns the script directly without a shell
* If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing
- * If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. This happens even on exit 0. The reference’s [Exit code output](</docs/en/hooks#exit-code-0>) section covers the exit-code and JSON combinations
+ * If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. If it shows a JSON parse message, the stdout looked like a JSON object but wasn’t valid JSON. Both happen even on exit 0. To fix a parse failure, build the payload with a JSON encoder such as `jq` instead of string concatenation, so quotes and backslashes inside values are escaped. The reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section covers the exit-code and JSON combinations
* If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
###
@@ -983,7 +983,7 @@
* **Successful run** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback.
* To confirm a hook ran, check for its effect, like a reformatted file, or turn on debug logging as described below and trigger the hook again
* **Blocking error** : on most events you see the hook’s feedback. When the hook’s JSON made a blocking decision, the feedback is the reason from that decision; otherwise it is the hook’s stderr. On a few events, such as `ConfigChange` and `Elicitation`, a block surfaces no message.
- * **Non-blocking error** : the action proceeded, and you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr prefixed with `Failed with non-blocking status code:` or a JSON validation message.
+ * **Non-blocking error** : the action proceeded, and you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr prefixed with `Failed with non-blocking status code:`, or a JSON validation or parse message.
Which exit-code and JSON combinations produce each outcome, including the per-event exceptions, is defined in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -166,7 +166,7 @@
`auth_success`| Authentication completes
`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about six seconds
`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds
-`elicitation_complete`| An MCP elicitation form is submitted or dismissed
+`elicitation_complete`| An MCP server reports that a [URL-mode elicitation](</docs/en/hooks#elicitation-input>) is complete
`elicitation_response`| An MCP elicitation response is sent back to the server
`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
@@ -405,7 +405,7 @@
When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it can’t clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
-`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). It is never persisted as `defaultMode`.
+`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>) or by starting the session in [restricted mode](</docs/en/cli-reference#cli-flags>). It is never persisted as `defaultMode`.
To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
@@ -558,7 +558,7 @@
The exit code determines what happens next:
* **Exit 0** : the hook reports no objection through its exit code. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
- * **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart`, `Setup`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
* A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
* A parsed object that fails schema validation: a non-blocking error; the notice carries the validation message.
@@ -586,7 +586,7 @@
With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`:
- * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
+ * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
@@ -891,7 +891,7 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) or MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -161,7 +161,7 @@
Matcher| Fires when
---|---
-`permission_prompt`| Claude needs you to approve a tool use and the prompt has waited about six seconds
+`permission_prompt`| Claude needs you to approve a tool use or a sandboxed command’s [network request](</docs/en/sandboxing#network-isolation>), and the prompt has waited about six seconds
`idle_prompt`| Claude finished responding about 60 seconds ago and you haven’t typed since
`auth_success`| Authentication completes
`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about six seconds
@@ -174,7 +174,7 @@
`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
-Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
@@ -421,7 +421,7 @@
}
}
-Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields.
+Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every tool permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -170,8 +170,11 @@
`elicitation_response`| An MCP elicitation response is sent back to the server
`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
-
-Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+`quota_auto_resume_fired`| Claude Code continues your task after a claude.ai usage limit paused it: at the reset, or sooner when something you do in Claude Code during the wait, such as adding usage credits, upgrading your plan, or switching models, makes usage available again, with the [model-setting exception](</docs/en/interactive-mode#wait-for-a-usage-limit-to-reset>)
+`quota_auto_resume_stale`| A claude.ai usage limit reset while your computer slept for more than about 30 minutes. Claude Code waits for you to press `Enter` instead of continuing. After a shorter sleep it continues and fires `quota_auto_resume_fired` instead
+`quota_auto_resume_disabled`| Claude Code ends its wait for a claude.ai usage limit without continuing your task: [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) turned off or the reset moved more than 24 hours away during a wait Claude Code started on its own, the continued task kept hitting the limit, or the continuation was blocked before it reached the model. Doesn’t fire when you press `Esc` or `Ctrl+C`, or pick **Don’t continue automatically**
+
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
@@ -631,7 +634,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`, `quota_auto_resume_fired`, `quota_auto_resume_stale`, `quota_auto_resume_disabled`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
@@ -762,7 +765,7 @@
[Skill](</docs/en/skills>) frontmatter| The rest of the session once the skill is invoked. See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
[Subagent](</docs/en/sub-agents>) frontmatter| While that subagent is running| Yes, defined in the subagent file
-Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -197,7 +197,7 @@
}
}
-To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques.
+To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques. To reformat a specific file however it changes, including when a `Bash` command rewrites it, use a [FileChanged](</docs/en/hooks#filechanged>) hook instead.
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
@@ -621,7 +621,7 @@
The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. On Claude Code v2.1.191 or later, a comma separates alternatives the same way, so `"Edit, Write"` is equivalent. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
-Claude can also create or modify files by running shell commands. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash|PowerShell` and have your script list modified and untracked files with `git status --porcelain`. The [PowerShell hook input section](</docs/en/hooks#powershell>) explains why matching `Bash` alone is not enough.
+Claude can also create or modify files by running shell commands. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash|PowerShell` and have your script list modified and untracked files with `git status --porcelain`. The [PowerShell hook input section](</docs/en/hooks#powershell>) explains why matching `Bash` alone is not enough. To run a hook when a specific file changes on disk, whatever wrote it, use a [FileChanged](</docs/en/hooks#filechanged>) hook.
Each event type matches on a specific field:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -630,7 +630,7 @@
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
-`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
+`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -161,17 +161,17 @@
Matcher| Fires when
---|---
-`permission_prompt`| Claude needs you to approve a tool use and you haven’t typed for about 6 seconds
+`permission_prompt`| Claude needs you to approve a tool use and the prompt has waited about six seconds
`idle_prompt`| Claude finished responding about 60 seconds ago and you haven’t typed since
`auth_success`| Authentication completes
-`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about 6 seconds
-`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about 6 seconds
+`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about six seconds
+`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds
`elicitation_complete`| An MCP elicitation form is submitted or dismissed
`elicitation_response`| An MCP elicitation response is sent back to the server
`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
-The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -63,7 +63,7 @@
Test the hook
-Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
+Press `Esc` to return to the CLI. Press `Shift+Tab` until the status bar shows `⏸ manual mode on`, ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
The `/hooks` menu is read-only. To add, modify, or remove hooks, edit your settings JSON directly or ask Claude to make the change.
@@ -277,7 +277,7 @@
Re-inject context after compaction
-When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Any text your command writes to stdout is added to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:
+When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Claude Code adds plain text your command writes to stdout to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:
{
"hooks": {
@@ -554,12 +554,12 @@
The exit code determines what happens next:
- * **Exit 0** : the hook reports no objection through its exit code. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
+ * **Exit 0** : the hook reports no objection through its exit code. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context.
* **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart`, `Setup`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
- * JSON that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
- * JSON that parses but fails schema validation: a non-blocking error; the notice carries the validation message.
- * No JSON on stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
+ * A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
+ * A parsed object that fails schema validation: a non-blocking error; the notice carries the validation message.
+ * Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
####
@@ -759,7 +759,8 @@
`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
-[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
+[Skill](</docs/en/skills>) frontmatter| The rest of the session once the skill is invoked. See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>)| Yes, defined in the skill file
+[Subagent](</docs/en/sub-agents>) frontmatter| While that subagent is running| Yes, defined in the subagent file
Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
@@ -769,16 +770,16 @@
Prompt-based hooks
-For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model, Haiku by default, to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
+For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model, Haiku by default, to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON:
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
- * `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working
+ * `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working, unless the response also sets `"impossible": true` to mark the condition as one that can never be satisfied, in which case Claude Code allows the stop and the turn ends
* `PreToolUse`: the tool call is denied; by default the turn ends and the deny `reason` appears in the chat as a warning line. Set `continueOnBlock: true` on the hook to instead return the `reason` to Claude as the tool error, so it can adjust and continue. Before v2.1.210, the deny `reason` was returned to Claude as the tool error and the turn continued
* `PostToolUse`: by default the turn ends and the `reason` appears in the chat as a warning line. Set `continueOnBlock: true` to feed the `reason` back to Claude and continue the turn instead
* `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line
-This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
+This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false` because the condition isn’t met yet, Claude keeps working and uses the `reason` as its next instruction:
{
"hooks": {
@@ -805,7 +806,7 @@
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
-When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. The `$ARGUMENTS` placeholder in the prompt is replaced with the hook’s JSON input. See [prompt and agent hook fields](</docs/en/hooks#prompt-and-agent-hook-fields>). This example verifies that tests pass before allowing Claude to stop:
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the `"ok"` / `"reason"` response format with a longer default timeout of 60 seconds and up to 50 tool-use turns. They don’t support the prompt-hook `impossible` field. On `ok: false`, Claude Code handles an agent hook the way it handles a prompt hook with `continueOnBlock: true` on the same event, so on `PreToolUse` and `PostToolUse` the turn continues; agent hooks have no `continueOnBlock` field. See [agent hook configuration](</docs/en/hooks#agent-hook-configuration>) for the fields, including the `$ARGUMENTS` placeholder that Claude Code replaces with the hook’s JSON input. This example verifies that tests pass before allowing Claude to stop:
{
"hooks": {
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -761,7 +761,7 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
-Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
##
@@ -899,8 +899,7 @@
* Run `/hooks` and confirm the hook appears under the correct event
* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
- * Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after
- * In non-interactive mode with the `-p` flag, `PermissionRequest` hooks fire only when the Agent SDK’s `canUseTool` callback supplies the prompt, or for tool calls inside background subagents. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks instead
+ * Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission; see the limitations for the non-interactive cases
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -707,8 +707,6 @@
}
}
-For full matcher syntax, see the [Hooks reference](</docs/en/hooks#configuration>).
-
####
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -436,7 +436,7 @@
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a tool call needs a permission decision
-`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
+`PermissionDenied`| When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
@@ -447,7 +447,7 @@
`TaskCreated`| When a task is being created via `TaskCreate`
`TaskCompleted`| When a task is being marked as completed
`Stop`| When Claude finishes responding
-`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
+`StopFailure`| When the turn ends due to an API error
`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
@@ -554,11 +554,12 @@
The exit code determines what happens next:
- * **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
- * **Exit 2** : Claude Code blocks the action. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
- * **Any other exit code** : the action proceeds
- * The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`
- * To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session
+ * **Exit 0** : the hook reports no objection through its exit code. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
+ * **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart`, `Setup`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout:
+ * JSON that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section.
+ * JSON that parses but fails schema validation: a non-blocking error; the notice carries the validation message.
+ * No JSON on stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session.
####
@@ -568,7 +569,7 @@
Exit codes only let you block or stay silent. For more control, exit 0 and print a JSON object to stdout instead.
-Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don’t mix them: Claude Code ignores JSON when you exit 2.
+Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Choose one approach per hook. For what happens when you mix them, see [Exit code output](</docs/en/hooks#exit-code-output>).
For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:
@@ -918,6 +919,7 @@
* If you see “command not found”, use absolute paths or `${CLAUDE_PROJECT_DIR}` to reference scripts. To avoid shell quoting entirely, add `"args": []` to switch to [exec form](</docs/en/hooks#exec-form-and-shell-form>), which spawns the script directly without a shell
* If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing
+ * If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. This happens even on exit 0. The reference’s [Exit code output](</docs/en/hooks#exit-code-0>) section covers the exit-code and JSON combinations
* If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
###
@@ -953,14 +955,14 @@
-JSON validation failed
-
-Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+Hook JSON has no effect
+
+Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
-Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells:
+The combined output no longer starts with `{`, so Claude Code treats all of stdout as plain text and ignores the JSON. On exit 0 nothing is reported in the transcript; the parse attempt is recorded only in the [debug log](</docs/en/hooks#debug-hooks>). To fix this, wrap echo statements in your shell profile so they only run in interactive shells:
# In ~/.zshrc or ~/.bashrc
if [[ $- == *i* ]]; then
@@ -977,12 +979,12 @@
Press `Ctrl+O` to open the transcript view to check the outcome of a hook run:
- * After a successful run, where the hook exited 0, you see nothing
+ * **Successful run** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback.
* To confirm a hook ran, check for its effect, like a reformatted file, or turn on debug logging as described below and trigger the hook again
- * After a blocking error, where the hook exited 2 and Claude Code stopped the action, you see the hook’s stderr
- * After a non-blocking error, where the hook exited with any other code and the action proceeded, you see a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`
-
-For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+ * **Blocking error** : on most events you see the hook’s feedback. When the hook’s JSON made a blocking decision, the feedback is the reason from that decision; otherwise it is the hook’s stderr. On a few events, such as `ConfigChange` and `Elicitation`, a block surfaces no message.
+ * **Non-blocking error** : the action proceeded, and you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr prefixed with `Failed with non-blocking status code:` or a JSON validation message.
+
+Which exit-code and JSON combinations produce each outcome, including the per-event exceptions, is defined in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -81,7 +81,7 @@
Get notified when Claude needs input
-Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
+Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
* macOS
@@ -161,10 +161,11 @@
Matcher| Fires when
---|---
-`permission_prompt`| Claude needs you to approve a tool use
-`idle_prompt`| Claude is done and waiting for your next prompt
+`permission_prompt`| Claude needs you to approve a tool use and you haven’t typed for about 6 seconds
+`idle_prompt`| Claude finished responding about 60 seconds ago and you haven’t typed since
`auth_success`| Authentication completes
-`elicitation_dialog`| An MCP server opens an elicitation form
+`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about 6 seconds
+`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about 6 seconds
`elicitation_complete`| An MCP elicitation form is submitted or dismissed
`elicitation_response`| An MCP elicitation response is sent back to the server
`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
@@ -629,7 +630,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -634,6 +634,7 @@
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
+`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root`
`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -196,7 +196,7 @@
}
}
-To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques.
+To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques.
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
@@ -585,7 +585,7 @@
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but doesn’t override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted, and so are connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
{
"hookSpecificOutput": {
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -219,6 +219,9 @@
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
+
+ # Normalize Windows backslash separators so the patterns below match
+ FILE_PATH="${FILE_PATH//\\//}"
PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -422,7 +422,7 @@
How hooks work
-Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs all matching hooks in parallel and deduplicates identical hook commands automatically. The table below shows each event and when it triggers:
+Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs all matching hooks in parallel; see [Hook handler fields](</docs/en/hooks#hook-handler-fields>) for how duplicate handlers are treated. The table below shows each event and when it triggers:
Event| When it fires
---|---
@@ -616,7 +616,7 @@
The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. On Claude Code v2.1.191 or later, a comma separates alternatives the same way, so `"Edit, Write"` is equivalent. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
-Claude can also create or modify files by running shell commands through the `Bash` tool. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash` and have your script list modified and untracked files with `git status --porcelain`.
+Claude can also create or modify files by running shell commands. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash|PowerShell` and have your script list modified and untracked files with `git status --porcelain`. The [PowerShell hook input section](</docs/en/hooks#powershell>) explains why matching `Bash` alone is not enough.
Each event type matches on a specific field:
@@ -950,7 +950,7 @@
JSON validation failed
-Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -129,6 +129,14 @@
}
}
+If no notification appears
+
+`notify-send` needs a desktop notification daemon, which headless servers, SSH sessions, and most containers don’t have. Test the command directly first:
+
+ notify-send 'Claude Code' 'test'
+
+If the command isn’t found, install the `libnotify-bin` package on Debian and Ubuntu, or your distribution’s equivalent.
+
{
"hooks": {
"Notification": [
@@ -144,6 +152,10 @@
]
}
}
+
+If no dialog appears
+
+This command opens a dialog box rather than a notification in the corner of your screen, so the dialog can open behind your terminal window. Test the command directly in PowerShell first. If you run Claude Code inside WSL, `powershell.exe` must be available on your `PATH` through Windows interop.
The empty `matcher` fires on all notification types. To fire only on specific events, set it to one of these values:
@@ -184,7 +196,7 @@
}
}
-To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
+To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques.
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
@@ -540,7 +552,9 @@
* **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
* **Exit 2** : Claude Code blocks the action. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
- * **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
+ * **Any other exit code** : the action proceeds
+ * The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`
+ * To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session
####
@@ -956,7 +970,14 @@
Debug techniques
-The transcript view, toggled with `Ctrl+O`, shows a one-line summary for each hook that fired: success is silent, blocking errors show stderr, and non-blocking errors show a `<hook name> hook error` notice followed by the first line of stderr. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+Press `Ctrl+O` to open the transcript view to check the outcome of a hook run:
+
+ * After a successful run, where the hook exited 0, you see nothing
+ * To confirm a hook ran, check for its effect, like a reformatted file, or turn on debug logging as described below and trigger the hook again
+ * After a blocking error, where the hook exited 2 and Claude Code stopped the action, you see the hook’s stderr
+ * After a non-blocking error, where the hook exited with any other code and the action proceeded, you see a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`
+
+For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -436,6 +436,7 @@
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
+`DirectoryAdded`| When a working directory is added mid-session via `/add-dir` or the SDK `register_repo_root` control request
`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
@@ -496,15 +497,21 @@
Hook input
-Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin:
-
- {
- "session_id": "abc123", // unique ID for this session
- "cwd": "/Users/sarah/myproject", // working directory when the event fired
- "hook_event_name": "PreToolUse", // which event triggered this hook
- "tool_name": "Bash", // the tool Claude is about to use
- "tool_input": { // the arguments Claude passed to the tool
- "command": "npm test" // for Bash, this is the shell command
+Every event includes common fields like `session_id`, a unique ID for the session, and `cwd`, the working directory when the event fired, but each event type adds different data. When Claude runs a Bash command, a `PreToolUse` hook receives these fields on stdin:
+
+ * `hook_event_name`: the event that triggered the hook
+ * `tool_name`: the tool Claude is about to use
+ * `tool_input`: the arguments Claude passed to the tool. For Bash, its `command` field holds the shell command.
+
+For example, the hook input for an `npm test` command looks like this:
+
+ {
+ "session_id": "abc123",
+ "cwd": "/Users/sarah/myproject",
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "npm test"
}
}
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -1,4 +1,4 @@
-Hooks are user-defined shell commands that execute at specific points in Claude Code’s lifecycle. They provide deterministic control over Claude Code’s behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
+Hooks are user-defined shell commands. Claude Code runs them at specific points in its lifecycle, which gives you deterministic control: certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
@@ -81,7 +81,7 @@
Get notified when Claude needs input
-Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
+Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
* macOS
@@ -366,7 +366,7 @@
Auto-approve specific permission prompts
-Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission, and returning `"behavior": "allow"` answers the request on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
+Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. Claude Code runs `PermissionRequest` hooks when it’s about to ask you for permission, and if your hook returns `"behavior": "allow"`, Claude Code answers the request on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -410,7 +410,7 @@
How hooks work
-Hook events fire at specific lifecycle points in Claude Code. When an event fires, all matching hooks run in parallel, and identical hook commands are automatically deduplicated. The table below shows each event and when it triggers:
+Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs all matching hooks in parallel and deduplicates identical hook commands automatically. The table below shows each event and when it triggers:
Event| When it fires
---|---
@@ -532,7 +532,7 @@
The exit code determines what happens next:
* **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
- * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Exit 2** : Claude Code blocks the action. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -184,7 +184,7 @@
}
}
-On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
+To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
@@ -249,6 +249,12 @@
}
}
+4
+
+Test the hook
+
+Ask Claude to add a comment to your `.env` file. Claude Code blocks the edit before it runs and passes the script’s `Blocked:` message to Claude as feedback.
+
###
@@ -299,7 +305,7 @@
}
}
-The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema.
+The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema. To confirm the hook records changes, edit a settings file in another editor while a session is running, then open `~/claude-config-audit.log`: the hook appends one JSON line per change with the timestamp, source, and file path.
###
@@ -360,7 +366,7 @@
Auto-approve specific permission prompts
-Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
+Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission, and returning `"behavior": "allow"` answers the request on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -413,7 +419,7 @@
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
-`PermissionRequest`| When a permission dialog appears
+`PermissionRequest`| When a tool call needs a permission decision
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
@@ -725,7 +731,7 @@
---|---|---
`~/.claude/settings.json`| All your projects| No, local to your machine
`.claude/settings.json`| Single project| Yes, can be committed to the repo
-`.claude/settings.local.json`| Single project| No, gitignored when Claude Code creates it
+`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
@@ -842,8 +848,11 @@
* `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.
* `prompt`: 30 seconds.
* `agent`: 60 seconds.
+ * [`SessionEnd`](</docs/en/hooks#sessionend>) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.
* `PostToolUse` hooks can’t undo actions since the tool has already executed.
- * `PermissionRequest` hooks don’t fire in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Use `PreToolUse` hooks for automated permission decisions.
+ * `PermissionRequest` hooks fire when Claude Code is about to ask you for permission.
+ * In [non-interactive mode](</docs/en/headless>) with the `-p` flag, that prompt only exists when the Agent SDK’s [`canUseTool` callback](</docs/en/agent-sdk/permissions>) supplies it. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks for automated permission decisions instead.
+ * Background subagents can’t show a prompt in non-interactive mode. Claude Code still runs the hooks for their tool calls, and if no hook returns a decision, it denies the call. In an interactive session, background subagent prompts surface in your main session and the hooks fire as usual.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
* When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
@@ -866,7 +875,7 @@
* Run `/hooks` and confirm the hook appears under the correct event
* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
* Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after
- * If using `PermissionRequest` hooks in non-interactive mode with the `-p` flag, switch to `PreToolUse` instead
+ * In non-interactive mode with the `-p` flag, `PermissionRequest` hooks fire only when the Agent SDK’s `canUseTool` callback supplies the prompt, or for tool calls inside background subagents. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks instead
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -743,8 +743,9 @@
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
* `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working
- * `PreToolUse`: the tool call is denied and the `reason` is returned to Claude as the tool error, so it can adjust and continue
- * `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line
+ * `PreToolUse`: the tool call is denied; by default the turn ends and the deny `reason` appears in the chat as a warning line. Set `continueOnBlock: true` on the hook to instead return the `reason` to Claude as the tool error, so it can adjust and continue. Before v2.1.210, the deny `reason` was returned to Claude as the tool error and the turn continued
+ * `PostToolUse`: by default the turn ends and the `reason` appears in the chat as a warning line. Set `continueOnBlock: true` to feed the `reason` back to Claude and continue the turn instead
+ * `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line
This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -431,8 +431,8 @@
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
-`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
-`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
+`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior
+`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session
`PreCompact`| Before context compaction
`PostCompact`| After context compaction completes
`Elicitation`| When an MCP server requests user input during a tool call
@@ -502,7 +502,7 @@
}
}
-Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, or `compact`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
+Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, `compact`, or `fork`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
####
@@ -596,7 +596,7 @@
Event| What the matcher filters| Example matcher values
---|---|---
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
-`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -14,7 +14,7 @@
Add the hook to your settings
-Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see Get notified when Claude needs input for Linux and Windows commands.
+Open `~/.claude/settings.json` and add a `Notification` hook. If the file doesn’t exist, create it. The example below uses `osascript` for macOS; see Get notified when Claude needs input for Linux and Windows commands.
{
"hooks": {
@@ -773,7 +773,7 @@
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
-When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. The `$ARGUMENTS` placeholder in the prompt is replaced with the hook’s JSON input. See [prompt and agent hook fields](</docs/en/hooks#prompt-and-agent-hook-fields>). This example verifies that tests pass before allowing Claude to stop:
{
"hooks": {
@@ -852,7 +852,7 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) or MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) or MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -166,7 +166,7 @@
Auto-format code after edits
-Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
+Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.org/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
{
"hooks": {
@@ -186,7 +186,7 @@
On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
-The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
+The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -551,11 +551,20 @@
With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`:
- * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply
+ * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>)
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but doesn’t override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks.
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but doesn’t override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted, and so are connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `hookSpecificOutput.additionalContext` instead to inject text into Claude’s context. Nest `additionalContext` inside `hookSpecificOutput`; if you place it at the top level of the JSON, Claude Code silently ignores it. For example, this output adds the current branch state to every prompt:
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": "Current branch: release-42. Deploy freeze until Friday."
+ }
+ }
+
+See [UserPromptSubmit decision control](</docs/en/hooks#userpromptsubmit-decision-control>) for the full output shape, including blocking prompts and setting the session title. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks.
###
@@ -578,7 +587,7 @@
}
}
-The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
+The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. On Claude Code v2.1.191 or later, a comma separates alternatives the same way, so `"Edit, Write"` is equivalent. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
Claude can also create or modify files by running shell commands through the `Bash` tool. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash` and have your script list modified and untracked files with `git status --porcelain`.
@@ -843,7 +852,7 @@
Hooks and permission modes
-`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings, and it can’t suppress the prompt for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) or MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -673,8 +673,6 @@
Filter by tool name and arguments with the `if` field
-The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
-
The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
{
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -629,7 +629,7 @@
}
}
-MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr. Writing to stderr keeps stdout clean for JSON output and sends the message to the [debug log](</docs/en/hooks#debug-hooks>):
+MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Tools from a [plugin-bundled server](</docs/en/mcp#plugin-provided-mcp-servers>) use a scoped server segment instead, such as `mcp__plugin_my-plugin_db__query`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr. Writing to stderr keeps stdout clean for JSON output and sends the message to the [debug log](</docs/en/hooks#debug-hooks>):
{
"hooks": {
Show diff (306 lines)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -73,17 +73,7 @@
What you can automate
-Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. The most common patterns:
-
- * Get notified when Claude needs input
- * Auto-format code after edits
- * Block edits to protected files
- * Re-inject context after compaction
- * Audit configuration changes
- * Reload environment when directory or files change
- * Auto-approve specific permission prompts
-
-For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
+Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
###
@@ -165,8 +155,10 @@
`elicitation_dialog`| An MCP server opens an elicitation form
`elicitation_complete`| An MCP elicitation form is submitted or dismissed
`elicitation_response`| An MCP elicitation response is sent back to the server
-
-Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
+`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
+
+The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
@@ -174,7 +166,7 @@
Auto-format code after edits
-Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
+Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
{
"hooks": {
@@ -192,7 +184,9 @@
}
}
-The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
+On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
+
+The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
###
@@ -227,7 +221,7 @@
2
-Make the script executable (macOS/Linux)
+Make the script executable on macOS and Linux
Hook scripts must be executable for Claude Code to run them:
@@ -313,7 +307,7 @@
Reload environment when directory or files change
-Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
+Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool doesn’t pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -340,7 +334,7 @@
}
}
-Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`. To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
+Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`. To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. When building the watch list, Claude Code splits this value into literal filenames rather than evaluating it as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
{
"hooks": {
@@ -384,7 +378,7 @@
}
}
-When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
+When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it can’t clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). It is never persisted as `defaultMode`.
@@ -458,7 +452,7 @@
Combine results from multiple hooks
-When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` does not stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer wins, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
+When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` doesn’t stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer applies, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
{
"hooks": {
@@ -480,7 +474,7 @@
}
}
-When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny wins, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
+When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny takes precedence, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
###
@@ -508,7 +502,7 @@
}
}
-Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, clear, compact), and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
+Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, or `compact`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
####
@@ -516,7 +510,7 @@
Hook output
-Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:
+Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. The following `PreToolUse` hook blocks a command:
#!/bin/bash
INPUT=$(cat)
@@ -532,7 +526,7 @@
The exit code determines what happens next:
* **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
- * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events cannot be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
@@ -561,7 +555,7 @@
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but does not override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Prompt-based hooks (`type: "prompt"`) handle output differently: see Prompt-based hooks.
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but doesn’t override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks.
###
@@ -569,7 +563,7 @@
Filter hooks with matchers
-Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:
+Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits, not after every tool call, add a matcher to your `PostToolUse` hook:
{
"hooks": {
@@ -596,7 +590,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
@@ -609,7 +603,7 @@
`UserPromptExpansion`| command name| your skill or command names
`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `MessageDisplay`| no matcher support| always fires on every occurrence
-A few more examples showing matchers on different event types:
+The tabs below show a few more matchers on different event types.
* Log every Bash command
@@ -617,7 +611,7 @@
* Clean up on session end
-Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:
+Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts only the command string, which `>>` appends to the log file:
{
"hooks": {
@@ -653,7 +647,7 @@
}
}
-The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:
+The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on the `clear` reason, set when you run `/clear`, not on normal exits:
{
"hooks": {
@@ -681,7 +675,7 @@
The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
{
"hooks": {
@@ -710,7 +704,7 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
@@ -737,7 +731,7 @@
Prompt-based hooks
-For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
+For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model, Haiku by default, to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
@@ -772,7 +766,7 @@
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
-When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
{
"hooks": {
@@ -819,7 +813,7 @@
}
}
-The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone cannot block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
+The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone can’t block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
##
@@ -833,15 +827,17 @@
Limitations
- * Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
+Keep these constraints in mind when designing hooks:
+
+ * Command hooks communicate through stdout, stderr, and exit codes only. They can’t trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
* `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.
* `prompt`: 30 seconds.
* `agent`: 60 seconds.
- * `PostToolUse` hooks cannot undo actions since the tool has already executed.
- * `PermissionRequest` hooks do not fire in [non-interactive mode](</docs/en/headless>) (`-p`). Use `PreToolUse` hooks for automated permission decisions.
- * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
- * When multiple PreToolUse hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish wins. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
+ * `PostToolUse` hooks can’t undo actions since the tool has already executed.
+ * `PermissionRequest` hooks don’t fire in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Use `PreToolUse` hooks for automated permission decisions.
+ * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
+ * When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
###
@@ -849,7 +845,7 @@
Hooks and permission modes
-PreToolUse hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users cannot bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` does not bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
@@ -860,9 +856,9 @@
The hook is configured but never executes.
* Run `/hooks` and confirm the hook appears under the correct event
- * Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)
- * Verify you’re triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)
- * If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead
+ * Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
+ * Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after
+ * If using `PermissionRequest` hooks in non-interactive mode with the `-p` flag, switch to `PreToolUse` instead
###
@@ -890,7 +886,7 @@
You edited a settings file but the hooks don’t appear in the menu.
* File edits are normally picked up automatically. If they haven’t appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.
- * Verify your JSON is valid (trailing commas and comments are not allowed)
+ * Verify your JSON is valid: trailing commas and comments aren’t allowed
* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks
###
@@ -899,7 +895,7 @@
Stop hook hits the block cap
-Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks 8 times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
+Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
#!/bin/bash
INPUT=$(cat)
@@ -916,7 +912,7 @@
JSON validation failed
-Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook (one without `args`), it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations (such as `BASH_ENV` pointing at `~/.bashrc`) still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -174,7 +174,7 @@
Auto-format code after edits
-Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
+Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
{
"hooks": {
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -458,7 +458,7 @@
Combine results from multiple hooks
-When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` does not stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer wins: `deny` overrides `ask`, which overrides `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
+When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` does not stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer wins, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
{
"hooks": {
@@ -708,7 +708,7 @@
`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches
`Bash(git *)`| `echo $(git log)`| yes| commands inside `$()` and backticks are checked; `git log` matches
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
-`Bash(git push *)`| `echo $(date)`| yes| patterns that constrain past the command name fail open on `$()`, backticks, or `$VAR`
+`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
@@ -724,12 +724,12 @@
---|---|---
`~/.claude/settings.json`| All your projects| No, local to your machine
`.claude/settings.json`| Single project| Yes, can be committed to the repo
-`.claude/settings.local.json`| Single project| No, gitignored
+`.claude/settings.local.json`| Single project| No, gitignored when Claude Code creates it
Managed policy settings| Organization-wide| Yes, admin-controlled
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
-Run [`/hooks`](</docs/en/hooks#the-hooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -681,7 +681,7 @@
The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches, or when a Bash command is too complex to parse. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
{
"hooks": {
@@ -700,7 +700,17 @@
}
}
-The hook process only spawns when a subcommand of the Bash command matches `git *`, or when the command is too complex to parse into subcommands. For compound commands like `npm test && git push`, Claude Code evaluates each subcommand and fires the hook because `git push` matches. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+Whether your hook command runs depends on the shape of your `if` pattern and the Bash command Claude is invoking:
+
+`if` pattern| Bash command| Hook runs?| Why
+---|---|---|---
+`Bash(git *)`| `git push`| yes| command name matches
+`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches
+`Bash(git *)`| `echo $(git log)`| yes| commands inside `$()` and backticks are checked; `git log` matches
+`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
+`Bash(git push *)`| `echo $(date)`| yes| patterns that constrain past the command name fail open on `$()`, backticks, or `$VAR`
+
+The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
Hooks are user-defined shell commands that execute at specific points in Claude Code’s lifecycle. They provide deterministic control over Claude Code’s behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
@@ -607,7 +601,7 @@
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -831,7 +831,7 @@
* Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
- * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds.
+ * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.
* `prompt`: 30 seconds.
* `agent`: 60 seconds.
* `PostToolUse` hooks cannot undo actions since the tool has already executed.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -88,6 +88,8 @@
* Audit configuration changes
* Reload environment when directory or files change
* Auto-approve specific permission prompts
+
+For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
###
@@ -429,6 +431,7 @@
`PostToolUseFailure`| After a tool call fails
`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
`Notification`| When Claude Code sends a notification
+`MessageDisplay`| While assistant message text is displayed
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
`TaskCreated`| When a task is being created via `TaskCreate`
@@ -610,7 +613,7 @@
`ElicitationResult`| MCP server name| same values as `Elicitation`
`FileChanged`| literal filenames to watch (see [FileChanged](</docs/en/hooks#filechanged>))| `.envrc|.env`
`UserPromptExpansion`| command name| your skill or command names
-`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `MessageDisplay`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -530,11 +530,11 @@
exit 2 # exit 2 = block the action
fi
- exit 0 # exit 0 = let it proceed
+ exit 0 # exit 0 = no decision; the normal permission flow applies
The exit code determines what happens next:
- * **Exit 0** : the action proceeds. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
+ * **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
* **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events cannot be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
@@ -544,7 +544,7 @@
Structured JSON output
-Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.
+Exit codes only let you block or stay silent. For more control, exit 0 and print a JSON object to stdout instead.
Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don’t mix them: Claude Code ignores JSON when you exit 2.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -604,7 +604,7 @@
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -890,9 +890,9 @@
-Stop hook runs forever
-
-Claude keeps working in an infinite loop instead of stopping. Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
+Stop hook hits the block cap
+
+Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks 8 times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
#!/bin/bash
INPUT=$(cat)
@@ -901,6 +901,8 @@
fi
# ... rest of your hook logic
+If your hook legitimately needs more than eight iterations to converge, raise the cap with [`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`](</docs/en/env-vars>).
+
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -827,7 +827,10 @@
Limitations
* Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
- * Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).
+ * Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
+ * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds.
+ * `prompt`: 30 seconds.
+ * `agent`: 60 seconds.
* `PostToolUse` hooks cannot undo actions since the tool has already executed.
* `PermissionRequest` hooks do not fire in [non-interactive mode](</docs/en/headless>) (`-p`). Use `PreToolUse` hooks for automated permission decisions.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -722,7 +722,7 @@
[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
-Run [`/hooks`](</docs/en/hooks#the-hooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable all hooks at once, set `"disableAllHooks": true` in your settings file. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+Run [`/hooks`](</docs/en/hooks#the-hooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -867,7 +867,7 @@
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh
echo $? # Check the exit code
- * If you see “command not found”, use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts
+ * If you see “command not found”, use absolute paths or `${CLAUDE_PROJECT_DIR}` to reference scripts. To avoid shell quoting entirely, add `"args": []` to switch to [exec form](</docs/en/hooks#exec-form-and-shell-form>), which spawns the script directly without a shell
* If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing
* If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
@@ -904,7 +904,7 @@
JSON validation failed
-Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook’s JSON:
+Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook (one without `args`), it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations (such as `BASH_ENV` pointing at `~/.bashrc`) still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -448,12 +448,42 @@
`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
`SessionEnd`| When a session terminates
-When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Four other types are available:
+Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Four other types are available:
* `"type": "http"`: POST event data to a URL. See HTTP hooks.
* `"type": "mcp_tool"`: call a tool on an already-connected MCP server. See [MCP tool hooks](</docs/en/hooks#mcp-tool-hook-fields>).
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
* `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks.
+
+###
+
+
+
+Combine results from multiple hooks
+
+When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` does not stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer wins: `deny` overrides `ask`, which overrides `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -r .tool_input.command >> ~/.claude/bash.log"
+ },
+ {
+ "type": "command",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm-rf.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny wins, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -703,7 +703,10 @@
For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
* `"ok": true`: the action proceeds
- * `"ok": false`: the action is blocked. For `Stop` and `SubagentStop` hooks, the `reason` is fed back to Claude so it keeps working. For other events, the turn ends and the `reason` appears in the chat as a warning line. Claude does not see it.
+ * `"ok": false`: what happens depends on the event:
+ * `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working
+ * `PreToolUse`: the tool call is denied and the `reason` is returned to Claude as the tool error, so it can adjust and continue
+ * `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line
This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -703,7 +703,7 @@
For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
* `"ok": true`: the action proceeds
- * `"ok": false`: the action is blocked. The model’s `"reason"` is fed back to Claude so it can adjust.
+ * `"ok": false`: the action is blocked. For `Stop` and `SubagentStop` hooks, the `reason` is fed back to Claude so it keeps working. For other events, the turn ends and the `reason` appears in the chat as a warning line. Claude does not see it.
This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -158,6 +158,19 @@
]
}
}
+
+The empty `matcher` fires on all notification types. To fire only on specific events, set it to one of these values:
+
+Matcher| Fires when
+---|---
+`permission_prompt`| Claude needs you to approve a tool use
+`idle_prompt`| Claude is done and waiting for your next prompt
+`auth_success`| Authentication completes
+`elicitation_dialog`| An MCP server opens an elicitation form
+`elicitation_complete`| An MCP elicitation form is submitted or dismissed
+`elicitation_response`| An MCP elicitation response is sent back to the server
+
+Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -561,7 +561,7 @@
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
-`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
Hooks are user-defined shell commands that execute at specific points in Claude Code’s lifecycle. They provide deterministic control over Claude Code’s behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
@@ -400,6 +406,7 @@
Event| When it fires
---|---
`SessionStart`| When a session begins or resumes
+`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
@@ -485,7 +492,7 @@
The exit code determines what happens next:
* **Exit 0** : the action proceeds. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
- * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.
+ * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events cannot be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
@@ -537,15 +544,20 @@
}
}
-The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated. Each event type matches on a specific field:
+The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated.
+
+Claude can also create or modify files by running shell commands through the `Bash` tool. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](</docs/en/hooks#stop>) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash` and have your script list modified and untracked files with `git status --porcelain`.
+
+Each event type matches on a specific field:
Event| What the matcher filters| Example matcher values
---|---|---
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
-`SubagentStart`| agent type| `Bash`, `Explore`, `Plan`, or custom agent names
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -407,6 +407,7 @@
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
+`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call
`Notification`| When Claude Code sends a notification
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
@@ -427,9 +428,10 @@
`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
`SessionEnd`| When a session terminates
-When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:
+When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Four other types are available:
* `"type": "http"`: POST event data to a URL. See HTTP hooks.
+ * `"type": "mcp_tool"`: call a tool on an already-connected MCP server. See [MCP tool hooks](</docs/en/hooks#mcp-tool-hook-fields>).
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
* `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks.
@@ -553,7 +555,7 @@
`ElicitationResult`| MCP server name| same values as `Elicitation`
`FileChanged`| literal filenames to watch (see [FileChanged](</docs/en/hooks#filechanged>))| `.envrc|.env`
`UserPromptExpansion`| command name| your skill or command names
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
@@ -646,7 +648,7 @@
}
}
-The hook process only spawns when a subcommand of the Bash command matches `git *`, or when the command is too complex to parse into subcommands. For compound commands like `npm test && git push`, Claude Code evaluates each subcommand and fires the hook because `git push` matches. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. Adding it to any other event prevents the hook from running.
+The hook process only spawns when a subcommand of the Bash command matches `git *`, or when the command is too complex to parse into subcommands. For compound commands like `npm test && git push`, Claude Code evaluates each subcommand and fires the hook because `git push` matches. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -401,6 +401,7 @@
---|---
`SessionStart`| When a session begins or resumes
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
+`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a permission dialog appears
`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
@@ -481,7 +482,7 @@
The exit code determines what happens next:
- * **Exit 0** : the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
+ * **Exit 0** : the action proceeds. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
* **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
@@ -551,6 +552,7 @@
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
`FileChanged`| literal filenames to watch (see [FileChanged](</docs/en/hooks#filechanged>))| `.envrc|.env`
+`UserPromptExpansion`| command name| your skill or command names
`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -298,24 +298,34 @@
Reload environment when directory or files change
-Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. A `CwdChanged` hook fixes this: it runs each time Claude changes directory, so you can reload the correct variables for the new location. The hook writes the updated values to `CLAUDE_ENV_FILE`, which Claude Code applies before each Bash command. Add this to `~/.claude/settings.json`:
-
- {
- "hooks": {
+Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
+
+ {
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""
+ }
+ ]
+ }
+ ],
"CwdChanged": [
{
"hooks": [
{
"type": "command",
- "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""
- }
- ]
- }
- ]
- }
- }
-
-To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
+ "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`. To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
{
"hooks": {
@@ -325,7 +335,7 @@
"hooks": [
{
"type": "command",
- "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""
+ "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""
}
]
}
@@ -420,7 +430,7 @@
* `"type": "http"`: POST event data to a URL. See HTTP hooks.
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
- * `"type": "agent"`: multi-turn verification with tool access. See Agent-based hooks.
+ * `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks.
###
@@ -615,7 +625,7 @@
The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches, or when a Bash command is too complex to parse. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
{
"hooks": {
@@ -634,7 +644,7 @@
}
}
-The hook process only spawns when the Bash command starts with `git`. Other Bash commands skip this handler entirely. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+The hook process only spawns when a subcommand of the Bash command matches `git *`, or when the command is too complex to parse into subcommands. For compound commands like `npm test && git push`, Claude Code evaluates each subcommand and fires the hook because `git push` matches. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. Adding it to any other event prevents the hook from running.
###
@@ -691,6 +701,8 @@
Agent-based hooks
+Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
+
When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
{
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -359,7 +359,11 @@
}
}
-When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only. To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
+When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
+
+`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). It is never persisted as `defaultMode`.
+
+To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
{
"hookSpecificOutput": {
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -32,7 +32,26 @@
}
}
-If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than replacing the whole object. You can also ask Claude to write the hook for you by describing what you want in the CLI.
+If your settings file already has a `hooks` key, add `Notification` as a sibling of the existing event keys rather than replacing the whole object. Each event name is a key inside the single `hooks` object:
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
+ }
+ ],
+ "Notification": [
+ {
+ "matcher": "",
+ "hooks": [{ "type": "command", "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'" }]
+ }
+ ]
+ }
+ }
+
+You can also ask Claude to write the hook for you by describing what you want in the CLI.
2
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -296,7 +296,7 @@
}
}
-To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch (pipe-separated). The `matcher` both configures which files to watch and filters which hooks run. This example watches `.envrc` and `.env` for changes in the current directory:
+To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
{
"hooks": {
@@ -450,7 +450,7 @@
* **Exit 0** : the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
* **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.
- * **Any other exit code** : the action proceeds. The transcript shows a one-line error notice; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
+ * **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
@@ -501,7 +501,7 @@
}
}
-The `"Edit|Write"` matcher is a regex pattern that matches the tool name. The hook only fires when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. Each event type matches on a specific field. Matchers support exact strings and regex patterns:
+The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](</docs/en/hooks#matcher-patterns>) for how plain names and regular expressions are evaluated. Each event type matches on a specific field:
Event| What the matcher filters| Example matcher values
---|---|---
@@ -517,7 +517,7 @@
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
-`FileChanged`| filename (basename of the changed file)| `.envrc`, `.env`, any filename you want to watch
+`FileChanged`| literal filenames to watch (see [FileChanged](</docs/en/hooks#filechanged>))| `.envrc|.env`
`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
@@ -827,7 +827,7 @@
Debug techniques
-The transcript view, toggled with `Ctrl+O`, shows a one-line summary for each hook that fired: success is silent, blocking errors show stderr, and non-blocking errors show only the hook name. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
+The transcript view, toggled with `Ctrl+O`, shows a one-line summary for each hook that fired: success is silent, blocking errors show stderr, and non-blocking errors show a `<hook name> hook error` notice followed by the first line of stderr. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -450,7 +450,7 @@
* **Exit 0** : the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
* **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.
- * **Any other exit code** : the action proceeds. Stderr is logged but not shown to Claude. Toggle verbose mode with `Ctrl+O` to see these messages in the transcript.
+ * **Any other exit code** : the action proceeds. The transcript shows a one-line error notice; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
@@ -546,7 +546,7 @@
}
}
-MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`):
+MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr. Writing to stderr keeps stdout clean for JSON output and sends the message to the [debug log](</docs/en/hooks#debug-hooks>):
{
"hooks": {
@@ -827,7 +827,7 @@
Debug techniques
-Toggle verbose mode with `Ctrl+O` to see hook output in the transcript, or run `claude --debug` for full execution details including which hooks matched and their exit codes.
+The transcript view, toggled with `Ctrl+O`, shows a one-line summary for each hook that fired: success is silent, blocking errors show stderr, and non-blocking errors show only the hook name. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path.
##
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -370,6 +370,7 @@
`UserPromptSubmit`| When you submit a prompt, before Claude processes it
`PreToolUse`| Before a tool call executes. Can block it
`PermissionRequest`| When a permission dialog appears
+`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call
`PostToolUse`| After a tool call succeeds
`PostToolUseFailure`| After a tool call fails
`Notification`| When Claude Code sends a notification
@@ -471,13 +472,13 @@
}
}
-Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`:
+With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`:
* `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-Returning `"allow"` skips the interactive prompt but does not override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Prompt-based hooks (`type: "prompt"`) handle output differently: see Prompt-based hooks.
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but does not override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Prompt-based hooks (`type: "prompt"`) handle output differently: see Prompt-based hooks.
###
@@ -504,7 +505,7 @@
Event| What the matcher filters| Example matcher values
---|---|---
-`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
+`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
@@ -610,7 +611,7 @@
}
}
-The hook process only spawns when the Bash command starts with `git`. Other Bash commands skip this handler entirely. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. Adding it to any other event prevents the hook from running.
+The hook process only spawns when the Bash command starts with `git`. Other Bash commands skip this handler entirely. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -392,7 +392,7 @@
`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
`SessionEnd`| When a session terminates
-Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:
+When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:
* `"type": "http"`: POST event data to a URL. See HTTP hooks.
* `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
@@ -728,11 +728,20 @@
Limitations
- * Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger commands or tool calls directly. HTTP hooks communicate through the response body instead.
+ * Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).
* `PostToolUse` hooks cannot undo actions since the tool has already executed.
* `PermissionRequest` hooks do not fire in [non-interactive mode](</docs/en/headless>) (`-p`). Use `PreToolUse` hooks for automated permission decisions.
* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
+ * When multiple PreToolUse hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish wins. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
+
+###
+
+
+
+Hooks and permission modes
+
+PreToolUse hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users cannot bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` does not bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -93,6 +93,14 @@
]
}
}
+
+If no notification appears
+
+`osascript` routes notifications through the built-in Script Editor app. If Script Editor doesn’t have notification permission, the command fails silently, and macOS won’t prompt you to grant it. Run this in Terminal once to make Script Editor appear in your notification settings:
+
+ osascript -e 'display notification "test"'
+
+Nothing will appear yet. Open **System Settings > Notifications**, find **Script Editor** in the list, and turn on **Allow Notifications**. Run the command again to confirm the test notification appears.
{
"hooks": {
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -575,6 +575,35 @@
For full matcher syntax, see the [Hooks reference](</docs/en/hooks#configuration>).
+####
+
+
+
+Filter by tool name and arguments with the `if` field
+
+The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
+
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "if": "Bash(git *)",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-git-policy.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The hook process only spawns when the Bash command starts with `git`. Other Bash commands skip this handler entirely. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`. Adding it to any other event prevents the hook from running.
+
###
Show diff (385 lines)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -15,12 +15,6 @@
Add the hook to your settings
Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see Get notified when Claude needs input for Linux and Windows commands.
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -84,12 +78,6 @@
* Windows (PowerShell)
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Notification": [
@@ -106,12 +94,6 @@
}
}
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Notification": [
@@ -128,12 +110,6 @@
}
}
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Notification": [
@@ -158,12 +134,6 @@
Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PostToolUse": [
@@ -195,12 +165,6 @@
Create the hook script
Save this to `.claude/hooks/protect-files.sh`:
-
-Report incorrect code
-
-Copy
-
-Ask AI
#!/bin/bash
# protect-files.sh
@@ -225,12 +189,6 @@
Hook scripts must be executable for Claude Code to run them:
-Report incorrect code
-
-Copy
-
-Ask AI
-
chmod +x .claude/hooks/protect-files.sh
3
@@ -239,12 +197,6 @@
Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PreToolUse": [
@@ -269,12 +221,6 @@
When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Any text your command writes to stdout is added to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"SessionStart": [
@@ -301,12 +247,6 @@
Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each change to an audit log. Add this to `~/.claude/settings.json`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"ConfigChange": [
@@ -333,12 +273,6 @@
Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. A `CwdChanged` hook fixes this: it runs each time Claude changes directory, so you can reload the correct variables for the new location. The hook writes the updated values to `CLAUDE_ENV_FILE`, which Claude Code applies before each Bash command. Add this to `~/.claude/settings.json`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"CwdChanged": [
@@ -356,12 +290,6 @@
To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch (pipe-separated). The `matcher` both configures which files to watch and filters which hooks run. This example watches `.envrc` and `.env` for changes in the current directory:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"FileChanged": [
@@ -388,12 +316,6 @@
Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PermissionRequest": [
@@ -411,12 +333,6 @@
}
When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only. To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hookSpecificOutput": {
@@ -451,10 +367,11 @@
`Notification`| When Claude Code sends a notification
`SubagentStart`| When a subagent is spawned
`SubagentStop`| When a subagent finishes
+`TaskCreated`| When a task is being created via `TaskCreate`
+`TaskCompleted`| When a task is being marked as completed
`Stop`| When Claude finishes responding
`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
-`TaskCompleted`| When a task is being marked as completed
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
@@ -489,12 +406,6 @@
Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"session_id": "abc123", // unique ID for this session
"cwd": "/Users/sarah/myproject", // working directory when the event fired
@@ -515,12 +426,6 @@
Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:
-Report incorrect code
-
-Copy
-
-Ask AI
-
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
@@ -550,12 +455,6 @@
For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
@@ -579,12 +478,6 @@
Filter hooks with matchers
Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -616,7 +509,7 @@
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
`FileChanged`| filename (basename of the changed file)| `.envrc`, `.env`, any filename you want to watch
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
@@ -628,12 +521,6 @@
Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PostToolUse": [
@@ -652,12 +539,6 @@
MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`):
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"PreToolUse": [
@@ -675,12 +556,6 @@
}
The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -732,12 +607,6 @@
This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
-Report incorrect code
-
-Copy
-
-Ask AI
-
{
"hooks": {
"Stop": [
@@ -762,12 +631,6 @@
Agent-based hooks
When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -794,12 +657,6 @@
HTTP hooks
Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team. This example posts every tool use to a local logging service:
-
-Report incorrect code
-
-Copy
-
-Ask AI
{
"hooks": {
@@ -863,12 +720,6 @@
* Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:
-Report incorrect code
-
-Copy
-
-Ask AI
-
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh
echo $? # Check the exit code
@@ -895,12 +746,6 @@
Stop hook runs forever
Claude keeps working in an infinite loop instead of stopping. Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
-
-Report incorrect code
-
-Copy
-
-Ask AI
#!/bin/bash
INPUT=$(cat)
@@ -917,22 +762,10 @@
Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook’s JSON:
-Report incorrect code
-
-Copy
-
-Ask AI
-
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells:
-
-Report incorrect code
-
-Copy
-
-Ask AI
# In ~/.zshrc or ~/.bashrc
if [[ $- == *i* ]]; then
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -67,6 +67,7 @@
* Block edits to protected files
* Re-inject context after compaction
* Audit configuration changes
+ * Reload environment when directory or files change
* Auto-approve specific permission prompts
###
@@ -323,6 +324,61 @@
}
The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema.
+
+###
+
+
+
+Reload environment when directory or files change
+
+Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. A `CwdChanged` hook fixes this: it runs each time Claude changes directory, so you can reload the correct variables for the new location. The hook writes the updated values to `CLAUDE_ENV_FILE`, which Claude Code applies before each Bash command. Add this to `~/.claude/settings.json`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "CwdChanged": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch (pipe-separated). The `matcher` both configures which files to watch and filters which hooks run. This example watches `.envrc` and `.env` for changes in the current directory:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "FileChanged": [
+ {
+ "matcher": ".envrc|.env",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+See the [CwdChanged](</docs/en/hooks#cwdchanged>) and [FileChanged](</docs/en/hooks#filechanged>) reference entries for input schemas, `watchPaths` output, and `CLAUDE_ENV_FILE` details.
###
@@ -401,6 +457,8 @@
`TaskCompleted`| When a task is being marked as completed
`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
`ConfigChange`| When a configuration file changes during a session
+`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv
+`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch
`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
`PreCompact`| Before context compaction
@@ -557,7 +615,8 @@
`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
`Elicitation`| MCP server name| your configured MCP server names
`ElicitationResult`| MCP server name| same values as `Elicitation`
-`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+`FileChanged`| filename (basename of the changed file)| `.envrc`, `.env`, any filename you want to watch
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`| no matcher support| always fires on every occurrence
A few more examples showing matchers on different event types:
Show diff (904 lines)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -0,0 +1,901 @@
+Hooks are user-defined shell commands that execute at specific points in Claude Code’s lifecycle. They provide deterministic control over Claude Code’s behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use prompt-based hooks or agent-based hooks that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](</docs/en/skills>) for giving Claude additional instructions and executable commands, [subagents](</docs/en/sub-agents>) for running tasks in isolated contexts, and [plugins](</docs/en/plugins>) for packaging extensions to share across projects.
+
+This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>).
+
+##
+
+
+
+Set up your first hook
+
+To create a hook, add a `hooks` block to a settings file. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.
+
+1
+
+Add the hook to your settings
+
+Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see Get notified when Claude needs input for Linux and Windows commands.
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than replacing the whole object. You can also ask Claude to write the hook for you by describing what you want in the CLI.
+
+2
+
+Verify the configuration
+
+Type `/hooks` to open the hooks browser. You’ll see a list of all available hook events, with a count next to each event that has hooks configured. Select `Notification` to confirm your new hook appears in the list. Selecting the hook shows its details: the event, matcher, type, source file, and command.
+
+3
+
+Test the hook
+
+Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.
+
+The `/hooks` menu is read-only. To add, modify, or remove hooks, edit your settings JSON directly or ask Claude to make the change.
+
+##
+
+
+
+What you can automate
+
+Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. The most common patterns:
+
+ * Get notified when Claude needs input
+ * Auto-format code after edits
+ * Block edits to protected files
+ * Re-inject context after compaction
+ * Audit configuration changes
+ * Auto-approve specific permission prompts
+
+###
+
+
+
+Get notified when Claude needs input
+
+Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`:
+
+ * macOS
+
+ * Linux
+
+ * Windows (PowerShell)
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+###
+
+
+
+Auto-format code after edits
+
+Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
+
+###
+
+
+
+Block edits to protected files
+
+Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.
+
+1
+
+Create the hook script
+
+Save this to `.claude/hooks/protect-files.sh`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ # protect-files.sh
+
+ INPUT=$(cat)
+ FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
+
+ 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
+
+2
+
+Make the script executable (macOS/Linux)
+
+Hook scripts must be executable for Claude Code to run them:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ chmod +x .claude/hooks/protect-files.sh
+
+3
+
+Register the hook
+
+Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+###
+
+
+
+Re-inject context after compaction
+
+When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Any text your command writes to stdout is added to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "SessionStart": [
+ {
+ "matcher": "compact",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](</docs/en/memory>) instead. For environment variables, see [`CLAUDE_ENV_FILE`](</docs/en/hooks#persist-environment-variables>) in the reference.
+
+###
+
+
+
+Audit configuration changes
+
+Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each change to an audit log. Add this to `~/.claude/settings.json`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "ConfigChange": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema.
+
+###
+
+
+
+Auto-approve specific permission prompts
+
+Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PermissionRequest": [
+ {
+ "matcher": "ExitPlanMode",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only. To switch the session to `acceptEdits`, your hook writes this JSON to stdout:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionRequest",
+ "decision": {
+ "behavior": "allow",
+ "updatedPermissions": [
+ { "type": "setMode", "mode": "acceptEdits", "destination": "session" }
+ ]
+ }
+ }
+ }
+
+Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields.
+
+##
+
+
+
+How hooks work
+
+Hook events fire at specific lifecycle points in Claude Code. When an event fires, all matching hooks run in parallel, and identical hook commands are automatically deduplicated. The table below shows each event and when it triggers:
+
+Event| When it fires
+---|---
+`SessionStart`| When a session begins or resumes
+`UserPromptSubmit`| When you submit a prompt, before Claude processes it
+`PreToolUse`| Before a tool call executes. Can block it
+`PermissionRequest`| When a permission dialog appears
+`PostToolUse`| After a tool call succeeds
+`PostToolUseFailure`| After a tool call fails
+`Notification`| When Claude Code sends a notification
+`SubagentStart`| When a subagent is spawned
+`SubagentStop`| When a subagent finishes
+`Stop`| When Claude finishes responding
+`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored
+`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle
+`TaskCompleted`| When a task is being marked as completed
+`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session
+`ConfigChange`| When a configuration file changes during a session
+`WorktreeCreate`| When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior
+`WorktreeRemove`| When a worktree is being removed, either at session exit or when a subagent finishes
+`PreCompact`| Before context compaction
+`PostCompact`| After context compaction completes
+`Elicitation`| When an MCP server requests user input during a tool call
+`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server
+`SessionEnd`| When a session terminates
+
+Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:
+
+ * `"type": "http"`: POST event data to a URL. See HTTP hooks.
+ * `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks.
+ * `"type": "agent"`: multi-turn verification with tool access. See Agent-based hooks.
+
+###
+
+
+
+Read input and return output
+
+Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script’s stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code.
+
+####
+
+
+
+Hook input
+
+Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "session_id": "abc123", // unique ID for this session
+ "cwd": "/Users/sarah/myproject", // working directory when the event fired
+ "hook_event_name": "PreToolUse", // which event triggered this hook
+ "tool_name": "Bash", // the tool Claude is about to use
+ "tool_input": { // the arguments Claude passed to the tool
+ "command": "npm test" // for Bash, this is the shell command
+ }
+ }
+
+Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, clear, compact), and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
+
+####
+
+
+
+Hook output
+
+Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ INPUT=$(cat)
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
+
+ if echo "$COMMAND" | grep -q "drop table"; then
+ echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback
+ exit 2 # exit 2 = block the action
+ fi
+
+ exit 0 # exit 0 = let it proceed
+
+The exit code determines what happens next:
+
+ * **Exit 0** : the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
+ * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.
+ * **Any other exit code** : the action proceeds. Stderr is logged but not shown to Claude. Toggle verbose mode with `Ctrl+O` to see these messages in the transcript.
+
+####
+
+
+
+Structured JSON output
+
+Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.
+
+Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don’t mix them: Claude Code ignores JSON when you exit 2.
+
+For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Use rg instead of grep for better performance"
+ }
+ }
+
+Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`:
+
+ * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply
+ * `"deny"`: cancel the tool call and send the reason to Claude
+ * `"ask"`: show the permission prompt to the user as normal
+
+Returning `"allow"` skips the interactive prompt but does not override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Prompt-based hooks (`type: "prompt"`) handle output differently: see Prompt-based hooks.
+
+###
+
+
+
+Filter hooks with matchers
+
+Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write",
+ "hooks": [
+ { "type": "command", "command": "prettier --write ..." }
+ ]
+ }
+ ]
+ }
+ }
+
+The `"Edit|Write"` matcher is a regex pattern that matches the tool name. The hook only fires when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. Each event type matches on a specific field. Matchers support exact strings and regex patterns:
+
+Event| What the matcher filters| Example matcher values
+---|---|---
+`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`| tool name| `Bash`, `Edit|Write`, `mcp__.*`
+`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
+`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`
+`SubagentStart`| agent type| `Bash`, `Explore`, `Plan`, or custom agent names
+`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
+`SubagentStop`| agent type| same values as `SubagentStart`
+`ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`
+`StopFailure`| error type| `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`
+`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`
+`Elicitation`| MCP server name| your configured MCP server names
+`ElicitationResult`| MCP server name| same values as `Elicitation`
+`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`| no matcher support| always fires on every occurrence
+
+A few more examples showing matchers on different event types:
+
+ * Log every Bash command
+
+ * Match MCP tools
+
+ * Clean up on session end
+
+Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) in the reference for the full list of examples.The command below extracts the tool name from the hook’s JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`):
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "mcp__github__.*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "SessionEnd": [
+ {
+ "matcher": "clear",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "rm -f /tmp/claude-scratch-*.txt"
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+For full matcher syntax, see the [Hooks reference](</docs/en/hooks#configuration>).
+
+###
+
+
+
+Configure hook location
+
+Where you add a hook determines its scope:
+
+Location| Scope| Shareable
+---|---|---
+`~/.claude/settings.json`| All your projects| No, local to your machine
+`.claude/settings.json`| Single project| Yes, can be committed to the repo
+`.claude/settings.local.json`| Single project| No, gitignored
+Managed policy settings| Organization-wide| Yes, admin-controlled
+[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin
+[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the skill or agent is active| Yes, defined in the component file
+
+Run [`/hooks`](</docs/en/hooks#the-hooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable all hooks at once, set `"disableAllHooks": true` in your settings file. If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.
+
+##
+
+
+
+Prompt-based hooks
+
+For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
+
+ * `"ok": true`: the action proceeds
+ * `"ok": false`: the action is blocked. The model’s `"reason"` is fed back to Claude so it can adjust.
+
+This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "prompt",
+ "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+For full configuration options, see [Prompt-based hooks](</docs/en/hooks#prompt-based-hooks>) in the reference.
+
+##
+
+
+
+Agent-based hooks
+
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "agent",
+ "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
+ "timeout": 120
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase. For full configuration options, see [Agent-based hooks](</docs/en/hooks#agent-based-hooks>) in the reference.
+
+##
+
+
+
+HTTP hooks
+
+Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team. This example posts every tool use to a local logging service:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "hooks": [
+ {
+ "type": "http",
+ "url": "http://localhost:8080/hooks/tool-use",
+ "headers": {
+ "Authorization": "Bearer $MY_TOKEN"
+ },
+ "allowedEnvVars": ["MY_TOKEN"]
+ }
+ ]
+ }
+ ]
+ }
+ }
+
+The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone cannot block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
+
+##
+
+
+
+Limitations and troubleshooting
+
+###
+
+
+
+Limitations
+
+ * Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger commands or tool calls directly. HTTP hooks communicate through the response body instead.
+ * Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).
+ * `PostToolUse` hooks cannot undo actions since the tool has already executed.
+ * `PermissionRequest` hooks do not fire in [non-interactive mode](</docs/en/headless>) (`-p`). Use `PreToolUse` hooks for automated permission decisions.
+ * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
+
+###
+
+
+
+Hook not firing
+
+The hook is configured but never executes.
+
+ * Run `/hooks` and confirm the hook appears under the correct event
+ * Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)
+ * Verify you’re triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)
+ * If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead
+
+###
+
+
+
+Hook error in output
+
+You see a message like “PreToolUse hook error: …” in the transcript.
+
+ * Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh
+ echo $? # Check the exit code
+
+ * If you see “command not found”, use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts
+ * If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing
+ * If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh`
+
+###
+
+
+
+`/hooks` shows no hooks configured
+
+You edited a settings file but the hooks don’t appear in the menu.
+
+ * File edits are normally picked up automatically. If they haven’t appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.
+ * Verify your JSON is valid (trailing commas and comments are not allowed)
+ * Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks
+
+###
+
+
+
+Stop hook runs forever
+
+Claude keeps working in an infinite loop instead of stopping. Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ #!/bin/bash
+ INPUT=$(cat)
+ if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
+ exit 0 # Allow Claude to stop
+ fi
+ # ... rest of your hook logic
+
+###
+
+
+
+JSON validation failed
+
+Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook’s JSON:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ Shell ready on arm64
+ {"decision": "block", "reason": "Not allowed"}
+
+Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells:
+
+Report incorrect code
+
+Copy
+
+Ask AI
+
+ # In ~/.zshrc or ~/.bashrc
+ if [[ $- == *i* ]]; then
+ echo "Shell ready"
+ fi
+
+The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.
+
+###
+
+
+
+Debug techniques
+
+Toggle verbose mode with `Ctrl+O` to see hook output in the transcript, or run `claude --debug` for full execution details including which hooks matched and their exit codes.
+
+##
+
+
+
+Learn more
+
+ * [Hooks reference](</docs/en/hooks>): full event schemas, JSON output format, async hooks, and MCP tool hooks
+ * [Security considerations](</docs/en/hooks#security-considerations>): review before deploying hooks in shared or production environments
+ * [Bash command validator example](<https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py>): complete reference implementation