claude@cli:~/docs$ cat claude-code.md

Claude Code: How Do Hooks Work?

# Hooks execute deterministic shell commands at specific points in Claude Code’s workflow.

author: words: 17444 read_time: 87m updated: 2026-12-01 00:00

Part 3 of New to Claude Code

Hooks execute deterministic shell commands at specific points in Claude Code’s workflow.

Last updated: 2026-12-01 · 87 min read · 17K+ words

$ less claude-code.md

Hooks execute deterministic shell commands at specific points in Claude Code’s workflow. Unlike prompting Claude to perform actions, hooks guarantee execution regardless of model behavior. They’re essential for enforcing team standards and automating repetitive tasks. See Decision Frameworks for the “Which Hook Type?” decision tree covering command, prompt, and agent hooks.

Why hooks instead of prompts: Telling Claude “always run Prettier after editing files” works sometimes. But Claude might forget, prioritize speed, or decide the change is “too small.” Hooks guarantee execution: every Edit or Write triggers your formatter, every time, no exceptions. For compliance, security, and team standards, deterministic beats probabilistic.3

Available Events

Event Timing Can Block Purpose
PreToolUse Before tool executes Yes Validate, log, or block operations
PostToolUse After tool completes No Format output, run linters, trigger builds
PostToolUseFailure After tool fails No Log failures, send alerts, provide corrective feedback
PostToolBatch After a batch of parallel tool calls, before the next model call Yes Checkpoint or halt the agentic loop between model calls3
UserPromptSubmit User sends prompt Yes Add context, validate input, inject data
UserPromptExpansion A typed command expands into a prompt Yes Audit or veto skill/slash-command expansions; stdout adds context3
PreSkillShellCommand Before a skill’s or command’s inline ! shell command runs while it loads Yes Log or refuse injected commands, which PreToolUse hooks never see: exit 2 or permissionDecision: "deny" skips the command and the skill still loads; it cannot approve or change one. Match both Bash and PowerShell, use a command, http, or mcp_tool hook that is not async, and set onFailure: "block" (v2.1.332+; an older version that finds the event in a settings file opens a warning dialog at start)529
Notification Alert triggered No Custom notification handling
MessageDisplay Assistant message text is displayed No Transform or hide on-screen text via displayContent — display-only, transcript unchanged (v2.1.152+)264
Stop Claude finishes response Yes Prevent premature stopping, enforce completion criteria. Includes last_assistant_message (v2.1.47+)
SubagentStart Subagent spawns No Log agent type, inject context via additionalContext
SubagentStop Subagent completes Yes Prevent subagent from stopping, enforce quality gates. Includes last_assistant_message (v2.1.47+)
TeammateIdle Agent team member idles Yes Enforce quality gates before teammate stops (v2.1.33+)
TaskCreated Task created via TaskCreate Yes Enforce task naming and scope rules; exit 2 rolls back creation (v2.1.84+). Since v2.1.268 the task tools are on by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5 and earlier models; on newer models (background and cloud sessions aside) this event fires only after CLAUDE_CODE_ENABLE_TODO_TOOLS=1 or --allowedTools TaskCreate turns them on (v2.1.233 first turned them off on newer models)129251213315
TaskCompleted Task marked complete Yes Enforce completion criteria, run tests (v2.1.33+)
SessionStart Session begins No Environment setup, load context, set env vars
SessionEnd Session closes No Cleanup, final logging
Setup --init-only, or --init/--maintenance with -p; never on a normal start No One-time environment setup from CI or scripts (v2.1.10+)52316
InstructionsLoaded CLAUDE.md or .claude/rules/*.md loaded No Log which instruction files load; the event has no output channel, so it cannot block or add context (v2.1.69+)316
ConfigChange Config file changes during session Yes Audit settings changes, enforce security policies (v2.1.49+)
DirectoryAdded A new working directory is registered mid-session No React to /add-dir or the SDK register_repo_root control request — load per-repo context, re-scope linters, audit scope expansion (v2.1.219+)193
CwdChanged Working directory changes No Reload direnv-style environments (v2.1.83+)121
FileChanged A watched file changes on disk No React to watched-file changes: the matcher names the files to watch, separated by a pipe (.envrc and .env, for example), and a SessionStart, CwdChanged or FileChanged hook can add more through watchPaths (v2.1.83+)121316
WorktreeCreate Worktree being created Yes Custom VCS setup (replaces default git behavior) (v2.1.50+)
WorktreeRemove A worktree made by your WorktreeCreate hook is being removed Yes Custom VCS cleanup; any non-zero exit fails the removal if the directory still exists afterward (v2.1.50+)316
PreCompact Before context compaction Yes (v2.1.105+) Validation, logging, blocking compaction (exit 2 or {"decision":"block"}); output cut at 10,000 characters since v2.1.314, so a huge hook cannot fail or repeat compaction281
PostCompact After context compaction No Logging, cache reuse optimization (v2.1.76+)116
Elicitation MCP server requests structured input Yes Intercept/override MCP elicitation dialogs (v2.1.76+)116
ElicitationResult User responds to MCP elicitation Yes Validate/transform elicitation responses (v2.1.76+)116
StopFailure Turn ends due to API error (rate limits, auth failures) No Error alerting, retry logic (v2.1.78+)118
PermissionRequest A tool call needs a permission decision JSON only Custom approval logic; exit 2 is not honored, so deny with hookSpecificOutput.decision.behavior: "deny"316
PermissionDenied Auto mode denies a tool call No Log denials; return hookSpecificOutput.retry: true to tell the model it may retry (ignored when the classifier gave no verdict) (v2.1.89+)125316
PreModelSwitch Before a model switch you or a client requested: /model and the pickers, the /config Model setting, a fast-mode toggle that changes the model, an SDK or Remote Control set_model Yes Block, confirm, or price a model switch. The matcher compares the canonical name derived from to_model (aliases, dated IDs, and Bedrock IDs all resolve to it; exact names, pipe-separated lists, and regexes work); input carries from_model/to_model plus cache-cost fields (context_tokens, prompt_cache_warm, cache_ttl, estimated_cache_write_usd). Exit 2 or permissionDecision: "deny" cancels, "ask" prompts the user, and a hook canceled at its 30s default timeout blocks the switch. Not run for switches Claude Code makes on its own (v2.1.251+)203205
PostModelSwitch After the session’s model changes, including changes Claude Code makes on its own: automatic fallback, opusplan phase changes, the model restored on resume No Model-specific guidance: plain-text stdout on exit 0 (or JSON additionalContext) is delivered to Claude as context with the next request after the switch. Same canonical-name matcher and inputs as PreModelSwitch, plus source values auto and resume; 30s default timeout (v2.1.251+)203205

SessionStart source values. SessionStart hook input includes a source field telling you how the session began: "startup", "resume", "clear", or "compact". As of v2.1.214, a session that begins life as a fork reports source: "fork" instead of "resume", the hook-side counterpart to v2.1.212’s /fork-to-background change. If a SessionStart hook branches on source (say, re-injecting context only on "resume"), update its match list to cover "fork" too.187 As of v2.1.251, when source is "resume" or "fork" and the transcript holds at least one prior response from Claude, SessionStart hooks also receive four resume-cost fields: seconds_since_last_response, context_tokens (what the first request re-sends as its prompt), prompt_cache_likely_expired (true when the last response is older than the session’s cache TTL or a later compaction replaced the cached conversation), and estimated_cache_write_usd. With them a hook can report what resuming a stale conversation costs before the first request.203205

Hook Configuration

Define hooks in a settings file (~/.claude/settings.json, .claude/settings.json, .claude/settings.local.json), in a plugin’s hooks/hooks.json, or in skill and subagent frontmatter:316

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/validate-bash.sh"
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/inject-context.sh"
          }
        ]
      }
    ]
  }
}

Matchers

The matcher field determines which tools trigger a hook:502

  • {"matcher": "*"}: match all tools
  • {"matcher": "Bash"}: match the Bash tool
  • {"matcher": "Edit|Write"}: match Edit or Write
  • {"matcher": "mcp__github__.*"}: match every tool from the github MCP server
  • {"matcher": ""}: match all, the same as "*" or leaving matcher out; an event without matcher support, such as UserPromptSubmit, ignores the field and always fires

Use | to match multiple tools (Edit|Write). Comma-separated matchers (e.g. Bash,PowerShell) work too (v2.1.191+).175 A matcher made only of letters, digits, _, -, spaces, , and | is compared as an exact string (or a list of exact strings), never as a substring; anything else is an unanchored JavaScript regular expression. (Hyphenated names such as code-reviewer follow the exact-match rule from v2.1.195.) To match every tool from an MCP server, the .* is required: mcp__github__.*, mcp__brave-search__.*. A bare mcp__github matches no tool.176316

Hook if: path conditions are cwd-scoped as of v2.1.214. The same single-segment scoping change that hit permission allow rules (see Permission Rules Syntax) applies to hook if: conditions: a condition like dir/** now matches only <cwd>/dir, not every dir/ in the tree. Write **/dir/** when you want any-depth matching back.187 Since v2.1.314 a condition such as Monitor(tail *) matches the Monitor tool’s shell commands the way Bash(tail *) matches Bash’s, and hooks that match Bash run on those commands too, where they can block or ask but not approve or rewrite.281

Hook Input/Output Protocol

Hooks receive JSON on stdin:

{
  "session_id": "abc-123",
  "transcript_path": "/Users/you/.claude/projects/my-project/abc-123.jsonl",
  "cwd": "/Users/you/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  },
  "tool_use_id": "toolu_01ABC123"
}

Every event carries session_id, transcript_path, cwd and hook_event_name; most also carry permission_mode. The other fields depend on the event.316

Hook event enrichment (v2.1.69+): All hook events now include agent_id and agent_type fields when triggered from a subagent or --agent session, plus a worktree field in status line hook commands.108

Stop/SubagentStop hooks (v2.1.47+) receive an additional last_assistant_message field containing Claude’s final response text, so hooks can inspect the output without parsing transcript files:

{
  "session_id": "abc-123",
  "last_assistant_message": "I've completed the refactoring. Here's what changed..."
}

Soft feedback without a block (v2.1.163+): Stop and SubagentStop hooks can return hookSpecificOutput.additionalContext in their JSON output to hand Claude feedback and keep the turn going, without the response being labeled a hook error. The other lever, the exit-2 block, reads as an error and counts toward the consecutive-block cap; additionalContext is a steering channel for “here’s what you missed, continue” guidance that doesn’t fight the loop.261

Exit codes control behavior:

  • 0: Success: Claude Code applies any JSON output fields the hook printed, and the action goes ahead unless those fields block or deny it. Stdout counts as JSON output only when the hook prints one JSON object with nothing around it but whitespace; anything else is read as plain text or as a parse failure. On UserPromptSubmit, UserPromptExpansion, SessionStart, and PostModelSwitch, plain-text stdout is added as context Claude can see and act on, and on PreCompact stdout becomes instructions for the compaction summary. Claude never sees stderr from a hook that exits 0.274316
  • 2: Blocking error on the events that can block: the operation stops and stderr is fed back to Claude. On events that cannot block, the effect varies: PostToolUse and PostToolUseFailure still show stderr to Claude, several events show it only to you, and events such as PermissionRequest, Setup, Notification and PermissionDenied ignore exit 2 (see the Can Block column above).316
  • 1, 3, etc.: Non-blocking error: operation continues unless the hook is one whose failure blocks the action, such as one with onFailure set to "block". When stdout is plain text or empty, a <hook name> hook error notice (on events such as PreToolUse) reads Failed with non-blocking status code: followed by the hook’s stderr, and the debug log has the rest when the notice cuts it off; JSON that passes validation is still applied, with the exit code ignored (for a hook whose failure blocks the action, the run counts as a failure instead).274

Block on failure (v2.1.295+): by default a hook that cannot start, times out, exits with a code other than 0 or 2, gets an HTTP error, has its MCP server disconnected or its MCP tool return an error, or prints output that fails JSON validation is a non-blocking error, so a policy hook with a mistyped path lets everything through. Set "onFailure": "block" on a command or http hook, or since v2.1.328 an mcp_tool hook, and each of those failures does what exit code 2 does on that event: a PreToolUse failure blocks the tool call and a UserPromptSubmit failure blocks the prompt, while on PermissionRequest it denies the request. The error line reads failed; blocking because onFailure is "block" (timed out after a timeout), followed by the hook’s own output. A command hook that exits 1 with JSON that allows the action still counts as a failure; to return a JSON decision, exit 0. The field is ignored on Stop, SubagentStop, TaskCompleted, and TeammateIdle hooks, where exit 2 sends Claude back to work, and on async or asyncRewake command hooks. The other value is "continue". With the field unset a failure is a non-blocking error, with one exception: on Windows without Git Bash, a shell-form PreToolUse, PermissionRequest, or PreSkillShellCommand command hook that fails can block the action, and "onFailure": "continue" on that hook lets the call go ahead.235237274529

Skill shell commands get their own event (v2.1.332). A skill or command can run shell commands while it loads (the ! lines shown under Inline Bash Execution), and PreToolUse hooks do not fire for them. PreSkillShellCommand does. Its input carries tool_name (Bash or PowerShell), tool_input.command, command_name (the skill or command that is loading), command_source, and invoked_by. The hook runs after the permission check on injected commands, so it sees the commands that passed, and it also runs in bypassPermissions mode. Define it in a settings file or a plugin: a skill’s injected commands run without the hooks in that skill’s own frontmatter on its first load in a session. In auto mode a command that would need approval does not run while the skill loads; Claude can run it afterward as a tool call, which fires PreToolUse, so keep a blocking script on both events. A prompt or agent hook on this event cannot run, and Claude Code blocks each command it matches.527529

{
  "hooks": {
    "PreSkillShellCommand": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh", "args": [], "onFailure": "block" }
        ]
      }
    ]
  }
}

The script is the one the hooks reference builds under “How a hook resolves”, and the reference says to reuse it on this event. Save it as .claude/hooks/block-rm.sh in the project and make it executable with chmod +x .claude/hooks/block-rm.sh; it needs jq on your PATH:

#!/bin/bash
# .claude/hooks/block-rm.sh
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked by hook"
    }
  }'
else
  exit 0  # no decision; normal permission flow applies
fi

The same file serves both events: leave hookEventName as PreToolUse when one script runs on both, and a script that exits 2 blocks on either event too. On PreSkillShellCommand a hook can block a command but cannot approve or change one.529

For advanced control, a hook prints JSON on stdout and exits 0. For a hook that is not async, print nothing else on stdout: a line your shell profile echoes at startup is enough to keep Claude Code from reading the object as JSON. The reference describes three kinds of fields: universal fields that every event accepts (some events discard them or deliver systemMessage somewhere other than the transcript; each event’s section of the reference says which), top-level decision and reason that some events use to block or give feedback, and hookSpecificOutput, a nested object for events that need richer control, which requires a hookEventName field set to the event name. The universal fields:274

Field Default Description
continue true false stops Claude from processing entirely after the hook runs. It does not block a PreToolUse tool call: to do that, also return permissionDecision: "deny"
stopReason none Message shown to the user when continue is false; it stays in the conversation, so Claude sees it if the conversation continues
suppressOutput false Has no effect
systemMessage none Warning shown to the user; in the Agent SDK and --output-format stream-json output it can arrive as an SDKInformationalMessage
terminalSequence none A terminal escape sequence Claude Code emits on the hook’s behalf (desktop notification, window title, bell); restricted to OSC 0, 1, 2, 9, 99, 777 and BEL, and ignored if the value contains anything else; written only in an interactive session while the interface is on screen, and ignored under -p and in the Agent SDK
{
  "continue": false,
  "stopReason": "The deploy window is closed. Nothing else runs until it reopens.",
  "systemMessage": "deploy-gate stopped this turn"
}

On PreToolUse, this output alone does not stop the tool call the hook was checking: the reference says continue: false “doesn’t block a PreToolUse tool call”. A guard that has to stop the call returns permissionDecision: "deny" in hookSpecificOutput, as in the next example, or exits 2. The field also behaves differently by event: on Stop and SubagentStop it takes precedence over exit code 2, so the turn ends, and Claude Code ignores it on TaskCreated.274

PreToolUse decision control (preferred format): PreToolUse hooks use hookSpecificOutput for richer control: four outcomes (allow, deny, ask, defer) plus the ability to modify tool input and inject context:87316

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Command validated and modified",
    "updatedInput": {
      "command": "npm test -- --coverage --ci"
    },
    "additionalContext": "Note: This database has a 5-second query timeout."
  }
}
Field Values Description
permissionDecision "allow", "deny", "ask", "defer" allow skips the permission prompt (deny and ask rules still apply, and actions no mode auto-approves still prompt), deny blocks, ask prompts the user, defer ends the turn so a wrapping -p process can resume the call later (v2.1.89+; multi-hook precedence deny > defer > ask > allow)316
permissionDecisionReason String ask: shown to the user in the prompt. deny: shown to Claude. allow and defer: written to the debug log only316
updatedInput Object Modifies tool input before execution; as of v2.1.300 it is validated like Claude’s own input: unknown keys are dropped and input the tool rejects denies the call270
additionalContext String Injected into Claude’s context for that turn43

Note: Top-level decision and reason fields are deprecated for PreToolUse. Use hookSpecificOutput.permissionDecision and hookSpecificOutput.permissionDecisionReason instead. Other events (PostToolUse, Stop, etc.) still use top-level decision.87

UserPromptSubmit session title (v2.1.94+): UserPromptSubmit hooks can set the session title via hookSpecificOutput.sessionTitle.138

UserPromptSubmit runs before expansion (v2.1.299). UserPromptSubmit hooks run before a skill or custom slash command expands, so a hook that blocks the prompt also stops the command’s embedded ! shell lines; UserPromptExpansion still fires on the expansion itself. A UserPromptSubmit hook declared in a skill’s own frontmatter first runs on the prompt after the one that invoked the skill.268269

Async Hooks (January 2026)

Hooks can now run in the background without blocking Claude Code’s execution. Add async: true to a command hook’s configuration:79421

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/notify-slack.sh",
            "async": true
          }
        ]
      }
    ]
  }
}

When to use async hooks:

  • Notifications (Slack, email, Pushover) that shouldn’t slow down the session
  • Logging and telemetry that can run in the background
  • Non-critical post-processing (analytics, backups)

When not to use async hooks:

  • Formatting (must complete before next edit)
  • Validation (must block on failure)
  • Any hook that needs to modify tool input/output

Prompt-Based and Agent-Based Hooks (v2.1.32+)

Beyond shell command hooks (type: "command"), Claude Code supports two LLM-powered hook types that evaluate conditions using AI reasoning rather than scripts.87

Prompt hooks (type: "prompt") send a single-turn prompt to a Claude model (by default the one Claude Code uses for background work). The model returns { "ok": true } to allow or { "ok": false, "reason": "..." } to block:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all requested tasks are complete and tests pass.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

HTTP hooks (type: "http") send the event’s JSON input as a POST request to a URL and receive JSON back. Use these for webhooks, external notification services, or API-based validation (v2.1.63+):102

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "http",
            "url": "https://api.example.com/notify",
            "headers": {
              "Authorization": "Bearer $MY_TOKEN"
            },
            "allowedEnvVars": ["MY_TOKEN"]
          }
        ]
      }
    ]
  }
}

HTTP hooks use the same decision format as command hooks (return JSON with decision and reason). They’re routed through the sandbox network proxy when sandboxing is enabled. Not supported for SessionStart/Setup events.

Agent hooks (type: "agent") spawn a subagent with tool access (Read, Grep, Glob) for multi-turn verification. Use these when checking requires inspecting actual files or test output:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "agent",
            "prompt": "Verify all unit tests pass. Run the test suite and check results. $ARGUMENTS",
            "timeout": 120
          }
        ]
      }
    ]
  }
}

Use $ARGUMENTS as a placeholder for the hook’s JSON input. Both types take model (default: the model Claude Code uses for background work; since v2.1.330 a prompt hook’s model accepts an alias such as haiku or sonnet527) and timeout in seconds (default 30 for prompt, 60 for agent). Agent hooks are experimental. Events that take both: PreToolUse, PostToolUse, PostToolUseFailure, PostToolBatch, PermissionDenied, UserPromptSubmit, UserPromptExpansion, Stop, SubagentStop, TaskCreated, TaskCompleted, TeammateIdle. PermissionRequest takes prompt hooks only, and a prompt hook’s ok: false has no effect there: deny from a command hook instead. On PermissionDenied the output of a prompt or agent hook is discarded, because only a command hook can return retry.317

PermissionRequest no longer runs agent-type hooks (v2.1.280). The reason is worth stating plainly, because it explains a class of hook that never worked: an agent hook’s answer could never allow or deny the request, so an agent hook registered on PermissionRequest was doing work whose result was discarded. Rather than keep accepting the configuration silently, Claude Code now shows an error pointing you at command or http hooks, which can return a verdict. If you have a PermissionRequest agent hook in a settings file or plugin, it was not gating anything before this release either: the error is the first time you are being told. Port the logic to a command hook.217

Hook concurrency (v2.1.312+). Prompt and agent hooks run at most 24 at a time per session, subagents included, plus at most 12 that have waited longer than their event’s timeout, and a timeout under one second counts as one second. Command hooks are unaffected. The hooks reference states the per-event figure: matching hooks run in parallel, and when more than 12 of them are prompt or agent hooks, 12 run at once and the rest start as running ones finish.272273281317

MCP Tool Hooks (v2.1.118+)

Hooks can now invoke an MCP tool directly via type: "mcp_tool", sidestepping the need to wrap a Bash subprocess that calls the server.149

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "mcp_tool",
            "server": "linear",
            "tool": "create_comment",
            "input": {"issue_id": "ENG-123", "body": "Auto-updated by Claude Code"}
          }
        ]
      }
    ]
  }
}

This pairs well with the MCP servers users already have configured: any tool reachable from /mcp becomes hook-callable.

duration_ms in PostToolUse Hooks (v2.1.119+)

PostToolUse and PostToolUseFailure hook inputs now include duration_ms, the tool’s execution time excluding permission prompts and PreToolUse hooks.149 Useful for slow-tool detection, audit logs, and per-tool latency metrics. The field is optional, so the example treats a missing value as 0:421

#!/bin/bash
# Stderr-flagged warning when an Edit takes more than 10 seconds
INPUT=$(cat)
DUR=$(jq -r '.duration_ms // 0' <<<"$INPUT")
FILE=$(jq -r '.tool_input.file_path // "?"' <<<"$INPUT")
if [ "$DUR" -gt 10000 ]; then
  echo "[slow-edit] ${DUR}ms — investigate $FILE" >&2
fi

updatedToolOutput for All Tools (v2.1.121+)

PostToolUse hooks could at first replace a tool’s output only for MCP tools, through updatedMCPToolOutput (which still works for MCP tools). As of v2.1.121, hookSpecificOutput.updatedToolOutput works for any PostToolUse hook: built-in tools (Bash, Read, Edit, Glob, Grep, etc.), subagent tools, and MCP tools. Prefer it over the MCP-only field.316 Use cases: redacting sensitive content from any tool’s output, normalizing structure for downstream consumers, injecting metadata before the agent reads the result.151

Hook Environment Variables

Hooks have access to environment variables for resolving paths:87

Variable Available In Description
$CLAUDE_PROJECT_DIR All hooks Project root directory (quote for paths with spaces)
${CLAUDE_PLUGIN_ROOT} Plugin hooks Plugin’s root directory
$CLAUDE_ENV_FILE SessionStart, Setup, CwdChanged, FileChanged (not in PowerShell hooks)316 File path for persisting env vars for subsequent Bash commands
$CLAUDE_CODE_REMOTE All hooks Set to "true" in remote web environments
$CLAUDE_EFFORT All hooks + Bash tool subprocess Current effort level. Hooks also receive it via the effort.level JSON input field (v2.1.133+).157
$CLAUDE_CODE_SESSION_ID Bash and PowerShell tool subprocesses, hook commands, stdio MCP servers Session ID matching the session_id passed to hooks. Lets long-running shells correlate output across the same session (v2.1.132+).156318

Persist environment variables from SessionStart:

#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
  echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
fi
exit 0

Claude Code Hooks vs Agent SDK Hooks

The same lifecycle events — PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, and the rest of the roster above — exist in two consumption models, and searches for the Agent SDK’s hook lifecycle land here often enough that the distinction deserves its own heading.

Claude Code (CLI) hooks are what this section documents: handlers configured in settings.json, receiving event JSON on stdin and answering with exit codes or JSON on stdout. Enforcement is the CLI’s — a PreToolUse deny blocks the tool call before it runs, even in bypassPermissions mode.3

Agent SDK hooks are the programmatic surface for harnesses that embed the Claude Code runtime as a library. In claude-agent-sdk-python, setting include_hook_events=True on ClaudeAgentOptions makes HookEventMessage objects (PreToolUse, PostToolUse, Stop, and the others) yield from the same iterator as assistant messages and tool results; the TypeScript SDK mirrors this with includeHookEvents, and its control protocol tracks the CLI’s event roster (the TypeScript SDK added DirectoryAdded in the same release that shipped it in the CLI). Payload shapes match the CLI’s stdin JSON (session_id, hook_event_name, tool_input, and the per-event fields), and PreToolUse decision semantics keep the same precedence (deny > defer > ask > allow).3496

The enforcement caveat is the part worth memorizing. SDK-side hook enforcement has twice been shown to fail open at lifecycle edges: a caller abort arriving during a pending hook callback was converted into hook success in the TypeScript SDK, which let PreToolUse-gated tools run after the abort (fixed in 0.3.208), and a stream-close path in the Python SDK silently bypassed PreToolUse for SDK MCP tool calls made by background tasks (fixed in 0.2.127).422 Both are fixed, but the pattern is structural: when the transport dies before the hook verdict is collected, a bypassed hook looks exactly like a hook that approved. If SDK hooks gate anything security-relevant, pin current SDK versions and keep a CLI-layer shell hook as the enforcement you can prove. The Agent Architecture guide covers the SDK hook surface, the version floors, and the harness patterns in depth.

Fail closed when a callback fails. On most events, an SDK hook callback that throws, returns nothing, or returns output that fails validation does not stop the action: the action goes ahead and the app receives a warning message tagged hook_callback_failed, so a PreToolUse guard that crashes lets the tool call reach the normal permission flow. To block the action instead, set onFailure: "block" on the matcher in TypeScript, or on_failure="block" on HookMatcher in Python (TypeScript Agent SDK v0.3.317 or later, Python Agent SDK v0.2.177 or later). Stop, SubagentStop, TaskCompleted, and TeammateIdle ignore the option, and with it set a query fails at startup when the Claude Code it connects to cannot honor it. Return {} from a callback that has no opinion, because with "block" set a path with no return blocks the action. TypeScript SDK 0.3.325 also added a system/informational warning tagged hook_no_verdict, sent when a PreToolUse hook cannot run or answer, or times out, without refusing its tool call; that tag is in the SDK changelog and not in the Agent SDK hooks docs as read on November 25, 2026.549

HTTP hook security (v2.1.51+): HTTP hooks that interpolate environment variables into headers now require an explicit allowedEnvVars list. This prevents arbitrary environment variable exfiltration through header values. HTTP hooks are also routed through the sandbox network proxy when sandboxing is enabled, enforcing the domain allowlist. HTTP hooks are not supported for SessionStart/Setup events.96

{
  "hooks": {
    "PostToolUse": [{
      "hooks": [{
        "type": "http",
        "url": "https://api.example.com/notify",
        "headers": { "Authorization": "Bearer $MY_TOKEN" },
        "allowedEnvVars": ["MY_TOKEN"]
      }]
    }]
  }
}

Hook workspace trust (v2.1.51+): statusLine and fileSuggestion hook commands now require workspace trust acceptance before executing in interactive mode, closing a potential security vector.96

Practical Hook Examples

Auto-format TypeScript files after editing:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r \".tool_input.file_path // empty\"); [[ \"$FILE\" == *.ts ]] && npx prettier --write \"$FILE\" || true'"
          }
        ]
      }
    ]
  }
}

Log all bash commands:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command' >> ~/.claude/bash-history.log"
          }
        ]
      }
    ]
  }
}

Block reads and edits of sensitive files by path:

#!/bin/bash
# .claude/hooks/protect-files.sh
data=$(cat)
path=$(echo "$data" | jq -r '.tool_input.file_path // empty')

if [[ "$path" == *".env"* ]] || [[ "$path" == *"secrets/"* ]] || [[ "$path" == *".pem"* ]]; then
  echo "Blocked: Cannot access sensitive file $path" >&2
  exit 2  # Exit 2 = block the tool call. Exit 1 = non-blocking error (hook failure only).
fi
exit 0

Register it on PreToolUse for the three file tools, whose input carries file_path:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

The script checks tool_input.file_path only, so it does not see what a Bash command reads. For that, add Read deny rules, which also cover the file commands Claude Code recognizes in Bash such as cat, and for OS-level enforcement on shell commands turn on the sandbox and turn off the unsandboxed retry (sandbox.allowUnsandboxedCommands: false).421

Run tests after code changes:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r \".tool_input.file_path // empty\"); [[ \"$FILE\" == *.test.ts ]] || npm run test:affected'"
          }
        ]
      }
    ]
  }
}

Custom notification system:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "notify-send 'Claude Code' 'Waiting for your input'"
          }
        ]
      }
    ]
  }
}

Inject dynamic context into prompts:

#!/bin/bash
# .claude/hooks/inject-context.sh
# Add current git branch and recent commits to every prompt

branch=$(git branch --show-current 2>/dev/null)
commits=$(git log --oneline -3 2>/dev/null | tr '\n' ' ')

if [ -n "$branch" ]; then
  echo "[Context: Branch '$branch', Recent: $commits]"
fi
exit 0

Hook Debugging

Enable debug mode to troubleshoot hooks:

claude --debug

--debug does not print to the terminal. Read the log at ~/.claude/debug/<session-id>.txt, or start with claude --debug-file <path> to choose the file.316

The debug log records:

  • Which hooks ran, for which event and matcher, and how each run ended
  • Each hook’s output and whether it parsed as JSON
  • Durations: since v2.1.296 each command hook leaves a Hooks: line ending in its run time, as in Hooks: PostToolUse:Write [.claude/hooks/log-write.sh] finished with status 0 (31ms)
  • Matcher counts and query matching, when CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose is set

Hook source display (v2.1.75+): When a hook requires user confirmation, the permission prompt now shows the hook’s source (settings, plugin, or skill), making it easier to identify which component is requesting access.115

Component-Scoped Hooks (v2.1.0+)

Hooks can be defined directly in Skills, subagents, and slash commands using frontmatter. They use the same format as hooks in settings, and any hook event can appear. A subagent’s hooks run only while that subagent runs (its Stop hook becomes SubagentStop); a skill’s hooks register when the skill is invoked and keep running for the rest of the session.33317423

Skill with embedded hooks:

---
name: secure-deployment
description: Deployment skill with security validation
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: ".claude/hooks/validate-deploy.sh"
  PostToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: ".claude/hooks/log-deploy.sh"
  Stop:
    - hooks:
        - type: command
          command: ".claude/hooks/cleanup.sh"
          once: true  # Removed after its first successful run
---

Each matcher entry holds a hooks: list, and each handler in it carries a type. A flat entry, with matcher and command side by side and no hooks: list, is not this format: the hooks reference says frontmatter hooks use “the same configuration format as settings-based hooks”, and its skill example nests each handler under a hooks: list in this way.317

once: true (skill frontmatter only) removes the hook after its first successful run, which is useful for cleanup or finalization tasks. A run that fails, blocks with exit code 2, or times out leaves the hook in place. Settings files and agent frontmatter ignore the field.317

Agent frontmatter hooks require workspace trust (v2.1.218). Hooks declared in an agent file’s frontmatter no longer run from untrusted folders: the folder containing the agent file must itself have accepted workspace trust before its hooks execute. This closes the gap where an agent file dropped into an untrusted directory could execute hook commands without any trust prompt, extending the v2.1.51 statusLine/fileSuggestion trust requirement to agent-scoped hooks.192 The requirement covers project-level agent files: hooks from agents in ~/.claude/agents/ and from definitions passed with --agents run without that step.495

Long-Running Sessions Strategy

For overnight or unattended Claude Code sessions, configure hooks to keep Claude on track without manual intervention. The key insight: use linting and testing hooks as guardrails that force Claude to fix issues before continuing.55

The “Don’t Stop Until Tests Pass” Pattern:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "{ npm run lint && npm run typecheck; } 1>&2 || exit 2",
            "timeout": 60
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm test 1>&2 || exit 2"
          }
        ]
      }
    ]
  }
}

Exit code 2 is what sends the output to Claude: on PostToolUse Claude reads the stderr, and on Stop it also keeps Claude from stopping. A plain failure (exit 1) is a non-blocking error Claude never sees, and stdout from a hook that exits 0 goes to the debug log. timeout is in seconds. Claude Code overrides a Stop hook that blocks eight times in a row with no tool call in between, and a hook script can read stop_hook_active from its input to tell that it already forced a continuation.319

Strategy for overnight sessions:

  1. Pre-flight check: Use a SessionStart hook to verify the environment is ready. A Setup hook does not fire on a normal start; it runs only with claude --init-only, or with --init or --maintenance in -p mode316
  2. Continuous validation: PostToolUse hooks run tests after each change
  3. Gate completion: Stop hooks verify all acceptance criteria before Claude declares “done”
  4. Notification: Stop hooks can notify you via Slack/Pushover when Claude finishes or gets stuck

Combine with --dangerously-skip-permissions in a sandboxed container for fully autonomous overnight runs. Claude will keep iterating until tests pass or it exhausts its options.

References


  1. Claude Code Docs. Hooks Guide. Redirected from docs.anthropic.com December 2025; canonical URL updated February 2026. ↩↩↩↩↩

  2. Claude Code CHANGELOG, section 2.1.0, fetched November 11, 2026: “Added hooks support to agent frontmatter, allowing agents to define PreToolUse, PostToolUse, and Stop hooks scoped to the agent’s lifecycle”; “Added hooks support for skill and slash command frontmatter”; “Added support for once: true config for hooks”. That section lists 109 changes. A 2.1.1 followed on npm on January 7, 2026 and has no CHANGELOG section. ↩

  3. Claude Code CHANGELOG, section 2.1.9, fetched November 11, 2026: “Added support for PreToolUse hooks to return additionalContext to the model”; “Added ${CLAUDE_SESSION_ID} string substitution for skills to access the current session ID”; “Added auto:N syntax for configuring the MCP tool search auto-enable threshold, where N is the context window percentage (0-100)”; “Added plansDirectory setting to customize where plan files are stored”. ↩

  4. Claude Code CHANGELOG, section 2.1.10, fetched November 11, 2026: “Added new Setup hook event that can be triggered via --init, --init-only, or --maintenance CLI flags for repository setup and maintenance operations”; “Added keyboard shortcut ‘c’ to copy OAuth URL when browser doesn’t open automatically during login”. ↩

  5. @trq212, October 9, 2025, passing on a colleague’s setup: “Daisy’s tip for getting Sonnet 4.5 to run for 6-8 hours overnight: use hooks”; “hooks for linting & testing to make sure that Claude runs the tests and prompts it to not stop until they pass”. ↩

  6. Hooks reference, Claude Code documentation, fetched November 11, 2026, on the async field of a command hook: “If true, runs in the background without blocking.” ↩

  7. Claude Code Docs. Hooks reference: prompt-based hooks, agent-based hooks, hook environment variables ($CLAUDE_PROJECT_DIR, $CLAUDE_ENV_FILE), hookSpecificOutput format for PreToolUse. February 2026. Claude Code Docs. Create custom subagents: --agents CLI flag, disallowedTools, maxTurns, mcpServers, delegate permission mode. February 2026. The sub-agents page as captured on February 12, 2026 listed the permissionMode values default, acceptEdits, delegate, dontAsk, bypassPermissions, or plan. The page fetched November 10, 2026 has no delegate value: “default, acceptEdits, auto, dontAsk, bypassPermissions, plan, or manual as an alias for default”. ↩↩↩↩

  8. Claude Code v2.1.51 release notes, GitHub, February 24, 2026, fetched November 11, 2026: “Env var interpolation now requires an explicit allowedEnvVars list in the hook configuration.”; “HTTP hooks are now routed through the sandbox network proxy when sandboxing is enabled, enforcing the domain allowlist. HTTP hooks are not supported for SessionStart/Setup events.” Claude Code CHANGELOG, section 2.1.51, same fetch: “Added claude remote-control subcommand for external builds, enabling local environment serving for all users.”; “Added support for custom npm registries and specific version pinning when installing plugins from npm sources”; “Updated plugin marketplace default git timeout from 30s to 120s and added CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to configure.”; “Tool results larger than 50K characters are now persisted to disk (previously 100K).”; “BashTool now skips login shell (-l flag) by default when a shell snapshot is available, improving command execution performance.”; “Fixed a security issue where statusLine and fileSuggestion hook commands could execute without workspace trust acceptance in interactive mode.”; “The /model picker now shows human-readable labels”. Orchestrate teams of Claude Code sessions, Claude Code documentation, same fetch, covers plan approval for teammates and, under “Enforce quality gates with hooks”, the TeammateIdle and TaskCompleted hooks. ↩↩

  9. GitHub Releases. v2.1.63 (Feb 28): /simplify and /batch bundled slash commands, worktree-shared project configs and auto-memory, ENABLE_CLAUDEAI_MCP_SERVERS=false opt-out, HTTP hooks type: http handler, /copy ‘Always copy full response’ option, VSCode session rename/remove, /clear resets skill cache, multiple memory leak fixes, REPL bridge race condition fix. February 28, 2026. ↩

  10. GitHub Releases. v2.1.69: /claude-api skill, InstructionsLoaded hook event, agent_id/agent_type/worktree in hook events, ${CLAUDE_SKILL_DIR}, /reload-plugins, sandbox.enableWeakerNetworkIsolation, includeGitInstructions setting, remote-control custom names, Voice STT 10 new languages (20 total), effort level display, Ctrl+U exit bash, numeric keypad support, Sonnet 4.5→4.6 auto-migration. 70+ bug fixes. March 5, 2026. ↩

  11. Claude Code CHANGELOG, section 2.1.75 (March 13, 2026), fetched November 11, 2026: “Added 1M context window for Opus 4.6 by default for Max, Team, and Enterprise plans (previously required extra usage)”; “Added /color command for all users to set a prompt-bar color for your session”; “Added session name display on the prompt bar when using /rename”; “Added last-modified timestamps to memory files, helping Claude reason about which memories are fresh vs. stale”; “Added hook source display (settings/plugin/skill) in permission prompts when a hook requires confirmation”; “Breaking change: Removed deprecated Windows managed settings fallback at C:\ProgramData\ClaudeCode\managed-settings.json”. ↩

  12. GitHub Releases. v2.1.76: MCP elicitation support: MCP servers can request structured input mid-task via interactive dialogs (form fields or browser URL). New Elicitation and ElicitationResult hooks. -n/--name CLI flag for session display names. worktree.sparsePaths for git sparse-checkout in monorepos. PostCompact hook. /effort slash command. Session quality survey (feedbackSurveyRate). Bug fixes: deferred tools losing input schemas after compaction, plan mode re-approval, voice mode keypresses, auto-compaction circuit breaker (3 attempts max), clipboard copying in tmux over SSH, Remote Control session stability. March 14, 2026. ↩↩↩

  13. GitHub Releases v2.1.78. v2.1.78: StopFailure hook event, ${CLAUDE_PLUGIN_DATA} persistent plugin state, agent frontmatter (effort/maxTurns/disallowedTools), ANTHROPIC_CUSTOM_MODEL_OPTION, tmux notification passthrough, line-by-line response streaming. Security: visible warning on missing sandbox deps. Fixes: large session truncation >5MB, infinite stop hook loop, sandbox absolute paths, voice WSL2, Homebrew PATH in VS Code. March 17, 2026. ↩

  14. GitHub Releases v2.1.83. v2.1.83: managed-settings.d/ drop-in directory, CwdChanged/FileChanged hook events, sandbox.failIfUnavailable, CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1, transcript search, initialPrompt agent frontmatter, Ctrl+X Ctrl+E external editor alias, stop-all-agents changed to Ctrl+X Ctrl+K, TaskOutput deprecated. 35+ bug fixes. March 25, 2026. ↩↩

  15. Claude Code CHANGELOG, section 2.1.89 (npm, March 31, 2026), fetched November 11, 2026: “Added PermissionDenied hook that fires after auto mode classifier denials”; “Added CLAUDE_CODE_NO_FLICKER=1 environment variable to opt into flicker-free alt-screen rendering with virtualized scrollback”. v2.1.88 was published to npm on March 30, 2026 and later withdrawn: the registry keeps its publish time but no longer lists the version, GitHub has the tag but no release, and the CHANGELOG has no 2.1.88 section, so its items sit under 2.1.89. ↩

  16. GitHub Releases v2.1.84. v2.1.84: PowerShell tool (Windows opt-in), TaskCreated hook event, WorktreeCreate HTTP hook support, ANTHROPIC_DEFAULT model capability env vars, CLAUDE_STREAM_IDLE_TIMEOUT_MS, allowedChannelPlugins managed setting, paths: YAML glob list in rules/skills, MCP 2KB description cap, idle-return prompt after 75+ min, token counts 1.5m format, CJK IME fix. 25+ bug fixes. March 26, 2026. ↩

  17. GitHub Releases v2.1.94. v2.1.94: Bedrock via Mantle (CLAUDE_CODE_USE_MANTLE=1), default effort level changed from medium to high for API/Bedrock/Vertex/Foundry/Team/Enterprise, compact Slack MCP header, hookSpecificOutput.sessionTitle for UserPromptSubmit hooks, plugin skill name from frontmatter, 429 rate-limit surfacing, macOS keychain login fix, plugin hook fixes, scrollback/rendering fixes. April 7, 2026. v2.1.96 (April 8): Bedrock auth regression hotfix. ↩

  18. Claude Code CHANGELOG, composite reference for v2.1.116 (April 20, 2026), v2.1.117 (April 22, 2026), v2.1.118 (April 23, 2026), and v2.1.119 (April 23, 2026). v2.1.116: /resume 67% faster on 40MB+ sessions; faster MCP startup with multiple stdio servers (resources/templates/list deferred to first @-mention); inline thinking spinner (“still thinking”, “thinking more”, “almost done thinking”); /config search now matches option values; /doctor opens during a turn; plugin auto-install missing dependencies; Bash tool surfaces gh GitHub API rate-limit hint; Settings Usage tab shows immediately and survives rate-limited usage endpoint; agent frontmatter hooks: fire when running as main-thread agent via --agent; security fix: sandbox auto-allow no longer bypasses dangerous-path check for rm/rmdir targeting /, $HOME, or other critical roots. (The April 16 system-prompt verbosity constraint that v2.1.116 reverted is documented in the postmortem at 150 rather than the v2.1.116 release notes.)

    v2.1.117: CLAUDE_CODE_FORK_SUBAGENT=1 for forked subagents on external builds; agent frontmatter mcpServers load for main-thread agent sessions via --agent; /model selections persist across restarts even when project pins different model and startup header shows pin source; /resume offers stale-session summary; concurrent MCP startup (local + claude.ai) by default; blockedMarketplaces/strictKnownMarketplaces enforced on plugin install/update/refresh/autoupdate; Advisor Tool experimental with label, learn-more link, startup notification when enabled; cleanupPeriodDays retention sweep covers ~/.claude/tasks/, ~/.claude/shell-snapshots/, ~/.claude/backups/; OTel user_prompt events include command_name/command_source (custom/MCP names redacted unless OTEL_LOG_TOOL_DETAILS=1); cost.usage/token.usage/api_request/api_error include effort attribute; native macOS/Linux builds replace Glob/Grep with embedded bfs/ugrep via the Bash tool; default effort for Pro/Max on Sonnet 4.6 and Opus 4.6 is now high (was medium); fix: Opus 4.7 sessions were computing /context against 200K window instead of native 1M, causing premature autocompact. v2.1.118: vim visual mode (v) and visual-line mode (V) with selection, operators, visual feedback; /cost and /stats merged into /usage (typing shortcuts retained); named themes via /theme or ~/.claude/themes/*.json (plugins ship themes/ directory); hooks invoke MCP tools directly via type: "mcp_tool"; DISABLE_UPDATES env var blocks all update paths including manual claude update (stricter than DISABLE_AUTOUPDATER); WSL inherits Windows-side managed settings via wslInheritsWindowsSettings policy; $defaults sentinel in autoMode.allow/soft_deny/environment adds custom rules alongside built-in list; “Don’t ask again” auto mode opt-in; claude plugin tag creates release git tags with version validation.

    v2.1.119: /config settings (theme, editor mode, verbose) persist to ~/.claude/settings.json with project/local/policy precedence; prUrlTemplate setting points footer PR badge at custom code-review URL instead of github.com; CLAUDE_CODE_HIDE_CWD hides working directory in startup logo; --from-pr accepts GitLab MR, Bitbucket PR, GitHub Enterprise PR URLs; --print honors agent tools:/disallowedTools: frontmatter; --agent <name> honors permissionMode for built-in agents; PowerShell tool commands auto-approve in permission mode (matches Bash); PostToolUse/PostToolUseFailure hook inputs include duration_ms (tool execution time, excluding permission prompts and PreToolUse hooks); subagent and SDK MCP server reconfiguration connects servers in parallel; security: blockedMarketplaces correctly enforces hostPattern and pathPattern entries; OTel tool_result and tool_decision events include tool_use_id; tool_result includes tool_input_size_bytes; status line stdin JSON includes effort.level and thinking.enabled; tool search disabled by default on Vertex AI (opt in with ENABLE_TOOL_SEARCH). ↩↩

  19. An update on recent Claude Code quality reports. Anthropic engineering postmortem, April 23, 2026. Covers three independent quality regressions resolved by April 20 (v2.1.116), with usage limits reset for all subscribers on April 23: (1) Reasoning effort default: changed from high to medium on March 4, 2026 to cut very long latency that made the UI appear frozen; reverted April 7 after users said they would rather default to higher intelligence and opt into lower effort for simple tasks. Affected Sonnet 4.6 and Opus 4.6. (2) Prompt cache thinking-clear bug: a change meant to clear older thinking once from sessions idle for over an hour instead cleared it on every turn for the rest of the session, causing forgetfulness, repetition, and faster usage limit drain. Active March 26 to April 10, fixed in v2.1.101. Affected Sonnet 4.6 and Opus 4.6. (3) System prompt verbosity constraint: added April 16 to handle Opus 4.7’s chattiness; the post says “One of these evaluations showed a 3% drop for both Opus 4.6 and 4.7” and “This impacted Sonnet 4.6, Opus 4.6, and Opus 4.7”; reverted April 20 in v2.1.116. Anthropic’s stated mitigations: a larger share of internal staff on the exact public build, improvements to the Code Review tool it uses internally, tighter controls on system prompt changes with a broad suite of per-model evals for each one, and, for any change that could trade off against intelligence, “soak periods, a broader eval suite, and gradual rollouts”. Fetched November 11, 2026. 

  20. Claude Code release notes — composite reference for v2.1.121 (April 28, 2026, 00:31 UTC) and v2.1.122 (April 28, 2026, 22:05 UTC). v2.1.121: alwaysLoad MCP server-config option (skip tool-search deferral); MCP startup auto-retry 3x; claude plugin prune and --prune cascade; type-to-filter /skills; PostToolUse hookSpecificOutput.updatedToolOutput extended from MCP-only to all tools; .claude/skills/, .claude/agents/, .claude/commands/ exempt from --dangerously-skip-permissions prompt; Vertex AI X.509 cert-based Workload Identity Federation (mTLS ADC); SDK mcp_authenticate redirectUri; OTel adds stop_reason, gen_ai.response.finish_reasons, and user_system_prompt (gated behind OTEL_LOG_USER_PROMPTS) to LLM-request spans; /terminal-setup enables iTerm2 clipboard access for /copy from tmux; tab title in language setting; CLAUDE_CODE_FORK_SUBAGENT=1 extended to non-interactive claude -p; faster post-upgrade startup (Recent Activity panel removed from release-notes splash); claude.ai connector deduplication against same upstream URL. v2.1.122: ANTHROPIC_BEDROCK_SERVICE_TIER env var (default/flex/priority) sent as X-Amzn-Bedrock-Service-Tier; /resume PR URL search across GitHub, GHE, GitLab, Bitbucket; /mcp shows hidden connectors with remove-duplicate hint and clarifies post-browser unauthorized message; OTel claude_code.at_mention log event for @-mention resolution; numeric attributes on api_request/api_error emitted as numbers (was strings). High-signal fixes across both: ~2GB memory leak in /usage, multi-GB RSS growth on image-heavy sessions, --resume corrupt-transcript-line skip + large external-build session crash fix, Bash recovery when CWD deleted/moved, Bedrock thinking-on-application-inference-profile fix, Vertex/Bedrock output_config extra-input rejection on structured output, ToolSearch missing nonblocking MCP tools that connected after session start, image-resize ceiling 2576→2000 px on newer models, !exit/!quit in bash mode no longer kills CLI, scrollback duplication on tmux/GNOME/Windows Terminal/Konsole, malformed hooks entry no longer invalidates the entire settings.json. ↩

  21. Claude Code v2.1.132 release notes. May 6, 2026. Adds CLAUDE_CODE_SESSION_ID env var to the Bash tool subprocess (matches the session_id passed to hooks). Adds CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1 env var to opt out of the fullscreen alternate-screen renderer and keep the conversation in the terminal’s native scrollback. Updates the /tui fullscreen startup banner to describe additional renderer benefits (lower memory usage, mouse support, auto-copy on select). Plus 20+ fixes spanning terminal/input handling (SIGINT, SSH disconnects, terminal modes, cursor positioning), text editing and pasting (emoji and grapheme corruption, vim operators, escape sequences, swallowed text after paste-starts-with-/), UI/rendering (fullscreen blank screen after sleep, scroll speed, scroll-wheel handling, autocomplete popup), session management (--resume failures, emoji truncation, plan-mode --permission-mode flag), command utilities (/usage, /terminal-setup, /effort, /status, /login, /upgrade), MCP server integration (tool fetching, authorization display, non-protocol data, unbounded memory growth in stdio MCP servers, tools/list retry), platform-specific issues (Windows Terminal, JetBrains IDE, macOS keyboards, X11 Linux), and Bedrock+Vertex 400 errors when ENABLE_PROMPT_CACHING_1H is set. ↩

  22. Claude Code v2.1.133 release notes. May 7, 2026. Adds worktree.baseRef setting (fresh | head); per the release notes, “the default fresh changes EnterWorktree’s base back to origin/<default> (it has been local HEAD since 2.1.128)”, and “set worktree.baseRef: "head" to keep unpushed commits in new worktrees.” Hooks now receive the active effort level via the effort.level JSON input field and the $CLAUDE_EFFORT env var; Bash tool commands can also read $CLAUDE_EFFORT. Adds sandbox.bwrapPath and sandbox.socatPath managed settings (Linux/WSL) for custom bubblewrap and socat binary locations. Adds parentSettingsBehavior admin-tier key ('first-wins' | 'merge') to opt SDK managedSettings (parent tier) into the policy merge. Fixes subagents not discovering project, user, or plugin skills via the Skill tool. Other fixes: parallel-session 401-after-refresh-token race, drive-root allow-rule scoping, MCP OAuth proxy and mTLS support, Remote Control stop/interrupt completing the cancel, cross-session /effort leakage, --remote-control listed in --help. ↩

  23. Claude Code v2.1.191 release notes and the Claude Code Changelog (canonical). June 24, 2026. v2.1.191: /rewind supports resuming a conversation from before /clear was run; the sandbox network-permission dialog remembers allowed hosts for the session; ~37% CPU reduction during streaming responses; reduced long-session memory growth from the terminal-output cache. Fixes: stopping a background agent from the tasks panel is now permanent (no resurrection); scroll no longer jumps to the bottom while reading earlier output mid-stream; /voice explains an org-policy restriction instead of a generic “not available”; /login URL no longer truncates when wrapped in Windows Terminal; Cmd+click links in fullscreen Ghostty over ssh/tmux; claude agents no longer sends builtin slash commands (e.g. /usage) as prompt text and shows the [Image #N] placeholder for pasted images; hooks with comma-separated matchers (e.g. Bash,PowerShell) no longer silently never fire; /permissions Recently-denied approvals persist on close; the agent panel no longer jumps a row past the overflow cap; the welcome splash no longer overflows an 80×24 Terminal; managed forceRemoteSettingsRefresh now takes effect via MDM/file policy; improved MCP server reliability. Fetched June 25, 2026. ↩

  24. Claude Code Changelog (canonical), June 25 to 26, 2026 (v2.1.192 and v2.1.194 were not released). v2.1.193 (June 25): new autoMode.classifyAllShell setting routes all Bash/PowerShell commands through the auto-mode classifier instead of only arbitrary-code-execution patterns; auto-mode denial reasons added to the transcript, the denial toast, and /permissions recent denials; new claude_code.assistant_response OpenTelemetry log event carries the model’s response text, redacted unless OTEL_LOG_ASSISTANT_RESPONSES=1: when that var is unset it follows OTEL_LOG_USER_PROMPTS, so deployments already logging prompt content start receiving response content on upgrade (set OTEL_LOG_ASSISTANT_RESPONSES=0 to keep prompts-only); live file-path autocomplete in bash mode (!); startup notice when MCP servers need authentication, pointing at /mcp; automatic memory-pressure reaping for idle background shell commands (disable with CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP=1); plus fixes for stale /model state after /login, spurious backgrounding cancellation, phantom resumed-subagent spawns, and MCP headersHelper re-auth on 401/403. v2.1.195 (June 26): new CLAUDE_CODE_DISABLE_MOUSE_CLICKS env var disables mouse click/drag/hover in fullscreen mode while keeping wheel scroll; hook matchers with hyphenated identifiers (e.g. code-reviewer, mcp__brave-search) now exact-match instead of substring-matching (use mcp__brave-search__.* to match all tools from a hyphenated MCP server); plus voice-dictation fixes (macOS device-change silence; auto-submit for space-less languages), plugin enable/consent fixes, and background-job/agent-daemon reliability fixes. Fetched June 30, 2026. ↩

  25. Claude Code CHANGELOG, v2.1.214 entry. July 2026. v2.1.214: single-segment dir/** allow rules (e.g. Edit(src/**)) now match only <cwd>/dir instead of any nested dir/ in the tree, while deny/ask rules keep any-depth matching, and hook if: conditions gain the same cwd scoping (write **/dir/** for any-depth); permission fail-closed hardening: Windows PowerShell 5.1 bypass fixed, Bash file-descriptor redirect forms fail closed, commands over 10,000 characters always prompt, zsh subscripts/modifiers in [[ ]] prompt, unsafe help/man variants no longer auto-approved, remote-session prompts cannot proceed before local confirmation, docker/Podman daemon-redirect flags (--url, --connection, --identity, remote mode) prompt, and file -m/--magic-file/-f/--files-from requires permission; new EndConversation tool for ending sessions on highly abusive input or jailbreak attempts; SessionStart hooks report source "fork" for forked sessions (previously "resume"); OTel log events gain message.uuid, client_request_id, and tool_source attributes, CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH configures the 60 KB content-truncation limit, and the subagentStatusLine payload includes reasoning effort. Fetched July 21, 2026. (v2.1.213 was never released.) ↩↩

  26. Claude Code CHANGELOG, v2.1.218 entry. July 2026. v2.1.218: /code-review runs as a background subagent so review work no longer fills the conversation, with stacked slash commands remaining its review target; skills with context: fork run in the background by default, with per-skill opt-out via the new background: false frontmatter key; the dangerous-rm, background-&, and suspicious-Windows-path checks no longer open permission dialogs (the auto-mode classifier adjudicates them), and plan mode with auto no longer prompts for Bash commands the static analyzer can’t prove read-only; agent frontmatter hooks require the agent file’s own folder to have accepted workspace trust before running; /deep-research starts only when invoked manually. Plus: left-arrow discard confirmation and Esc-returns-from-agent-view; benign server-managed feature/cost toggles skip the settings-approval prompt; agent names with : rejected; yes/no/on/off/1/0 accepted for skill and plugin frontmatter booleans; trust dialogs name the repository root; improved sandbox restrictions for IDE interactions; Ctrl+B background-shell caps; Bedrock ARN spend metering; fork-session lineage after compaction in headless/SDK sessions; Windows \u-path corruption fix; remote-session zombie-heartbeat fix. Fetched July 24, 2026, when v2.1.218 (published 2026-07-22T21:24Z) was npm latest. (Attribution correction, July 25, 2026: the claude mcp list//mcp HTTP-status-and-error-text item and the MCP hidden-whitespace warning were originally listed here under v2.1.218; the raw changelog places both in the v2.1.219 entry. Moved to 193.) ↩

  27. Claude Code CHANGELOG, v2.1.219 and v2.1.220 entries. July 2026. v2.1.219 (July 24): adds Claude Opus 5 (claude-opus-5) as the new default Opus model, with 1M context, fast mode at $10/$50 per MTok; adds the sandbox.network.strictAllowlist setting to deny non-allowlisted hosts for sandboxed commands without prompting; adds the DirectoryAdded hook, which fires after /add-dir or the SDK register_repo_root control request registers a new working directory mid-session; adds mcp_server_errors to the headless stream-json init event, listing --mcp-config entries skipped by config validation (terminal runs print a startup warning); adds the workflowSizeGuideline settings key so the advisory Dynamic workflow size guideline can be set from any settings file, with the /config row hidden while one does; adds nested subagent forwarding in stream-json, so subagents spawned at depth-2+ appear when --forward-subagent-text is set, keyed by their spawning Agent tool_use id; changes dynamic workflows to default to a medium size guideline (aim for fewer than 15 agents); removes Opus 4.7 from fast mode: /fast now applies to Opus 5 and Opus 4.8; subagents can now spawn nested subagents up to depth 3 by default (was 1); set CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1 to disable nesting; updates the claude-api skill to default to Claude Opus 5 with a migration path from Opus 4.8; adds HTTP status and error text to claude mcp list and /mcp when a server fails to connect, plus a warning for MCP config values with hidden leading or trailing whitespace;

    changes managed MCP allowlist/denylist ${VAR} entries to resolve from the startup environment and managed-settings env instead of settings-file env; adds the current default workflow size to the running-workflow status line; fixes claude -p text output dropping the answer already produced when a turn dies on a mid-stream API error, the Fable row showing a stale “Requires usage credits” label, the /model picker showing the merged Opus row as plain “Opus” instead of “Opus (1M context)”, the new-release highlight covering more than the newest model’s name, GNU screen copy-on-select printing base64, Remote Control clients keeping a stale fast-mode status after a model switch/reconnect/failed org check, CLAUDE_CODE_GIT_BASH_PATH on Windows exiting or being used as bash when the path isn’t a bash/sh binary (now ignored with a warning), Vim mode ← on an empty prompt not returning to the agent view from NORMAL mode, and screen-reader mode rewriting the entire input line on every keystroke; improves the “Remote Control is only available via api.anthropic.com” error to name the setting that caused it and claude --teleport to show which repo the current checkout points at on a mismatch. v2.1.220 (July 25): bug fixes and reliability improvements only, with no user-facing feature, setting, command, or pricing changes. Fetched July 25, 2026. ↩

  28. Claude Code CHANGELOG, sections 2.1.248, 2.1.250, and 2.1.251, fetched August 30, 2026. npm published 2.1.248 on August 27, 2026 at 20:35 UTC and 2.1.250 at 22:27 UTC the same day (its section is the verbatim “Bug fixes and reliability improvements”), and 2.1.251 on August 28, 2026 at 15:34 UTC (dist-tag latest: 2.1.251); 2.1.249 was never published on npm. Verbatim 2.1.248: “Added --restricted (or CLAUDE_CODE_RESTRICTED=1): removes the built-in tools that run commands or code and WebFetch (unless named in --tools), keeps file tools inside the working directory, refuses bypassPermissions, and ignores user, project and local settings files”; “Added experimental.cacheTtl ("5m" or "1h") to agent frontmatter: a per-agent prompt cache TTL used when no subagent TTL setting is configured”; “Added claude self-hosted-runner --client-label <label> (or SELF_HOSTED_RUNNER_CLIENT_LABEL) to override the label the runner registers with (default: hostname)”; “Added server-managed settings diagnostics: a startup warning when the settings fail to load, and a /doctor and /status line explaining a load failure or why they weren’t fetched (Bedrock/Vertex/third-party provider, custom ANTHROPIC_BASE_URL)”; “Added /usage-credits for Enterprise organizations billed through AWS Marketplace, self-serve Enterprise, and Enterprise trials, so members can request a higher usage limit from their admin”;

    “Added cross-session messaging (SendMessage / ListAgents) between sessions on the same machine on Bedrock, Vertex, and Foundry, and when telemetry is disabled”; the desktop-retention fix: “the transcript cleanup now keeps desktop-written sessions while they are in the app (unless org policy manages retention); the new desktopSessionCleanupPeriodDays setting caps the exemption”; “Improved managed settings: client-side timeout, MCP startup-mode, and stream-watchdog env vars no longer trigger the settings-approval prompt”; “Changed /loop: self-paced dynamic mode and the no-prompt autonomous default are now always available, including on Bedrock/Vertex/Foundry”; “Improved the Workflow tool’s prompt footprint: its description is now about 1k tokens instead of 5.7k, with the script-writing reference moved into a bundled workflow-authoring skill”; and the upload fix: “Fixed /ultrareview and locally seeded cloud sessions uploading uncommitted edits to prod.env-style and *.tfvars files, or to editor swap, temp, and backup copies of credential files (e.g. key.pem.tmp, id_rsa.swo); they now stay on your machine”.

    Verbatim 2.1.251: “Added PreModelSwitch and PostModelSwitch hook events (block, confirm, or annotate a model switch); SessionStart resume hooks now receive session staleness and the estimated re-cache cost”; “Added live streaming of a foreground subagent’s tool calls and results to Remote Control clients (background subagents, the default, still show status only)”; “Added a Spend limit bar to /usage and a rate_limits.spend_limit status line field for developers behind a Claude apps gateway with spend limits”; “Added a per-session prompt-cache line to /cost (hit ratio, misses, tokens re-cached, warm/cold) and a matching prompt_cache object for status line scripts”; “Added attach, logs, stop, respawn, and rm to claude --help; the --resume message for a running background session now names the exact claude attach <id> command”; “Changed Claude in Chrome so browser actions always go through Claude Code’s permission checks, including in sessions with telemetry disabled, which previously used the Chrome extension’s own prompts”; “Changed CLAUDE_CODE_SUBAGENT_MODEL to set the default subagent model rather than override everything: an agent definition’s model: and an explicit per-spawn model now take precedence over it”; “Changed the default model for seat-based Enterprise subscriptions to Opus 5, matching other premium plans”; “Changed /effort to save your default effort level per model, so each model keeps its own setting when you switch”;

    “Changed server-managed settings that terminate sandbox TLS, route sandbox traffic through your own proxy, inject credentials, or weaken sandbox isolation to require approval before they apply”; “Changed ANTHROPIC_CUSTOM_HEADERS from managed or project settings to require approval when it sets a credential, org/tenant, routing, or API-behavior header (e.g. Authorization, Host)”; “Changed project-level .claude/settings.json env to no longer set CLAUDE_CONFIG_DIR, CLAUDE_CODE_TMPDIR, or TMPDIR/TMP/TEMP; set them in your shell, user, or managed settings instead”; “Fixed /usage-credits for Team and Enterprise members whose admin set the org’s usage-credit limit to $0: it now offers to ask the admin instead of saying a cap was reached”; security fixes verbatim: “Fixed file tools (Read, Write, Edit) following a symlink swapped inside the working directory after the permission check, which could read or write outside the approved location”; “Fixed plugin commands declared in a marketplace entry being able to point outside the plugin directory; such paths are now rejected with a path-traversal error”; “Fixed Bash permission checks auto-approving commands that assign an arithmetic expression to an integer shell variable (e.g. OPTIND=1/0, RANDOM=2+2); these now prompt for approval”; “Fixed Grep and Glob not applying Read(...) deny rules to files reached through a symlinked search path”. ↩↩↩

  29. Hooks reference, fetched August 30, 2026. PreModelSwitch: “Runs before Claude Code applies a model switch that you or a client requested”; “PreModelSwitch requires Claude Code v2.1.251 or later”; it runs for /model <name> and the pickers, the Model setting in /config, fast-mode toggles that change the session’s model, and SDK/Remote Control set_model or apply_flag_settings requests, but not “for switches it makes on its own, such as an automatic model fallback or restoring the model when you resume a session. Those changes reach PostModelSwitch only”; “Claude Code compares the matcher against the canonical name of the model the session is switching to, ignoring any [1m] suffix”, and when it “can’t determine a canonical name for the target”, “it runs every PreModelSwitch hook regardless of matcher”; decision control: exit code 2 or decision: "block" cancels the switch, and permissionDecision accepts "allow", "deny", and "ask"; the command-hook default timeout is lowered to 30 seconds on UserPromptSubmit, PreModelSwitch, and PostModelSwitch, and “On PreModelSwitch, a hook canceled at its timeout blocks the model switch.”

    PostModelSwitch: “Runs after the session’s model changes”; “It can’t block, because the model has already changed”; it is among the events where “Claude Code adds plain-text stdout as context that Claude can see and act on”, delivered “with the next request after the switch”; its input adds source values "auto" and "resume". SessionStart resume fields: “When source is "resume" or "fork" and the transcript contains at least one response from Claude, SessionStart hooks also receive the four fields below”; “These fields require Claude Code v2.1.251 or later”: seconds_since_last_response, context_tokens, prompt_cache_likely_expired, estimated_cache_write_usd. ↩↩↩

  30. Claude Code release notes v2.1.266 (September 8, 2026), v2.1.267 (September 9), v2.1.268 (September 10), v2.1.269 (September 11), v2.1.270 (September 12), v2.1.271 (September 14), and v2.1.272 (npm September 14, GitHub release September 15 at 00:42 UTC), and the canonical CHANGELOG on September 15, 2026 – all seven release bodies and their CHANGELOG sections are identical. npm dist-tags on September 15 (~13:15 PT): latest 2.1.272, next 2.1.273, stable 2.1.236; 2.1.273 (published September 15 at 18:06 UTC) has no GitHub release and no CHANGELOG section, so its content is not documented here; and 2.1.263 still carries only “Bug fixes and reliability improvements” – no backfill ever landed. Source for, verbatim where quoted: the /output-style revival (“Added /output-style [name] to list and switch output styles, including over Remote Control and in cloud and other headless sessions”, v2.1.269); claude plugin eval (“run a plugin’s eval suite against Claude Code and get scored, reproducible results (JSON + HTML report)”, v2.1.269); fast mode in Claude Code Remote sessions (“cloud and self-hosted runners: the host’s fast-mode setting or /fast typed in the session applies where your organization allows it”, v2.1.271) and the /fast off fix;

    the maxEffortLevel setting (“top-level or per model under modelSettings: caps the effort level on every provider, including Bedrock, Vertex and Foundry; users can still pick a lower level”, v2.1.267); --system-prompt-snapshot off (v2.1.267); the v2.1.267 prompt-cache stability batch (resumed-session tool-list, tool-description, and MCP-announcement rewrites; /model switches re-sending every tool definition, with attribution text now a conversation note; --system-prompt/--append-system-prompt sessions recording the prompt and tool definitions once; mid-session MCP and plugin tools as deferred definitions); the effort: frontmatter fix on pinned-default-effort models (Opus 4.7, Opus 4.8, Fable 5; v2.1.267); the marketplace backslash containment fix (v2.1.267); the task-tracking allowlist (“Changed the task-tracking tools (TaskCreate/Get/Update/List, TodoWrite) to be offered only on” Claude 3.x, Opus 4.0 to 4.7, Sonnet 4.0 to 4.6 and Haiku 4.5, with “set CLAUDE_CODE_ENABLE_TODO_TOOLS=1 elsewhere”, v2.1.268); the symlinked-directory and env -C/eval deny-rule fixes (v2.1.268); the WebFetch/Artifact rule split (“Changed plain WebFetch deny and ask rules to no longer apply to Artifact tool reads and updates; use an Artifact rule (or WebFetch(domain:claude.ai)) to block or gate them”, v2.1.268); /plugin changes applying on menu close (v2.1.268); the WebFetch 300-second deadline and CLAUDE_CODE_WEBFETCH_DEADLINE_MS (v2.1.268); gatewayInternalNetworks, the empty-allow_cidrs warnings, and the gateway pricing: rate sync (v2.1.268) plus the multiplier above 1 up to 10 (v2.1.271);

    the ${VAR} and git-URL secret-hygiene fixes (v2.1.268); configDirectory in claude auth status --json (v2.1.268); the third-party ANTHROPIC_BASE_URL HTTP-400 regression fix (v2.1.268); bashEditDiffEnabled (v2.1.269); the attribution-reminder fix (“Fixed the attribution reminder overriding a CLAUDE.md or memory rule against commit and pull request attribution; lines set by managed settings still apply”, v2.1.269); the env vars OTEL_METRICS_INCLUDE_REPOSITORY, CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS (1-256), CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS (default 3s), and CLAUDE_CODE_BG_TASKS_REPORT_RUNNING (v2.1.269); the v2.1.247 keyboard-regression fix and the kitty-query keyboard support over SSH (v2.1.269); the Edit()/tee, Bash(tee:*), and leading-! scoping fixes (v2.1.269); per-command allowed_domains on Bash, PowerShell, and Monitor in auto mode with sandboxing (v2.1.271); omitClaudeMd agent frontmatter and --agents JSON (v2.1.271); the auto-mode inline-! and subagent hand-back mechanics changes (v2.1.271); claude plugin install/update --accept-command <sha256> (v2.1.271); --resume keeping [1m] across model families (v2.1.271); the fail-closed unreadable managed-mcp.json (v2.1.271); the fmt/column, wildcard-expansion, variable-declaration-flag, and blockReadsOutsideWorkingDirectories checker fixes (v2.1.271); and Markdown artifacts rendering as styled document pages with artifact watches rising to 10 (v2.1.271). v2.1.266 carries one line (the CLAUDE_CODE_USE_GATEWAY regression fix), v2.1.270 one line (the v2.1.269 git-prompting regression fix), and v2.1.272 only “Bug fixes and reliability improvements”. ↩

  31. Claude Code v2.1.280 release notes (npm published September 22, 2026 at 15:44 UTC; GitHub release 16:38 UTC), and the canonical CHANGELOG on September 22 and September 23, 2026. Source for every v2.1.280 item in this guide. npm dist-tags on September 23: latest and next 2.1.280, stable 2.1.267; no 2.1.279 was ever published. Key quotes: “Added Claude Opus 5.5 (claude-opus-5-5), now the default Opus model”, with “1M context, $4/$20 per Mtok with $0.20/Mtok cache reads”; “Changed the default model on Pro and Team Standard plans from Sonnet to Opus, matching Max, Team Premium, and Enterprise”; “Fixed auto mode denying actions over and over without pause when a safety check gave no answer; retries now back off, and the turn stops with a message after ten in a row”. ↩

  32. Claude Code canonical CHANGELOG, sections 2.1.293 through 2.1.296, fetched October 11, 2026, and npm registry metadata for @anthropic-ai/claude-code read the same day: 2.1.293 published October 7, 2026 at 17:18 UTC, 2.1.294 October 8 at 03:42 UTC, 2.1.295 October 8 at 18:22 UTC, 2.1.296 October 9 at 16:58 UTC; dist-tags latest and next 2.1.296, stable 2.1.287. The GitHub release bodies (published 18:10, 05:03, 19:48, and 19:28 UTC) carry 56, 2, 143, and 79 bullets, identical to the CHANGELOG. Source for every v2.1.293 through v2.1.296 item in this guide.

    Key quotes: “Added Claude Haiku 5.5 (claude-haiku-5-5), now the default Haiku model on the Anthropic API” with “1M context, $0.10/$0.50 per Mtok ($0.50/$2.50 for prompts over 100K)”; “Added onFailure: "block" for command and HTTP hooks: a hook that can’t start, times out, or exits with an unexpected code blocks the action instead of letting it through”; “Changed the default limit on MCP tool descriptions sent up front and on MCP server instructions from 2,048 to 4,096 characters”; “Changed MCP tool descriptions the model loads through tool search to be cut at 16,384 characters instead of 2,048”; “Changed subagents to preload at most 32 skills from the skills field, each once”; “Added autoCompactWindow to subagent frontmatter and --agents definitions, so a subagent can auto-compact earlier than the main conversation’s window”; “Updated /cost, the status line, --max-budget-usd and the SDK’s cost figures to price Sonnet 5.5 cache reads at $0.10 per million tokens (was $0.20)”; “Added an allow_large option to the Read tool”; “Reverted the auto mode denial message change from 2.1.281”; “Fixed a saved Claude apps gateway sign-in being ignored on machines whose managed settings set forceLoginMethod to gateway with no forceLoginGatewayUrl (regression in 2.1.295)”. ↩

  33. Claude Code documentation, fetched October 11, 2026. Hooks: onFailure is “Whether the action that triggered the hook goes ahead when the hook fails: "continue" or "block"… Requires Claude Code v2.1.295 or later”; the failures it counts are “Can’t start”, “Exit code other than 0 or 2”, “HTTP error”, “Timeout”, and “Invalid output”; “With "block" set, a failure does what exit code 2 does on that event, except on PermissionRequest, where it denies the request”; “The field has no effect on” Stop, SubagentStop, TaskCompleted, TeammateIdle, and background (async, asyncRewake) command hooks. Environment variables: CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS “Starting delay in milliseconds of the backoff between retries of a request that the API rejects with a 529 overloaded error (default: 500)… Give whole milliseconds from 500 to 32000 in plain digits… Requires Claude Code v2.1.292 or later”; CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS “When unset, the wait has no limit. Requires Claude Code v2.1.295 or later”; CLAUDE_CODE_WEB_SEARCH_REFILLS_PER_HOUR “The default is 100 in an interactive terminal session. In a non-interactive session the default is 0, which turns refill off”; CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS “A read that Claude makes with the allow_large parameter can go past this limit when the context window has room”; VERTEX_REGION_CLAUDE_HAIKU_5_5 “Added in v2.1.293”; no entry for CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS or CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL. Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording.

    Sub-agents: the skills field preloads “up to the first 32 distinct names in the list”; the per-invocation effort parameter “overrides the effort field and stays in effect when the subagent is resumed… requires Claude Code v2.1.292 or later”; autoCompactWindow is not among the listed frontmatter fields. Status line: agentType “Requires Claude Code v2.1.293 or later”. MCP: “Claude Code asks stdio servers for that revision by default. To keep a stdio channel server on the earlier handshake, set MCP_PROTOCOL_NEGOTIATION to legacy, which keeps every server on it.” Plugin CLI reference: claude plugin install takes --marketplace <source>, “Requires Claude Code v2.1.292 or later”. Mods reference: still written “as of v2.1.290”; no entry for $.ui.notify or prompt.autocomplete. ↩

  34. Claude Code v2.1.233 release notes, August 14, 2026. Adds GitLab MR support to --worktree/claude agents (!N), opt-in forward_user_identity gateway setting, CLAUDE_CODE_TOOL_MEMORY_LIMIT (Linux cgroup for Bash commands), CLAUDE_CODE_WEBFETCH_CACHE_TTL_MS; removes todo/task-tracking tools by default on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, and newer (CLAUDE_CODE_ENABLE_TODO_TOOLS=1 restores); fixes the v2.1.232 Windows auto-mode approval regression and reverts v2.1.232’s Cygwin-symlink and input-redirection permission changes pending a narrower version; NTLM \??\ path-validation fix, MCP v2 reconnect fix, Notification-hook and Linux idle-CPU fixes, bundled-skill alias shadowing fix. Fetched August 15, 2026. ↩

  35. Claude Code v2.1.163 release notes and the Claude Code Changelog (canonical). June 4, 2026; the changelog jumps from v2.1.160 to v2.1.163 with no published 161/162. Adds requiredMinimumVersion/requiredMaximumVersion managed settings (refuse to start outside an approved version range), /plugin list with --enabled/--disabled filters, Stop/SubagentStop hookSpecificOutput.additionalContext for non-error feedback that keeps the turn going, /btw “c to copy” raw markdown, skills \$ literal-dollar escape, and stdio MCP servers receiving the session’s CLAUDE_CODE_SESSION_ID on --resume. Fixes include claude -p hanging on never-exiting background commands, Bedrock/Vertex/Foundry claude -p under CI=true demanding an Anthropic key, the v2.1.154 $TMPDIR regression breaking bazel/EDR-protected Go, OneDrive/read-only session-env EEXIST on Windows, late-applying org-managed permission rules, background sessions losing tasks across updates, hook if: "Bash(...)" over-matching $()/$VAR, and ~-path deny rules not blocking $HOME references. Fetched June 4, 2026. ↩

  36. Claude Code v2.1.152 release notes, Claude Code v2.1.153 release notes, Claude Code v2.1.154 release notes, and Claude Code Changelog (canonical). No 2.1.151 was published; the May 23, 2026 infrastructure-only release is v2.1.150. v2.1.152 (May 27, 2026) introduces /code-review --fix apply-to-working-tree, disallowed-tools skill/command frontmatter, /reload-skills, SessionStart hook reloadSkills/sessionTitle outputs, the MessageDisplay hook event, pluginSuggestionMarketplaces managed setting, --fallback-model mid-session switching, removal of auto-mode opt-in, vim / reverse history, plus rendering, performance, and reliability fixes. v2.1.153 (May 28, 2026) adds skipLfs to plugin marketplaces, makes /model save as the new-session default (with s for session-only and a modelPicker:thisSessionOnly keybind replacing modelPicker:setAsDefault), and puts COLUMNS/LINES in status-line env; macOS background agents persist Privacy & Security grants; plus 25+ fixes covering stateful MCP tools/list reconnect loops, custom-gateway OAuth-credential leak, subagent MCP policy enforcement, Windows installer / update channel fixes, and background-session attach reliability.

    v2.1.154 (May 28, 2026) makes Opus 4.8 the default with high effort by default and a new /effort xhigh level, introduces dynamic workflows orchestrating tens to hundreds of agents in the background via /workflows, makes Fast mode on Opus 4.8 available at 2× standard rate for 2.5× speed, defaults the lean system prompt for all models except Haiku/Sonnet/Opus 4.7-and-earlier, narrows the multiple-choice-question prompt to genuinely unmakeable decisions, reverts /simplify to cleanup-only review separate from /code-review --fix’s bug-hunting pass, relabels /effort slider to “Faster”/”Smarter”, adds claude agents ! <command> background-shell sessions plus claude --bg --exec '<command>', lets plugins declare defaultEnabled: false, pins suggested plugins to the current directory in /plugin Discover, makes streaming tool execution always-on, passes CLAUDE_CODE_SESSION_ID and CLAUDECODE=1 to stdio MCP subprocess env, marks unapproved .mcp.json servers as ⏸ Pending approval instead of auto-connecting, and deprecates CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE (removed June 1; switch to /model claude-opus-4-6[1m] then /fast on). Fetched May 28, 2026. ↩

  37. Claude Code canonical CHANGELOG, section 2.1.299, fetched October 14, 2026, and npm registry metadata for @anthropic-ai/claude-code read the same day: 2.1.299 published October 14, 2026 at 00:23 UTC and 2.1.300 at 14:27 UTC; dist-tags latest 2.1.299, next 2.1.300, stable 2.1.287; no 2.1.297 or 2.1.298 on npm and no CHANGELOG section for them or for 2.1.300. The GitHub release (02:49 UTC) carries 190 bullets, identical to the CHANGELOG. Source for every v2.1.299 item in this guide. Key quotes: “Added idle compaction in the terminal: a 200K+ token conversation left idle for about 54 minutes is compacted before its one-hour prompt cache expires, so your next message doesn’t reprocess it all”; “Added CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS to change idle compaction’s 200K-token minimum; "idleCompaction": false in settings.json turns it off. Both need v2.1.290 or later”; “Added CLAUDE_CODE_DISABLE_FILE_MENTIONS environment variable: Claude gets the paths of @ file mentions to read with its file tools, not the files’ contents”; “Changed MCP allow rules to reach only the server they name: mcp__a no longer allows a server named a__b or a_; write mcp__<server>__* with the server’s whole normalized name”;

    “Changed agent tools: lists to take only the named MCP server’s tools; list a server whose name contains __ as mcp__<whole name>__*”; “Changed MCP tool descriptions and server instructions from Anthropic’s first-party MCP servers at api.anthropic.com to reach Claude in full instead of being cut at 4,096 characters”; “Changed cloud session and Remote Control MCP connectors to negotiate MCP protocol version 2026-07-28 by default on installs that fetch no flags; MCP_PROTOCOL_NEGOTIATION=legacy opts out”; “Changed UserPromptSubmit hooks to run before a skill or custom slash command expands, so a hook that blocks the prompt now also stops its embedded shell commands”; “Changed the turn.start mod hook to also hear subagents’ and teammates’ turns, not only the main loop’s; tell them apart by e.agentId (absent on the main loop)”; “Fixed rm prompts on shell -c scripts that don’t run rm. An rm built at run time in a script Claude Code can’t read no longer prompts unless CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT=1”;

    “Added --shutdown-drain-sec to claude self-hosted-runner orchestrator: on SIGTERM it stops polling and gives the poll in flight and running spawn hooks up to that many seconds to finish”; “Added --disallow-tools and a disallowed_tools case field to claude plugin eval to keep specific built-in tools, such as Agent, out of eval runs”; “Added support for turning off the attribution block in Claude Desktop’s Code tab: set CLAUDE_CODE_ATTRIBUTION_HEADER=0 in the env of a Claude apps gateway’s code policy”; “Added /effort and /fast in agent view to set what new sessions start with; a bare /model, /effort or /fast there now opens a picker”; “Changed actions a plugin hook can block to be refused, not let through, when the hook cannot be handed them or cannot hand back its answer; a tool that already ran has its result withheld”; “Fixed a regression in 2.1.296 where cloud and headless sessions could run an approved tool call twice if a new message arrived as the session resumed after a restart”; “Changed the cyber safeguard notice to no longer ask people to apply to the Cyber Verification Program”. ↩

  38. Claude Code documentation, fetched October 14, 2026. Settings reference: idleCompaction, “Stop Claude Code from compacting a long conversation that you’ve stepped away from”; “Idle compaction is on by default for conversations that meet its conditions. To turn it off, set idleCompaction to false. Requires Claude Code v2.1.290 or later”. Environment variables: CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS “Context size, in tokens, at which idle compaction applies to a conversation (default: 200000)”, with values below 100000 raised to 100000; CLAUDE_CODE_DISABLE_FILE_MENTIONS “Requires Claude Code v2.1.299 or later”, ignored in project and local settings; CLAUDE_CODE_ATTRIBUTION_HEADER “Set to 0 to omit the attribution block”; CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS “Ceiling in milliseconds on the backoff between retries of a request that the API rejects with a 529 overloaded error (default: 32000)”; still no entry for CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL or CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT. Sub-agents: autoCompactWindow is now a listed frontmatter field, “a token count of 100000 or more”; tools and disallowedTools “also take entries for a whole MCP server”. Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording.

    Mods reference: still “as of v2.1.290”; “On skill.prompt, e.source, e.pluginName, e.path, e.frontmatter, and e.frontmatterProblem require Claude Code v2.1.299 or later”; turn.start is listed among the events; no $.prompt.media, $.session.identity, tabular, or serverToolUses. Plugin evals: “Before v2.1.299, such a run was graded on what it had produced”; no --disallow-tools. MCP: the limits list still reads “Server instructions, and the description of a tool that loads upfront: 4,096 characters” with no first-party exception; on the v2 runtime Claude Code “Asks HTTP, stdio, and claude.ai connector servers whether they support the newer revision, and uses it with those that do”. Permissions: “Allow rules accept tool-name globs only after a literal mcp__<server>__ prefix. The server segment must be glob-free so the rule names a specific server you configured.” Hooks: CLAUDE_CODE_DISABLE_FILE_MENTIONS is described (“your matching PreToolUse hooks run”); no statement that UserPromptSubmit runs before a skill or command expands. ↩

  39. Claude Code canonical CHANGELOG, section 2.1.300, fetched October 14, 2026 (21:40 PT), and npm registry metadata for @anthropic-ai/claude-code read at the same time: 2.1.300 published October 14 at 14:27 UTC; dist-tags latest 2.1.300, next 2.1.300, stable 2.1.292 (it was 2.1.287 that morning). The GitHub release (18:24 UTC) carries 88 bullets, identical to the CHANGELOG. Source for every v2.1.300 item in this guide. Key quotes: “Added /advisor on Claude Platform on AWS; no advisor runs until you pick one with /advisor, advisorModel or --advisor, and CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1 turns it off”; “Added virtualText to a mod’s prompt decorations: text drawn in the prompt box that never enters the draft or the submitted prompt”; “Added $.ui.view({ agentId }) for mods: shows an agent’s transcript in the main view when you ask, and $.ui.view({}) goes back”; “Added the prompt.change mod hook, raised when the prompt box’s text changes without a typed edit: a recalled history entry, a clear, an undo, or a plugin’s fill”; “Added cache_creation_5m_tokens and cache_creation_1h_tokens to the OpenTelemetry api_request event, splitting cache writes by lifetime”;

    “Added OpenTelemetry GenAI semantic-convention attributes to trace spans, such as gen_ai.provider.name, gen_ai.conversation.id, gen_ai.tool.name and error.type”; “Changed large requests to api.anthropic.com to use gzip compression even when telemetry is disabled; set CLAUDE_CODE_GZIP_REQUEST_BODIES=0 to turn it off”; “Changed hooks: updatedInput from PreToolUse and PermissionRequest hooks is now validated like Claude’s own input: unknown keys are dropped, and input the tool rejects denies the call”; “Removed the --sandbox and --no-sandbox flags from claude remote-control, which had no effect; passing either now exits with an error. Set sandbox.enabled in settings to sandbox sessions”; “Changed local session transcripts to also record each API request’s system prompt, tools and parameters, so a transcript you choose to share can reproduce a request exactly”; “Changed exit to force-kill background commands still running 1.5 seconds after being asked to stop”; “Fixed SessionEnd hooks sometimes not running when you exit while a background command is still running”; “Fixed claude daemon stop --any printing "stopped" while a stuck background service kept running: it now waits, force-kills the service, and says so with exit 1 if it is still there”. ↩

  40. Claude Code canonical CHANGELOG, sections 2.1.301 and 2.1.302, fetched October 17, 2026 (15:40 PT), and npm registry metadata for @anthropic-ai/claude-code read at the same time: 2.1.301 published October 15 at 14:34 UTC, 2.1.302 on October 16 at 16:48 UTC; dist-tags latest 2.1.302, next 2.1.302, stable 2.1.292. The GitHub releases v2.1.301 (19:22 UTC, 51 bullets) and v2.1.302 (20:53 UTC, 63 bullets) are identical to the CHANGELOG. Source for every v2.1.301 and v2.1.302 item in this guide. Key quotes, 2.1.302: “Changed claude -p and Agent SDK sessions with no permission mode to start in default mode on third-party providers, with telemetry off or on a fresh install; --permission-mode auto keeps auto”; “Changed fork subagents (subagent_type: "fork") to be on by default in claude -p, the Agent SDK, the desktop app and VS Code, as they already are in the terminal; CLAUDE_CODE_FORK_SUBAGENT=0 turns them off, and claude mcp serve never offers them”; “Changed the desktop app and VS Code to always run the main conversation’s subagents in the background, as the terminal does, rather than let Claude choose; a subagent’s own Agent calls in claude -p, the Agent SDK, the desktop app and VS Code now run in the foreground by default”;

    “Changed prompt and agent hooks so that at most 12 of one event run at a time; the rest wait their turn”; “Added CLAUDE_CODE_AUTO_MODE_MODEL to choose the model the client-side auto mode classifier uses; it does not change the model for server-side auto mode”; “Added an Idle compaction row to /config for turning idle compaction off or back on; the notices shown after an idle compaction now say how to turn it off”; “Added a notice to /design-sync and /design-login that standalone Claude Design (claude.ai/design) closes by December 14, 2026”; “Fixed the Read tool loading an image file of any size, or a pipe or device named like an image, entirely into memory; image sources over 128 MB are now refused”; “Improved auto mode with the server-side classifier: a conversation too long for the safety check is now compacted, instead of every checked tool call being denied”.

    2.1.301: “Added CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS so unattended retry mode (CLAUDE_CODE_RETRY_WATCHDOG) ends a request at a usage limit that resets too far away instead of waiting”; “Added the % motion to vim mode: jump to the matching bracket, alone or with d/c/y”; “Added rows to a mod’s Input: a text field of several lines in the terminal, where Enter submits and Shift+Enter or a backslash before Enter starts a new line”; “Added classifier_verdict and permission_mode to OpenTelemetry tool_decision events, so auto mode classifier decisions can be told apart from permission rules”; “Added classifier_category to OpenTelemetry tool_decision events, naming the built-in rule a classifier block matched, when OTEL_LOG_TOOL_DETAILS=1”; “Fixed the fable (and best) model alias erroring on the Anthropic API when the newest Fable model is not available to your organization: Claude Code now retries once on the previous Fable model”; “Improved switching to a model with a smaller context window: a conversation too long for the new model is now summarized by the previous model first”; “Changed a mod hook’s .catch handler to run only when the hook throws or times out; events raised beneath the hook’s own calls now skip that hook without asking its .catch”; “Changed a mod’s $.env.set to resolve with {} once the variable is set or unset, or with { deny } saying why when the write is not made”. ↩

  41. Claude Code documentation, fetched October 17, 2026. Interactive mode: “% | Jump to the matching (), [], or {} bracket, starting from the next bracket on the current line when the cursor isn’t on a bracket. Requires Claude Code v2.1.301 or later” and “d%/c%/y% | Delete, change, or yank from the cursor through the bracket that % jumps to”. VS Code lists LaTeX math rendering. Still on the pre-2.1.302 rules: the permission modes table (“claude -p or the Agent SDK | default in sessions that fetch feature flags. In sessions that don’t, such as on a third-party provider or with telemetry off, auto with Claude Code v2.1.285 or later”); the environment variables page (CLAUDE_CODE_FORK_SUBAGENT “is on by default in interactive sessions only. Set to 1 to turn it on in claude -p and the Agent SDK as well, or 0 to turn it off in every kind of session”); and the subagents page (“Fork mode is off in non-interactive mode with -p and in the Agent SDK unless you turn it on”).

    Not in the docs at all: CLAUDE_CODE_AUTO_MODE_MODEL, CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS, the tool_decision attributes classifier_verdict, permission_mode, and classifier_category (monitoring lists none of them), the /config Idle compaction row, the Claude Design closing date, and the 12-hook cap (hooks: “All matching hooks run in parallel”). The mods docs now form a section: overview, reference (“Entries cover the Claude Code CLI and the Desktop app as of v2.1.290, and the VS Code extension as of v2.1.299”), events (.catch: “When guard throws or times out on a Bash call, Claude Code calls the handler with the same event”, without the v2.1.301 re-entry rule), API, and interface; none of the new pages mentions rows on Input, $.env.set, nothing-to-fork, virtualText, $.ui.view, prompt.change, $.prompt.media, or $.session.identity. The advisor page still says the tool “is not available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry”. ↩

  42. Hooks reference, Claude Code documentation, fetched October 21, 2026 and re-read November 25, 2026; every quotation here is the November 25 wording. JSON output: “Print nothing but the JSON object to stdout.”; “Universal fields like continue are listed in the table below. Every event accepts them, but some events discard them or deliver systemMessage somewhere other than the transcript. Each event’s section says so.”; “Top-level decision and reason are used by some events to block or provide feedback.”; “hookSpecificOutput is a nested object for events that need richer control. It requires a hookEventName field set to the event name.” Universal fields table: continue “If false, Claude stops processing entirely after the hook runs. It doesn’t block a PreToolUse tool call, so to do that, also return permissionDecision: "deny"”; stopReason “Message shown to the user when continue is false. It stays in the conversation, so Claude sees it if the conversation continues”; suppressOutput “Has no effect”; systemMessage “Warning message shown to the user. In Agent SDK and --output-format stream-json output, it can arrive as an SDKInformationalMessage”; terminalSequence “A terminal escape sequence for Claude Code to emit on your behalf, such as a desktop notification, window title, or bell. Restricted to OSC 0/1/2/9/99/777 and BEL. If the value contains anything outside the allowlist, the field is ignored.”, with the limit “Claude Code writes the sequence only in an interactive session, and only while its interface is open. In non-interactive mode with the -p flag and in the Agent SDK, it ignores the field.” Where continue: false does something else: “on events such as Stop and SubagentStop, the field takes precedence over exit code 2, so Claude or the subagent ends its turn”; “On PreToolUse, the tool call stays blocked with or without the field.”; TaskCreated, “Claude Code ignores continue: false from this event and Claude keeps working.” Exit code 0: “your stdout counts as JSON output only when you print one JSON object, on one line or several, with nothing around it but whitespace”; “Claude never sees stderr from a hook that exits 0.” Other exit codes: “A <hook name> hook error notice with Failed with non-blocking status code: means your hook didn’t exit 0 or 2 and its stdout was plain text or empty.”; “If the notice cuts off your stderr, turn on debug logging”. Failed hooks on Windows without Git Bash: “a shell-form PreToolUse, PermissionRequest, or PreSkillShellCommand command hook that fails with onFailure unset can instead block the action”; “The call should go ahead when the hook fails: add "onFailure": "continue" to the hook”. Failures counted: “MCP failure: an mcp_tool hook’s server isn’t connected, or its tool returns an error.”

    The word “modifications” occurs on the page only in the ConfigChange prose (“block unauthorized modifications to configuration files”), never as an output field. Exit code 0: “For most events, Claude Code writes stdout to the debug log and doesn’t show it in the transcript. The exceptions are UserPromptSubmit, UserPromptExpansion, SessionStart, and PostModelSwitch, where Claude Code adds plain-text stdout as context that Claude can see and act on.” JSON output: “Print nothing but the JSON object to stdout. For a hook that isn’t async, other text there, such as a line your shell profile echoes at startup, keeps Claude Code from reading the object as JSON, and Hook JSON has no effect shows how to find and silence that text.”

    Exit code 0 with JSON: “Claude Code applies any JSON output fields your hook printed, and the action goes ahead unless those fields block or deny it.” Other exit codes: “Unless the hook is one whose failure blocks the action, this is a non-blocking error, so your hook didn’t stop the action.”; “To capture your hook’s full stderr rather than the first line the notice shows, enable debug logging.”; and in the output table, any other exit code with a “JSON object that passes schema validation” is “Success. Claude Code ignores the exit code, and the fields alone decide. For hooks whose failure blocks the action, the run counts as a failure instead”. terminalSequence: “Claude Code writes the sequence only in an interactive session, and only while its interface is on screen. In non-interactive mode with the -p flag and in the Agent SDK, it ignores the field.” Re-read November 10, 2026: the page now adds “PreCompact: your stdout becomes instructions for the compaction summary” to the events whose stdout is used. ↩↩↩↩↩

  43. Claude Code CHANGELOG, v2.1.311 through v2.1.317 (commits 2026-10-26T21:51Z, 10-27T20:23Z, 10-30T01:06Z, 10-31T01:01Z, and 11-03T01:25Z) and the matching GitHub releases v2.1.311 (2026-10-26T21:51:23Z), v2.1.312 (10-27T20:24:20Z), v2.1.314 (10-30T01:06:26Z), v2.1.316 (10-31T01:01:35Z), and v2.1.317 (11-03T01:25:46Z), each identical to its CHANGELOG section; npm publish times from npm view @anthropic-ai/claude-code time: 2.1.311 2026-10-26T19:47:57Z, 2.1.312 10-27T18:36:10Z, 2.1.314 10-30T00:12:56Z, 2.1.315 10-30T21:05:24Z (no CHANGELOG entry, no GitHub release), 2.1.316 10-31T00:42:05Z, 2.1.317 11-02T23:57:53Z; dist-tags on 2026-11-02: latest and next 2.1.317, stable 2.1.311. Verbatim, 2.1.311: “Changed ultrathink in the interactive terminal to run its turn at xhigh effort on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 through Anthropic’s API; typed while Claude is working, it raises the rest of that turn”. 2.1.316: “Deprecated fast mode for Opus 4.8 as of October 30, 2026; it will be removed on November 30, 2026. After removal, fast mode requests on Opus 4.8 return an error and do not fall back to standard Opus 4.8. Migrate to Opus 5.5 to keep the speedup”. 2.1.314: “Added permissions.blockWritesOutsideWorkingDirectories: Write, Edit and NotebookEdit refuse paths outside the working directories in every permission mode”. 2.1.312: “Changed prompt and agent hooks to run at most 24 at a time per session, sub-agents included, plus at most 12 that have waited longer than their event’s timeout; a timeout under 1 second now counts as 1 second”; “Changed Claude Code to stop sending the claude_code.safety_event OpenTelemetry event”. 2.1.317: “Added anthropic.plan, anthropic.seat_type, anthropic.provider and anthropic.custom_base_url to OTel metrics, events and spans”. ↩↩↩

  44. Tools reference, Claude Code documentation, fetched November 10, 2026. Task tools: “The task-tracking tools, TaskCreate, TaskGet, TaskUpdate, TaskList, and TodoWrite, are available by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlier models”, with CLAUDE_CODE_ENABLE_TODO_TOOLS=1 or claude --allowedTools TaskCreate to opt in, and “In background sessions and in cloud sessions, Claude Code provides the same tools on every model”. WebSearch: “An interactive terminal session has a limit of 200 WebSearch calls”; “on Claude Code v2.1.290 or later, an interactive terminal session’s limit refills at about 100 calls per hour”; “The cap can be raised but not turned off”; “In non-interactive mode with -p and in the Agent SDK, the limit applies per turn, not per session.” ↩

  45. Hooks reference, Claude Code documentation, fetched November 10, 2026. Matchers: “Only letters, digits, _, -, spaces, ,, and |” are compared as an “Exact string, or list of exact strings”, and “The .* is required: a matcher like mcp__memory or mcp__brave-search contains only exact-match characters, so it is compared as an exact string and matches no tool.” Events: Setup fires “When you start Claude Code with --init-only, or with --init or --maintenance in -p mode” and “Fires only when you launch Claude Code with --init-only, or with --init or --maintenance in non-interactive mode with the -p flag”; FileChanged: “The matcher field specifies which filenames to watch”; WorktreeRemove: “Any non-zero exit code causes worktree removal to fail if the directory still exists afterward”; PermissionRequest: “Not read as a decision. Deny through the decision object instead”; PermissionDenied: “Use JSON hookSpecificOutput.retry: true to tell the model it may retry”; InstructionsLoaded: “Exit code is ignored”. Output: “PreCompact: your stdout becomes instructions for the compaction summary”. PreToolUse decisions: “"allow" skips the permission prompt, except for actions no mode auto-approves and reads from network paths” and, for the reason, “For "allow" and "defer", written to the debug log only”. Also the source for the common input fields, the hook locations (settings files, plugin hooks/hooks.json, skill and agent frontmatter), “CLAUDE_ENV_FILE is available for SessionStart, Setup, CwdChanged, and FileChanged hooks”, updatedMCPToolOutput (“Replaces the output for MCP tools only. Prefer updatedToolOutput”), and the debug log: “The --debug flag doesn’t print to the terminal.” Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording. ↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩

  46. Hooks reference, Claude Code documentation, fetched November 11, 2026. Hook types by event: “Events that support all five hook types (command, http, mcp_tool, prompt, and agent)” lists PermissionDenied, PostToolBatch, PostToolUse, PostToolUseFailure, PreToolUse, Stop, SubagentStop, TaskCompleted, TaskCreated, TeammateIdle, UserPromptExpansion and UserPromptSubmit; “PermissionRequest supports command, http, mcp_tool, and prompt hooks but not agent hooks”; “PermissionRequest: ok: false doesn’t deny the request”; “Agent hooks are experimental.” Timeouts: “Defaults: 600 for command, http, and mcp_tool; 30 for prompt; 60 for agent.” Concurrency: “If more than 12 of them are prompt or agent hooks, 12 of those run at once and the rest start as running ones finish.” Hooks in skills and agents: defined “in the same configuration format as settings-based hooks”; “Claude Code converts a Stop hook here to SubagentStop”; skill hooks are kept “for the rest of the session”; once: “If true, Claude Code removes the hook after its first successful run … Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter”. The page’s skill example nests each handler under a hooks: list inside its matcher entry. Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording. ↩↩↩↩↩

  47. Environment variables, Claude Code documentation, fetched November 10, 2026: CLAUDE_CODE_SESSION_ID: “Set automatically to the current session ID in Bash and PowerShell tool subprocesses, hook command subprocesses, and stdio MCP server subprocesses”; CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION: “Removed in v2.1.224 and now a no-op”; CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: “Set to 1 to disable adaptive reasoning on Opus 4.6 and Sonnet 4.6 and fall back to the fixed thinking budget controlled by MAX_THINKING_TOKENS”; MAX_THINKING_TOKENS: “Claude Code caps it at one token below the request’s max output tokens and never below 1,024 … When unset and thinking is enabled, models with adaptive reasoning choose their own thinking depth, and other models use the cap … For a positive value, Claude Code ignores the number itself on adaptive reasoning models”. ↩

  48. Automate actions with hooks and the Hooks reference, Claude Code documentation, fetched November 10, 2026. Guide: “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”. Reference: timeout is “Seconds before canceling”; on exit 2, PostToolUse “Shows stderr to Claude; the tool already ran” and Stop “Prevents Claude from stopping, continues the conversation”. ↩

  49. Hooks reference, Claude Code documentation, fetched November 11, 2026. Async hooks: “set "async": true to run the hook in the background while Claude continues working”; “This field is only available on type: "command" hooks.” duration_ms: “Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks”. The Read, Edit and Write tool inputs each list file_path: “Absolute path to the file to read”, “Absolute path to the file to edit”, “Absolute path to the file to write”. Automate actions with hooks, same fetch, under “Block edits to protected files”: “Add a PreToolUse hook to .claude/settings.json that runs the script before any Edit or Write tool call”. Configure permissions, same fetch: “Read and Edit deny rules apply to Claude’s built-in file tools, to file commands Claude Code recognizes in Bash, such as cat, head, tail, sed, and tee”; “For OS-level enforcement on sandboxed shell commands, enable the sandbox and turn off the unsandboxed retry.” Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording. ↩↩↩

  50. Agent SDK changelogs, fetched November 11, 2026. TypeScript SDK CHANGELOG, 0.3.208: “Fixed a caller abort during a pending SDK hook callback being converted into hook success, which let PreToolUse-gated tools execute after the abort”. Python SDK CHANGELOG, 0.2.127: “Previously, closing stdin too early caused SDK-MCP tool calls from background tasks to fail with "Stream closed" and silently bypassed PreToolUse hooks.” ↩

  51. Claude Code CHANGELOG, fetched November 11, 2026. 2.0.72: “Changed thinking toggle from Tab to Alt+T to avoid accidental triggers”. 2.1.0: “Added hooks support to agent frontmatter, allowing agents to define PreToolUse, PostToolUse, and Stop hooks scoped to the agent’s lifecycle”; “Added hooks support for skill and slash command frontmatter”; “Improved subagents (Task tool) to continue working after permission denial, allowing them to try alternative approaches”. 2.1.7: “Enabled MCP tool search auto mode by default for all users. When MCP tool descriptions exceed 10% of the context window, they are automatically deferred and discovered via the MCPSearch tool instead of being loaded upfront.” ↩

  52. Create custom subagents, Claude Code documentation, fetched November 11, 2026. Permission modes: “If you leave it unset, the subagent inherits the main conversation’s permission mode.”; “The main conversation’s permission mode decides whether Claude Code uses the value you set”; “When the main conversation is in bypassPermissions, acceptEdits, or auto mode, your subagent runs in that same mode and Claude Code ignores the permissionMode you set.”; “When the main conversation is in plan mode, the subagent stays in plan mode whichever permissionMode you set, unless it runs as an agent team teammate under the agent teams rules.”; “When the main conversation is in default or dontAsk mode, the subagent runs in the permission mode you set. It keeps the main conversation’s permission mode instead in cases such as these”; “You set bypassPermissions. The bypassPermissions exception requires Claude Code v2.1.267 or later.”; “You set auto and auto mode isn’t available to the subagent”. Re-read November 25, 2026; the quotations that had drifted are given in that day’s wording.

    Tools: “To restrict tools, use the tools field as an allowlist or the disallowedTools field as a denylist.”; “Inherits every tool available to subagents if omitted.”; Explore and Plan each list “read-only tools; Write and Edit are denied”. Context and model: “Each subagent starts with a fresh, isolated context window.”; “A fork is a subagent that inherits the entire conversation so far instead of starting fresh.”; the model order is “The per-invocation model parameter”, “The subagent definition’s model frontmatter, where inherit selects the main conversation’s model”, “The CLAUDE_CODE_SUBAGENT_MODEL environment variable, when you set it to a model alias or model ID”, “The main conversation’s model”.

    omitClaudeMd: “managed policy files still load, except for managed subagents”; “Ignored when the agent runs as the main session agent via --agent or the agent setting.” experimental: “ignores 1h while your Claude subscription is using usage credits”. memory: “if you turn auto memory off, with the autoMemoryEnabled setting or CLAUDE_CODE_DISABLE_AUTO_MEMORY, the memory field has no effect”. skills: “You can’t preload skills that set disable-model-invocation: true”. mcpServers: “Claude Code loads an inline MCP server from an agent file in your project’s .claude/agents/ directory, or in an --add-dir directory’s .claude/agents/, only after you trust the folder the agent file came from. Before v2.1.238, Claude Code loaded these servers without checking trust.” Frontmatter hooks: “To let a project-level subagent’s frontmatter hooks run, accept the workspace trust dialog for the folder that contains the agent file. Hooks from user-level subagents in ~/.claude/agents/ and from definitions you pass with --agents run without this step.” Choose a permission mode, same fetch: “With Claude Code v2.1.283 or later, auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions.” ↩

  53. Agent SDK reference - Python and Agent SDK reference - TypeScript, Claude Code documentation, fetched November 11, 2026. Python, include_hook_events on ClaudeAgentOptions (default False): “Include hook lifecycle events in the message stream as HookEventMessage objects”. TypeScript, includeHookEvents (default false): “Include hook lifecycle events in the message stream as SDKHookStartedMessage, SDKHookProgressMessage, and SDKHookResponseMessage.” ↩

  54. Claude Code documentation, fetched November 11, 2026. Claude Code settings: “Settings files are strict JSON: a // comment or a trailing comma is a syntax error, and Claude Code reports the file as a Settings Error at the next start.” Hooks reference, under “Matcher patterns”: a matcher of *, an empty string, or no matcher at all is evaluated as “Match all”; “Bash matches the Bash tool”; “mcp__memory__.* matches every tool from the memory server”; “If you add a matcher field to an event without matcher support, it is silently ignored.”; the row that lists UserPromptSubmit reads “no matcher support” and “always fires on every occurrence”. Orchestrate teams of Claude Code sessions: “Enable them by setting the CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS environment variable to 1, either in your shell environment or through settings.json”. ↩

  55. Claude Code CHANGELOG, v2.1.323 through v2.1.332, fetched November 25, 2026 (294, 139, 367, 173, 144, 130, 142, 135, and 150 top-level bullets for 2.1.323, 2.1.325, 2.1.326, 2.1.327, 2.1.328, 2.1.329, 2.1.330, 2.1.331, and 2.1.332; no 2.1.324 section), and the GitHub releases v2.1.323 (2026-11-12T22:12:13Z), v2.1.325 (11-13T20:40:01Z), v2.1.326 (11-16T22:11:05Z), v2.1.327 (11-17T23:17:45Z), v2.1.328 (11-19T01:14:04Z), v2.1.329 (11-19T22:14:41Z), v2.1.330 (11-20T22:32:56Z), v2.1.331 (11-23T21:34:41Z), and v2.1.332 (11-25T01:32:14Z); no v2.1.324 release exists. npm publish times from npm view @anthropic-ai/claude-code time: 2.1.323 2026-11-12T20:29:28Z, 2.1.324 11-13T18:42:36Z, 2.1.325 11-13T20:07:25Z, 2.1.326 11-16T18:43:39Z, 2.1.327 11-17T20:33:19Z, 2.1.328 11-18T23:09:39Z, 2.1.329 11-19T18:40:25Z, 2.1.330 11-20T19:16:01Z, 2.1.331 11-23T18:36:26Z, 2.1.332 11-24T22:06:38Z; dist-tags on 2026-11-25: latest 2.1.332, next 2.1.332, stable 2.1.326. Verbatim, 2.1.332: “Changed the default model on Microsoft Foundry to Sonnet 5.5: deploy claude-sonnet-5-5, or set ANTHROPIC_DEFAULT_SONNET_MODEL to a model you have deployed”; “Changed the sonnet model alias on Google Cloud’s Agent Platform and Microsoft Foundry to Sonnet 5.5, and Foundry’s opus alias to Opus 5.5; sonnet on Amazon Bedrock stays at Sonnet 4.5”; “Added a PreSkillShellCommand hook event that can refuse a skill or command’s inline shell commands as it loads; on 2.1.331 and older, a settings file naming it opens a dialog at start”; “Added skills from MCP servers (beta). They show as server:skill in the / menu; other skills keep their names”; “Changed /schedule, permission prompts and /loop’s cloud offer to say “cloud scheduled task” instead of “routine” or “cloud schedule”; /routines still works”. 2.1.330: “Changed recurring scheduled tasks and /loop to run up to 30 days instead of 7 while their session keeps running, and say when they end; tasks made before this release still end at 7 days”. 2.1.328: “Added auto mode for Claude Opus 4.6 and Sonnet 4.6 on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry and Claude apps gateway; interactive sessions with no permission mode start in it”. 2.1.325: “Changed sandboxed Bash commands to follow the normal permission flow by default; set sandbox.autoAllowBashIfSandboxed: true to keep running them without prompts”. 2.1.323: “Added Code Mode, an experimental opt-in in which Claude writes JavaScript to call its tools”; “Removed the subagentStatusLine setting: subagent rows always use the default look, and settings files that still hold the key load as before”; “Changed the context window assumed for a model ID that Claude Code doesn’t recognize from 200K to 1M; use /autocompact to compact earlier, or CLAUDE_CODE_DISABLE_1M_CONTEXT=1 to keep 200K”; “Changed MCP_SDK_GENERATION=v1 to run the v2 MCP client in a compatibility mode (earlier handshake, relaxed OAuth sign-in checks), because the v1 MCP client is removed”. ↩↩

  56. Hooks reference, Claude Code documentation, fetched November 25, 2026 (34 rows in the event table). PreSkillShellCommand: “Runs before an injected command, a shell command that runs while a skill or a command such as /security-review loads. PreToolUse hooks don’t fire for injected commands.”; “Requires Claude Code v2.1.332 or later, including in the desktop app and VS Code extension.”; “an earlier version such as v2.1.331 opens each interactive terminal session with a warning dialog: Unknown hook event "PreSkillShellCommand" was ignored”; “If you configure a prompt or agent hook on this event, Claude Code can’t run it and blocks each command the hook matches.”; “Your script runs after the permission check on injected commands, so it gets the commands that passed. It also runs in bypassPermissions mode.”; “You can block a command from this hook, but you can’t approve or change one.” On failures: “set "onFailure": "block" on a command, http, or mcp_tool hook. Requires Claude Code v2.1.295 or later. On mcp_tool hooks, onFailure requires v2.1.328 or later.” Reusing the script: “You can reuse the blocking script from How a hook resolves.”; “To use one script on both events, leave hookEventName as PreToolUse.”; the script printed under “How a hook resolves” is saved as .claude/hooks/block-rm.sh, and the page adds “install jq and make sure it is on your PATH”. ↩↩↩↩

  57. Intercept and control agent behavior with hooks, Claude Agent SDK documentation, fetched November 25, 2026, “Block the action when a callback fails”: “On most events, if a callback throws or returns output that fails validation, the action goes ahead and your app receives an SDKInformationalMessage warning whose tag is hook_callback_failed.”; “To block the action instead, set onFailure: "block" in TypeScript or on_failure="block" in Python on the matcher. Requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later.”; “Stop, SubagentStop, TaskCompleted, and TeammateIdle: these events ignore the option, so the action goes ahead.”; “With "block" set, a path with no return blocks the action.” TypeScript Agent SDK CHANGELOG, 0.3.317: “Added onFailure to hook matchers: with "block", a hook that throws or returns invalid output blocks the action”; 0.3.325: “Added a system/informational warning, tagged hook_no_verdict, when a PreToolUse hook can’t run or answer, or times out, without refusing its tool call”. Python Agent SDK CHANGELOG, 0.2.177: “Set on_failure="block" to block the action when a callback raises, returns None, or returns a value the CLI rejects.” ↩