Core 1 showed the agent loop from where you sit: you type, Claude reads, edits, runs commands and answers. This session opens the hood. You will look at the loop the way Claude Code's own code sees it: one API request per model step, a stream of typed events, a result that says exactly why the run ended, and a permission pipeline in front of every tool call. You'll also see where each instruction source lands in the request, which actions keep or break the prompt cache, what survives compaction, and where the sandbox's boundary really sits.
By the end you will be able to:
Read a stream-json transcript and say why a run stopped, using stop_reason, terminal_reason and subtype from the result event, in that order, never arithmetic on num_turns.
Choose turn and budget limits with headroom, and handle interrupts in the terminal, in claude -p and in the Agent SDK.
Compose an instruction stack (system prompt, output style, CLAUDE.md, appended prompts) and predict where each piece sits and what it costs.
Predict prompt-cache hits and misses, write instructions that survive compaction, and know what memory files load when.
Trace any tool call through the permission evaluation order, and configure a sandbox whose limits you can test.
This is the first Agents session, so it goes into internals. Basics such as permission modes, CLAUDE.md placement and /context are in Core 2; this page links back to them instead of repeating them. The next session, Building Agents with the Claude Agent SDK, drives this same loop as a library.
Version stampEverything on this page was checked against the live docs at code.claude.com/docs as of 2026-10-24 · v2.1.310. Claude Code ships weekly, so features that need a minimum version say "requires v2.1.xxx+" where they appear. The stream excerpts follow the documented event format and the shapes recorded from real v2.1.303 runs by the course labs.
Agent Loop
Claude Code is a harness around a stateless model. Each step of the loop is one API request that re-sends the whole context, one assistant message that may ask for tools, a permission decision and tool execution per call, and a tool result appended to history. The loop ends when a response asks for no tools, or when something else stops it first: a limit, a hook, an error or you. Every one of those exits leaves a different fingerprint in the result event.
Turns and Tool Calls
What it is. The model doesn't remember anything between requests. On every step Claude Code sends the system prompt and tool definitions, the project context, every earlier message and tool result, and whatever is new. The model answers with an assistant message made of content blocks: text, thinking, and zero or more tool_use blocks. If at least one tool was requested, Claude Code runs each call through the permission check, executes the tools that pass, appends a user message holding the tool_result blocks, and sends the next request. A response with no tool calls ends the agentic loop, and Claude Code writes a result. The docs describe the same loop in plain words as "gather context, take action, and verify results" (How Claude Code works).
Claude Code runs on your machine and the model sits at the other end of one wire. Step through one turn: each step lights the part that works and names the stream-json event it emits, and a packet crossing the wire is an API request or response. Use the step buttons, or play.
Two meanings of "turn"
The word is used two ways, and mixing them up breaks scripts. In the interactive product and in the hooks docs, a turn is everything between your prompt and Claude's final reply: UserPromptSubmit and Stop fire once per turn, and "every prompt you send that starts a turn creates a new checkpoint". In the Agent SDK and headless docs, a turn is one round trip inside the loop: "Claude produces output that includes tool calls, the SDK executes those tools, and the results feed back to Claude automatically" (How the agent loop works). --max-turns and the SDK's max_turns count the second kind: "Maximum tool-use round trips".
How the loop shows up in stream-json
Run claude -p with --output-format stream-json --verbose and every stage becomes one line of JSON. The first line is normally {"type":"system","subtype":"init"}, carrying the model, the tool list, MCP servers, the permission mode and a capabilities array. Then come the loop events:
assistant events, one per content block. Blocks from the same model response share message.id, and each line repeats that response's usage. A response with a text block and two parallel Read calls arrives as three lines with one id.
user events carrying tool_result blocks, with is_error: true on a failure. The top-level tool_use_result holds the tool's structured output, such as {"filenames": [...], "numFiles": 4} for Glob. On an error it's a plain string.
system events for loop machinery: api_retry before a retried request, permission_denied when a call is refused without a prompt, compact_boundary after compaction. The permission_denied event is best-effort and skips denials decided on the PreToolUse hook path; "permission_denials on the result message is the authoritative record".
A final result event with subtype, is_error, num_turns, stop_reason, terminal_reason, total_cost_usd, usage, modelUsage and permission_denials, plus result on success.
Messages from subagents appear as assistant and user events whose parent_tool_use_id names the Agent call that started them. Main-conversation events carry null there (Follow subagent messages).
Four runs in the documented event format, abridged from the course fixtures: max_turns_stop and permission_denied follow real v2.1.303 runs event for event, and the other two are built from the same event shapes, tool_error_recovery from a real run's first events (labs/common/fixtures/stream/; long tool output is cut with "…"). Pick a run, click an event to see its JSON, and compare the counters computed from the events (the strip above the list) with the fields reported on the result. It opens on max_turns_stop, which follows a real v2.1.303 run event for event.
Facts from real v2.1.303 runsThree behaviors the course labs recorded that trip up hand-written parsers. stop_reason is null on every assistant event, so read it from the final result event. num_turns doesn't follow simple arithmetic: one tool call plus an answer reported 2, and a --max-turns 2 run stopped with num_turns: 3. And an error tool_use_result is a plain string, not an object. Read the fields; don't compute them.
Parallel calls
When one response asks for several tools, read-only tools (Read, Glob, Grep, MCP tools marked read-only) can run concurrently, while "tools that modify state (like Edit, Write, and Bash) run sequentially to avoid conflicts" (agent loop). Custom SDK tools are sequential unless their annotations set readOnlyHint. All results for the batch return together in one user message, and the PostToolBatch hook fires once the batch resolves, before the next model call. So a single "turn" can contain several tool calls, which is one more reason not to equate tool calls with turns.
One recorded run from the course labs, written as a score: lanes for you, the harness, the model and its tools, and one bar per model response. Notes are spaced by their position in the stream, not by time. Two tool calls in one response share a message.id and stack as a chord, and num_turns at the double bar is the reported field, not a count of bars. Pick a run (the first two follow real v2.1.303 runs event for event; the other two are built from the same event shapes), press play, or click a note to see its JSON and select it in the inspector above. Costs and durations aren't drawn.
Practice: trace your own loop
# A read-only, capped, headless run. It costs a few cents.
claude -p "Where is DISCOUNTS defined, and who calls apply_discount?" \
--output-format stream-json --verbose \
--tools Read,Grep,Glob --allowedTools Read,Grep,Glob \
--permission-mode dontAsk \
--max-turns 6 --max-budget-usd 0.25 > run.jsonl
# Model responses in the main loop: distinct message ids, not assistant lines
jq -r 'select(.type=="assistant" and .parent_tool_use_id==null) | .message.id' run.jsonl | sort -u | wc -l
# Every tool call, in order
jq -r 'select(.type=="assistant") | .message.content[]
| select(.type=="tool_use") | "\(.name) \(.input|tostring)"' run.jsonl
# Failed tool results
jq -c 'select(.type=="user") | .message.content[]?
| select(.type=="tool_result" and .is_error==true) | .tool_use_id' run.jsonl
# Why it ended: the last result event (other events can follow it)
jq -c 'select(.type=="result") | {subtype, is_error, num_turns, stop_reason, terminal_reason, total_cost_usd}' run.jsonl | tail -n 1
On macOS, Linux and WSL the default tool set leaves out Glob and Grep. "With --tools you get the ones you list, and naming either tool in --allowedTools restores both. An allow rule in a settings file doesn't have this effect." Without them Claude searches with find and grep through Bash instead (Glob tool behavior). Always check the init event's tools array instead of assuming.
Pitfalls
Summing usage over assistant lines double counts, because every block of a response repeats the response's usage. Deduplicate by message.id; even then, "per-step output_tokens is a placeholder", so read output tokens from the result (cost tracking). The result's modelUsage also covers subagents; its usage covers the main loop only.
Parsing tool_use_result as an object crashes on the first failed call, where it's a string.
Breaking out of the stream on the result line. A few trailing system events, such as prompt_suggestion, can follow it. Read to EOF.
Parsing the session JSONL under ~/.claude/projects/ instead of the stream. That file's entry format "is internal to Claude Code and changes between versions" (Manage sessions). Use stream-json, --output-format json or the SDK for anything a script relies on.
Three counters that disagree: requests, tool-use turns and num_turns
A run has at least three different "how many" numbers, and each answers a different question.
Model requests are the distinct message.id values on assistant events. That's the count that drives latency and the cost of re-sending the prefix. Compaction, retries (system/api_retry) and helper calls add requests that don't show up as assistant events in the main stream.
Tool-use round trips are the responses that contained at least one tool_use. This is what --max-turns limits. In the recorded --max-turns 2 fixture, the first response called Read and the second called Glob and Read in parallel. That's two round trips. Both batches ran and returned results, but the cap stopped the loop before the third request was sent, and the run ended with error_max_turns.
num_turns is what Claude Code reports, and it's the number to log. The same fixture reports 3. Don't reverse-engineer the formula, which can change between versions. Treat it as an opaque measure of loop length and detect limits from subtype and terminal_reason.
Two more subtleties come from the turns and budget docs. With streaming input (--input-format stream-json), a message still queued when a turn hits the limit "stays queued" and starts a new turn, and "the max-turns count starts over for that turn". The budget total keeps accumulating across those messages. And background work changes the picture: with background tasks, a -p run can take another turn after its first result, and the text output then prints "each turn's result" (v2.1.295+).
The cost side has its own trap. usage on the result covers "only the main agent loop"; modelUsage and total_cost_usd include subagents and internal calls such as compaction. Both are "client-side estimates, not authoritative billing data" (cost tracking).
What you build: a tracer that rebuilds the loop from stream-json: one row per model response (grouped by message.id) with its tool calls and results, permission denials, and a verdict from the result event. It runs the four recorded common fixtures plus a real api_error run (a v2.1.303 run whose credentials never loaded), then synthetic endings (budget stop, full context, interrupt, two refusals, killed process) that change only documented result fields. It can also trace your own transcript.
cd labs && python3 agents-1/loop_trace.py
python3 agents-1/loop_trace.py --only explore_readonly # one fixture, full step table
python3 agents-1/loop_trace.py --transcript run.jsonl # a run you saved
# opt-in, costs money: one capped, read-only run in a temp copy of the sample repo
python3 agents-1/loop_trace.py --real --max-turns 2 --max-budget-usd 0.05 --model haiku
What to observe:explore_readonly has two Read calls in one response, so four responses hold four tool calls; max_turns_stop ends with num_turns 3, stop_reason: tool_use and no result text; api_error is the case a subtype-only check calls a success; both refusals end REFUSAL (stop_reason: "refusal", subtype: "success"), including the one whose terminal_reason reads api_error, because the verdict checks stop_reason first, then terminal_reason, then subtype.
What it is. The loop has one natural exit and many forced ones. The natural exit is a response with no tool calls, normally with stop_reasonend_turn. Forced exits include a limit you set, an API error, a refusal, an interrupt, a hook that ends processing, a deferred tool call, structured-output retries running out, and context problems such as auto-compaction thrashing. Each one surfaces in the result event through three fields that answer different questions.
Field
Answers
Typical values
stop_reason
Why did the model stop generating on its last response?
end_turn, max_tokens, refusal, tool_use, tool_deferred, tool_deferred_unavailable, or null after a crash
terminal_reason
Why did the query loop end?
completed, max_turns, api_error, aborted_streaming, aborted_tools, tool_deferred, and more (see the deep dive)
The rule that matters: "To tell failures apart, check data["stop_reason"] first, then terminal_reason, then subtype" (Python SDK reference). Two failures hide behind subtype: "success". A declined response has stop_reason: "refusal", usually with subtype: "success", and "its terminal_reason doesn't single it out": it can read completed or api_error. A failed final request also has subtype: "success", with its cause in terminal_reason, such as api_error for an API error. In the API-error case is_error is true, api_error_status carries the HTTP status when there was a response (it's null when the request never got one), and result may hold the error string or nothing. The course lab's real recorded api_error run, whose cloud credentials didn't load, shows api_error_status: null, result: "API Error: Could not load AWS credentials …", zero cost and an unhelpful stop_reason: "stop_sequence". A wrapper that trusts subtype == "success" will report an outage as a finished task.
Pick how a run ended. The lamps show the result fields that identify it, grouped in the check order (stop_reason, then terminal_reason, then subtype), and the card says what a wrapper should do. Excerpts show only the fields that matter (others are elided with "…"). Where the docs don't pin a value down, the lamp shows "?" and the excerpt leaves it out.
Exits you trigger through hooks
Hooks change the exit, not just the path. A Stop hook that returns {"decision": "block", "reason": "..."} or exits 2 keeps Claude working: the reason becomes the next instruction. Claude Code caps this at eight consecutive continuations ("after stop hooks have continued the turn eight times in a row, Claude Code overrides the next block and ends the turn"), resets the count whenever Claude calls a tool, and passes stop_hook_active: true so your hook can tell it's already in a continuation (Stop hooks). Any hook can instead return {"continue": false, "stopReason": "..."}, which stops processing entirely and overrides decision fields. A PreToolUse hook that returns permissionDecision: "defer" (added in v2.1.89) ends the run with stop_reason: "tool_deferred" and the pending call in deferred_tool_use. The calling process collects an answer and runs claude -p --resume <session-id>, and the same tool call fires PreToolUse again. The limits are strict: defer is honored only in -p (interactive sessions log a warning and ignore it), and "only works when Claude makes a single tool call in the turn"; with parallel calls it's ignored and the tool goes through the normal flow. If the deferred tool is gone on resume, for example because its MCP server isn't connected, the run exits with stop_reason: "tool_deferred_unavailable" (Defer a tool call).
The script below is a one-time nudge, not a gate. It blocks the first stop while tests fail; on the next attempt stop_hook_active is true and it lets Claude stop, pass or fail. Removing the guard doesn't make it a gate either: the 8-continuation cap resets each time Claude calls a tool, and Claude re-runs the tests between blocks, so the loop has no bound. A Stop hook that crashes also fails open, and onFailure has no effect on Stop. A hard gate needs its own counter or state file (for example, allow the stop after three attempts and say so in the reason), and CI stays the real gate.
.claude/hooks/require-green-tests.sh (make it executable)
#!/usr/bin/env bash
# .claude/hooks/require-green-tests.sh: a one-time nudge while tests fail.
# Not a gate: the guard below allows the next stop, and CI must still check.
input=$(cat)
# Already continuing because of this hook? Let Claude stop. Without the guard
# nothing bounds the loop: the 8-continuation cap resets on every tool call.
if [ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ]; then
exit 0
fi
if ! npm test --silent >/dev/null 2>&1; then
echo '{"decision": "block", "reason": "Tests are failing. Run npm test, fix the failures, then finish."}'
fi
exit 0
Other ways a run ends
Context exhaustion. Auto-compaction normally keeps a full window from ending the session. If a single huge output refills the window right after each summary, "Claude Code stops auto-compacting after a few attempts and shows an error instead of looping" (When context fills up).
Refusal. Detect it with stop_reason == "refusal" on the result. An automatic content fallback can also move a flagged request to another model, which counts as a model switch.
Unattended goals. In interactive work, /goal <condition> keeps Claude working across turns until the condition holds; it's covered with Stop-hook gates in Autonomy 1.
Crashes. After a session crash, the synthesized error_during_execution result has stop_reason: null and possibly zeroed cost fields, and the process exits.
Practice: a wrapper that branches correctly
ci/ci-claude.sh
#!/usr/bin/env bash
# ci-claude.sh: run one capped task and map every exit to a CI outcome.
# Check order, as the SDK reference gives it: stop_reason, then terminal_reason, then subtype.
set -uo pipefail
out=$(claude -p "$1" --output-format json \
--permission-mode dontAsk --allowedTools "Read,Grep,Glob" \
--max-turns 12 --max-budget-usd 1.00) # exits non-zero on error results
reason=$(jq -r '.terminal_reason // "unknown"' <<<"$out")
stop=$(jq -r '.stop_reason // "null"' <<<"$out")
subtype=$(jq -r '.subtype' <<<"$out")
if [ "$stop" = "refusal" ]; then echo "::error::model refused"; exit 6; fi
case "$reason" in
completed) jq -r '.result' <<<"$out" ;;
max_turns) echo "::warning::hit --max-turns; narrow the task or raise the cap"; exit 3 ;;
api_error) echo "::error::API error $(jq -r '.api_error_status // "no response"' <<<"$out"): $(jq -r '.result' <<<"$out")"; exit 4 ;;
budget_exhausted) echo "::warning::hit --max-budget-usd at $(jq -r '.total_cost_usd' <<<"$out")"; exit 7 ;;
*) echo "::error::ended with subtype=$subtype terminal_reason=$reason"; exit 5 ;;
esac
The default branch matters as much as the named ones. The terminal_reason enum has grown across releases, so treat unknown values as failures and log them, never as success.
The full terminal_reason enum, and which values you'll actually see
The TypeScript reference lists every value of terminal_reason (SDKResultMessage): completed, max_turns, tool_deferred, aborted_streaming, aborted_tools, hook_stopped, stop_hook_prevented, background_requested, blocking_limit, rapid_refill_breaker, prompt_too_long, image_error, model_error, api_error, malformed_tool_use_exhausted, budget_exhausted, structured_output_retry_exhausted, tool_deferred_unavailable and turn_setup_failed.
The docs explain only some of them directly. completed and max_turns appear in the recorded fixtures, and real v2.1.303 runs recorded budget_exhausted on a --max-budget-usd stop (with subtype: "error_max_budget_usd" and exit code 1). api_error is the "success but failed" case above. aborted_streaming and aborted_tools mean "the turn was aborted before completing", commonly by interrupt() or a permission callback returning PermissionResultDeny(interrupt=True). tool_deferred pairs with a defer hook decision. For the rest, the names suggest the cause (a hook stopping the loop, a stop hook preventing it, a context or refill breaker), but write your wrapper so the meaning of any value is something you log and review, not something you hard-code from a guess. The field is also None on CLI versions that predate it, on local commands like /usage that bypass the loop, and on the synthesized results Claude Code writes after a fatal error.
The API's own stop reasons sit underneath: end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal and model_context_window_exceeded. A hand-written loop on the Messages API should fail closed on any unexpected value instead of falling into the tool branch. Claude Code does that work for you and reports the outcome through terminal_reason.
Interrupts
What it is. You're part of the loop. You can stop it, steer it without stopping it, or push a slow step into the background, and each of these lands at a different point in the turn. Headless runs and SDK hosts have their own interrupt signals with different guarantees about what gets recorded.
Action
Where
What happens
Esc
Terminal
"Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far." Queued messages are sent next. On a permission prompt, Esc declines.
Type, then Enter
Terminal
The message is queued, not an interrupt. "If you queue a message while Claude is running tool calls, Claude Code passes it to Claude as soon as those tool calls finish, within the same turn."
Ctrl+Enter (or Ctrl+X Ctrl+S)
Terminal, v2.1.275+
Sends queued messages now. Background-capable work (shell commands, subagents) moves to the background and Claude reads your message in the same turn; otherwise the turn is interrupted and your message goes next (this split requires v2.1.281+).
Ctrl+B
Terminal
Backgrounds running Bash commands and agents (press twice in tmux). Claude gets a task ID and keeps working.
Ctrl+C
Terminal
Interrupts a running operation; with nothing running, the first press clears input and a second exits.
SIGINT
claude -p
Ends the turn, so it can be recorded.
SIGTERM
claude -p
Exit code 143. The in-progress turn is left unfinished with no result; running Bash process trees are terminated; SessionEnd hooks run.
interrupt()
Agent SDK
Ends the current turn; drain the stream to get its result, whose terminal_reason is aborted_streaming or aborted_tools.
A scripted turn for "fix the failing test": stream, run npm test, stream, Edit, run the tests again, final answer. Drag the cursor on the bar (or use the slider) and pick an action; hatched segments are tool calls running, and the marks between segments are the tool boundaries where a queued message lands. The rules come from the docs; the timeline itself is illustrative.
Why steering beats stopping
A queued correction is often better than Esc. It arrives at a tool-call boundary, so nothing is half-done, and the model reads it with full context before choosing its next step. Esc is for "stop now": a command heading somewhere you don't want, or a plan you can already see is wrong. After an interrupt, the work done so far stays. File edits made with the file tools can be undone with EscEsc or /rewind, and so can later Bash changes to those same files. "A file that only Bash commands changed isn't tracked and stays as it is", and remote side effects can't be rewound at all (Checkpointing).
Interrupts in code
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage
async def main():
opts = ClaudeAgentOptions(allowed_tools=["Read", "Grep", "Glob"],
permission_mode="dontAsk", max_turns=20)
async with ClaudeSDKClient(options=opts) as client:
await client.query("Audit every module for unused imports")
await asyncio.sleep(5) # the user clicked "stop" in your UI
await client.interrupt() # only ClaudeSDKClient can interrupt
async for msg in client.receive_response(): # drain: the buffer isn't cleared
if isinstance(msg, ResultMessage):
print("ended:", msg.terminal_reason) # aborted_streaming or aborted_tools
await client.query("Just list the modules instead")
async for msg in client.receive_response():
if isinstance(msg, ResultMessage) and msg.subtype == "success":
print(msg.result)
asyncio.run(main())
Two SDK details. interrupt() "does not clear the message buffer", so drain receive_response() before sending the next query. And a permission callback can interrupt as well as deny: PermissionResultDeny(message=..., interrupt=True) refuses the call and ends the turn. The system/init event's capabilities array (for example interrupt_receipt_v1, interrupt_cancel_queued_v1) lets a host feature-detect interrupt behaviors instead of comparing version strings.
Pitfall: killing a CI job with SIGTERMA job runner that times out with SIGTERM leaves no result for the turn, so your wrapper sees exit 143 and nothing to parse. If you want a recorded, resumable stop, send SIGINT first, give it a moment, and only then escalate. For hosts that restart Claude Code, CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1 continues a session that ended mid-turn on resume, and CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS keeps it from re-running a stale prompt. A background command the main conversation started also keeps a -p run open after its result, until the command exits or reaches its time limit.
Turn and Budget Limits
What it is. Two caps bound a headless run. --max-turns N limits "the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default." --max-budget-usd X "stop[s] the run once estimated spend on API calls reaches this amount (print mode only)" (CLI reference). The SDK equivalents are max_turns / maxTurns and max_budget_usd / maxBudgetUsd, and subagent definitions take their own maxTurns.
How the budget is enforced
It's an estimate. The cap is checked "against its client-side cost estimate, which can differ from your bill".
It's checked after each response arrives, because each response's cost comes from the usage the API returns with it. "The response that reaches the cap still completes", so "spend can therefore pass the cap by up to the cost of that one response, plus anything that subagents still running at that moment spend before they stop" (Budget headroom).
Subagents count. Their spend goes toward the total. Once the cap is reached, spawning another fails with Budget limit reached and running background subagents are stopped (v2.1.217+).
Resumes start fresh against the cap. With --continue or --resume, totals restored from earlier runs don't count toward the CLI cap, even though total_cost_usd includes them (CLI 2.1.277+).
Background work stops. When a -p run reaches its budget cap, Claude Code stops remaining background work instead of waiting for it.
Toy model with illustrative costs: each response costs a little more than the last as context grows. The budget is checked after each response, so the run overshoots by part of one response. The max-turns line counts tool-use round trips. The cap that trips first carries the highlight; hover the line for each response.
Choosing values
Set the turn cap from the task, not from fear. Measure a few real runs, take the largest num_turns you saw for a successful run, and add 30 to 50%. A cap below the task's natural length turns every run into error_max_turns, which looks like a model failure in your dashboards. Set the budget from the cost of the largest single response you expect, because that's the overshoot you have to tolerate. With --json-schema, the structured answer itself arrives through a tool call, so --max-turns 1 ends in error_max_turns; allow at least two or three turns. The course labs require both caps on every real run, with --max-turns between 1 and 30 and --max-budget-usd above 0 and at most 5.
Interactive sessions have no turn or budget flag. There, the bounds are your attention, /usage, plan usage limits, Stop hooks and /goal. The Stop-hook continuation cap (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP, default 8) is the closest thing to a turn limit in the interactive product.
Agent SDK options (excerpt)
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition
opts = ClaudeAgentOptions(
max_turns=25, # tool-use round trips for the main loop
max_budget_usd=2.00, # estimate; leave headroom for one response + running subagents
agents={
"explorer": AgentDefinition(
description="Read-only codebase search",
prompt="Find code and report file:line evidence.",
tools=["Read", "Grep", "Glob"],
maxTurns=8, # camelCase: AgentDefinition fields are camelCase
)
},
)
Why "turns" is a poor proxy for cost, and what to cap instead
The cost of turn k isn't constant. Each request re-sends the whole prefix, so the input side of turn k is roughly the cached prefix (billed at the cache-read rate) plus whatever is new since the last request (billed at the cache-write rate). With a warm cache the read part is cheap per token, but it grows linearly with the conversation, so cumulative input cost over n turns grows roughly quadratically in n until compaction resets the history. Output tokens, including thinking, add a per-turn term that depends on effort.
That's why a turn cap alone doesn't bound spend: twenty turns early in a session can cost far less than twenty turns near a full window. Use both caps. The turn cap catches loops that stop making progress; the budget cap catches the expensive cases. And put cost-shaping where it works: delegate large reads to subagents so the main prefix stays small, compact at natural breaks, and lower effort for routine agents (the SDK docs recommend "low" "for agents doing simple, well-scoped tasks").
Exercise: find your run's real shape
Run the read-only command from Turns and Tool Calls against a repository you know, three times with --max-turns 2, 4 and 8. For each, record the distinct response count, the tool calls, num_turns, subtype, terminal_reason and total_cost_usd. Then write the one-line rule your CI wrapper should use to tell "hit the cap" from "finished".
Show a solution
You should see the low cap end with subtype: "error_max_turns", is_error: true, terminal_reason: "max_turns", no result field, and an errors array such as ["Reached maximum number of turns (2)"]. Its stop_reason is "tool_use", because the last response requested tools; they ran, but the cap stopped the loop before their results went back to the model. The higher caps should finish with terminal_reason: "completed" and stop_reason: "end_turn". num_turns won't equal your response count in every run, which is the point.
The rule: check stop_reason for "refusal" first, then branch on terminal_reason (max_turns means the cap, completed means finished), fall back to subtype on CLIs that predate the field, and treat any other value as a failure to investigate.
for n in 2 4 8; do
claude -p "Where is DISCOUNTS defined?" --output-format stream-json --verbose \
--tools Read,Grep,Glob --allowedTools Read,Grep,Glob --permission-mode dontAsk \
--max-turns "$n" --max-budget-usd 0.25 > "run-$n.jsonl"
echo "max-turns=$n responses=$(jq -r 'select(.type=="assistant" and .parent_tool_use_id==null)|.message.id' "run-$n.jsonl" | sort -u | wc -l)"
jq -c 'select(.type=="result") | {subtype,num_turns,stop_reason,terminal_reason,total_cost_usd}' "run-$n.jsonl" | tail -n 1
done
Key takeaways
One model step is one API request that re-sends the whole context; one response can hold several tool calls, and each content block is its own assistant event sharing a message.id.
"Turn" means a whole prompt-to-answer exchange in the UI and hooks, and a tool-use round trip in --max-turns and the SDK. Read num_turns; don't compute it.
Decide why a run ended from the result event: stop_reason first, then terminal_reason, then subtype. A refusal and an API error can both arrive as subtype: "success" with is_error: true.
Queue a message to steer at the next tool boundary; press Esc to stop now. In -p, SIGINT records the turn and SIGTERM doesn't.
The budget cap is a client-side estimate checked after each response, so it overshoots by up to one response plus running subagents. Set both caps, with headroom.
Instructions
Claude Code assembles Claude's instructions from four places that look alike but behave differently: the system prompt, which Claude Code owns and records once per conversation; output styles, which reshape it and add per-session instructions; CLAUDE.md, which arrives as a message after the system prompt; and the flags that append to or replace the system prompt. Where each one lands decides how strongly it weighs, when an edit takes effect, and what it does to the cache.
System Prompt
What it is. The system prompt is the first layer of every request: Claude Code's core instructions for behavior, tool use and response formatting, together with the tool definitions. "Claude Code's system prompt isn't published" (Settings), so you can't read or patch it directly, but you can see what surrounds it, choose which variant you get, append to it, or replace it.
How it's built
Two variants.CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT chooses "between Claude Code's full system prompt and a shorter one with abbreviated tool descriptions. When unset, Haiku 4.5, Sonnet 5, Opus 4.7, and earlier models in those families use the full prompt by default, and newer models use the shorter one" (Environment variables). Both keep the full tool set, hooks, MCP and CLAUDE.md discovery.
Why the shorter one exists. The Claude Code team describes the shift: "We removed over 80% of Claude Code's system prompt for models like Claude Opus 5 and Claude Fable 5 with no measurable loss on our coding evaluations" (claude.dev).
A dynamic section. The default prompt embeds per-user context such as your auto memory location, an absolute path under ~/.claude/projects/. That's why two machines running the same task can't share a cache entry for it. --exclude-dynamic-system-prompt-sections (with -p; SDK exclude_dynamic_sections) moves that context into the first user message, so identical configurations share the system prompt's cache across users. It applies only to the default prompt.
Recorded once. "Claude Code builds the system prompt once, on a conversation's first request, with the text from any system prompt flags applied, and records it in the session. Until the conversation is compacted, every later request uses that recorded prompt, including after you return to the conversation with --resume or --continue" (CLI reference). --system-prompt-snapshot off (v2.1.257+) rebuilds it on every request while you iterate on wording.
What is not in the system prompt
A lot of what shapes Claude arrives in the conversation instead, as system reminders: messages Claude Code adds "alongside your messages" (Context Claude Code adds on its own). They include your CLAUDE.md files, the active output style's instructions, the commit and PR attribution lines, hook additionalContext, the lists of available skills and subagents, notes that a file you read changed on disk, and task-list nudges. The working directory, platform, shell and OS version, and the git status snapshot, also open the conversation rather than sitting in the system prompt. "If Claude follows a rule you didn't write, such as adding a Co-Authored-By trailer to a commit, the rule may have come from a system reminder." Turn off the built-in git guidance with "includeGitInstructions": false and change attribution with the attribution setting.
Toggle flags and settings and watch the pieces move between the system prompt board, the conversation board and the dropped tray; the piece that just moved carries the highlight. Piece names describe the content, not the real text, which isn't published.
Minimal prompts: bare mode and the SDK
--bare (or CLAUDE_CODE_SIMPLE=1) runs "with a minimal system prompt and only the Bash, file read, and file edit tools" and skips hooks, skills, commands, subagents, plugins, MCP auto-discovery, auto memory and CLAUDE.md. Since v2.1.286 it also sends no system reminders, so Claude isn't told when a file it read changes. In bare mode Claude Code "never reads OAuth credentials or the system keychain", so a subscription login doesn't carry over: supply ANTHROPIC_API_KEY or an apiKeyHelper through --settings. It's the recommended mode for scripted calls and "will become the default for -p in a future release" (Headless). The Agent SDK goes further by default: without a system_prompt option it uses "a minimal prompt that covers tool calling but omits the rest of the claude_code preset's content, including its security and safety instructions" (Modifying system prompts). Agents 2 covers choosing between the preset and your own prompt.
Pitfalls
Fighting the system prompt from CLAUDE.md. If your instruction contradicts built-in guidance, such as commit conventions, turn the built-in part off with its setting rather than writing louder instructions.
Assuming the prompt is stable across upgrades. "A new Claude Code version typically updates the system prompt or tool definitions", so the first conversation after an upgrade builds its cache from the top.
Expecting a flag change to reach a resumed session. The recorded prompt wins until compaction.
Why the split between system prompt and conversation exists
Prompt caching matches the start of a request exactly, so anything that changes per user, per directory or per turn should sit as late as possible. Claude Code's layering follows from that: the system prompt and tool definitions first (rarely change), project context next (changes at session start, /clear or /compact), conversation last. The engineering post on the design puts the rule in one line: "The best way to do this is static content first, dynamic content last" (Prompt caching is everything). It also explains why mid-session changes such as plan mode, skill loading and output-style switches are delivered as messages: appending keeps the cached prefix intact.
There's a cost to putting things in messages. The SDK docs note that text moved out of the system prompt "still reaches Claude, but in a user message", and "instructions in a user message carry marginally less weight than the same text in the system prompt". That's the tradeoff behind exclude_dynamic_sections, and the reason --append-system-prompt exists for rules that must sit at system level.
Output Styles
What it is. An output style is "a set of instructions that sets Claude's role, tone, and response format for every response in a session" (Output styles). Claude Code starts in Default, which adds no style instructions. Four built-in styles keep the default instructions and add their own: Proactive (starts work right away and makes reasonable assumptions about routine decisions), Concise (leads with the result; requires v2.1.237+), Explanatory (adds ★ Insight blocks) and Learning (also leaves TODO(human) pieces for you to write).
How it works
Claude Code "sends the active style's instructions with every request", as a reminder in the main conversation. A mid-session switch is delivered "as a message in the conversation", so it keeps the cache, and since v2.1.251 it applies "starting with your next message" (before that, a switch kept the cache but waited for /clear or a new session).
A custom style also changes the system prompt: "On the full system prompt, custom output styles leave out Claude Code's section of built-in software engineering instructions, such as how to scope changes, write comments, and verify work, unless keep-coding-instructions is set to true." The shorter prompt, the default on newer models, has no such section, so the field has no effect there unless you set CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT=0.
Styles apply to the main conversation and to forks, which inherit the parent's system prompt. Other subagents "run their own system prompt", so styles don't change how they respond.
Proactive doesn't change your permission mode. Its instruction to "check with you in the conversation before an action that deletes data or changes a shared or production system" is separate from permission prompts.
Practice
.claude/output-styles/incident-scribe.md
---
description: Terse, timestamped incident notes; no code changes unless asked
keep-coding-instructions: true
---
You are the scribe for a live incident. For every response:
- Start with one line: what changed since the last update.
- Then a bulleted timeline in `HH:MM UTC - event` form, newest last.
- Quote commands and their exit codes exactly; never paraphrase error text.
- End with "Open questions:" and at most three items.
Don't edit files unless the user asks for a change in this message.
Save it as .claude/output-styles/incident-scribe.md; with no name field, the file name is the style name. Use the project directory or ~/.claude/output-styles/ for every project; managed and plugin output-styles/ directories also work. Switch with /output-style incident-scribe (v2.1.269+; it also works in -p and SDK sessions) or /config. Both save outputStyle to .claude/settings.local.json. In a settings file the value is case-sensitive: "outputStyle": "Explanatory" works, and "explanatory" silently gives you Default. The terminal reads style files at startup, so restart after editing one. A plugin style can set force-for-plugin: true to apply itself whenever the plugin is enabled.
✓ Good fit for an output style
How every response should read: voice, length, format, or a different role entirely ("you are a data analyst"). It applies session-wide and you can switch it with one command.
✗ Poor fit for an output style
Project facts (CLAUDE.md), one task's procedure (a skill), anything that must always happen (a hook), or a hard boundary (a permission rule). "An output style gives Claude instructions to follow. It doesn't guarantee that something always happens or never happens."
CLAUDE.md as Instructions
What it is.Core 2 covered where CLAUDE.md files live and how they load. Here the question is how they act as instructions. The memory docs are direct about it: "CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself. Claude reads it and tries to follow it, but there's no guarantee of strict compliance, especially for vague or conflicting instructions" (Memory). Claude Code introduces the files "with a line telling Claude that the instructions override default behavior", so project instructions can take precedence over Claude Code's generic defaults even though they arrive after the system prompt.
How the instruction text is assembled
All discovered files are concatenated, not overridden: managed, user, then project from the root down, with CLAUDE.local.md after CLAUDE.md in each directory. User-level rules load before project rules. If two instructions conflict, "Claude may pick one arbitrarily".
Root and user files are "read once at session start and held in memory". A mid-session edit keeps the cache but "doesn't apply" until /clear, /compact or a restart. Nested CLAUDE.md files and paths:-scoped rules load later, when Claude touches matching files, and an edit made before they load does take effect.
Block-level HTML comments are stripped before injection, so maintainers' notes cost nothing.
In auto mode, the classifier also sees your CLAUDE.md, so it shapes what gets blocked as well as what Claude tries.
Writing for adherence
The docs give the levers: concrete instructions you could verify ("Use 2-space indentation", not "Format code properly"), under 200 lines per file, headers and bullets, and no contradictions. Skip the emphasis: current models "follow a plainly worded line, and piling on emphasis mostly makes Claude over-apply the rule" (best practices). Run /doctor prompt-audit (v2.1.283+) to find instructions written for older models, references to files that don't exist, and files that contradict each other.
✗ Instruction that drifts
CLAUDE.md (excerpt)
## Rules
- IMPORTANT: be careful with the database
- YOU MUST write good tests
- Never push to main!!!
- Think carefully before every change
Vague, unverifiable, all emphasized, and one line is really a boundary that belongs in a permission rule.
✓ Instruction that holds
CLAUDE.md (excerpt)
## Database
- Migrations live in `db/migrations/`; generate them with `make migration name=...`, never by hand.
- Tests that touch the DB use the `pg_tmp` fixture in `tests/conftest.py`.
## Verification
- Before you say you're done, run `make test` and paste the summary line.
## Compact Instructions
Preserve the current task, files changed, and the last test output.
Concrete, checkable, and the "never push" rule moved to "deny": ["Bash(git push origin main*)"] plus a hook, because those are enforced.
Pick a home for each rule, then check. The aim is to put guidance where the model reads it and guarantees where Claude Code enforces them.
Debug a rule Claude ignoresRun /context and look under Memory files for the files that loaded at launch. A subdirectory CLAUDE.md doesn't appear there; a Loaded line prints when it loads. To log every load with its reason (session_start, nested_traversal, path_glob_match, include, compact), register an InstructionsLoaded hook. If the rule must run at a specific moment, it was never a CLAUDE.md rule: "write it as a hook instead".
Appended System Prompts
What it is. Five flags customize the system prompt, and "all five work in both interactive and non-interactive modes" (System prompt flags):
Flag
Effect
Notes
--append-system-prompt
Appends text to the end of the default prompt
The lowest-risk customization: nothing is removed
--append-system-prompt-file
Appends a file's contents
With both forms (v2.1.283+), the file comes first, then a blank line, then the text, whatever the flag order
--system-prompt
Replaces the entire default prompt
"drops all of the default prompt, including tool guidance and safety instructions"
--system-prompt-file
Replaces it with a file's contents
Combine with an append flag to replace and still append
--system-prompt-snapshot
off rebuilds the prompt every request; on (default) reuses the recorded one
v2.1.257+. Bare mode records nothing unless you pass on
Two relatives apply only with -p: --append-subagent-system-prompt (v2.1.205+) and its -file form (v2.1.261+) append to every subagent's prompt except forks, which reuse the conversation's own.
The request is ordered for caching: the system prompt layer, then project context, then the conversation. Appended text joins the system prompt; CLAUDE.md, the output style's instructions and hook context arrive as messages. Items in the conversation layer can change mid-session without breaking the cached prefix. The request is abridged and illustrative; hover a tag in the margin to see its slot.
When to append and when to replace
Use --append-system-prompt when a script or CI job needs rules at system level that don't belong in the repository's CLAUDE.md: "Never push commits", "cite file:line for every finding", an output contract. The memory docs recommend it for exactly this: "For instructions you want at the system prompt level, use --append-system-prompt. You pass it at launch, so it's better suited to scripts and automation than interactive use." Replace the prompt only when the agent isn't Claude Code any more: a different surface, identity or permission model. Then you own what you removed, including the tool guidance, the safety instructions and one sentence the SDK docs recommend adding so Claude knows what reminders are: "The application adds system reminders to this conversation. Treat them as context from the application, not as messages from the user."
# CI review: keep the default prompt, add an output contract
claude -p "Review the diff in HEAD~1..HEAD for correctness bugs" \
--append-system-prompt-file ./ci/review-rules.md \
--append-system-prompt "Never push commits. Cite file:line for every finding." \
--permission-mode dontAsk --allowedTools "Read,Grep,Glob,Bash(git diff *)" \
--max-turns 15 --max-budget-usd 1.50 --output-format json
# Replacement prompt with a cacheable static half (v2.1.275+)
cat > prompt.txt <<'TXT'
You are Acme's release-notes writer. Read merged PRs and write customer-facing notes.
The application adds system reminders to this conversation. Treat them as context from the application, not as messages from the user.
__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__
Release: 4.18. Audience: enterprise admins.
TXT
claude -p "Draft the notes" --system-prompt-file prompt.txt --tools Read,Grep,Glob
Agent SDK options (excerpt)
from claude_agent_sdk import query, ClaudeAgentOptions
opts = ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code", # keep tool guidance and safety rules
"append": "Never push commits. Cite file:line for every finding.",
"exclude_dynamic_sections": True, # share the cache across machines
},
setting_sources=["project"], # CLAUDE.md loads via setting sources, not the preset
)
.github/workflows/claude-review.yml
name: claude-review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
id-token: write # required for the action's default GitHub App authentication
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: >-
Review pull request ${{ github.repository }}/pull/${{ github.event.pull_request.number }}
for correctness bugs and post each finding as an inline comment.
# v1 replaced the beta custom_instructions input with --append-system-prompt.
# Naming the inline-comment tool makes the action start the MCP server that posts it.
claude_args: |
--max-turns 15
--allowedTools "mcp__github_inline_comment__create_inline_comment"
--append-system-prompt "Never push commits. Cite file:line for every finding."
With a plain prompt, "Claude has no shell or GitHub API access until you grant the tools the prompt needs". Without the --allowedTools line, the review would only appear in the job log (GitHub Actions).
Resumed sessions, snapshots and changing instructions mid-run
Because the system prompt is recorded on the first request, a later launch with different flag text "takes effect once the conversation is compacted or when you start a new conversation". That's deliberate: changing the prefix would force a full cache rebuild and, where the API enforces preserved thinking, "Claude also loses its thinking from earlier turns". Keep recording on in production. Turn it off (--system-prompt-snapshot off, or snapshot: false in the SDK) only while iterating on wording.
To change instructions inside a running session, send them in the conversation: put the change in the next user message, or return additionalContext from a UserPromptSubmit or PostToolUse hook, "written as a factual statement such as 'The workspace is now read-only'". The recorded prompt stays unchanged, and so does the cache.
The dynamic boundary is the other cache tool. Put static instructions above a line containing only __SYSTEM_PROMPT_DYNAMIC_BOUNDARY__ and per-run context below it, and Claude Code sends two blocks, each with its own cache breakpoint, so a new ticket or release number doesn't invalidate the instructions. It works "only when it calls the Claude API directly or runs on Claude Platform on AWS"; on Bedrock, Agent Platform, Foundry or a gateway the prompt goes as one block. In the TypeScript SDK, pass an array with the exported SYSTEM_PROMPT_DYNAMIC_BOUNDARY marker instead.
Exercise: build and inspect an instruction stack
In a scratch repository: (1) write a two-rule CLAUDE.md, (2) create the incident-scribe style above, (3) run claude -p twice with --append-system-prompt "Answer in French.", once with --output-format stream-json --verbose, and read the init event's output_style field. Then (4) start an interactive session, run /context, edit CLAUDE.md, and ask Claude to quote your rules back. Explain each observation.
Show a solution
The appended French rule applies in both runs, because append flags join the system prompt. The init event's output_style shows the active style (default until you switch). /context lists the CLAUDE.md under Memory files. After the edit, Claude quotes the old rules: root CLAUDE.md is read once at session start, and the edit applies after /clear, /compact or a restart. If you then switch styles with /output-style incident-scribe, the next reply follows it without a cache miss, because the instructions arrive as a message. And if you resume the -p session with --continue and a different append text, the original text keeps applying until compaction, unless you pass --system-prompt-snapshot off.
Key takeaways
The system prompt holds Claude Code's core instructions and tool definitions; it's unpublished, recorded on the first request, and reused until compaction, even across resume.
Newer models get a shorter system prompt by default, with no software-engineering section, so keep-coding-instructions only matters on the full prompt (CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT=0).
CLAUDE.md, output-style instructions, hook context and environment details arrive as messages and system reminders, not in the system prompt. That's what keeps mid-session changes cache-safe.
Append for system-level rules in scripts; replace only for a different agent, and then re-add tool guidance, safety rules and the system-reminder sentence.
Guidance lives in instructions; guarantees live in hooks and permission rules.
Context and Memory
Everything Claude knows in a session is either in the request or on disk waiting to be read. Transcripts record the request history; prompt caching makes re-sending it affordable; compaction rewrites it when it grows too large; memory files carry what should outlive it. Each mechanism has rules about what it keeps, and the expensive surprises (a slow uncached turn, a rule that vanished after /compact, a fact that never loaded) come from not knowing them.
Transcripts
What it is. "Each message, tool use, and result is written to a plaintext JSONL file under ~/.claude/projects/, which enables rewinding, resuming, and forking sessions" (How Claude Code works). A transcript is the durable form of the loop: the same messages and tool results that go into each request, plus metadata entries.
~/.claude/projects/
└── -Users-alice-code-shop/ # cwd with non-alphanumerics replaced by "-"
├── 5e1c3a10-....jsonl # one session: messages, tool calls, results, metadata
├── 5e1c3a10-.../subagents/
│ └── agent-<agentId>.jsonl # each subagent's own transcript
└── memory/ # auto memory (next concepts), not a transcript
├── MEMORY.md
└── feedback_testing.md
How it works
Written continuously, so you can return after exiting or /clear. claude --continue reopens the latest conversation in this directory (it skips -p and SDK sessions; claude -p --continue includes them), claude --resume <id|name|path> a specific one, and --fork-session or /branch copies history into a new session ID. A resumed conversation restores the recorded system prompt too.
The format is private. "Each line is a JSON object: a message, a tool use or result, a record of a request Claude Code sent the model, or a metadata entry. The entry format is internal to Claude Code and changes between versions, so scripts that parse these files directly can break on any release" (Manage sessions).
It holds everything a tool saw. "Anything that passes through a tool is written to a transcript on disk: file contents, command output, pasted text." Transcripts "are not encrypted at rest. OS file permissions are the only protection." If Claude reads a .env, the values are in the JSONL.
Retention.cleanupPeriodDays (default 30; 0 fails validation) deletes old sessions; claude purge clears a project sooner. For a single -p run, --no-session-persistence skips the write, and CLAUDE_CODE_SKIP_PROMPT_HISTORY skips transcript writes in every mode. The course labs found that even with --no-session-persistence the CLI created empty ~/.claude/projects/<tmp>/memory/ folders.
Practice: the supported interfaces
For a person, run /export review-notes.txt inside the session: it writes a rendered, readable transcript. For scripts, use the structured interfaces:
# A script reading a run: structured and versioned
claude -p "..." --output-format json | jq '{session_id, num_turns, total_cost_usd}'
# A script asking an existing session a question
claude -p --resume "$SESSION_ID" --output-format json "summarize what we changed" | jq -r .result
# React to sessions as they happen: hooks and the status line get transcript_path
jq -r '.transcript_path' <<<"$HOOK_INPUT" # e.g. archive it from a SessionEnd hook
In the terminal, Ctrl+O opens the transcript viewer for the current session. For SDK hosts, the session helpers (list_sessions, get_session_messages and friends) and SessionStore adapters are covered in Agents 2, and transcript mining for evals in Agents 5.
Pitfall: secrets in transcriptsA denial in the permission layer keeps a secret out of the transcript; a sandbox read denial for a shell command does too. Asking Claude "not to look" doesn't. Add Read deny rules for credential paths, lower cleanupPeriodDays on shared machines, and when you report a memory problem with /heapdump, attach only the -diagnostics.json file: "the .heapsnapshot contains your full conversation and credentials, so don't share it".
Prompt Caching
What it is. "Each time you send a message in Claude Code, it makes a new API request. The model doesn't remember anything between requests, so Claude Code re-sends the full context." Prompt caching is how the API avoids reprocessing the part that didn't change: it "caches by matching the start of each request, called the prefix, against content it recently processed ... The match is exact, so a change anywhere in the prefix recomputes everything after it. There is no per-file or per-segment caching" (How Claude Code uses prompt caching). Core 1 introduced the cost side; this concept is the mechanism.
How the prefix is ordered
Layer
Content
Changes when
System prompt
Core instructions, tool definitions
The set of loaded tool definitions changes
Project context
CLAUDE.md, auto memory, unscoped rules
Session starts, or after /clear or /compact
Conversation
Your messages, Claude's responses, tool results
Every turn
Two settings sit outside the table but still split the cache. Each model has its own cache, and on most models each effort level does too; on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 with an API key or a Claude subscription, effort changes keep the cache (not on Bedrock, Agent Platform or a Claude apps gateway).
Each request is the previous one plus the latest exchange. While the prefix matches, it's read from cache and only the new tail is written. On the fourth request a model switch means no prefix matches, and the whole request is processed and written again. The ▼ cursor marks the first token that doesn't match the cache. Sizes are illustrative.
What breaks the cache, and what doesn't
Invalidates (one slow, expensive turn)
Switching models, including opusplan plan-mode toggles, a skill whose model differs, and automatic content fallback
Changing effort, except on the 5.5 models and Fable 5.1 with an API key or subscription
The first time you turn on fast mode in a conversation (a header that's part of the cache key)
Connecting or removing an MCP server, or toggling a plugin's MCP server, when tools load upfront (tool search off or unavailable)
Denying a whole tool by bare name, again only without tool search
Compacting (by design), accumulating many images, upgrading Claude Code
Keeps the cache
Editing repository files: Claude Code appends a "file changed" reminder
Editing CLAUDE.md mid-session, which also means the edit doesn't apply yet
Changing permission mode (except opusplan + plan)
Changing output style (v2.1.251+), invoking skills and commands, /recap
/rewind: it truncates to a prefix that's already cached
Spawning a subagent: the call and result append to the parent's conversation
How long the cache lives
Cached prefixes expire after inactivity; "each request that hits the cache resets the timer". Claude Code puts every request in one of two TTL buckets:
Request bucket
Claude subscription, within plan usage
Usage credits, API key, or cloud provider
Main conversation (interactive turns, -p runs, SDK turns)
Five minutes, except some server-controlled helpers
Five minutes
Choose your own TTL with promptCacheTtl / CLAUDE_CODE_PROMPT_CACHE_TTL (main) and subagentPromptCacheTtl / CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL (everything else), each 5m or 1h (v2.1.242+). The first match wins: FORCE_PROMPT_CACHING_5M=1, then the bucket's environment variable, then its setting, then a subagent's experimental.cacheTtl, then ENABLE_PROMPT_CACHING_1H=1, then the default. To confirm what a run used, read usage.cache_creation from claude -p "hello" --output-format json: one-hour writes appear under ephemeral_1h_input_tokens, five-minute writes under ephemeral_5m_input_tokens.
Each request is a column in time order: cache read in ink, cache written stacked on top in the highlight (hatched when it goes to the 5-minute bucket), and its input cost as the thin line above. The events you trigger are flags between columns; hover a column for why it missed. Toy model: one request per prompt, illustrative token sizes, input side only. Rules follow the prompt-caching docs; prices are Claude API list prices per million input tokens (Opus 5.5 $4, Sonnet 5.5 $2), with cache reads at 0.05× and writes at 1.25× (5-minute TTL) or 2× (1-hour TTL). On a subscription the dollar figure is a list-price estimate, like /usage.
Cache scope
"In Claude Code, the cache is effectively scoped to one machine and directory. The system prompt embeds your auto memory paths, and the conversation opens with an announcement of the working directory, platform, shell, and OS version." Parallel sessions in the same directory build matching prefixes and read each other's cache; sequential ones share it only when the git status snapshot taken at startup matches. A subagent "starts its own conversation with its own system prompt and tool set", so its first request is cold, and it falls in the five-minute bucket even on a subscription. A fork "inherits the parent's system prompt, tools, and conversation history exactly, so its first request reads the parent's cache".
Message threads: send less, still read everything
Caching saves the API from reprocessing the unchanged prefix. It doesn't save the client from re-sending it: "Without a thread, every turn uploads the whole conversation again, and the API validates and tokenizes all of it again." A message thread (a Messages API beta) "keeps a conversation on the server for a short time. You send the full conversation once, with your system prompt and tools. On each later turn, you send only the new messages and the id of the previous response" (Message threads). Anthropic describes it as "on by default for most Claude Code users", with a "median TTFT drop by about 35%" (time to first token) for requests of 500K to 1M tokens (Make long-running agents faster with message threads, November 2026). The quote at the top of this concept still holds for what the model sees; a thread changes what goes over the wire.
Prompt caching
Message thread
Saves
Reprocessing the matched prefix: cost and latency
Uploading, validating and tokenizing the history: latency only
Billing
Cached reads at a fraction of the input rate
"Threads do not change pricing or rate limits." "Claude still reads the full conversation on every turn, so token usage stays the same."
Lifetime
5 minutes or 1 hour idle, reset by each hit
"It expires 5 minutes after its last request"; then the client re-sends the full conversation to start a new one
Breaks on
Any change in the prefix
Any edit to history: "A thread is append-only ... To edit or branch an earlier message, start a new thread"
The two stack: "A thread does not cache your prompt for you. Prompt caching works as it does without a thread", so the cache rules above still decide what each turn costs. The advice doesn't change either. A thread can only be appended to, and its model is fixed ("To change a create-only or fixed field, start a new thread"), so compaction, /rewind and a model switch each need a new thread, which means one full upload on top of whatever the cache miss costs.
Practice
"Pick your model and effort level at the top of a session, then save /compact for natural breaks between tasks." Connect MCP servers before you start, or rely on tool search (the default on supported models) to keep mid-session connections cache-safe.
Watch the hit rate. A status line script can read cache_creation_input_tokens and cache_read_input_tokens from current_usage, or the prompt_cache object. /usage shows a Prompt cache (main) line with hit ratio, misses and whether the cache is warm (v2.1.251+), and names the likely cause of the last miss, such as likely cause: tool definitions changed (v2.1.260+).
Behind an LLM gateway, check that it forwards the cache_control markers. If a gateway "removes the markers while returning success", then "your entire conversation history bills as uncached input on every turn", and nothing in the session warns you except a zero cache_read_input_tokens.
Abandoning a path? /rewind to before it. Rewinding truncates back to a prefix that's already cached, while compaction builds a new one.
On an API key with long idle gaps, consider "promptCacheTtl": "1h", then measure; the deep dive has the break-even.
TTL economics: when the 1-hour cache pays for itself
Let the cached prefix be P tokens and the base input price be p. Cache reads cost 0.05·p on Opus 5.5 and Sonnet 5.5 (0.025·p on Fable 5.1, 0.1·p on most other models), five-minute writes cost 1.25·p, and one-hour writes cost 2·p (Claude API pricing, October 2026). Two costs compete:
On the 5-minute TTL, every idle gap longer than five minutes turns the next request's read of P into a write: 1.25·p·P instead of 0.05·p·P, an extra 1.2·p·P per gap.
On the 1-hour TTL, every token you write costs 0.75·p more. If a session writes W tokens in total (the first prefix plus every new tail), the premium is 0.75·p·W.
So the hour pays off when the number of gaps between 5 and 60 minutes, g, satisfies 1.2·g·P > 0.75·W. With P = 120K tokens late in a session and W = 300K written over the session, one coffee break (g = 1) already saves 144K-token-equivalents against a 225K premium, so it takes two such gaps to come out ahead. A meeting-heavy day with several 20-minute gaps clears it easily; a focused 40-minute burst never does. That's why Claude Code defaults to the hour only where you aren't billed per token, and drops back to five minutes "once you go over your plan's usage limit".
Compaction interacts with this. To produce the summary, Claude Code "sends a separate request", which "repeats your conversation's system prompt, tools, and the history being summarized" and "ends with a summarization instruction". While the cache is warm that request reads the prefix: "A mid-session /compact then costs a fraction of what the context size suggests" (prompt caching). After a break longer than the TTL, the summarization request reprocesses the full history uncached, which is why the docs advise compacting before a break, not after it. Claude Code can also compact an idle conversation shortly before a one-hour cache expires (idleCompaction, v2.1.290+ to turn off).
What you build: an offline simulator that replays scripted sessions (steady, coffee-break, switches, subagents) and prices every request: tokens read from cache, tokens written, the TTL bucket, and why each miss happened. It also shows the per-request read/write pattern from a real-shaped transcript, and accepts your own timeline as JSON.
cd labs && python3 agents-1/cache_sim.py
python3 agents-1/cache_sim.py --scenario coffee-break --billing api
python3 agents-1/cache_sim.py --scenario switches --billing cloud # Bedrock, Agent Platform or a gateway
python3 agents-1/cache_sim.py --main-ttl 1h --sub-ttl 5m
What to observe: the coffee-break pause rebuilding the cache on a 5-minute TTL but not on the hour; in switches, a model switch missing while switching back within the TTL hits the old cache, a CLAUDE.md edit keeping the cache, and the first request after /compact missing at the project layer (with --billing cloud, the /effort change misses too); in subagents, a cold subagent next to a fork that reads the parent's cache.
What it is. When context approaches its limit, Claude Code "compacts the conversation into a summary" (When context fills up). Compaction replaces the message history with a structured summary and then rebuilds the startup context, so the session can continue in a much smaller window. /compact [instructions] runs it on demand; in the stream it shows up as a system event with subtype compact_boundary.
When it runs
Models with a native 1M window (Fable models, Sonnet 5+, Haiku 5.5, Opus 4.7+) compact "at about 967K tokens by default"; others at their context limit (Model configuration).
Move the threshold with /autocompact 500k (v2.1.221+; per model under modelSettings v2.1.288+), the autoCompactWindow setting, --autocompact, or CLAUDE_CODE_AUTO_COMPACT_WINDOW (highest). Unit trap: "CLAUDE_CODE_AUTO_COMPACT_WINDOW=200 means 200 tokens even though /autocompact 200 means 200,000."
Turn auto-compaction off with autoCompactEnabled: false or DISABLE_AUTO_COMPACT ("the manual /compact command keeps working"); DISABLE_COMPACT removes both.
What survives
The context-window docs list it per mechanism. The pattern: anything loaded from disk at startup is re-injected; anything loaded into history on demand is summarized away and reloads when triggered again; anything said only in conversation survives only as far as the summary keeps it.
Choose what's in the session, set how many files Claude has read or edited, then run compaction: each item drops from above the cut line into the bin that says what happens to it. Outcomes follow the "What survives compaction" table in the docs.
Steering the summary
CLAUDE.md (excerpt)
## Compact Instructions
When summarizing, preserve:
- the current task and its acceptance criteria
- every file path read or modified, and why
- the last test command and its full summary line
- decisions made and the reason for each
Put a section like this in CLAUDE.md (the compactor "matches on intent, so the section header is free-form"), or pass focus text: /compact focus on the auth bug fix. To compress only part of the history, open /rewind, pick a message and choose Summarize from here or Summarize up to here. To restore context the summary can't carry, register a SessionStart hook with the compact matcher; its output is added to the compacted context:
Boundaries given in chat. The auto mode docs warn that "a boundary can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead."
Path-scoped rules you need everywhere. "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md."
Long skills. Re-injected skill bodies are capped at 5,000 tokens each and 25,000 in total, oldest dropped first, and "truncation keeps the start of the file, so put the most important instructions near the top of SKILL.md".
Thrashing. A single output so large that the window refills right after each summary makes Claude Code stop auto-compacting and show Autocompact is thrashing. Cut the output (a narrower command, a subagent), don't raise the window.
Compaction from the cache's point of view
Compaction replaces the history with a summary. "By design, this invalidates the conversation layer: the next request has a new, shorter history that doesn't share a prefix with the old one." The system prompt layer is reused, and project context is reloaded from disk: "The next request reads it from the cache only if CLAUDE.md and memory are unchanged since the session started" (prompt caching). That's also the moment a mid-session CLAUDE.md edit finally applies.
The summary itself comes from a separate request that shares the conversation's prefix, so its cost depends on cache temperature, as in the TTL deep dive. Its own writes fall in the "everything else" bucket, five minutes. The summarization request inherits your session's extended-thinking configuration (v2.1.198+), and the turn after compaction rebuilds the cache only for the much shorter summary, "so that turn isn't the slow part".
If you build your own loop on the Client SDK, the same ideas appear as explicit controls: the automatic context compaction cookbook uses tool_runner(..., compaction_control=...), and context engineering compares compaction with tool-result clearing and memory. Those recipes use the Client SDK, not the Agent SDK.
Memory Files
What it is. Memory files are what outlives a context window. Claude Code has two systems, and "both are loaded at the start of every conversation. Claude treats them as context, not enforced configuration" (Memory). CLAUDE.md and .claude/rules/ are files you write (placement and loading are in Core 2). Auto memory is a directory Claude writes for itself.
Auto memory, mechanically
Kinds. Claude saves four kinds of notes and records the kind as a type field in frontmatter: user (role, expertise, preferences), feedback (corrections and confirmed approaches), project (ongoing work and decisions not derivable from the code), and reference (where outside information lives). It skips what it can derive from the codebase and what CLAUDE.md already says.
Layout.~/.claude/projects/<project>/memory/ holds a MEMORY.md index plus one topic file per memory. The <project> path "is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory". It's machine-local and isn't shared across machines or cloud environments.
Loading. "The first 200 lines of MEMORY.md, or the first 25KB, whichever comes first, are loaded at the start of every conversation." Topic files aren't; Claude reads them on demand with its file tools. Near a limit, Claude Code reminds Claude to shorten the index; over it, the write succeeds but returns an error telling Claude to rewrite the index, "because everything past the limit is dropped on the next load".
Scope. The main conversation's auto memory isn't loaded into subagents, except forks. A subagent's own memory: frontmatter field gives it a separate directory under ~/.claude/agent-memory/, .claude/agent-memory/ or .claude/agent-memory-local/ (Agents 4). Memory files are exempt from the cleanupPeriodDays sweep and re-injected after compaction.
Compaction as a tide. The conversation history goes out, taking what was loaded on demand with it, and comes back in as a summary. The seawall of startup content is re-injected from disk, and only invoked skill bodies and up to five recently modified files come back with the new conversation. Run /compact, then hover a block for its rule. Every outcome is a row of the What survives compaction table; the drawing's levels are illustrative.
Practice
~/.claude/projects/<project>/memory/MEMORY.md
- [Use pnpm, never npm](feedback_pnpm.md): installs and scripts go through pnpm
- [API tests need local Redis](project_redis.md): start it with `make redis` first
- [Latency dashboards](reference_dashboards.md): where to check p95 after deploys
---
type: project
modified: 2026-10-14T09:12:03Z
---
The `tests/api/` suite connects to Redis on localhost:6379.
Start it with `make redis` before `pytest tests/api`.
CI starts its own service container, so this is local-only.
Claude Code writes the modified timestamp when Claude writes a memory file that begins with frontmatter, so both you and Claude can judge how current a fact is. Browse and edit everything with /memory, which also has the auto memory toggle (it saves autoMemoryEnabled). Turn auto memory off for one project with "autoMemoryEnabled": false in its settings, everywhere with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, or move it with autoMemoryDirectory (an absolute path or one starting ~/; a repository's settings get it only after workspace trust, and a -p run counts as trusted, so there the repository's value applies). Ask "remember that ..." to write auto memory; ask "add this to CLAUDE.md" to write the shared file instead.
Security: memory is persistent inputAnthropic's containment write-up lists "persistent memory poisoning" as a risk: CLAUDE.md files and memories are "reloaded each time the agent starts" (How we contain Claude). Content Claude read from an untrusted page can end up in a memory file and steer every later session. Review /memory after sessions that touched untrusted input, and in multi-tenant SDK hosts set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 and a per-tenant CLAUDE_CONFIG_DIR.
Choosing between CLAUDE.md, rules, auto memory, skills and files on disk
Each store trades always-on cost for reliability of recall. CLAUDE.md and unscoped rules cost tokens on every request (cached, but still in the window) and are re-injected after compaction, so they suit short, always-relevant facts. Path-scoped rules cost nothing until a matching file is touched, and vanish at compaction until touched again. Auto memory's index is always loaded but capped, and topic files cost only when read, which makes recall depend on a good one-line hook in the index. Skills load only a description up front and the body when invoked. Plain files on disk, such as a PROGRESS.md or a JSON task list, cost nothing until read and are the most reliable state for long runs, the pattern Anthropic recommends in Effective harnesses for long-running agents.
A useful test before adding a line to CLAUDE.md is the docs' own: "Could it find this by reading the code?" and "Would it actually go and look?" If both are yes, leave it out. If the line only matters sometimes, it belongs in a skill, a rule or a file Claude reads when it needs it.
Exercise: catch a silent invalidator, then make a rule compaction-proof
(1) In a long interactive session, run /usage and note the Prompt cache (main) line. Switch models with /model (accept the warning), send one prompt, and run /usage again. (2) Add a rule to a path-scoped file in .claude/rules/, trigger it, run /compact, and ask Claude to quote it. (3) Make the rule survive.
Show a solution
(1) The hit ratio drops and the miss count rises by one; on v2.1.260+ the line names a likely cause. Claude Code warned you before the switch because the cache was warm. On an API key, a five-minute idle gap produces the same miss with no warning. (2) After compaction Claude can't quote the rule until it touches a matching file again, because path-scoped rules load into history on demand. (3) Either drop paths: so the rule loads at launch like .claude/CLAUDE.md, move it to the project-root CLAUDE.md, or re-inject it with a SessionStart hook on the compact matcher. If it's a boundary rather than guidance, make it a deny rule.
Key takeaways
Transcripts are plaintext JSONL with a private format: read runs through stream-json, --output-format json, hooks' transcript_path or the SDK, and keep secrets out with deny rules.
The cache matches the exact prefix: system prompt and tools, then project context, then conversation. Model, effort (on most setups), first fast-mode toggle, upfront tool-set changes, compaction and upgrades invalidate it.
On a subscription within plan usage the main conversation gets a one-hour TTL and everything else five minutes; API keys and cloud providers get five minutes unless you set promptCacheTtl.
Compaction re-injects what loaded from disk at startup, reloads on-demand content when triggered, and only summarizes what you said in chat. Put boundaries in deny rules.
Auto memory's index loads up to 200 lines or 25KB at start; topic files load on demand; subagents don't get it unless they're forks.
Tools
Tools are where the loop touches your machine. Every call passes the same gate: hooks, then permission rules, safety checks and the permission mode, then a prompt, a classifier or a denial. After the gate, each tool has its own behavior and limits, and the shell-command tools can run inside an OS-enforced sandbox. Knowing exactly which layer decides what is the difference between a setup that feels safe and one that is.
Tool Permissions
What it is. Two separate questions decide whether a tool call happens. Availability: does the tool exist in this session? --tools restricts the built-in set ("" for none, "default", or names), a bare tool name in --disallowedTools or a deny rule removes it from Claude's context, and MCP tools need --disallowedTools "mcp__*" because --tools doesn't affect them. Approval: may this particular call run? That's decided by permission rules, the permission mode, hooks and, at the end, a person, a classifier or a refusal. "Permission rules are enforced by Claude Code, not by the model" (Permissions). --allowedTools only pre-approves; "to restrict which tools are available, use --tools instead".
The evaluation order
No single docs page lists all of these steps; this order is composed from the permissions and permission modes pages and the SDK's six-step order.
PreToolUse hooks run first, for every tool except EndConversation, "in every permission mode, including dontAsk". A hook that exits 2 "stops the tool call before permission rules are evaluated". JSON decisions from several hooks combine as deny > defer > ask > allow.
Deny rules from any scope block the call. "Deny rules block in every mode, including bypassPermissions", and "if a tool is denied at any level, no other level can allow it" (mods aside; see below).
Ask rules force a prompt, even in bypassPermissions. A hook's allow doesn't skip them. In dontAsk, a call that would prompt is denied.
Safety checks run before allow rules: writes to protected paths (.git, .claude, .vscode, shell rc files, .mcp.json and others) follow a per-mode table and are "never auto-approved except in bypassPermissions mode" and in plan-mode sessions where bypass permissions are available; a recognized rm or rmdir critical-path removal such as rm -rf ~ can't be pre-approved by any allow rule or hook, and asks in every mode that can ask, including bypassPermissions and auto (with a two-minute limit in the terminal), while dontAsk denies it; reads from network paths always prompt.
The mode sets the baseline: bypassPermissions runs everything still standing, apart from the actions no mode auto-approves (such as AskUserQuestion and MCP tools marked requiresUserInteraction); acceptEdits approves edits and common filesystem commands in scope; plan never auto-approves edits; auto sends what's left to the classifier; dontAsk denies what isn't pre-approved.
Allow rules pre-approve matching calls. They "have no effect in bypassPermissions", and on entering auto mode broad ones are dropped: Bash(*), wildcarded interpreters like Bash(python*), package-manager run commands, and Agent and Monitor allow rules.
No-approval actions run: file reads in the working directories and the built-in read-only Bash commands. The read-only set runs without a prompt even on paths outside the working directories, so cat ~/.ssh/id_ed25519 needs no approval unless a Read deny rule matches it or permissions.blockReadsOutsideWorkingDirectories (v2.1.257+) is on, which makes such shell reads prompt and makes the file tools refuse them.
Fallback: a prompt in Manual, acceptEdits and plan; the classifier in auto; a denial in dontAsk, and in -p when nothing can answer a prompt.
The Agent SDK documents a six-step version: hooks, deny rules, ask rules, permission mode, allow rules, then canUseTool, with the no-approval reads handled inside its allow step (Agents 2). An installed mod that handles tool.check answers after the rules and hooks; on machines without managed settings or a Team or Enterprise login it can approve a call a deny rule refused, which is one more reason to keep personal setups lean (Precedence among rules, hooks, and mods).
Toy model of the documented evaluation order. It shows the stage that decides each call; real sessions add details this omits (symlink checks, network paths, mods, managed-only locks), and the classifier's verdict is a model call, so it's shown as "classifier reviews" rather than allow or block. The call descends the locks in the documented order; the first lock that decides sends it to a basin, and the locks below it stay dry. Lock 4 holds what no allow rule lifts: protected paths, and critical-path removals like rm -rf ~, which ask even in bypassPermissions (with a two-minute limit in the terminal) and are denied in dontAsk.
Narrow allow rules like Bash(npm test) survive auto mode; Bash(npm *) might not. The ask rule on dangerouslyDisableSandbox:true makes every unsandboxed retry prompt, even in auto and bypass. The Read denies also block Edit and Write on those paths, and they cover the file commands Claude Code recognizes in Bash (cat, head, tail, sed, and tee on v2.1.269+) and redirect targets (>, >>, 2>, and < on v2.1.257+). They don't cover a command that reads without naming the file, such as grep -r pattern ., or a script that opens files itself. That's why secrets need both Read(~/.ssh/**)-style deny rules and sandbox denyRead. Remember the limits: "using WebFetch alone doesn't prevent network access. If Bash is allowed, Claude can still use curl", and the curl deny matches the command as written, not /usr/bin/curl or sh -c. That's what the sandbox is for.
Edge cases in the order that bite in practice
A hook's allow is weaker than it looks. "PreToolUse hook decisions don't bypass permission rules": a matching deny rule still blocks, a matching ask rule still prompts, and in plan mode an allow "has no effect on a file edit or another call that isn't read-only". A hook's deny, by contrast, "blocks the tool even in bypassPermissions mode".
Timeouts don't gate. A PreToolUse command hook that times out or crashes is a non-blocking error unless you set "onFailure": "block" (v2.1.295+). The SDK documents callback timeouts as blocking; don't build policy on either. "Don't count on a stalled hook to act as a gate."
Workspace trust. A project's permissions.allow and additionalDirectories apply only after the trust dialog, while deny and ask rules apply immediately. "A claude -p run or an SDK session never shows it". Trusting a parent folder doesn't count for these rules. So in a folder you never trusted interactively, -p ignores the project's allow rules (with a this workspace has not been trusted warning) yet still runs its hooks, its env block and helper commands, and connects its .mcp.json servers. The mitigations cover different pieces: --setting-sources user reads neither the project's settings nor its .mcp.json; --bare skips hooks, skills, plugins and .mcp.json but still applies the project's env block and helpers such as awsAuthRefresh; --settings '{"disableAllHooks": true}' turns off hooks only; a disabledMcpjsonServers entry rejects one server by name (What runs before you trust a folder).
Auto mode keeps explicit rules. In auto, "actions matching your allow, ask, or deny rules resolve immediately", with exceptions. Writes to protected paths "route to the classifier even when an allow rule matches"; no allow rule approves critical-path removals; and network-path reads, requiresUserInteraction MCP tools and content-scoped ask rules like Bash(git push *) fall back to a prompt. Read-only actions and working-directory edits skip the classifier, with one exception: "In a session with server-side classifier review, read-only and sandboxed shell commands wait for that review and are blocked if it flags them."
The two numbers on auto mode. Anthropic's engineering post reports a 0.4% false-positive rate and "17% FNR" on real overeager actions; the containment post frames it as catching "roughly 83% of overeager behaviors". "Auto mode reduces permission prompts but does not guarantee safety" (permission modes docs; see also the auto mode deep dive).
Bash
What it is. The Bash tool "runs each command in a separate process" (Bash tool behavior). It's the most powerful tool in the set and, on macOS, Linux and WSL, also the search tool: with Glob and Grep absent by default, Claude runs find and grep, which "run embedded versions of bfs and ugrep, and the searches reach your hooks and permission rules as Bash calls".
What persists between commands
A cd carries over while it stays inside the project or an added directory; outside them Claude Code resets and appends Shell cwd was reset to <dir>. Subagents never carry it over.
Environment variables don't persist: an export is gone by the next command. Activate your virtualenv before launching, or point CLAUDE_ENV_FILE at a script (a SessionStart hook can write it).
Aliases, functions and shell options from ~/.zshrc, ~/.bashrc or ~/.profile are captured at session start and applied to every command.
Time and output limits
Limit
Default
Control
Foreground timeout
2 minutes, or what Claude passes as timeout, capped at 10 minutes
BASH_DEFAULT_TIMEOUT_MS, BASH_MAX_TIMEOUT_MS
At the timeout
Moved to the background, not killed (unless it starts with sleep): Command did not complete within its 120s timeout and was moved to the background
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 or --bare make it stop instead
Successful output inline
About 30,000 characters; beyond that, a saved file's path plus a 2,000-character preview
bashOutputMaxChars up to 128,000 (v2.1.261+)
Failed output inline
About 10,000 characters, as a head-and-tail excerpt with no file path
BASH_MAX_OUTPUT_LENGTH widens the read-back window (30,000 default, 150,000 max)
Background commands in unattended sessions
30 minutes (up to 2 hours with timeout); 10 minutes in a -p run whose prompt is text
Requires v2.1.285+; raise with the same two variables
Exit code 1 counts as a valid result only for commands where it's benign: grep, rg, egrep, fgrep, find, diff, test, [, git diff and git grep. Any other exit 1, such as jq -e finding nothing, is treated as a failure, so its output is cut to the shorter failure excerpt. Pipe long logs through tail or grep yourself, or ask Claude to; a failing 2 MB test log reaches Claude as roughly 10,000 characters of head and tail.
How commands are matched against rules
Bash rules match the command text after Claude Code splits compound commands on &&, ||, ;, |, |&, & and newlines, and strips wrappers (timeout, time, nice, nohup, stdbuf, command, builtin, noglob, bare xargs). "A rule must match each subcommand independently", while deny and ask rules apply when any subcommand matches, even inside a subshell or a for loop. The read-only commands (ls, cat, echo, pwd, head, tail, grep, find, wc, which, diff, stat, du, cd, read-only git) never prompt, with exceptions such as cd into another directory combined with git, which can run that directory's hooks. "Never prompt" includes paths outside the working directories: only a Read deny rule or permissions.blockReadsOutsideWorkingDirectories stops cat ~/.aws/credentials from running unasked. Commands over 10,000 characters always prompt.
Type a command and edit the rules. The matcher splits on the documented separators, strips the documented wrappers, and checks each part against deny, ask, allow and the read-only set. It's a simplified model: real parsing also handles quoting edge cases, subshells, redirect targets and more exceptions. The tree shows the split: separators branch, and the pruned twigs are wrappers and variables stripped before matching.
A Bash deny rule isn't a boundary"A deny or ask rule covers the invocation Claude usually produces and isn't a security boundary around the program." Bash(rm *) stops rm -rf build/ but not /bin/rm -rf build/ or bash -c 'rm -rf build/'; Bash(git push *) doesn't stop git -C . push origin main. For enforcement that doesn't depend on command text, use the sandbox; to inspect the full text with your own logic, use a PreToolUse hook.
Two more details matter for verification. /rewind undoes a Bash change such as sed -i only in a file Claude already edited with its file tools; a file that only Bash commands changed, such as a generator's fresh output, isn't tracked and stays as it is (Checkpointing), so revert it with git. Also, on v2.1.269+ a PostToolUse hook can read tool_response.bashEditDiff (public beta, up to 200 files) to see what a command changed in a Git repository. By default Claude Code records it only in auto and bypassPermissions modes, when it directs Claude to edit through Bash; the bashEditDiffEnabled setting records it in every mode, so set it if you want the diff in Manual sessions. And on Linux and WSL, CLAUDE_CODE_TOOL_MEMORY_LIMIT=4G (v2.1.233+) caps the memory all of a session's commands can use together.
File Tools
What it is.Read, Edit, Write and NotebookEdit, plus Glob and Grep where they're enabled. They don't run in a shell, so the sandbox doesn't apply to them; Read(...) and Edit(...) permission rules do (Tools reference).
Read
Takes an absolute path and returns numbered lines. One call returns at most 25,000 tokens (CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS) and refuses a whole file over 256 KB. Over the token limit, Claude gets the first page with a PARTIAL view notice and pages on with offset and limit; on v2.1.296+ it can set allow_large: true to read a big file in one call, sized against the room left in the window.
Images come back as visual content, downscaled when large. PDFs over 10 pages are read in ranges with pages, up to 20 at a time, which needs pdftoppm from poppler. Notebooks return cells with outputs. Binary formats such as .xlsx or .zip are refused with a suggestion. Directories can't be read; Claude uses ls.
Edit and Write
Edit "performs exact string replacement. It takes an old_string and a new_string ... It doesn't use regex or fuzzy matching." Before it applies: a Read deny rule on the path refuses it; the file must have been read in this conversation (always on Opus 4.6, Haiku 4.5 and older models; newer models can skip the read when it wouldn't need a prompt); old_string must match exactly, whitespace included; and it must match exactly once, or Claude passes more context or replace_all: true. Viewing a single file with cat, head, tail, sed -n 'X,Yp', grep or rg (no pipes or redirects) counts as a read. Files that aren't valid UTF-8 are refused, because saving them would corrupt bytes. Write "creates a new file or overwrites an existing one with the full content provided. It doesn't append or merge."
Try an old_string that's ambiguous, one with a whitespace difference, and one that's unique. The checks follow the documented order; messages are paraphrased, not Claude Code's exact error text. Every occurrence is marked in the file itself, and a dashed mark is a near miss.
Glob and Grep
Where enabled (Windows by default; elsewhere when named in --tools or --allowedTools, when Bash is removed, or for a subagent that lists them without Bash), Glob returns at most 100 files sorted by modification time and doesn't respect .gitignore by default. Grep uses ripgrep syntax (so interface\{\}), respects .gitignore, and has three output modes: files_with_matches (the default), content and count.
Only Read(...) and Edit(...) path rules are consulted; a Write(docs/**) rule is accepted and never used, with a startup warning. A Read deny also blocks Edit and Write on that path, but not NotebookEdit. Paths use gitignore syntax: // is the filesystem root, ~/ your home, a single leading / is relative to the settings file's anchor, and a bare or ./ path is relative to the current directory. A .claudeignore file "has no effect, so move its entries into Read deny rules". Before every file-tool edit, Claude Code snapshots the file so /rewind can restore it.
Web Tools
What it is.WebFetch reads a URL; WebSearch finds URLs. Both bring untrusted text into the context, so their permission and safety rules matter as much as their output.
WebFetch is a pipeline, not a download
The page is converted to Markdown and, for most fetches, run through a separate model call with the extraction prompt, so Claude receives an answer about the page rather than the page itself. Each call reads up to 100,000 characters; on v2.1.290+ the result says how much went unread, and Claude can read on with offset. Sizes in the drawing are illustrative; hover a stage.
"WebFetch takes a URL and a prompt describing what to extract. It fetches the page and converts the response to Markdown when the server returns HTML. For most fetches, it then runs the prompt against the content in a separate model call, and Claude receives the result of that call rather than the raw page ... This makes WebFetch lossy by design" (WebFetch tool behavior). A result saying a page doesn't mention something "may only mean the prompt didn't ask about it". Other behaviors: localhost and dotless hostnames are refused (use curl through Bash for local servers); HTTP is upgraded to HTTPS; up to 100,000 characters are read per call (v2.1.290+ reports how much went unread); responses are cached for 15 minutes; a redirect to another host is reported, not followed; a five-minute deadline applies.
Permissions
In Manual and acceptEdits, WebFetch prompts except for domains your rules cover and "a built-in set of preapproved documentation domains". "Yes, and don't ask again" saves WebFetch(domain:...) to .claude/settings.local.json. The auto and bypassPermissions modes skip the prompt unless an explicit ask rule matches. Every fetch first passes a domain safety check that calls api.anthropic.com (skipWebFetchPreflight turns it off). Sandboxed shell commands don't inherit the preapproved domains, and WebFetch doesn't read the sandbox allowlist in return. CLAUDE_CODE_DISABLE_WEB_FETCH=1 (v2.1.285+) removes the tool.
WebSearch
WebSearch "returns result titles and URLs. It doesn't fetch the result pages." One call may run up to eight backend searches; Claude can scope with allowed_domains or blocked_domains (not both). Its permission rule takes no specifier: bare WebSearch in allow or deny. It's available on the Claude API, Claude Platform on AWS and Foundry, on Agent Platform with Opus 4, Sonnet 4, Haiku 4.5 and later, and not on Amazon Bedrock. An interactive session has a 200-call limit shared with subagents (CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION), refilling at about 100 an hour on v2.1.290+.
Untrusted input with tools attachedA fetched page can contain instructions. The danger peaks when one session combines private data, untrusted content and a way to send data out, the "lethal trifecta" (agents-5 Guardrails). In Claude Code the out-channel is usually Bash, not WebFetch: denying WebFetch doesn't stop curl. Combine Bash(curl *) and Bash(wget *) denies, WebFetch(domain:...) allow rules for the domains you need, and the sandbox's network allowlist, which holds regardless of command text.
Sandboxing
What it is. "The Bash sandbox is a boundary that the operating system enforces around the shell commands Claude runs on your machine" (Sandboxing). It uses Seatbelt on macOS and bubblewrap plus socat on Linux and WSL2; "on native Windows, Claude Code runs commands unsandboxed". It's built on the open-source @anthropic-ai/sandbox-runtime. Two facts frame everything else: "The sandbox is off by default", and "The sandbox covers shell commands only. Claude's file tools, MCP servers, and hooks run outside it." It covers Bash, PowerShell and Monitor commands and every process they start.
Access
Default inside the sandbox
Change it with
Writes
The working directory, a per-user temp directory and added directories; protected paths stay write-denied
Paths and domains from sandbox settings and permission rules "are merged into the final sandbox configuration", so a Read(~/.ssh/**) deny also becomes an OS-level read block for shell commands.
Modes, the retry hatch and strict mode
Auto-allow (autoAllowBashIfSandboxed, default true) runs sandboxed commands without a prompt, even under a bare Bash ask rule, though Bash deny rules, content-scoped ask rules such as Bash(git push *) and critical-path rm still apply. It's separate from auto mode, and plan mode doesn't use it. Some sandboxed commands still go through the regular flow, such as FOO=bar npm test, make CC=clang and eval "ls", where a variable or argument can change which program runs; Monitor commands aren't auto-approved either. Regular permissions mode keeps every prompt.
When a command fails inside the sandbox, Claude may retry it unsandboxed with dangerouslyDisableSandbox. That retry prompts in Manual and acceptEdits, goes to the classifier in auto, is denied in dontAsk and runs freely in bypass. A matching allow rule also approves the retry.
New hosts. A sandboxed command that connects to a host outside the allowlist waits for a decision: a prompt in Manual and acceptEdits, a refusal in dontAsk, a refusal in auto unless the command named the host for the classifier to review (v2.1.271+), and allowed without a prompt in bypass (and in plan mode with bypass available). A host in deniedDomains is refused in every mode. Choosing "Yes, and don't ask again" saves a WebFetch(domain:...) rule. sandbox.network.strictAllowlist: true (v2.1.219+; user, managed or --settings only) refuses every host outside the list in every mode.
Strict mode: "allowUnsandboxedCommands": false makes Claude Code ignore the parameter. Add "failIfUnavailable": true so a missing dependency stops the session instead of silently running unsandboxed (the default).
Sandbox paths use ordinary conventions (/tmp/build is absolute, ~/.kube is home-relative), unlike permission rules' // form. Prove the boundary with the docs' probes, asked of Claude rather than typed at !, which runs outside the sandbox in most sessions: touch ~/sandbox-probe should fail with Operation not permitted (macOS) or Read-only file system (Linux, WSL2), and curl --noproxy '*' https://example.com should fail with Could not resolve host.
Pick an action and a configuration. The widget says whether the sandbox applies, which layer decides, and what happens. Outcomes follow the sandboxing and permissions docs; prompts and classifier reviews are shown as such, not resolved. The dot shows which layers cover the action, and the tinted region is the one that decides. The case only the sandbox covers: python3 dump.py opens the key itself, so Read deny rules never see the path, while the sandbox's read denials apply to every process the command starts.
Where the boundary leaks, and what a real boundary looks like
The docs are candid: the sandbox "reduces risk but is not a complete isolation boundary". The known gaps:
Everything outside the shell. Read, Edit, Write, WebFetch and WebSearch follow permission rules only ("A denyRead entry doesn't stop the Read tool, and allowedDomains doesn't limit WebFetch"). Hooks, local MCP servers, plugin monitors, LSP servers, the status line command and apiKeyHelper run "with your full access".
Escape hatches you enable.excludedCommands run unsandboxed; the unsandboxed retry is on unless strict mode is; commands typed at ! usually run outside.
The network proxy. It doesn't inspect TLS, so "code running inside the sandbox can potentially use domain fronting", and every allowed domain is a capability: Anthropic's containment team found exfiltration through an allowlisted api.anthropic.com and concluded an allowlist "may be better conceptualized as a capability grant" (How we contain Claude).
Reads by default. Without denyRead, a sandboxed command can read your SSH keys and cloud credentials; the protection comes from the network boundary keeping them from leaving.
For unattended or high-autonomy runs, put the whole Claude Code process behind one boundary: a container, VM or the sandbox runtime, with credentials injected by a proxy so "the agent never sees the actual credentials", no mounted ~/.ssh or ~/.aws, and a non-root user. That's the only setting where --dangerously-skip-permissions belongs: "Isolated containers and VMs only", because bypass mode "offers no protection against prompt injection or unintended actions". The 2025 sandboxing post reported that sandboxing "safely reduces permission prompts by 84%" (Beyond permission prompts), which is the practical case for turning it on. Agents 5 builds the full guardrail stack on top.
Exercise: layer permissions and the sandbox, then prove it
In a throwaway repository, write a .claude/settings.local.json that (a) denies reads of .env and ~/.ssh, (b) asks before git push, (c) enables the sandbox in strict mode with registry.npmjs.org allowed. Then ask Claude to: read .env with the Read tool; cat ~/.ssh/known_hosts; run a Python one-liner that opens ~/.ssh/known_hosts; curl https://example.com; touch ~/sandbox-probe. Predict each outcome before you run it.
Expected: the Read of .env is denied by the permission rule (the sandbox isn't involved). cat ~/.ssh/known_hosts is denied twice over: cat is a file command Read deny rules cover, and the merged rule is an OS read block. The Python one-liner isn't covered by the permission rule (it opens the file itself), but the sandbox blocks the read because the deny rule was merged into its configuration; without the sandbox it would succeed. curl reaches the sandbox proxy, which holds the connection because example.com isn't allowed: in Manual mode you get a domain prompt, and if you decline it fails. Because strict mode is on, Claude can't retry it unsandboxed. To refuse new hosts without a prompt, set "sandbox": {"network": {"strictAllowlist": true}} in your user settings or --settings; a repository's settings can't set it. touch ~/sandbox-probe fails with Operation not permitted or Read-only file system. If anything succeeds unexpectedly, run /sandbox and check the Config tab and dependencies.
Key takeaways
Availability (--tools, bare-name denies) and approval (rules, mode, hooks, prompt) are separate; --allowedTools only pre-approves.
The order is hooks, deny, ask, safety checks, mode, allow, no-approval actions, then prompt, classifier or denial. Deny wins over allow rules, modes and hook approvals; only an installed mod can override it, and only on setups without managed settings or a Team or Enterprise login.
Bash rules match each subcommand after splitting and wrapper-stripping; a Bash deny rule matches text, so it isn't a security boundary.
Edit is exact, unique string replacement after a read; Read pages large files; WebFetch returns a model's extraction, not the page.
The sandbox is off by default, covers shell commands only, and reads most of the machine unless you deny paths. Strict mode plus failIfUnavailable closes its escape hatches; containers are the boundary for bypass mode.
Session wrap-up
You now have the loop at implementation depth. A run is a sequence of requests, each re-sending a cached prefix plus a new tail; each response can request tools; each tool call passes hooks, rules, safety checks and the mode before it runs; and the result event tells you exactly why it all stopped. Instructions land in two places: the recorded system prompt (plus anything appended) and the conversation (CLAUDE.md, output styles, reminders, hook context). That placement decides how strongly they weigh, when edits apply, and whether changing them costs a cache rebuild. Compaction keeps what was loaded from disk and loses what was only said, and the sandbox is an OS boundary around shell commands, nothing more and nothing less.
Agents 5: Reliability turns permission rules, the sandbox and hooks into a guardrail stack, and transcripts into evals and observability.
Labs index
Rebuild the loop from stream-json and classify how each run ended. cd labs && python3 agents-1/loop_trace.py; add --transcript run.jsonl for your own run, or --real --max-turns 2 --max-budget-usd 0.05 --model haiku for a capped, read-only real run.
Replay scripted sessions and see every cache read, write and miss reason under both TTL regimes. cd labs && python3 agents-1/cache_sim.py; try --scenario coffee-break --billing api.
Wrap one of your own headless jobs with the stop_reason → terminal_reason → subtype branching from Stop Conditions, and log num_turns, cost and the reason on every run.
Add a status line that shows cache_read_input_tokens against cache_creation_input_tokens, and watch it for a day. Note every miss and its cause.
Move every "never" and "always" in your CLAUDE.md into a deny rule, an ask rule or a hook, and add a Compact Instructions section.
Turn on the sandbox in strict mode for one project, deny credential paths, and run the two probes. Then continue to Agents 2 to drive this loop from code.