Reference

Claude Code Architecture Cheatsheet

114 commands, flags, settings keys and decision rules for running Claude Code on a team, grouped into six areas. Each row restates one of our architecture guides and links to the section that says it, plus the Claude Code documentation page that guide cites where it cites one. Check the linked docs before you change a production setting, since flags and defaults change between versions.

Published . Updated .

Context and compaction

What fills the context window, how to read it, and what survives when it is compacted, cleared or resumed.

Command, flag or ruleWhat it doesSource
/contextA colored grid of current context usage, with optimization suggestions for context-heavy tools, memory bloat and capacity warnings.Context engineering: How do you read /context, and what should you measure?
Claude Code docs: commands
/context allExpands the per-item breakdown. Its Memory files list confirms which CLAUDE.md files actually loaded at launch.Context engineering: How do you read /context, and what should you measure?
Claude Code docs: memory
Reading the /context rowsIf Messages is the largest row, a file or tool output is filling the window: use chunked reads, a focused compact or a subagent. If the startup rows together outweigh Messages, fix your instruction files and tool configuration.Context engineering: How do you read /context, and what should you measure?
Claude Code docs: troubleshooting
Default window and auto-compact pointClaude Opus 5.5, Sonnet 5.5 and Haiku 5.5 run with a 1M-token window by default and auto-compact at about 967K tokens.Context engineering: How much context window does Claude Code have?
Claude Code docs: model-config#default-auto-compact-thresholds
CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000Set this behind an LLM gateway that rejects requests above 200K. Claude Code gives each model it recognizes its Anthropic API window and cannot detect a lower limit the gateway enforces.Context engineering: How much context window does Claude Code have?
Claude Code docs: model-config#default-auto-compact-thresholds
CLAUDE_CODE_DISABLE_1M_CONTEXT=1Holds every session to a 200K window.Context engineering: How much context window does Claude Code have?
Claude Code docs: model-config#extended-context
/autocompactautoCompactWindow--autocompactSet the auto-compact window per model, for every model, or for one launch. The CLAUDE_CODE_AUTO_COMPACT_WINDOW environment variable takes precedence over all three. Minimum 100K, capped at the model window.Context engineering: When should you compact, clear or rewind?
Claude Code docs: model-config
/compactReplaces the conversation with a structured summary, and a focus such as /compact focus on the auth bug fix keeps what you name. Compact at a natural break between tasks: with a warm cache the summary request is cheap, and after the cache lifetime it reprocesses the history as uncached input.Context engineering: When should you compact, clear or rewind?
Claude Code docs: prompt-caching#compacting-the-conversation
/clearFor unrelated work. Costs nothing, keeps the old session resumable and resets the /usage session totals.Context engineering: When should you compact, clear or rewind?
Claude Code docs: prompt-caching#compacting-the-conversation
/rewindRestore conversation abandons a failed approach and reads the earlier cache entry instead of building a new one. Summarize up to here condenses a stale middle section and keeps later messages intact.Context engineering: When should you compact, clear or rewind?
Claude Code docs: checkpointing
/branch--fork-sessionCopies the history under a new session ID so you can try an alternative without losing the original. The copy starts with the full history and its size.Context engineering: When should you compact, clear or rewind?
Claude Code docs: sessions
idleCompaction: falseCLAUDE_CODE_IDLE_COMPACT_MIN_TOKENSIdle compaction is on by default for interactive sessions on the one-hour cache TTL: a conversation of 200,000 tokens that sits idle for about an hour is compacted. Turn it off with the key (v2.1.290 or later); the threshold variable cannot go below 100,000.Context engineering: When should you compact, clear or rewind?
Claude Code docs: settings-reference#idlecompaction
PreCompactPostCompactPreCompact hook stdout becomes instructions for the summary, capped at 10,000 characters per hook, and exit code 2 blocks compaction. A PostCompact hook receives the summary as compact_summary.Context engineering: When should you compact, clear or rewind?
Claude Code docs: hooks#precompact
What survives compactionRoot CLAUDE.md, unscoped rules and the auto memory index are re-injected from disk. Nested CLAUDE.md files and path-scoped rules are summarized with the conversation, and path-scoped rules reload only when a matching file is touched again.Context engineering: What fills the context window over a long session?
Claude Code docs: context-window#what-survives-compaction
Large files and skills after compactionA re-read file over 5,000 tokens comes back only as a path reference. Invoked skill bodies are re-injected but capped at 5,000 tokens per skill and 25,000 tokens in total, oldest dropped first.Context engineering: What fills the context window over a long session?
Claude Code docs: context-window#what-survives-compaction
SessionStartPin invariants in the project-root CLAUDE.md or an unscoped rule, and add a SessionStart hook with the compact matcher that prints them and the tail of the progress file.Context engineering: How should a task cross a context boundary?
Claude Code docs: hooks-guide#re-inject-context-after-compaction
claude --resumeReopens a saved session. A compacted session continues from the last summary, and flags such as --mcp-config, --add-dir, --settings and tool restrictions must be passed again.Context engineering: How should a task cross a context boundary?
Claude Code docs: sessions
autoMemoryEnabled: falseCLAUDE_CODE_DISABLE_AUTO_MEMORY=1Turn auto memory off per project or per environment. Only the first 200 lines or 25KB of MEMORY.md load at startup, and auto memory is machine-local, so promote anything the team needs into a committed CLAUDE.md or rules file.Context engineering: Does Claude Code have project context across sessions?
Claude Code docs: memory#auto-memory
/memoryReview auto memory files the way you would review any other configuration: they stay until someone edits or deletes them.Context engineering: Does Claude Code have project context across sessions?
Claude Code docs: memory#auto-memory
CLAUDE.md sizeTarget under 200 lines per file; files over 4 MiB are skipped.CLAUDE.md vs AGENTS.md: What does CLAUDE.md control that AGENTS.md does not?
Claude Code docs: memory
@AGENTS.mdMake AGENTS.md canonical and start CLAUDE.md with this import, followed by Claude-only guidance. Claude reads the import first and never reads AGENTS.md twice.CLAUDE.md vs AGENTS.md: How do teams sync rules across Claude Code, Codex and Cursor without duplication?
Claude Code docs: memory
.claude/rules/Conventions for one package or file type belong in a nested CLAUDE.md or in .claude/rules/ with paths, where they cost context only after Claude touches a matching file. Procedures belong in a skill.CLAUDE.md vs AGENTS.md: What belongs in always-loaded files versus on-demand skills?
Claude Code docs: memory
claudeMdExcludesSet it in .claude/settings.local.json for packages you never touch. The large codebase guide pairs it with a short root file plus one file per package.CLAUDE.md vs AGENTS.md: How much context budget do nested instruction files consume per subagent?
Claude Code docs: large-codebases

