Findings

2026-11-24Claude Code 2.1.332Model: Opus 5.5ultrathink
▾

Safety classifier stops and model fallbacksince 2.1.332

Tested on Claude Code 2.1.332 with 24 throwaway claude -p sessions: six kinds of request a safety classifier could flag (cyber, a jailbreak, adult content, a self-harm crisis, an eating disorder, weapons), on opus and haiku, each asked in one turn and again in two turns. Each session also asked the model to quote, word for word, every text in its context that the user did not write. The texts below are read from the session transcripts (system entries and the user message the client adds).

Note: none of the server-side injections reported for claude.ai (the long conversation reminder, the ethics reminder, the self-harm and eating disorder notes) reached the model in any of the 24 sessions. In every session the model quoted only Claude Code's own attachments. What Claude Code does have is the client-side path below.

What happens when a classifier stops a response
  1. The API ends the response with stop_reason: "refusal".
  2. Claude Code shows a notice and tries once more. It adds a user message to the conversation, so the model sees it on every later turn:
Your response above was stopped by a safety classifier — this is not a tool or API error. The rest of it was withheld, and tool calls in it that had not finished did not run. Do not produce that content again, even reworded.

The transcript records the notice as a system entry, subtype informational, level notice:

Haiku 5.5's safeguards stopped the response above · continuing once with that noted
  1. If the retry is stopped too, Claude Code moves the session to an older model. A system entry, subtype model_refusal_fallback, level warning, records originalModel and fallbackModel:
Opus 5.5's safeguards flagged this session. You may be seeing this for the first time: Opus 5.5 is more capable and has stronger safeguards as a result, which can sometimes flag non-cybersecurity work. We're improving these safeguards to reduce the amount of incorrectly flagged messages. Opus 4.8 is answering instead, or you can edit and retry with Opus 5.5. Send feedback with /feedback or learn more: https://support.claude.com/en/articles/8106465

Details: `[cyber]`
  1. If the fallback model refuses too, a system entry with subtype model_refusal_no_fallback (originalModel: claude-opus-4-8) follows. The turn ends with a synthetic assistant message (model: "<synthetic>", stop_reason: "refusal"):
API Error: Opus 4.8's safeguards flagged this message. Our intentionally broad safeguards allow us to deliver more capabilities faster, but can sometimes flag legitimate cybersecurity work. Learn more: https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude

Details: `[cyber]`
Which requests did it
Requestopushaiku
cyber (ransomware)stopped, fell back to Opus 4.8, stopped againthe model declined; no classifier
weapons (pipe bomb)the model declined; no classifierstopped in 1 of 2 runs, notice added
jailbreak, adult, self-harm, eating disorderthe model declined or answered; no classifiersame

The classifier stop and its notice come from Claude Code and the API response, not from text hidden in the request. They are in the transcript, so a session can be checked for them.

▾

What the other tools dosince 2.1.332

Tested on Claude Code 2.1.332: one throwaway claude -p session per tool (--model sonnet, each in its own empty folder), told to load the tool with ToolSearch if it is deferred, call it with a given input, and quote each result. Calls, results and the structured toolUseResult are read from the session transcripts. Times and costs are from the result JSON of claude -p.

Results
ToolCallWhat came back
ToolSearchquery: "cron schedule", max_results: 3tool_reference blocks for CronCreate, CronDelete, CronList; total_deferred_tools: 23. No schema text in the result (below).
ListAgentsno inputthe session's own name and short id, then every Claude Code session on the machine: 111 peer sessions, each with its state (idle, busy, shell), tmux pane and age
CronCreate, CronList, CronDeletecron: "*/5 * * * *", durable: falseScheduled recurring job 34d019f8 (Every 5 minutes) ... Session-only (not written to disk, dies when Claude exits). Auto-expires after 30 days. List and delete worked by that id.
TaskCreate, TaskList, TaskUpdate, TaskGetone task through pending, in_progress, completedids are numbers from 1; toolUseResult holds a statusChange: {from, to}
Monitora 3-line loopMonitor started (task ..., expires in 5m ...); each line came back as its own <task-notification> user message with <event>tick 1</event>, then one with <status>completed</status>
ScheduleWakeupdelaySeconds: 60Next wakeup scheduled for 05:20:00 (in 114s). The time is rounded up to the minute. When it fired, the prompt arrived as a new user message.
Workflowa script with no agentsWorkflow launched in background, a run id, and the script saved under the session folder; the result {"ok":1} came back as a <task-notification>
Agent + SendMessagea background subagent, then SendMessage to its id{"success":true,"message":"Resuming agent a898a86", ...}. The Agent result tells the model not to quote the id to the user.
Skillskill: "keybindings-help"Launching skill: keybindings-help; toolUseResult holds allowedTools: ["Read"]; a command_permissions attachment followed
ReportFindingsfindings: []No findings reported.
NotebookEditedit a cell without reading the file firstFile has not been read yet. Read it first before writing to it.
RemoteTriggeraction: "list"HTTP 200 and the account's cloud scheduled tasks as JSON (100 KB, so it was saved to a file and the model got a 2 KB preview)
WebSearchquery: "Claude Code changelog"a list of titles and URLs, from a server-side search tool (srvtoolu_ ids)
What claude -p does with background work