Permissions and settings precedence

Which settings file wins, how permission rules evaluate, and the keys only managed settings can enforce.

Command, flag or ruleWhat it doesSource
Settings precedenceManaged settings, then --settings, then .claude/settings.local.json, then .claude/settings.json, then ~/.claude/settings.json. The highest level that sets a key wins.Enterprise security: Which Claude Code settings file wins when two scopes disagree?
Claude Code docs: settings#settings-precedence
Lists mergepermissions.allow, permissions.deny and similar arrays combine across every file that sets them, so a lower scope can add entries without removing anyone else's.Enterprise security: Which Claude Code settings file wins when two scopes disagree?
Claude Code docs: settings#settings-precedence
ANTHROPIC_MODELEnvironment variables are not a level in the stack. Each variable and its paired key resolve pair by pair, so ANTHROPIC_MODEL exported in a shell beats the model key from any file.Enterprise security: Which Claude Code settings file wins when two scopes disagree?
Claude Code docs: settings#settings-precedence
permissions.blockReadsOutsideWorkingDirectoriesdisableClaudeAiConnectorsmaxEffortLevelSet to true, the first two win even over a managed value, and so does a lower maxEffortLevel. A developer can tighten these keys but never loosen them.Enterprise security: Which Claude Code settings file wins when two scopes disagree?
Claude Code docs: settings#settings-precedence
permissions.defaultModeThe values auto and bypassPermissions do not take effect from project or local settings (before v2.1.257, bypassPermissions did).Enterprise security: Which Claude Code settings file wins when two scopes disagree?
Claude Code docs: settings#settings-precedence
managedSourcesBehaviorThe default, "first-wins", applies only the highest-ranked managed source that delivers any policy key and skips the rest without a warning. "merge" (v2.1.242 or later) composes every admin source, with lists unioned and locks taking the strictest value.Enterprise security: Precedence inside the managed tier
Claude Code docs: managed-settings
/statusclaude doctorThe Setting sources line in /status names the managed source that applied, such as (remote), (plist) or (file). claude doctor lists the entries Claude Code rejected.Enterprise security: Precedence inside the managed tier
Claude Code docs: managed-settings
Rule evaluation orderDeny, then ask, then allow, and the first match decides. Specificity does not reorder them: a broad deny such as Bash(aws *) blocks aws s3 ls even when a narrower allow rule names it.Enterprise security: How do allow, ask and deny permission rules evaluate?
Claude Code docs: permissions
Bare versus scoped denyA bare tool name in a deny rule removes the tool from Claude's context entirely. A scoped deny leaves the tool available and blocks only matching calls.Enterprise security: How do allow, ask and deny permission rules evaluate?
Claude Code docs: permissions
--allowedTools--disallowedToolsA managed deny cannot be overridden by --allowedTools, while --disallowedTools can add restrictions on top of managed policy. Hook decisions do not bypass deny or ask rules either.Enterprise security: How do allow, ask and deny permission rules evaluate?
Claude Code docs: permissions
Bash(ls *)The space before * is part of the rule: it matches ls -la and bare ls, but not lsof.Enterprise security: Rule patterns that do not mean what they look like
Claude Code docs: permissions
Bash(curl *)Matches the command text Claude usually writes, not /usr/bin/curl or a sh -c wrapper. When a limit must hold, use the sandbox for filesystem and network access or a PreToolUse hook to inspect the full command.Enterprise security: Rule patterns that do not mean what they look like
Claude Code docs: permissions
Read(/secrets/**)In user settings a single leading slash anchors at the settings source and matches ~/.claude/secrets/**. Use // for absolute paths or ~/ for home.Enterprise security: Rule patterns that do not mean what they look like
Claude Code docs: permissions
Workspace trustProject permissions.allow rules apply only after a developer accepts the workspace trust dialog; deny and ask rules apply at once. claude -p and the Agent SDK never show the dialog.Enterprise security: Workspace trust, and what a repository can run without it
Claude Code docs: permissions#what-runs-before-you-trust-a-folder
defaultacceptEditsplanautodontAskbypassPermissionsSix modes set the baseline for calls no rule decides. Deny rules apply in every mode, including bypassPermissions, and permissions.allow entries do not pre-approve writes to protected paths such as .git and .claude.Enterprise security: Which permission mode belongs in which environment?
Claude Code docs: permission-modes
permissions.disableBypassPermissionsModedisableAutoModeBoth mode locks take the string "disable". They work from any scope but belong in managed settings, where nobody below can override them.Enterprise security: Which permission mode belongs in which environment?
Claude Code docs: permission-modes
allowManagedPermissionRulesOnlyManaged settings become the only source of permission rules: rules in user, project, local and --settings files are ignored, and so is --allowedTools. --disallowedTools and session deny rules still apply.Enterprise security: What can only managed settings enforce?
Claude Code docs: managed-settings
allowManagedMcpServersOnlyallowedMcpServersOnly the managed MCP allowlist is respected. Match entries by serverUrl or serverCommand, because a serverName entry is not a security control; deniedMcpServers merges from every scope.MCP vs CLI ADR: Who should own the MCP allowlist?
Claude Code docs: managed-mcp
failIfUnavailableallowUnsandboxedCommands: falseOff by default, the sandbox covers Bash, PowerShell and Monitor commands, not Claude's own file tools, hooks or local MCP servers. failIfUnavailable refuses to start without it, and allowUnsandboxedCommands: false removes the retry outside the sandbox.Enterprise security: Where does the sandbox sit relative to permission rules?
Claude Code docs: sandboxing
requiredMinimumVersionPins a minimum Claude Code version through managed settings. It fails open by design: an invalid value is dropped.Enterprise security: How managed policy fails
Claude Code docs: managed-settings
permissions.denyCLAUDE.md is context, not enforced configuration. Anything that must happen every time belongs in a hook or a permissions.deny rule.CLAUDE.md vs AGENTS.md: What belongs in always-loaded files versus on-demand skills?

Headless and CI

Flags for unattended claude -p runs and the gates a pull request review job needs.

Command, flag or ruleWhat it doesSource
claude -pRuns non-interactively and exits 0 on success or non-zero on failure. An invalid flag is reported on stderr before the run starts; a failure inside the run is printed as the result on stdout.Autonomous coding loops: How do headless claude -p runs behave inside a loop?
Claude Code docs: headless
Default mode for -pFrom v2.1.302, claude -p and Agent SDK runs with no mode set start in Manual (default), where any call that needs approval is denied unless a rule, hook or prompt tool approves it.Enterprise security: Which permission mode belongs in which environment?
Claude Code docs: permission-modes
--output-formattext by default, json for the result, session ID and metadata, or stream-json with --verbose. The JSON includes total_cost_usd, a client-side estimate that can differ from your bill.Autonomous coding loops: How do headless claude -p runs behave inside a loop?
Claude Code docs: headless
--json-schemaReturns schema-conforming data in structured_output. A run that ends without valid structured output has no such field, so check for it.Autonomous coding loops: How do headless claude -p runs behave inside a loop?
Claude Code docs: headless
--max-turns--max-budget-usdCap agentic turns and estimated spend for one run. Both are print-mode only and have no default limit.Autonomous coding loops: How do headless claude -p runs behave inside a loop?
Claude Code docs: cli-reference
--allowedToolsPre-approves tools or commands in permission rule syntax, such as Bash(git commit *). Mind the space: Bash(git diff*) would also match git diff-index.Autonomous coding loops: Permissions in an unattended run
Claude Code docs: cli-reference
--permission-mode dontAskDenies anything that would prompt; the docs describe it as useful for locked-down CI.Autonomous coding loops: Permissions in an unattended run
Claude Code docs: permission-modes
--permission-prompts nonepermissions.denyInsteadOfPromptingTurn any call that would wait on a prompt into a denial instead of a stalled job: the flag for one run (v2.1.259 or later), the key in user or managed settings.Enterprise security: Which permission mode belongs in which environment?
Claude Code docs: permission-modes
--bareSkips auto-discovery of hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md. It needs ANTHROPIC_API_KEY or an apiKeyHelper passed in --settings, and hooks do not run even when passed through --settings, so do not use it when containment depends on hooks.Autonomous coding loops: Bare mode versus hook-gated containment
Claude Code docs: headless
--setting-sources userReads neither the project's settings files nor its .mcp.json. Without it, a -p run in a folder nobody trusted still runs the repository's hooks and connects its .mcp.json servers without asking.Enterprise security: Workspace trust, and what a repository can run without it
Claude Code docs: permissions#what-runs-before-you-trust-a-folder
disableAllHooksPass --settings '{"disableAllHooks": true}' for the run. Setting it only in user settings is not enough, because project settings outrank user settings and can set it back.Enterprise security: Workspace trust, and what a repository can run without it
Claude Code docs: permissions#what-runs-before-you-trust-a-folder
--restrictedFrom v2.1.248, removes the built-in tools that run commands or code, and WebFetch, unless you name them in --tools. It confines the file tools to the working directories, loads only managed settings and --settings, and refuses bypassPermissions.Enterprise security: A reference job for any CI system
Claude Code docs: headless
anthropics/claude-code-action@v1claude_argsRuns Claude Code on your own runners and defaults to auto mode. Pass --permission-mode default and --max-turns in claude_args so the allowlist acts as a strict list and iterations are bounded.Enterprise security: A reference workflow with the GitHub Action
Claude Code docs: github-actions
CI billing and authenticationPlan for CI runs to bill as usage, with their own key, budget and alert. The GitHub Action accepts an API key, a subscription OAuth token or workload identity federation, and recommends an API key for secrets shared across repositories.Claude Code vs Codex vs Cursor: How Should Headless CI Runs Be Billed and Contained?
Claude Code docs: github-actions
CLAUDE_CODE_OAUTH_TOKENclaude setup-tokenServer-managed policy does not reach a CI job that authenticates with a Console API key. Use an OAuth token from claude setup-token set as CLAUDE_CODE_OAUTH_TOKEN, or bake a managed settings file into the runner image; --bare jobs need the file.Enterprise security: The CI credential gap
pull_request_targetworkflow_runBoth run with the base repository's secrets, so never check out an untrusted ref into the workspace root before the Action runs. Check out the base ref and pass the head into a subdirectory with --add-dir.Enterprise security: Untrusted pull requests
Review pipeline gatesActor and fork checks, base-branch configuration, a read-only tool set, turn and budget caps, a findings gate on structured output, and branch protection for the human merge.Enterprise security: What should a security architect standardize first?
--continue--resume--continue resumes the most recent conversation and --resume with a session ID resumes a specific one. A new claude -p call with neither starts from a fresh context.Autonomous coding loops: Fresh context or continued context

Plan mode and loops

Planning checkpoints, worktree isolation, and the stop conditions an autonomous loop needs.

Command, flag or ruleWhat it doesSource
/planclaude --permission-mode planPress Shift+Tab until the status bar reads plan mode on, prefix one prompt with /plan, or start with claude --permission-mode plan. Claude reads files and explores, then writes a plan without editing your source.Autonomous coding loops: What does Claude Code plan mode permit, and how do you approve a plan?
Claude Code docs: common-workflows
defaultModeclaudeCode.initialPermissionModeSet defaultMode to plan in .claude/settings.json to make plan mode the default for a project's terminal sessions. The VS Code extension ignores this and reads claudeCode.initialPermissionMode from user settings.Autonomous coding loops: What does Claude Code plan mode permit, and how do you approve a plan?
Claude Code docs: common-workflows
Approving a planChoose Yes, and use auto mode; Yes, manually approve edits; or No, keep planning. Ctrl+G opens the plan in your editor. At the approval prompt Shift+Tab approves the plan, so press Esc first if you only meant to leave plan mode.Autonomous coding loops: What does Claude Code plan mode permit, and how do you approve a plan?
Claude Code docs: permission-modes
Plan mode is not an edit barrierDo not rely on plan mode's blocks in interactive terminal sessions with bypass permissions available: an edit or shell command attempted during planning can run without a prompt.Autonomous coding loops: Plan mode as a governance checkpoint
Claude Code docs: permission-modes
permissionModeWhile the main conversation is in plan mode, a subagent stays in plan mode whatever permissionMode its definition sets. Agent team teammates are the exception.Autonomous coding loops: Plan mode as a governance checkpoint
Claude Code docs: sub-agents
claude --worktree-wclaude --worktree feature-auth creates .claude/worktrees/feature-auth/ on a new branch named worktree-feature-auth. The repository needs at least one commit, and -p runs skip the trust check.Autonomous coding loops: How do Claude Code worktrees isolate parallel sessions and subagents?
Claude Code docs: worktrees
worktree.baseRef.worktreeincludeWorktrees branch from the remote default branch unless worktree.baseRef is head. Gitignored files such as .env are absent unless a .worktreeinclude pattern copies them. Add .claude/worktrees/ to .gitignore.Autonomous coding loops: How do Claude Code worktrees isolate parallel sessions and subagents?
Claude Code docs: worktrees
Worktree isolation gapThe checks block edits, working directories and git redirects aimed at the main checkout, but not cp or a shell redirect into it. That falls to your permission rules and the Bash sandbox, which is off by default.Autonomous coding loops: What the isolation checks enforce, and what they miss
Claude Code docs: sandboxing
git worktree removegit worktree unlock-p runs get no exit prompt, so Claude Code leaves their worktrees and locks in place. Remove them with git worktree remove, running git worktree unlock first if git refuses.Autonomous coding loops: Worktree subagents and cleanup
Claude Code docs: worktrees
isolation: worktreeGives each invocation of a custom subagent a temporary worktree, removed automatically when the subagent finishes without changes.Autonomous coding loops: Worktree subagents and cleanup
Claude Code docs: worktrees
"onFailure": "block"From v2.1.295, makes a failed PreToolUse guard hook block the tool call. It has no effect on Stop hooks, so a Stop-hook gate that cannot run lets the turn end: test the failure path of every gate.Autonomous coding loops: Which execution pattern fits an autonomous Claude Code task?
Claude Code docs: hooks
CLAUDE_CODE_STOP_HOOK_BLOCK_CAPClaude Code caps Stop hooks at eight consecutive continuations, and the count resets every time Claude calls a tool. This variable raises the cap; 0 disables it and removes the last built-in backstop.Autonomous coding loops: Bash loop versus Stop-hook loop
Claude Code docs: env-vars
/ralph-loop--max-iterations/cancel-ralphThe official ralph-loop plugin feeds the same prompt back inside one session through a Stop hook. Iterations are unlimited by default and the README calls --max-iterations the primary safety mechanism; /cancel-ralph deletes the state file.Autonomous coding loops: The official ralph-loop plugin
Loop exit criteriaKeep both kinds of stop outside the model: verified success, an explicit blocked state, a script iteration cap, --max-turns and --max-budget-usd on every run, stall detection and an aggregate spend limit.Autonomous coding loops: What exit criteria and circuit breakers should end an autonomous loop?
--no-session-persistenceStops sessions from being saved or resumed. Avoid it in loops you may need to audit, and log each iteration's session ID instead.Autonomous coding loops: What exit criteria and circuit breakers should end an autonomous loop?
Budget cap overshootThe cap is checked after each model response arrives: the response that crosses it still completes and running subagents keep spending, so each iteration can overshoot by one response plus in-flight subagent spend.Autonomous coding loops: Worked example: the spend ceiling of a capped loop
Claude Code docs: agent-sdk/agent-loop
--dangerously-skip-permissionsUse it only when a container or VM is itself the boundary. Under bypassPermissions, allow rules have no effect and only deny rules and the outer boundary remain.Autonomous coding loops: How do you contain the blast radius of an unattended loop?
Claude Code docs: permission-modes

Cost controls

Where spend is visible, which settings cap or report it, and what breaks the prompt cache.

Command, flag or ruleWhat it doesSource
/usageOn paid plans it attributes recent usage to skills, subagents, plugins and MCP servers and recommends a change for any behaviour behind 10 percent or more of recent usage. Its figures come from local session history on one machine.Pricing architecture: Which Usage Patterns Break a Claude Code Budget?
Claude Code docs: costs
/statusAn ANTHROPIC_API_KEY on the machine makes Claude Code bill that key instead of the subscription once approved, and -p runs always use it when present. /status shows which credential is active.Pricing architecture: The credential, not the intent, decides the bill
Claude Code docs: authentication
forceLoginMethodforceLoginOrgUUIDDeployed through device management, either one blocks sessions that authenticate with ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or apiKeyHelper at startup. Do not rely on forceLoginOrgUUID to restrict saved Console credentials.Pricing architecture: The credential, not the intent, decides the bill
Claude Code docs: authentication
promptCacheTtlAPI keys and cloud providers default to a 5-minute cache. Setting it to 1h (v2.1.242 or later) trades a 2x write rate for fewer full-context rewrites; test it in a pilot rather than as a blanket policy.Pricing architecture: What prompt caching does to the bill
Claude Code docs: prompt-caching
Prompt cache breakersSwitching models, the first session after a Claude Code upgrade, and adding or removing MCP tools while tools load upfront all invalidate the cache. Under deferred tool search, a server connecting or disconnecting mid-session does not.MCP vs CLI ADR: What breaks the prompt cache?
Claude Code docs: prompt-caching
ENABLE_TOOL_SEARCH=falseTurns deferred tool search off, so every MCP tool definition loads upfront. In the site's measurement, ten MCP servers took 29.8k startup tokens with tool search on and 407k with it off.MCP vs CLI ADR: What did I measure, and how?
Claude Code docs: mcp#configure-tool-search
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETASSetting this variable keeps tool search off, a HIPAA configuration turns it off, and Microsoft Foundry deployments hosted on Azure reject it, so MCP tools load upfront. Measure /context on the machines and routes your team uses.MCP vs CLI ADR: Why did deferred tool search change the MCP vs CLI math?
Claude Code docs: mcp#configure-tool-search
alwaysLoadanthropic/alwaysLoadWhoever configures a server can set alwaysLoad for all of its tools, and a server author can mark a tool anthropic/alwaysLoad. Either puts the full definitions in the always-paid startup line.MCP vs CLI ADR: Why did deferred tool search change the MCP vs CLI math?
Claude Code docs: mcp#scale-with-mcp-tool-search
Deny unused MCP serversA deny rule with a bare server name removes that server's tools from context. Denying three unused connectors in the project .claude/settings.json cut the measured startup prefix from 29.8k to 26.2k tokens.MCP vs CLI ADR: What did I measure, and how?
Claude Code docs: permissions
Instruction hygieneMoving rules from a 332-line CLAUDE.md into four .claude/rules files with paths: frontmatter cut the always-loaded file from 8.5k tokens to 613, more than twice what denying three connectors recovered.MCP vs CLI ADR: How do the six integration tiers rank by token cost?
Claude Code docs: memory
Haiku 5.5 long-context pricingA Haiku 5.5 request whose prompt exceeds 100,000 tokens, counting cache reads and writes, pays the higher rate row for the whole request. Other Claude 4.6 and later models bill the full 1M-token window at standard rates.Pricing architecture: How Much Does Claude Code Cost per Token?
Thinking and effortExtended thinking tokens bill as output, and Opus 5.5, Sonnet 5.5 and Haiku 5.5 always think, so the effort level is the lever.Pricing architecture: How Much Does Claude Code Cost per Token?
Claude Code docs: costs
Cache read discountA cache hit costs 5% of base input on Opus 5.5 and Sonnet 5.5 and 10% on Haiku 5.5. It discounts processing; it does not shrink the tokens occupying the context window.Model routing and caching: 2. Use current prices, including the context threshold
modelPricingA managed setting that makes /usage, the status line, --max-budget-usd and OpenTelemetry report at your contract's rates. It changes what Claude Code reports, not what Anthropic charges.Pricing architecture: Seven governance patterns that hold up
Claude Code docs: settings-reference#modelpricing
autoContinueAtUsageLimitA managed setting with which fleet owners decide whether Claude Code waits for a usage reset and continues automatically.Pricing architecture: How the five-hour and weekly windows behave
Claude Code docs: costs
enforced_spend_limit_reachedStart tier organizations are capped at $500 a month and Build at $1,000. At the cap, requests return HTTP 429 with enforced_spend_limit_reached and no retry-after header until the next month, so give CI its own workspace with a lower limit.Pricing architecture: The Console tier cap is a rollout failure mode
Routing escalationEscalate on a failed schema check, a missing source or an unresolved acceptance condition, not on the model's confidence statement. Limit retries and the number of concurrent investigators.Model routing and caching: 7. Build a small routing policy with explicit escalation

Subagents and topology

Fan-out limits, what each worker loads, and when to move from subagents to agent teams or the Agent SDK.

Command, flag or ruleWhat it doesSource
SubagentsEach runs in its own context window with its own system prompt, tool access and permissions, and returns only a summary. By default a subagent can spawn its own subagents, up to three layers deep.Subagents vs teams vs SDK: What are subagents, agent teams and the Claude Agent SDK?
Claude Code docs: sub-agents
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTHDefaults to 3; set it to 1 to stop nested spawning.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Claude Code docs: agent-sdk/subagents
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTSDefaults to 20 in SDK releases bundling Claude Code v2.1.219 or later.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Claude Code docs: agent-sdk/subagents
max_budget_usdmaxBudgetUsdThe Agent SDK spend cap counts subagent requests and has no default limit.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Claude Code docs: agent-sdk/subagents
maxTurnserror_max_budget_usderror_max_turnsmaxTurns returns partial output at the turn limit and the spend cap ends the query with a distinct result subtype, so a CI step can treat error_max_budget_usd or error_max_turns as a failed gate.Subagents vs teams vs SDK: Why can agent teams not run in CI pipelines?
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1Enables agent teams, which are experimental and disabled by default. A lead spawns teammates that claim work from a shared task list and message each other through a mailbox.Subagents vs teams vs SDK: What are subagents, agent teams and the Claude Agent SDK?
Claude Code docs: agent-teams
Agent team token costAgent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, roughly proportional to team size. No equivalent ratio is published for subagents.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Claude Code docs: costs
Team sizeStart with 3 to 5 teammates and about 5 to 6 tasks each; the costs page suggests Sonnet for teammates.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Claude Code docs: costs
subagentPromptCacheTtlIn-process teammates keep a five-minute cache by default unless you set it to 1h.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Fan-out overheadEvery worker loads its own baseline context and spawn prompt before it reads a file, which is why fanning out trivial tasks costs more than doing them in one session.Subagents vs teams vs SDK: How many tokens does multi-agent coordination actually multiply?
Agent teams in CIIn -p mode and Agent SDK sessions Claude does not spawn teammates, and a named subagent runs as an ordinary subagent even with agent teams enabled, so design CI jobs for the subagent topology.Subagents vs teams vs SDK: Why can agent teams not run in CI pipelines?
Claude Code docs: agent-teams
Teammate permissionsSubagents can be restricted with a tools list and a permissionMode field. A new teammate starts with the lead's permission mode, including bypassPermissions.Subagents vs teams vs SDK: How should a platform team govern each topology?
When to move to the Agent SDKWhen a scheduler, CI job, queue consumer or product feature starts the run, a hard per-run budget must end it, or runs must resume by ID, fork, or continue on another host.Subagents vs teams vs SDK: When should teams switch from interactive subagents to the Claude Agent SDK?
omitClaudeMd: trueNon-fork subagents load the full CLAUDE.md hierarchy. The built-in Explore, Plan and web-fetch agents skip it, a custom agent can opt out with this field, and a fork inherits the parent conversation instead.CLAUDE.md vs AGENTS.md: How much context budget do nested instruction files consume per subagent?
Claude Code docs: sub-agents
Instruction taxInstruction tokens loaded across all context windows equal (1 + N) x stack size for N non-fork subagents, so the saving from trimming grows linearly with fan-out.CLAUDE.md vs AGENTS.md: Worked example: the instruction tax at 1, 5 and 15 subagents
Subagent memoryMain-conversation auto memory is not loaded into subagents, except forks. A subagent can keep its own memory through the memory field, scoped to user, project or local, and the docs recommend project scope.Context engineering: Does Claude Code have project context across sessions?
Claude Code docs: sub-agents#enable-persistent-memory
autoCompactWindowA subagent that reads long logs can compact earlier through an autoCompactWindow frontmatter value of 100000 or more, written as a plain integer.Context engineering: When should you compact, clear or rewind?
Claude Code docs: sub-agents
Pairing Antigravity with Claude CodeShare instructions through AGENTS.md: Antigravity treats it as an always-on rule, and Claude Code reads it when no CLAUDE.md exists or through an @AGENTS.md import when one does. Generate .agents/mcp_config.json and .mcp.json from one manifest, and keep identities apart.Antigravity architecture: A pairing layout that keeps one source of truth

Sources

Every row comes from one of these ten guides.

Two tools put numbers on the cost rows: the MCP vs CLI token cost calculator and the CLAUDE.md token budget checker.