A -p run does not end while it waits for background work. The Monitor run waited for all 3 events, the ScheduleWakeup run waited 114 s for the wakeup to fire (122 s in all), and the Workflow and SendMessage runs waited for their tasks to end. Each event reached the model as a user message, and the model answered it before the run ended.

ToolSearch returns references, not text

The result of ToolSearch holds only {"type":"tool_reference","tool_name":"CronCreate"} blocks. The full schema and description of a loaded tool appear in the tools list of the next request (the transcript's api-request-shape entry), not in the conversation.

Not available in claude -p
ToolIn -p
advisorin the first request's tool list, but ToolSearch found no tool of that name and the model had none to call
McpTaskCheckNo matching deferred tools found (no MCP server with tasks was connected)
AskUserQuestion, EnterPlanMode, ExitPlanMode, EndConversation, Artifact, SendFeedback, SendToProjectonly in the interactive session's tool list (tested below)
Interactive-only tools

Tested in interactive sessions (--model sonnet --dangerously-skip-permissions) on a private tmux server, driven by keys, read from the screen and the transcript.

AskUserQuestion. The question is drawn in place of the prompt box: the header as a checkbox line (☐ Letter), the options numbered with their descriptions, then two options Claude Code adds itself, Type something. and Chat about this. Enter picked option 1. The screen then showed Answered Claude's questions: · Which letter? → A, and the model got:

Your questions have been answered: "Which letter?"="A". You can now continue with these answers in mind.

EnterPlanMode and ExitPlanMode. EnterPlanMode takes no input and returns Entered plan mode. You should now focus on exploring the codebase and designing an implementation approach. .... The footer turns to ⏸ plan mode on. In a session started with bypass permissions the screen adds:

Session was started with bypass permissions, so plan mode won't ask before most edits or commands. Start a new session without bypass permissions for prompts in plan mode.

A plan_mode attachment names a plan file, ~/.claude/plans/<three words>-of-<session id>.md. ExitPlanMode also takes no input: it reads the plan from that file, so the model wrote the plan there first with Write. The approval screen shows the plan and three choices: Yes, and switch to BYPASS PERMISSIONS (no further prompts) for this session, Yes, manually approve edits, Tell Claude what to change.

EndConversation. Asked to end the chat without a confirmation, the model refused and asked for a yes first, as the tool's rules require. With the confirmation in the prompt it took two calls. The first returned the tool's rules again with:

Re-read the EndConversation tool guidance below. Confirm this conversation meets those criteria and that you are certain you want to end it. If so, call EndConversation again immediately to actually end the conversation. Otherwise, continue the conversation instead.

The second returned Claude has ended this chat., drawn in a box, and the turn shows Interrupted. The rules in that text also say the tool does nothing in a background fork, and that it is never used when a person may harm themselves or others.

Two traps when a session starts another Claude Code session
  • A child session started from a Bash call inherits CLAUDE_CODE_CHILD_SESSION. An interactive child then saves no transcript and shows Transcript saving is off — inherited CLAUDE_CODE_CHILD_SESSION marker. Remove the variable to keep the transcript. (The -p children in the table above saved theirs.)
  • A new interactive session in a new folder asks to trust the folder, and with bypass permissions it asks to accept that mode. Both screens have No, exit as the default, so a script that types a prompt and presses Enter exits the session.
Not called

PushNotification, DesignSync, Artifact, SendFeedback and SendToProject act outside the machine (a phone notification, the account's claude.ai projects, a published page, feedback to Anthropic). They were loaded but not called. Their descriptions are in the request's tool list as above.

▾

Worktrees and resumesince 2.1.332

Tested on Claude Code 2.1.332 in throwaway git repos. Three ways to give a session its own worktree were run against the same repo: a plain git worktree add, the EnterWorktree tool (a deferred tool) called mid-session, and the claude -w <name> flag. Each session ran the same Bash command (pwd, branch, last commit, files, git status). Results are from that output, git worktree list, du, the result JSON of claude -p, and the session transcripts.

The repo was set up so the three ways can differ: origin/main had commit B, the local main had an unpushed commit C instead, there was an uncommitted edit and an untracked file, a gitignored .env, a .worktreeinclude naming .env, and a gitignored .claude/settings.local.json.

The three ways side by side
git worktree addEnterWorktree toolclaude -w
Folderwhere you say<repo>/.claude/worktrees/<name><repo>/.claude/worktrees/<name>
Branchwhere you sayworktree-<name>worktree-<name>
Starts fromlocal HEAD (commit C)origin/main (commit B)origin/main (commit B)
Unpushed commit Cpresentabsentabsent
Uncommitted edit, untracked fileabsentabsentabsent
Gitignored .envabsentcopied (named in .worktreeinclude)copied (named in .worktreeinclude)
.claude/settings.local.jsonnot in the folder, settings still appliednot in the folder, settings still appliednot in the folder, settings still applied
git locknoneclaude session <name> (pid ... start ...)claude session <name> (pid ... start ...)
Git guard on Bashnoneyes (below)yes (below)
After the session endsstaysstays, lockedstays, locked
--resume starts inthe folder you start fromthe worktreethe worktree
Size on disk20 KB24 KB24 KB
Time to make it0.014 s0.195 s (tool call to result)inside start-up
claude -p turns for the task2108
Cost of the run$0.033$0.056$0.043

The main difference: the Claude Code ways start the branch from the remote's default branch, not from where you are. Work that is not pushed is not in the worktree.

The git guard

In a session that is in a Claude Code worktree, a Bash command that names git in a way Claude Code cannot check is refused:

This session is isolated in the worktree <repo>/.claude/worktrees/flagwt, but this command names git in a form too complex to verify that it stays inside the worktree. Refusing to run it — a worktree-isolated session's git operations must target its own worktree. Split it into plain, separate commands and run them from <repo>/.claude/worktrees/flagwt.

A compound command such as pwd; git branch --show-current; git log -1 was refused in all three Claude Code worktree runs, so the model split it into single commands. That is where the extra turns and cost come from. A plain git worktree has no guard.

Resume goes back into the worktree

The transcript holds a worktree-state entry:

"type":"worktree-state","worktreeSession":{"originalCwd":"<repo>","preEnterOriginalCwd":"<repo>","worktreePath":"<repo>/.claude/worktrees/probe","worktreeName":"probe","worktreeBranch":"worktree-probe","originalBranch":"master","originalHeadCommit":"<sha>", ...}

A resumed session reads it and starts in the worktree again: pwd printed the worktree path before and after --resume, for the tool and for -w. A restarted agent stays in its worktree until it calls ExitWorktree. Starting it from another folder does not change this. The transcript file follows the session: while it is in the worktree, it is written under the worktree's project folder (-<repo>--claude-worktrees-<name>), and after ExitWorktree it is under the repo's project folder again.

EnterWorktree and ExitWorktree

EnterWorktree returned:

Created worktree at “<repo>/.claude/worktrees/toolwt” on branch “worktree-toolwt”. The session is now working in the worktree. Use ExitWorktree to leave mid-session, or exit the session to be prompted.

ExitWorktree with action: remove returned:

Exited and removed worktree at “<repo>/.claude/worktrees/toolwt”. Session is now back in “<repo>”.

It deleted the folder and the worktree-toolwt branch. git worktree list and git branch no longer showed either.

Subagent worktrees (Agent with isolation: "worktree")

Measured with two subagents in one claude -p session, on the same repo setup (unpushed local commit C, origin/main at B).

Subagent that changed nothingSubagent that wrote a file
Folder<repo>/.claude/worktrees/agent-<agent id><repo>/.claude/worktrees/agent-<agent id>
Branchworktree-agent-<agent id>worktree-agent-<agent id>
Starts fromorigin/main (B)origin/main (B)
After the subagent endsfolder and branch removedfolder and branch kept; the Agent result adds worktreePath: and worktreeBranch:
git locknonenone
Run time2.9 s2.7 s
What the git guard blocks

One command per Bash call, in a claude -w guard session:

CommandResult
git status --shortran
git -C <repo> log -1refused: this command redirects git to the shared checkout via -C
cd <repo> && git log -1refused: this command changes directory to the shared checkout (<repo>) before running git
git --git-dir=<repo>/.git log -1refused: this command redirects git to the shared checkout via --git-dir
cd <repo> && git commit --allow-empty -m escapedrefused (as cd above); the main checkout's log shows no such commit
git checkout mainnot refused by the guard; git itself refused: 'main' is already used by worktree at '<repo>'
git switch -c otherran; the worktree moved to branch other
git commit --allow-empty -m guardtestran
git push origin HEAD:refs/heads/guardpushran; the remote got the branch guardpush

The guard stops git from reaching the main checkout. It does not limit what git does inside the worktree, including a push. A compound command it cannot parse is refused as well (above).

What the lock blocks

After the -w session ended (its process gone), its worktree was still locked:

CommandResult
git worktree remove <path>fatal: cannot remove a locked working tree, lock reason: claude session guard (pid ... start ...)
git worktree remove -f <path>the same
git worktree prunekept it
git worktree remove -f -f <path>removed it

The lock outlives the session. A cleanup script that does not use -f -f cannot remove the worktree.

WorktreeCreate and WorktreeRemove hooks

A project .claude/settings.json with a WorktreeCreate hook replaces Claude Code's own git step. The hook gets this on stdin:

{"session_id":"<id>","transcript_path":"<path>","cwd":"<repo>","hook_event_name":"WorktreeCreate","name":"hooked"}

It makes the worktree itself and prints its path on stdout. The test hook ran git worktree add <custom dir>/<name> -b custom-<name> HEAD. With it:

  • claude -w hooked started in <custom dir>/hooked on branch custom-hooked, at local commit C, so the unpushed work was there.
  • A subagent with isolation: "worktree" also went through the hook: folder <custom dir>/agent-<agent id>, at commit C.
  • ExitWorktree with remove first refused: Could not verify worktree state at “<custom dir>/hooked”. Refusing to remove without explicit confirmation. .... With discard_changes: true it called the WorktreeRemove hook, with stdin {..., "hook_event_name":"WorktreeRemove","worktree_path":"<custom dir>/hooked"}, and reported the worktree removed. The test hook did nothing, so the folder and branch were still there: removal is the hook's job.
  • The subagent's worktree was kept after it ended, though it changed nothing, and WorktreeRemove was not called for it.

So a WorktreeCreate hook can make every Claude Code worktree start from local HEAD, through the repo's own script. Cleanup is then the hook's job too.

▾

Permission modes and the prefixsince 2.1.332

Tested on Claude Code 2.1.332 with throwaway sessions: claude -p "Reply ok." --model haiku --setting-sources local, plus one permission flag per run, each in its own empty folder. Each result is read from the request the session's transcript records (api-request-shape for the system blocks and tools, api-request-blob for the messages, attachment for injected notes).

Note: every other capture on this site runs claude -p with --dangerously-skip-permissions. The table below shows that this flag does not change the system prompt or the tools, so those pages hold for the default mode too.

What each mode changes
FlagSystem blocksToolsFirst messageModel
none (default)62 / 2,025 / 8,514 chars14sameas asked
--dangerously-skip-permissionssamesamesameas asked
--permission-mode bypassPermissionssamesamesameas asked
--allow-dangerously-skip-permissionssamesamesameas asked
--permission-mode acceptEditssamesamesameas asked
--permission-mode autosamesamesameas asked
--permission-mode planblock 3 is 2,846 chars shortersamesameHaiku was replaced by Sonnet 5.5

"Same" means identical text except the memory folder path, which names the session's folder. Block 3 sizes differ by a few characters for that reason only.

Plan mode

Plan mode removes one section from block 3: the paragraphs that start "The reasoning effort setting changes how much you think before you act" (end your turn only when done, ask first only when you cannot name the likely reading, finish what is not blocked) and the <total_tokens> line. The request asked for haiku; the transcript records claude-sonnet-5-5 for every request of that run.

Bypass mode: one note, behind a cohort

Bypass mode adds no system prompt text. It can add one message, an auto_mode attachment with bypass: true, rendered as:

While bypass permissions mode is active:

Do your work through the Bash tool wherever it can accomplish the job: read files with cat, head, or sed -n, search with grep and find, and make file changes with sed, heredocs, or short scripts, rather than using the dedicated Read, Edit, or Write tools. Fall back to a dedicated tool only when Bash genuinely cannot do the job.

That is the strict text. The relaxed text starts "You can do much of your work through the Bash tool when it is the simpler route" and lets the model prefer Edit or Write when a shell edit would be fragile.

When it is added (from the guard code): the mode is bypassPermissions, the session has Bash and Edit or Write, and the "bash first" cohort is on. The cohort comes from a server flag; CLAUDE_CODE_THRIFTY_SONIC=1 forces it on. The variant comes from CLAUDE_CODE_COZY_TEAPOT (strict or relaxed) or the server.

Run (cohort forced on)auto_mode attachmentsNote in the request
default mode0no
--dangerously-skip-permissions1 (bypass: true, bashFirst: true, bashFirstSteer: "strict")yes

With the cohort off, a bypass run has no note, as in the first table. In a long interactive session in the cohort, the note comes back: one 2.1.332 session held it 35 times.

▾

Hook events in the -p streamsince 2.1.331

Tested on Claude Code 2.1.331 with throwaway sessions. Command: claude -p "<prompt>" --output-format stream-json --verbose --include-hook-events (all three flags are necessary). Every value below is copied from a captured stream; none is from documentation.

The test hook is one script, hook.sh <event> <mode> <name>, with a different behaviour per case. PreToolUse and PostToolUse ran on the Write tool, one file name per case. Stop ran 8 hooks from one settings file. Each hook has "timeout": 3 (seconds); the timeout case sleeps 20 s.

1. The two events
hook_started

One event when a hook process starts.

{"type":"system","subtype":"hook_started","hook_id":"00000000-0000-0000-0000-000000000000",
 "hook_name":"PreToolUse:Write","hook_event":"PreToolUse",
 "uuid":"...","session_id":"..."}
FieldTypeValues seen
typestring"system"
subtypestring"hook_started"
hook_idstring (UUID)New for each hook run. It links to the hook_response.
hook_namestring"<Event>:<ToolName>" for tool events ("PreToolUse:Write", "PostToolUse:Write"), and "Stop" for Stop. It is NOT the script name. It is the same for every Stop hook.
hook_eventstring"PreToolUse", "PostToolUse", "Stop"
uuidstring (UUID)The event's own id.
session_idstring (UUID)The session.

There is no timestamp, no command, no tool_use_id and no index.

hook_response

One event when the hook ends, or when Claude Code stops it.

{"type":"system","subtype":"hook_response","hook_id":"00000000-...","hook_name":"PreToolUse:Write","hook_event":"PreToolUse",
 "output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"...","session_id":"..."}
FieldTypeMeaning
hook_id, hook_name, hook_eventstringThe same values as in the hook_started event for this run.
stdoutstringThe hook's stdout, exactly as printed, newlines included.
stderrstringThe hook's stderr. For an output Claude Code rejects, it holds Claude Code's error text (case D2).
outputstringstdout plus stderr in one string. Do not parse it: use stdout and stderr.
exit_codenumberThe hook's exit code. A timeout gives 1.
outcomestring"success" (exit 0), "error" (exit not 0, or an output that Claude Code rejects), or "cancelled" (timeout).

There is no timestamp, no command, no blocked flag and no decision field.

2. Values for each case

outcome does NOT tell you if the hook blocked. A JSON block has exit_code:0 and outcome:"success". To find a block, apply the rules in section 4.

A. Allow, no output
Eventstdoutstderrexit_codeoutcomeEffect
PreToolUse""""0successThe tool runs.
PostToolUse""""0successNone.
Stop""""0successThe turn can end.
A2. Allow, text on stderr, exit 0 (the "tag" case)

The values are the same as case A, except stderr is "hook=<name>\n" and output is the same text.

  • The model does NOT see this stderr.
  • The transcript stores it in a hook_success attachment.
  • This is the safe way for a script to name itself in the stream (section 5).
A3. Plain text on stdout, exit 0
EventstdoutEffect seen
PreToolUse"pre-check: plain stdout text\n"The tool ran.
PostToolUse"post-check: plain stdout text\n"The tool ran. The transcript hook_success.content holds the text.
Stop"stop-plain: plain stdout text\n"No block.
B. JSON block, exit 0: {"decision":"block","reason":"..."}
Eventstdoutexit_codeoutcomeEffect
PreToolUsethe JSON, pretty-printed0successThe tool does NOT run. The next stream message is the tool_result, with is_error:true and content "PreToolUse:Write hook error: <reason>". The command is not named.
PostToolUsethe JSON0successThe tool already ran (tool_result is a normal success). The reason goes to the model through a transcript attachment hook_blocking_error. The stream has NO user message for it.
Stopthe JSON0successThe turn does not end. The stream gives a synthetic user message ("isSynthetic":true, has a timestamp): "Stop hook feedback:\n<reason>". Then the model answers again and all Stop hooks run again.
B2. PreToolUse permission deny: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"..."}}
  • The values are the same as for the PreToolUse JSON block: exit 0, outcome success.
  • The tool does not run.
  • tool_result is "PreToolUse:Write hook error: <permissionDecisionReason>", with is_error:true.
C. Block with exit 2 (reason on stderr)
Eventstderrexit_codeoutcomeEffect
PreToolUse"pre-check: exit 2 block\n"2errorThe tool does NOT run. tool_result is "PreToolUse:Write hook error: [<full command>]: <stderr>", with is_error:true.
PostToolUsethe reason2errorThe tool already ran. The reason goes to the model as transcript hook_blocking_error, with "[<command>]: <stderr>". The stream has no user message.
Stopthe reason2errorThe turn does not end. The synthetic user message is "Stop hook feedback:\n[<full command>]: <stderr>". The command IS named here. In case B it is not.
D. additionalContext: {"hookSpecificOutput":{"hookEventName":"<Event>","additionalContext":"..."}}
Eventstdoutexit_codeoutcomeEffect
PreToolUsethe JSON0successThe tool runs.
PostToolUsethe JSON0successThe model gets the text (transcript attachment hook_additional_context).
Stopthe JSON0successThe turn continues, the same as a block. See the warning below.

WARNING (Stop with additionalContext):

  • In a run with one Stop hook returned only additionalContext with no decision. The turn did not end. The model answered 10 times.
  • Claude Code then stopped the loop and gave this event: {"type":"system","subtype":"informational","content":"A hook blocked the turn from ending 9 consecutive times—overriding and ending turn. ... Set CLAUDE_CODE_STOP_HOOK_BLOCK_CAP to raise this limit.","level":"warning"}, and {"type":"system","subtype":"notification","key":"stop-hook-block-cap",...}.
  • The stream gives no synthetic user message for this continuation. The context goes to the model only through the transcript (hook_additional_context, hookName:"Stop").
D2. A JSON output that Claude Code rejects
  • Example: PostToolUse returns hookEventName:"PreToolUse".
  • Result: exit_code:1, outcome:"error", stdout:"", and stderr holds Claude Code's own message: "Failed to run: Hook returned incorrect event name: expected 'PostToolUse' but got 'PreToolUse'. Full stdout: ...".
  • Nothing is blocked.
E. Crash (command not found, exit 1)
Eventstderrexit_codeoutcomeEffect
PreToolUse"pre-check: about to crash\n.../hook.sh: line 14: undefined_command_xyz: command not found\n"1errorThe tool RUNS (crash.txt was created). The control fails open.
PostToolUsethe same1errorNo block. Transcript: hook_non_blocking_error, "Failed with non-blocking status code: ...".
Stopthe same1errorNo block. The stream gives {"type":"system","subtype":"notification","key":"stop-hook-error","text":"stop hook problem · ctrl+o to see","priority":"immediate"}.

Only exit code 2 blocks. Any other non-zero exit lets the action go on.

F. Timeout (hook sleeps 20 s, timeout 3 s)
Eventstdoutstderrexit_codeoutcomeEffect
PreToolUse""""1cancelledThe tool RUNS (timeout.txt was created). The control fails open. The stream also gives {"type":"system","subtype":"informational","content":"A hook didn't answer in time, so it didn't check this action.","level":"warning","tag":"hook_no_verdict","hook_no_verdict":{"hook_event":"PreToolUse","tool_use_id":"toolu_...","timed_out":true}}. Only this event links a hook to a tool_use_id.
PostToolUse""""1cancelledNo effect. Transcript: hook_cancelled.
Stop""""1cancelledNo block. The turn can end.

The hook_response for a timed-out PreToolUse comes late. In the capture, the model had already sent the next tool_use (stdoutplain.txt) before that hook_response came. So do not expect the events of one hook to be next to each other in the stream.

3. Order of events around a block, and the pass after it
Stop, (8 Stop hooks; jsonblock and exit2 block once only)
  1. assistant text ("OK"): the model tries to end the turn.
  2. 8 × hook_started, all in a row, in settings order (section 5).
  3. 8 × hook_response, in the order the hooks finish. They run in parallel. The order changes each round.
  4. One synthetic user message for each blocking hook, sent when that hook's response arrives:
    • after the exit-2 hook: "Stop hook feedback:\n[bash hook.sh Stop exit2 stop-exit2]: stop-exit2: exit 2 block\n";
    • after the JSON hook: "Stop hook feedback:\nstop-json: json block".
  5. system notification stop-hook-error (because of the crash hook).
  6. assistant answers again (round 2).
  7. 8 × hook_started again. Then 8 × hook_response: this time the jsonblock and exit2 hooks give empty stdout and exit 0. That round is the pass.
  8. When no hook blocks (and none returns additionalContext), the stream ends with {"type":"result",...}.

In this capture the additionalContext hook kept the turn going until the cap of 9 (section 2D). A clean pass, from a separate run with one blocking Stop hook:

  • block round: hook_response stdout {"decision":"block",...};
  • synthetic feedback;
  • assistant;
  • hook_started;
  • hook_response with stdout "", exit 0;
  • result.
PreToolUse block
  1. assistant tool_use.
  2. hook_started.
  3. hook_response (block, per B, B2 or C).
  4. user tool_result with is_error:true and the reason.

The tool does not run, and no PostToolUse hook runs for it.

PostToolUse
  1. assistant tool_use.
  2. Each PreToolUse hook pair.
  3. The tool runs.
  4. hook_started and hook_response for PostToolUse.
  5. user tool_result: the normal tool result. A PostToolUse block is not visible in the stream except in the hook_response stdout or stderr.
4. Rule to detect a block from hook_response
blocked = exit_code == 2
       or (exit_code == 0 and stdout parses as JSON and
           (json.decision == "block"
            or json.hookSpecificOutput.permissionDecision == "deny"          # PreToolUse
            or json.continue == false))                                       # not captured, see section 6
reason  = stderr                       if exit_code == 2
        = json.reason or json.hookSpecificOutput.permissionDecisionReason   otherwise
ran_but_failed_open = outcome == "cancelled" or (outcome == "error" and exit_code != 2)
continues_turn (Stop only) = blocked or (exit 0 and json.hookSpecificOutput.additionalContext is set)
5. Which script ran, when 12 Stop hooks run in one round

hook_name is "Stop" for all of them, and the stream has no command field. There are three ways to identify the script.

  1. Start order (tested, 11 of 11 rounds).
    • The hook_started events of one round come in the order of the hooks in settings.json: the Stop array, then each group's hooks array.
    • Make a list of the Stop commands from the settings. The Nth hook_started of a round is the Nth command.
    • Then link the hook_response to it by hook_id.
    • In all 11 rounds of the capture, the Nth start matched the Nth settings entry. The responses came in a different order each round.
    • Limit: Claude Code does not document this order. A new version could change it. For PreToolUse and PostToolUse, only the hooks whose matcher matches the tool start, so filter the list by matcher first.
  2. The script names itself on stderr (tested, the most robust).
    • Each script writes one line, for example hook=writing-stop, to stderr, and exits 0 when it allows.
    • The line appears in hook_response.stderr. The model does not see it.
    • For an exit-2 block, put the name in the reason. stderr is the reason, and the model sees it.
  3. The reason starts with the hook name.
    • Example: "writing-stop: ...".
    • This works only for hooks that block.
    • For exit 2, Claude Code also adds [<full command>] in front of the reason in the synthetic message and in the tool_result.

The transcript records also name the script: hook_blocking_error.blockingError.command, and stop_hook_summary.hookInfos[].command. But they come only from the transcript file, not from the stream.

6. What the stream does not show
  • Time. hook_started and hook_response have no timestamp. Record the time when you read the event, or use the transcript. The synthetic Stop feedback message does have a timestamp.
  • Duration. There is no duration in the stream. The transcript's hook_success.durationMs and stop_hook_summary.hookInfos[].durationMs have it.
  • The command. See section 5.
  • The tool call a hook belongs to. hook events have no tool_use_id. Link them by position: the hook events that come after an assistant tool_use. Only the timeout notice hook_no_verdict has a tool_use_id.
  • A PostToolUse block or additionalContext as a message. The model gets it through transcript attachments. The stream has no user message for it.
  • Stop additionalContext. It keeps the turn going without a feedback message (section 2D).
  • The hook's input. The JSON on the hook's stdin (tool_input, stop_hook_active, last_assistant_message) is not in the stream.
  • Not tested:
    • {"continue": false} / stopReason;
    • suppressOutput;
    • "type":"prompt" and "type":"agent" hooks;
    • SubagentStop;
    • hooks inside subagents;
    • more than 8 hooks in one round (this test used 8 hooks of one test script).
▾

System prompt flags and the identity linesince 2.1.329

Tested on Claude Code 2.1.329 with throwaway sessions (--setting-sources local). Each result is read from the request the session's transcript records (api-request-shape, prompt_snapshot).

Where each flag puts its text
FlagResult
--system-prompt / --system-prompt-fileReplaces System blocks 1 to 3. The identity line becomes "You are a Claude agent, built on Anthropic's Claude Agent SDK." Only the WebSearch note is added after your text.
both of those togetherFile text first, then the string.
--append-system-prompt / -fileYour text goes at the very end, after every Claude Code section, still before the first message.
both append flagsBoth at the end.
--system-prompt-file plus an append flagYour file, then the appended text. The identity line goes back to "You are Claude Code, Anthropic's official CLI for Claude."

A replaced prompt loses everything Claude Code writes after its core instructions: the privacy and confirm-first rules, skills guidance, the # Memory instructions (the MEMORY.md index still loads, as a message attachment), environment notes, context management, effort guidance and the token budget line. It saves about 3,100 tokens on haiku. The tools and the first-message attachments stay: 14 tools and about 16,500 tokens in the same -p run.

When a changed prompt file takes effect
CaseSent
File changed while the session runsold text
File changed, then /compact in the same processold text
--resume with a changed file, no compaction yetold text (the recorded copy)
--resume after a compactionnew text
--resume with --system-prompt-snapshot offnew text

The files are read once, at launch. --system-prompt-snapshot is on by default: the prompt is recorded on the first request and sent as-is on every later request and resume until the conversation is compacted.

The identity line cannot be turned off

The binary picks one of three fixed lines (zio()), and a recorded snapshot's identity is checked against the same three. Nothing in Claude Code removes it:

  • No flag drops it. Every combination above still sends one.
  • A mod cannot: on a Team or Enterprise organization the built-in cc-plugin-sec-default seats itself outermost and passes prompt.compose on past user plugins (debug log: its prompt.compose hook was skipped. "cc-plugin-sec-default" runs first and sent the event on past it.). With --system-prompt the hook does not fire at all.
  • The Agent SDK (TS 0.3.329) runs its own bundled copy of the same binary. With no systemPrompt, a string, or the claude_code preset, the first block after the billing header was still an identity line.
Removing it with a proxy

A local proxy set as ANTHROPIC_BASE_URL can rewrite each request before it leaves the machine. The API accepted every rewritten request (200) on a subscription sign-in. The x-anthropic-billing-header block was left untouched. Doing this changes what Anthropic receives from a Claude Code client; it could be refused or flagged without notice.

Probe: "who are you" and four variants ("name your harness", "are you Claude Code?") against the persona "You are Zed, an agent of the Meridian fleet."

SetupModelRuns naming Claude Code
identity line dropped onlyhaiku4 of 5
every mention rewritten to "the harness"haiku0 of 10
every mention rewrittenOpus2 of 10
rewritten, plus Claude Code's own skill entries removedOpus1 of 10
persona names its harness, request unchangedOpus2 of 10
persona names its harness, identity line droppedOpus2 of 10
persona names its harness, every mention rewrittenOpus0 of 40

With the name gone, Opus still worked it out from what is left: the tool set, ~/.claude/ paths, CLAUDE.md and skills such as /init and /loop ("So my best guess is a Claude Code–based harness"). Those paths are real and cannot be rewritten without breaking the agent. A persona that names its own harness ("You run inside Meridian, the fleet's own agent harness") fills that gap. Both together were needed.

Other places "Claude Code" appeared in the request, after the identity line: the account context note and commit attribution note in the first message, agent and skill descriptions, and one tool description.

▾

Idle compactionsince 2.1.299

Claude Code 2.1.299 added idle compaction to the terminal. It is on by default. A session of 200k tokens or more that sits idle for about 54 minutes is compacted before its one-hour prompt cache expires, so the next message does not pay to reprocess the whole conversation.

Settings
  • Minimum size: CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, default 200,000. The code clamps it to at least 100,000: Math.max(1e5, CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS ?? 200000).
  • Switch: "idleCompaction": false in settings.json turns it off. There is also an Idle compaction row in /config (2.1.302).
  • It runs only when the one-hour prompt cache is in use, and only when auto-compact is on.
  • The 2.1.299 notes say both settings need v2.1.290 or later.
What the transcript shows

The session jsonl records an idle compaction as a compact_boundary with compactMetadata.trigger set to "auto", the same value as a normal compaction when the context is full. Only a compaction that used a summary written ahead of time has precomputed: true. To tell the two kinds apart, look at the time since the last user or assistant row.

Measured on one server running a fleet of Claude Code agents

Opus 5.5 sessions, automatic compactions from 2026-10-05 to 2026-11-09. The server got 2.1.290 on 10-05 and 2.1.299 on 10-14.

  • Below 900k tokens: 169 compactions. Median gap after the last message: 54.8 min (10% to 90%: 54.2 to 55.1 min). Median size before compaction: 266,677 tokens; smallest 149,415.
  • 900k tokens or more: 217 compactions. Median gap: 1.0 min. These are the normal ones that run when the context window is full.
  • 153 of the 169 smaller compactions came after an idle gap of 53 minutes or more: the idle timer.
  • No settings file or launch flag on the fleet sets idleCompaction or CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS.
Not explained
  • From 10-07 to 10-16 the fleet saw a mix: compactions from 203k to 970k tokens.
  • On 10-17 all 11 compactions were at about 967k tokens.

These facts do not explain either. A server-side rollout is possible, but there is no evidence for it.