Every answer Claude Code gives is a function of one thing: what is in the context window on that turn. Your prompt is usually the smallest part of it. Before you type, Claude Code has already loaded a system prompt, tool definitions, your memory files, a skill listing and MCP tool names. As you work, file reads, command output, path-scoped rules and subagent reports pile on, until compaction rewrites the history. Context engineering in Claude Code means deciding, on purpose, what goes into that window, when, at what cost, and what survives when it is rewritten.

This session teaches the six levers you control as a user: memory files (CLAUDE.md, rules, auto memory, AGENTS.md), session commands (/context, /compact, /clear, branch and fork, @-mentions, /btw), settings (files, precedence, permission rules, modes, directories, environment variables), skills, tools and subagents. For each one you get the exact files, keys and commands, the mechanism behind them, and the ways they fail. Facts are as of 2026-10-24 (Claude Code v2.1.310); version-gated features say "requires v2.1.xxx+" where it matters.

You will be able to
  • Predict exactly which instruction files load for a given working directory and file, and fix a stack that loads the wrong ones.
  • Read /context, choose between /compact, /clear, /branch, /fork, /subtask and /btw, and know what survives compaction.
  • Resolve any setting across five scopes and evaluate a permission rule set against a tool call the way Claude Code does.
  • Keep skills, MCP tools and tool output from crowding the window, and decide when a subagent saves context and when it just costs tokens.
How it connects

Memory

"Memory" in Claude Code is a set of Markdown files that the harness reads into the window. Some load at launch, some load when Claude touches matching paths, and one is written by Claude itself. All of them are advisory context, not configuration. Learn which file loads when, where it lands in the request, and which instructions belong somewhere stronger.

CLAUDE.md Hierarchy

CLAUDE.md files hold the instructions you would otherwise re-explain every session: build and test commands, conventions, layout, "always do X" rules. Claude Code reads four scopes, listed here in the order they enter context, broadest first:

ScopePathShared with
Managed policymacOS /Library/Application Support/ClaudeCode/CLAUDE.md; Linux and WSL /etc/claude-code/CLAUDE.md; Windows C:\Program Files\ClaudeCode\CLAUDE.md; or the managed claudeMd keyEveryone on the machine. Can't be excluded
User~/.claude/CLAUDE.mdOnly you, every project
Project./CLAUDE.md or ./.claude/CLAUDE.mdThe team, through git
Local./CLAUDE.local.md (gitignore it)Only you, this project

How loading works

At launch Claude Code walks from your working directory up to the filesystem root and loads every CLAUDE.md and CLAUDE.local.md it finds. The files are concatenated, not merged or overridden: content runs from the root down to your working directory, so the instructions closest to where you launched are read last, and within one directory CLAUDE.local.md comes after CLAUDE.md. Files in subdirectories below the working directory don't load at launch. Each loads once Claude reads, writes or edits a file in that subdirectory, including through a Bash command that counts as a read, such as cat or head on a single file. An @-mention of a file also pulls in the CLAUDE.md files of that file's directory and its parents.

The combined text is delivered as a user message after the system prompt, not as part of the system prompt. That has three consequences. Claude treats it as context to weigh, so vague or conflicting lines get followed inconsistently ("if two instructions contradict each other, Claude may pick one arbitrarily"). Must-happen behavior belongs in a hook or a permission rule, which Claude Code enforces whatever the model decides. And because the file is part of the cached prefix, an edit mid-session is cache-safe but doesn't apply until /clear, /compact or a restart.

Session started in /repo/packages/api. The lit path is the walk from the filesystem root down to the working directory; the numbered files are concatenated in that order before your first prompt. Have Claude touch src/db/query.ts and the nested CLAUDE.md and the matching rule join the conversation later, in message history, so /compact summarizes them away. Hover a file for its rule.

Writing a file Claude actually follows

  • Size: "target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence." Claude Code loads a file that loads at launch in full up to 4 MiB and skips anything larger. A subdirectory CLAUDE.md or an on-demand rules file over a smaller per-file limit (40,000 characters with a 200K window; 150,000 on current models with a 1M window) arrives truncated: Claude gets only its start, with a note to read the rest with Read (v2.1.309+). Claude Code also warns at startup and in /status when a file passes the recommended length or the files add up past a combined limit.
  • Concrete and checkable: "Use 2-space indentation", not "format code properly"; "Run npm test before committing", not "test your changes". Emphasize one line at most; if every line says IMPORTANT, none stands out.
  • Comments are free: block-level HTML comments (<!-- maintainer note -->) are stripped before injection, except inside code blocks.
  • Start from a draft: /init writes a starter file, or suggests improvements if one exists; CLAUDE_CODE_NEW_INIT=1 switches it to a multi-phase flow that proposes CLAUDE.md, skills and hooks for review before writing anything.
  • Audit: /doctor prompt-audit (requires v2.1.283+) reports instructions written for older models, references to files that don't exist, and contradictions across your instruction files, then proposes edits. The /doctor checkup also proposes trims for content Claude can derive from the code.
# Payments service

## Commands
- Build: `pnpm build` · Test one file: `pnpm vitest run path/to/file.test.ts`
- Never run the full e2e suite locally; CI runs it.

## Conventions
- API handlers live in `src/api/handlers/`, one file per route.
- Money is integer cents (`amountCents: number`); never floats.
- Use `pnpm`, not `npm`.

## Compact Instructions
Keep: the current task, files changed, failing test names, decisions and their reasons.

<!-- Owner: payments-platform. This comment is stripped before Claude sees the file. -->
Outdated advice: the # shortcutOlder posts say "press # to add a memory". That shortcut was removed in v2.0.70. Ask Claude directly ("add this to CLAUDE.md") or open the file with /memory. Saying "remember X" saves to auto memory, not CLAUDE.md.
Verify what loadedRun /context and read the Memory files list. A subdirectory CLAUDE.md never appears there because it loads on demand; when it loads, a Loaded line with its path appears in the terminal. In a monorepo, skip other teams' files with claudeMdExcludes in .claude/settings.local.json, for example ["**/monorepo/other-team/CLAUDE.md"].
The result is drawn as one assembled sheet: each loaded file is a section joined to the next by a seam, in context order, and files that don't load lie beside it as loose slips, each carrying the rule that kept it out. A sample monorepo at /work/mono. Pick where you start Claude, which file it touches, which files exist, and the Project instructions setting. The explorer applies the documented load rules and lists what enters context, in order. Toy model of a real repo: it covers CLAUDE.md, CLAUDE.local.md and AGENTS.md; the rule matcher further down covers .claude/rules/.
Where CLAUDE.md sits in the request, and why that matters for caching and adherence

The prompt-caching docs describe three layers in the cached prefix: the system prompt (Claude Code's instructions and tool definitions), then project context (CLAUDE.md, auto memory, unscoped rules), then the conversation. "The match is exact, so a change anywhere in the prefix recomputes everything after it." That is why Claude Code captures your memory files at session start and keeps them fixed: editing CLAUDE.md mid-session doesn't invalidate the cache, and it also doesn't reach the model until the next /clear, /compact or restart re-reads the files.

Because CLAUDE.md is a user-turn message rather than system text, it competes with everything else in the conversation for attention, and it carries no special authority. When you need text at system-prompt level, for example in a CI script, use --append-system-prompt at launch. When you need a guarantee, use enforcement: a PreToolUse hook (exit code 2 blocks) or a deny rule. The managed-policy docs draw the same line: "Settings rules are enforced by the client regardless of what Claude decides to do. CLAUDE.md instructions shape Claude's behavior but are not a hard enforcement layer."

Cost model (illustrative numbers): a 200-line file at roughly 10–15 tokens per line is 2–3K tokens on every request of the session. On a warm cache those tokens bill as cache reads, a fraction of the input price, but they still occupy the window and still dilute attention. A 1,000-line file with the same density is 10–15K tokens, and the docs' adherence warning starts long before you feel the cost.

Docs: memory: how CLAUDE.md files load · monorepos and large repos · best practices

Imports

A CLAUDE.md can pull other files in with @path/to/file anywhere in its text. Imported files are expanded and loaded into context alongside the CLAUDE.md that references them, so the imports of a file that loads at launch load at launch too. The rules, all from the memory docs:

  • Relative paths resolve relative to the importing file, not the working directory. Absolute and ~/ paths work too.
  • Imports can import, up to a maximum depth of four hops.
  • A path with spaces needs a backslash before each space (@Design\ Docs/api.md); a quoted path isn't imported at all.
  • Code spans and fenced blocks are skipped, so `@README` in backticks stays literal text.
  • An import in a project file that resolves outside your working directory is external: the first time, Claude Code shows an approval dialog listing the files. Decline and the imports stay off. Imports in your own ~/.claude/CLAUDE.md and ~/.claude/rules/ load without the dialog (Cowork sessions on the desktop skip user-file imports that resolve outside the working directory).
See @README for the overview and @package.json for the available scripts.

# Additional instructions
- Git workflow: @docs/git-instructions.md
- My personal notes, shared across all worktrees of this repo: @~/.claude/my-project-instructions.md
Imports are not lazy loading"Imports help you organize a long file but don't reduce its context cost, because imported files load together with the CLAUDE.md that imports them." Splitting a 900-line CLAUDE.md into six imported files changes nothing about the tokens in every request. To make content conditional, move it into a path-scoped rule (loads when matching files are touched) or a skill (body loads when used). The best-practices guide also suggests pointing to docs ("see docs/deploy.md before changing the pipeline") rather than importing them, so Claude reads them only when relevant.

Two legitimate uses for imports remain. First, sharing one source of truth: @AGENTS.md at the top of a CLAUDE.md lets several tools share one instruction file (see AGENTS.md interop). Second, personal notes across worktrees: a gitignored CLAUDE.local.md exists only in the worktree where you created it, while an import from your home directory works in every worktree of the repo. Every imported file also fires the InstructionsLoaded hook with load_reason: "include" and a parent_file_path, which is the fastest way to see what an import chain really pulls in.

Docs: memory: imports

Path-Scoped Rules

Rules are Markdown files under .claude/rules/ (discovered recursively, symlinks supported), one topic per file. A rule without frontmatter loads at launch with the same priority as .claude/CLAUDE.md. A rule with paths: frontmatter loads only when Claude uses Read, Write or Edit on a matching file, or views one with a Bash command that counts as a read (cat, head on a single file). A grep -r over a directory isn't a read of a matching file, so it doesn't trigger the rule. User-level rules in ~/.claude/rules/ load before project rules; neither overrides the other.

---
paths:
  - "src/api/**/*.ts"
  - "lib/**/*.{ts,tsx}"
---

# API development rules
- Validate every request body with the shared zod schemas in `src/api/schemas/`.
- Return errors in the `{ error: { code, message } }` envelope.
  • paths is the only field Claude Code reads. Anything else in the frontmatter is ignored silently, and the frontmatter is stripped before loading. paths accepts a YAML list or a comma-separated string.
  • Glob semantics: patterns are relative to the project root. **/*.ts matches TypeScript at any depth; *.md matches Markdown in the root only; src/components/*.tsx matches one directory.
  • Brace expansion has a budget: each brace group multiplies patterns ({a,b}/{c,d}/*.{ts,tsx} is eight). A rule's whole paths list shares 1,000 expanded patterns and 4 MiB; over budget, the pattern is used unexpanded and its literal braces match nothing.
  • Brackets are syntax: [ starts a bracket expression, so photos [2024/** is invalid and matches nothing. Escape it as photos \[2024/**.
  • Broken YAML fails open: if the frontmatter doesn't parse, the rule loads as if it had no paths, at launch, everywhere. claude --debug shows the parse error.
  • Shared rules by symlink: a link whose target is outside the working directory counts as an external import. After you approve external imports for the project, only the linked rules without paths load. Rules in ~/.claude/rules/ need no approval.
Each row aligns its glob with the path segment by segment (✓ or ✕), so you can see where a pattern stops matching. Edit the paths globs, type a file path relative to the project root, and choose how Claude touches it. The matcher uses the documented glob forms (*, **, ?, {a,b}, [abc]) anchored at the project root. Toy model: it matches globs the way the docs describe, it isn't Claude Code's matcher.
Rules and compactionA path-scoped rule (and a nested CLAUDE.md) enters message history when its trigger file is touched, so compaction summarizes it away with everything else, and it comes back only when Claude touches a matching file again. The context-window docs are explicit: "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md."

Per-directory CLAUDE.md or path-scoped rule? The large-codebases guide puts it plainly. A per-directory CLAUDE.md lives with its code and suits directory owners who maintain their own conventions. A path-scoped rule lives in the central .claude/ and suits conventions that apply to many scattered paths, or when you want every convention in one place.

Docs: memory: path-specific rules · what survives compaction

Auto Memory

Auto memory is the memory Claude writes for itself. As it works, Claude saves notes of four types, recorded as a type field in each file's frontmatter: user (your role and preferences), feedback (corrections you gave and approaches you confirmed), project (ongoing work, deadlines and decisions it can't derive from code or git) and reference (where to find things outside the repo). It skips what it can derive from the codebase and what your CLAUDE.md already says, and it doesn't save something every session.

~/.claude/projects/<project>/memory/
├── MEMORY.md            # index, one line per memory, loaded into every session
├── user_role.md         # one memory per topic file, read on demand
├── feedback_testing.md
└── ...
  • What loads: "The first 200 lines of MEMORY.md, or the first 25KB, whichever comes first, are loaded at the start of every conversation." Topic files are read on demand with the normal file tools. After Claude writes the index, Claude Code checks it against those limits, reminds Claude to shorten it when it's near one, and returns an error asking for a rewrite when it's over, because everything past the limit is dropped on the next load.
  • Scope: the <project> path comes from the git repository, so every worktree and subdirectory of one repo shares one memory directory. It is machine-local: it doesn't follow you to another machine or a cloud session, and it is exempt from the cleanupPeriodDays transcript sweep.
  • Controls: on by default in local sessions. Toggle it in /memory (writes autoMemoryEnabled to user settings), set "autoMemoryEnabled": false in one project's settings, or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. autoMemoryDirectory relocates it (absolute or ~/ path).
  • Where it doesn't go: the main conversation's auto memory isn't loaded into subagents, except forks. A subagent's own memory: field gives it a separate directory and automatically enables Read, Write and Edit so it can manage those files.
  • Compaction: auto memory is re-injected from disk after every compaction.
A limit plane: lines across, average bytes per line up. The 200-line wall and the 25 KB curve (lines × bytes = 25,000) split it into three zones: all loads, cut by lines, cut by bytes. Your MEMORY.md is the point; drag it, use the arrow keys on the drawing, or the sliders. The index loads up to 200 lines or 25KB, whichever comes first. Toy model: KB is taken as 1,000 bytes and every line has the same length.
✗ Using auto memory as a rulebook

"Remember: never commit to main." It lands in a machine-local note your teammates never see, competes with the 200-line index, and is still only advice.

✓ Each kind of fact in its place

Team rule → deny rule Bash(git push origin main *) plus a line in CLAUDE.md. Personal preference ("I review diffs before commits") → let auto memory keep it. Audit it with /memory → open the auto memory folder; it's plain Markdown you can edit or delete.

Docs: memory: auto memory

AGENTS.md Interop

AGENTS.md is the instruction file other coding agents read. Claude Code (requires v2.1.277+) reads it directly through a built-in plugin, but with a precise default: it reads AGENTS.md only when you have no CLAUDE.md in your working directory or above it. What counts for that check, and what doesn't, is where most surprises come from:

Counts: Claude reads these instead of AGENTS.md
  • CLAUDE.md in the working directory or any ancestor
  • .claude/CLAUDE.md in the same places
  • CLAUDE.local.md in the same places
Doesn't count: loads alongside AGENTS.md
  • ~/.claude/CLAUDE.md
  • Your organization's managed CLAUDE.md
  • .claude/rules/ files

When nothing counts, Claude reads every AGENTS.md and .claude/AGENTS.md from the working directory upward at session start, and shows a line such as no CLAUDE.md found; AGENTS.md loaded: /home/you/repo/AGENTS.md. A subdirectory's AGENTS.md loads when Claude opens a file there with the Read tool and that subdirectory has no CLAUDE.md of its own. Imports inside AGENTS.md expand and claudeMdExcludes applies. Never read: AGENTS.local.md, AGENTS.override.md, anything under .agents/.

The Project instructions setting in /config changes the default:

ValueClaude reads
claude-md-or-agents-md (default)CLAUDE.md files, or AGENTS.md when no CLAUDE.md or CLAUDE.local.md exists at or above the working directory
claude-md-and-agents-mdBoth, each directory's CLAUDE.md files first and its AGENTS.md after; an AGENTS.md already imported or symlinked isn't read twice
claude-mdCLAUDE.md files only
managed-onlyOnly managed CLAUDE.md and auto memory at launch; subdirectory CLAUDE.md, rules and path-scoped rules still load on demand
{
  "pluginConfigs": {
    "cc-plugin-agents-md@builtin": {
      "options": { "instructionFiles": "claude-md-and-agents-md" }
    }
  }
}

The settings form is read from ~/.claude/settings.json, a --settings file or managed settings, and ignored in project and local files. Before v2.1.285 the plugin ID was agents-md@builtin; v2.1.285+ reads either.

The portable pattern

When a repository also needs a CLAUDE.md, or some sessions can't read AGENTS.md directly (versions before v2.1.277, the built-in plugin disabled, sometimes the first session after an upgrade), keep AGENTS.md as the shared file and import it:

@AGENTS.md

## Claude Code
Use plan mode for changes under `src/billing/`.

A symlink (ln -s AGENTS.md CLAUDE.md) also works, with two constraints: the Edit and Write tools refuse to write through a symlink and redirect Claude to edit AGENTS.md, and on Windows creating a symlink needs Administrator rights or Developer Mode, while checking a committed one out needs core.symlinks, or the clone gets a one-line CLAUDE.md. Prefer the import when anyone on the team uses Windows.

The CLAUDE.local.md trapYour repo relies on AGENTS.md. You add a CLAUDE.local.md for personal notes, and Claude stops reading AGENTS.md, because CLAUDE.local.md counts. Fix: set Project instructions to claude-md-and-agents-md, or add a CLAUDE.md with @AGENTS.md. Also remove old workarounds: a SessionStart hook that prints AGENTS.md now adds a second copy, and a CLAUDE.md that says "read AGENTS.md" in words only works if Claude decides to open the file. Two smaller differences: InstructionsLoaded doesn't fire for an AGENTS.md read through the setting, and an --add-dir directory's AGENTS.md doesn't load even with CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1.

Docs: memory: AGENTS.md

CLAUDE.local.md

CLAUDE.local.md is the personal, uncommitted layer of project instructions: your sandbox URLs, preferred test data, the shortcut you use and your teammates don't. It sits at the project root (or any ancestor directory in the walk), loads like CLAUDE.md, and is appended after the CLAUDE.md in the same directory, so it is the last thing Claude reads at that level.

  • Keep it out of git: add it to .gitignore. With CLAUDE_CODE_NEW_INIT=1, choosing the personal option in /init does this for you.
  • One worktree only: a gitignored file exists only in the checkout where you created it. Worktrees under .claude/worktrees/ don't get it. For notes that follow you into every worktree, import a home-directory file instead (@~/.claude/my-project-instructions.md).
  • Setting sources: it loads through the local source, so --setting-sources user,project (or an SDK setting_sources without "local") skips it.
  • It counts for AGENTS.md: as covered above, creating one silently switches a repo from AGENTS.md to CLAUDE.md files.
Not the same as settings.local.jsonCLAUDE.local.md holds advisory instructions. .claude/settings.local.json holds enforced configuration (permission rules, env, hooks) and is covered in Settings. Both are personal and uncommitted; they do completely different jobs.

Exercise: map and trim your instruction stack

  1. In your main repo, run /context and copy the Memory files list. Run wc -l on each file.
  2. Add a temporary logger to ~/.claude/settings.json (below), restart, touch a file in a subdirectory, then read the log.
  3. Pick the largest section that only matters for part of the tree and move it into .claude/rules/<topic>.md with paths:. Pick one must-happen line and replace it with a deny rule or hook.
  4. Restart, rerun /context, and compare.
{
  "hooks": {
    "InstructionsLoaded": [
      { "hooks": [ { "type": "command",
        "command": "jq -c '{load_reason, memory_type, file_path, trigger_file_path}' >> ~/.claude/instructions-loaded.log" } ] }
    ]
  }
}
Show a solution

A typical before/after for a web monorepo: a 420-line root CLAUDE.md shrinks to about 120 lines of repo-wide commands and conventions. The React section moves to .claude/rules/frontend.md with paths: ["apps/web/**/*.{ts,tsx}"], and the SQL style guide moves to .claude/rules/sql.md with paths: ["**/*.sql"]. "Never edit generated files" becomes "deny": ["Edit(**/generated/**)"]. The log then shows session_start entries for the managed, user and project files, and a path_glob_match entry with a trigger_file_path the first time Claude opens a .tsx file. Remove the logger hook afterwards; it runs on every load.

What you run: a read-only linter for an instruction stack. It resolves @ imports the way the docs describe (relative to the importing file, four hops, never inside code spans or quotes), totals what loads at launch, and flags files over 200 lines, vague rules, emphasis on many lines, content Claude can derive from the code, procedures that want to be skills, and must-rules with the hook or deny rule to move each one into.

cd labs && python3 core-2/claudemd_lint.py
python3 core-2/claudemd_lint.py --repo path/to/your/repo     # CLAUDE.md, .claude/CLAUDE.md, CLAUDE.local.md, AGENTS.md
python3 core-2/claudemd_lint.py --path path/to/CLAUDE.md --strict   # exit 1 on errors, for CI

Observe: the good sample passes with one import and its HTML comment stripped. The bloated sample is over 200 lines, has a quoted path that never imports and an import chain whose level4.md and level5.md (hops 5 and 6) never load, and gets one finding per "must" line naming the deny rule, PostToolUse hook or Stop hook to use instead. Read those suggestions with care. A deny rule or PreToolUse hook can block an action. A Stop hook guarded by stop_hook_active only nudges Claude once: Claude can stop on its next attempt, a crashing Stop hook lets the stop through, and onFailure has no effect on Stop. A hard "tests must pass" gate needs its own counter or state file, and CI stays the real gate. Token counts are a characters ÷ 2.5 estimate (the course-wide ratio).

Open the lab walkthrough

What you run: a resolver over a sample project and a sample home directory that parses paths: frontmatter (YAML list or comma string), expands braces within the 1,000-pattern budget, and prints the launch list in context order plus the rules each sample path triggers.

cd labs && python3 core-2/rules_match.py
python3 core-2/rules_match.py --path src/api/v2/orders.tsx --path README.md
python3 core-2/rules_match.py --project path/to/repo --no-home --path src/app.py

Observe: broken.md loads at launch because its YAML doesn't parse; src/components/forms/Input.tsx matches nothing because * doesn't cross /; a 1,296-way brace pattern goes over budget and matches no file; an unclosed [ pattern is invalid while the rule's other pattern still works.

Open the lab walkthrough

Docs: memory: where CLAUDE.md files live · InstructionsLoaded hook

Key takeaways

  • CLAUDE.md files from the root down to your working directory are concatenated at launch; subdirectory files and path-scoped rules load on demand and are summarized away at compaction.
  • Memory is context, delivered as a user message. Enforce must-happen behavior with hooks and permission rules.
  • Under 200 lines per file. Imports organize but don't save tokens; rules and skills do.
  • Auto memory loads the first 200 lines or 25KB of MEMORY.md, is machine-local, and is re-injected after compaction.
  • AGENTS.md loads only when no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md sits at or above the working directory; @AGENTS.md is the portable bridge.

Session Context

Memory is the stable part of the window; the conversation is the part that grows. Every file read, command result and reply stays in context until something removes it. Claude Code gives you commands to see the window, summarize it, reset it, copy it and ask questions around it without adding to it. Using the right one at the right moment is most of day-to-day context engineering.

Each turn deposits a band: tool outputs thick (dotted), prompts and replies thin, @-files and images as boulders, nested CLAUDE.md files and path rules as veins. Send turns, add an @file or ask a /btw (nothing settles). /compact presses the sediment into one summary band and re-lays the startup layers from disk; /clear digs out everything above them. The ≈967K waterline is the documented auto-compact point on native-1M models; band thicknesses are illustrative. The /context breakdown below follows this session.

/context

/context "visualize[s] current context usage as a colored grid" with a per-category breakdown, the list of Memory files that loaded, and optimization suggestions for context-heavy tools, memory bloat and capacity warnings. /context all expands the per-item breakdown, which fullscreen mode collapses to keep the grid visible. When the conversation is already over the window, the output says by how much and which command frees space. It is the first command to run when Claude seems to forget things, ignores a rule, or slows down.

The Agent SDK exposes the same payload, and its reference describes the structure precisely. In TypeScript, getContextUsage() returns categories whose rows each have a display name, a token count and a kind (the field requires Agent SDK v0.3.268+). Python's ClaudeSDKClient.get_context_usage() returns name, tokens, color and an optional isDeferred flag instead of kind. The kinds, from the TypeScript reference:

KindMeaningTypical rows
usedContent that occupies the windowSystem prompt and tools, MCP tool names, custom agent descriptions, memory files, the skill listing, Messages
freeThe remaining windowFree space
bufferThe compaction reserveAutocompact buffer
deferredTool schemas held out of the window and excluded from the total, listed for awarenessMCP tool definitions under tool search

Row display names vary between versions; classify by kind. The TypeScript response also attributes tokens per memory file (with a source label such as Project or User), per MCP tool, per custom subagent definition (built-ins aren't listed) and per skill. Computing it sends token-counting requests that don't appear in the message stream; token counting isn't billed on the Anthropic API. Docs: commands, context window.

Each category has its own glyph, as in the real /context grid; hover or tab to a legend row to light its cells. The Messages row follows the core sample above. Toy model with illustrative token counts (the docs' own walkthrough uses about 4,200 tokens for the system prompt and 1,800 for a project CLAUDE.md). Change your setup and watch the rows, the grid and the distance to compaction. Each MCP server has 15 tools; each grid cell is 0.5% of the window, and every nonzero row gets at least one cell. Real numbers: run /context.

Reading the breakdown

  • Messages dominate: the conversation is the problem. /compact with a focus if you're mid-task, /clear if you're switching tasks, a subagent next time for noisy reads.
  • Memory files are large before you type: trim CLAUDE.md, move sections to path-scoped rules or skills, exclude other teams' files with claudeMdExcludes.
  • MCP tools are large: tool search is probably off (ENABLE_TOOL_SEARCH=false, an older model, a Foundry deployment hosted on Azure, or a gateway that rejected the tool-search fields; before v2.1.304 a custom ANTHROPIC_BASE_URL also turned it off) or a server sets alwaysLoad. See MCP tool search.
  • Skills row is large: run /skill-doctor to find unused skills and hide them with skillOverrides. The row reports the listing after the budget is applied (v2.1.196+), so it matches what the model receives.
Why /context and the status line disagreeA status line reads the token counts from the last API response. /context adds an estimate for messages added since that response, so it can read higher until the next response arrives. Neither is wrong.

Compaction

Compaction keeps a session alive past a full window by replacing older history with a structured summary. Claude Code "compacts the conversation into a summary" (how Claude Code works). Separately, it can clear old tool results from context, which the costs page counts as a second kind of rewrite next to compaction. Compaction runs automatically, or when you type /compact [instructions].

When it runs

  • Models with a native 1M window (the Fable models, Sonnet 5 and later, Haiku 5.5, Opus 4.7 and later) compact "at about 967K tokens by default". With CLAUDE_CODE_DISABLE_1M_CONTEXT=1 they compact at the 200K boundary. Other models compact at their context limit.
  • Set the threshold with /autocompact 500k (requires v2.1.221+; saved per model under modelSettings from v2.1.288), the autoCompactWindow setting, --autocompact for one launch, or CLAUDE_CODE_AUTO_COMPACT_WINDOW, which beats all of them. Accepted windows run from 100K to 1M.
  • Idle compaction can run on a conversation you leave idle near cache expiry; idleCompaction: false turns it off (v2.1.290+).
  • Off switches: autoCompactEnabled: false or DISABLE_AUTO_COMPACT=1 stop the automatic pass ("The manual /compact command keeps working while auto-compact is off"); DISABLE_COMPACT disables compaction entirely.
The unit trap"CLAUDE_CODE_AUTO_COMPACT_WINDOW=200 means 200 tokens even though /autocompact 200 means 200,000." The command accepts a bare number from 100 to 1000 as thousands; the environment variable reads a number with no suffix as tokens. A value below 100,000 is treated as the 100k minimum with a warning, and on v2.1.304+ the variable also accepts 200k or 1M. Write 200000 in scripts that might meet older versions.
One compaction as a waterfall: each step changes the size of what's in context, in the documented order: the summary, then re-injection from disk, file re-reads and hooks. Press Play or step manually. Sizes are illustrative; the ≈967K trigger is documented.

What survives

What happens to each piece of context depends on how it got there. This is the documented table, with the rule behind each row:

MechanismAfter compaction
System prompt and output styleStill apply (not part of the conversation)
Project-root CLAUDE.md and unscoped rulesRe-injected from disk
Auto memoryRe-injected from disk
Skill descriptionsRebuilt from your current skills and re-injected (requires v2.1.304+)
Git status snapshotA fresh one is read, if the session started with one
The plan from plan modeRe-injected from disk
Path-scoped rules, nested CLAUDE.mdSummarized away; reload on demand when a matching file is touched
Files Claude read or editedUp to five re-read, most recently modified first; a file over 5,000 tokens comes back as a path reference (Referenced file instead of Read)
Invoked skill bodiesRe-injected, capped at 5,000 tokens per skill and 25,000 total; oldest dropped first
Background commands and subagentsKeep running; Claude is reminded which are still running
Context hooks added earlier, instructions given only in chatSummarized with the rest of the conversation
SessionStart hooks matching compactRun again; their output joins the compacted context
A realistic mid-session state. Change the setup, then run /compact: each item lands on the right intact, cut (partial) or lost, with the reason in place. The file and skill rules use the documented limits; sizes are illustrative.

Steering the summary

/compact focus on the payment retry bug: keep the failing test names, the diff so far and why we rejected the queue-based fix

A Compact Instructions section in CLAUDE.md applies to every compaction, including automatic ones. For surgery on part of the history, /rewind (or Esc Esc on an empty prompt) offers Summarize from here and Summarize up to here, which "compresses context, like a targeted /compact", and keeps you in the same session. For text that must come back every time, use a SessionStart hook with the compact matcher:

{
  "hooks": {
    "SessionStart": [
      { "matcher": "compact",
        "hooks": [ { "type": "command",
          "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing.'; git log --oneline -5" } ] }
    ]
  }
}
Things compaction can loseInstructions you only gave in chat. Path-scoped rules until they re-trigger. The middle of a long skill (re-attached skills keep their first 5,000 tokens, so put the important instructions at the top of SKILL.md). And auto mode boundaries: "a boundary can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead."
Cost and cache mechanics of compaction, and the thrashing error

Compaction is a big request. The costs page: "/compact reads the conversation it summarizes, so compacting a large context is itself a large request. When you want a fresh start instead of continuity, /clear costs nothing." The prompt-caching docs spell out the mechanics: the summary comes from a separate request that "repeats your conversation's system prompt, tools, and the history being summarized. It ends with a summarization instruction. While the cache is warm, that request reads your prefix from the cache. A mid-session /compact then costs a fraction of what the context size suggests." After a break longer than the cache lifetime there is nothing to read, and the request reprocesses the whole history uncached, which is why compacting a resumed old session is the expensive case. Either way, compaction invalidates the conversation layer by design (the new, shorter history shares no prefix with the old one), while the system prompt layer is read from the cache and the project context layer is reloaded from disk, read from the cache only if CLAUDE.md and memory are unchanged since the session started. Hence the two rules: pick model and effort at the top of a session and "save /compact for natural breaks between tasks", and the advice in Anthropic's cost post (What a task costs on Opus 5.5, official blog) to compact before a break, not after one. To abandon a path entirely, /rewind is cheaper still, because it "truncates back to a prefix that is already cached".

The summarization request inherits your session's extended-thinking configuration (v2.1.198+). Thinking changes how the summary is produced, not your settings afterwards. Cloud sessions set their own threshold.

Thrashing. If one file or tool output is so large that the window refills right after each summary, "Claude Code stops auto-compacting after a few attempts and shows an error instead of looping": Autocompact is thrashing: the context refilled to the limit. Recovery: read the file in chunks (Read's offset/limit), /compact with a narrow focus ("keep only the plan and the diff"), push the large read into a subagent, or /clear and restart from a written plan. Then check the Messages row in /context.

Hooks around it. PreCompact fires before compaction (matcher manual or auto) and exit code 2 blocks it; PostCompact fires after. The InstructionsLoaded hook reports re-loaded memory files with load_reason: "compact". See the hooks reference.

Docs: context window · auto-compact window · checkpointing · re-inject context after compaction

/clear and Fresh Starts

/clear (aliases /reset, /new) "start[s] a new conversation with empty context." Project memory reloads, so CLAUDE.md, rules and auto memory are back; the conversation, file reads and tool output are gone. The old conversation isn't deleted: /resume returns to it, and within the same Claude Code process the rewind menu has a previous-session entry. /clear release-prep names the conversation you're leaving so it's easy to find in the picker. /usage totals reset (v2.1.211+), and so does the per-session WebSearch count.

The docs give two triggers, one from the costs page and one from best practices:

  • Switching tasks. "Use /clear to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message."
  • Repeated corrections. "If you've corrected the same thing twice and it's still wrong, a third correction mostly adds to a conversation that already contains two failed attempts for Claude to keep re-reading. /clear plus one new prompt that folds in what you learned works better almost every time."

A fresh start loses nothing if the state you need is in files. Before clearing a half-finished task, have Claude write it down, then point the new conversation at it:

Write PLAN.md: goal, decisions with reasons, files changed, what's left, how to verify. Then stop.
/clear
Read PLAN.md and continue from "what's left". Run the verification step before you report done.
You wantUseCostKeeps
Unrelated next task/clearNothingMemory files only
Same task, less history/compact [focus]One large request; cache rewrittenA summary plus the survivors table
Drop a bad detour/rewind → restore or summarizeReuses an already-cached prefixEverything before the chosen point
Keep this thread, try another/branchThe branch continues on the same prefixA full copy
Spec first, then a clean sessionFor a large feature, the best-practices guide recommends letting Claude interview you (it uses AskUserQuestion), writing the result to SPEC.md, and then starting a fresh session to build from it. The new session gets the spec at full fidelity instead of a chat history full of discarded options.

Docs: sessions: manage context · best practices: steer the session

Resume, Fork and Branch

Every session is saved continuously as JSONL at ~/.claude/projects/<project>/<session-id>.jsonl, where <project> is the working directory with non-alphanumeric characters replaced by -. Retention follows cleanupPeriodDays (30 days by default). The line format "is internal to Claude Code and changes between versions", so scripts should use /export, claude -p --resume <id> --output-format json or a hook's transcript_path instead of parsing files.

Resume

CommandDoes
claude --continue / -cReopens the most recent session in the current directory, or prints No conversation found to continue
claude --resume / -rOpens the session picker; --resume <name|id|transcript-path> goes straight there. An ID resolves in any project on the machine
claude --from-pr <number>Picker filtered to sessions linked to that pull request
/resume (alias /continue)Switch sessions from inside a running one
--name / -n, /renameName a session so --resume <name> finds it

A resumed session restores the conversation (opening at the last Conversation compacted row if it was compacted), the model, an --agent it ran as, an active goal, unexpired session-scoped scheduled tasks and, for --continue or --resume <id|name> from a terminal without -p, the permission mode. It does not restore launch flags: pass --mcp-config, --settings, --plugin-dir, --fallback-model and --add-dir again, and directories added with /add-dir are gone. Settings files are re-read at launch, so anything in them comes back on its own. The system prompt is recorded on the first request and reused until compaction, including after --resume and --continue.

Branch, fork, subtask

These three look alike and do different things. The commands reference keeps them apart this way:

  • /branch [name] copies the conversation up to now and switches you into the copy. The original stays unchanged in the picker; return with /resume. From the shell: claude --continue --fork-session. Because /branch stays in the same process, "allow for this session" grants carry over; a --fork-session process starts without them. In-flight background subagents and commands keep running and report into the branch.
  • /fork [prompt] copies the conversation into a new background session while you keep working here. With a prompt the copy starts on it at once; without one it waits in agent view. Claude Code tells the copy to create its own worktree before code changes (v2.1.221+). With agent view turned off, /fork starts a forked subagent instead.
  • /subtask <task> spawns a forked subagent: it inherits the full conversation, works in the background, and its result returns to this conversation (v2.1.212+; needs agent view).
  • /background (/bg) detaches the whole session to run as a background agent and frees the terminal.
Drawn like git log --graph: each lane is a conversation and each dot a turn. /branch forks a lane you switch into, /fork a lane that runs on its own, and /subtask forks a subagent whose result merges back as one message; /clear starts a new root that carries only the memory files. /clear and /branch both leave the original resumable from the picker. Press a command or hover a lane.
Two terminals, one transcript"If you resume the same session in two terminals without forking, messages from both interleave into one transcript." Use --fork-session or /branch when you want two lines of work.
Pick a command for each situation, then check. The feedback quotes the behavior that makes it the right choice.

Docs: sessions · commands · forks

@-Mentions and Images

An @-mention puts content into your message before Claude starts, saving a tool round trip. Type @ for a path picker; Enter or Tab accepts.

You typeClaude receivesLimit or catch
@src/utils/auth.jsThe file's contentOnly when it fits the Read tool's limit, 25,000 tokens by default; a text file over 256KB isn't included
@src/componentsA directory listing, not contentsRead deny rules remove matching names from the listing (v2.1.290+)
@github:repos/owner/repo/issuesAn MCP resource, @server:resourceThe server must be connected
@"code-reviewer (agent)"Forces that subagent for this taskClaude still writes the subagent's prompt
  • An @-mention also adds the CLAUDE.md files from the file's directory and its parents, the same as Claude reading it.
  • Read deny rules apply on a best-effort basis to @-mentions. A file the Read tool refuses (binary formats such as .xlsx or .zip) arrives as a path without contents.
  • CLAUDE_CODE_DISABLE_FILE_MENTIONS=1 (requires v2.1.299+; shell or user settings only, ignored in project and local files) sends paths with a note to read them instead of inlining contents.
  • In VS Code, Option+K / Alt+K inserts a line-range mention such as @file.ts#5-10.

Images and large pastes

Add an image by dragging it into the window, pasting it with Ctrl+V (Alt+V on Windows and WSL), or giving its path in the prompt. It appears as an [Image #1] chip; Cmd+Click or Ctrl+Click opens it. The Read tool resizes and recompresses large images to fit the model's limits, so for pixel-level detail ask Claude to crop the region first and read the crop. Images cost context like anything else, and they accumulate: when the next request would pass the API's image or PDF limits, Claude Code removes a batch of the oldest ones, Claude can no longer see them, and the next request reprocesses the conversation from the earliest changed message. Share an image again if Claude needs it after that.

Pasted text over 800 characters or three lines collapses to a chip such as [Pasted text #1 +120 lines]. Claude Code "still sends the full content when you submit", marked as pasted rather than typed, and Claude is told a paste can contain instructions you didn't write. For really large inputs (a full log, a data dump), write a file and let Claude read or grep it. A Read with offset/limit or a grep pulls in the 40 lines that matter instead of 40,000.

Here's the failing screenshot [Image #1] and the handler @src/api/checkout.ts.
The full server log is in /tmp/checkout.log (2 MB): grep it for request id 7f3a, don't read it whole.
The ! prefix also adds context! npm test runs the command in your shell, adds its output to the conversation and, unless respondToBashCommands is false, has Claude respond, so it costs like a prompt. It runs outside the sandbox.

Docs: referencing files · images · large pastes

/btw Side Questions

/btw asks a question "about your current work without adding to the conversation history." Claude answers from what is already in context (your messages, its replies, the tool results it gathered), and the exchange never enters history. That makes it the cheapest way to recall something mid-task without bending the main thread.

you · while Claude is still running tests/btw which config file did you say controls the retry backoff?
side answer (overlay, not in history)config/resilience.yaml, key http.retry.backoff_ms. You read it at the start of this session; I haven't modified it.
keysSpace / Enter / Esc dismiss · c copy as Markdown · f fork into a subagent with tools · x clear earlier exchanges
  • Runs while Claude works. It doesn't interrupt the main turn and sees everything so far except the reply still being written.
  • No tools. It can't read files, run commands or search. If it writes tool calls as text anyway, the answer ends with a note that nothing ran.
  • One response. No follow-up turns in the overlay. Ask another /btw; Claude Code replays your newest 20 side exchanges with each ask until you clear them. Press f to fork the question and answer into a background subagent with full tools (local sessions).
  • Cheap on a warm cache. "While the conversation's prompt cache is warm, a side question costs little beyond the answer itself." /btw with no question reopens the overlay on the latest exchange.
✓ /btw

About what Claude already knows: "what did we decide about X", "which file was that", "summarize the plan so far". Full context, no tools, no history.

✓ Subagent

To find out something new: "search the repo for callers", "read these logs". Tools, a fresh window (or a copy, for a fork), only the summary comes back.

Why side channels matter: the economics of a clean main thread

A question asked in the main thread costs twice: once now, and again on every later request, because its question and answer stay in the prefix until compaction or /clear. Ten quick "what was that again?" turns in a 300K-token session add little per turn but compound across the remaining turns, and they can pull Claude's attention toward stale details. /btw pays only the first cost and leaves the prefix untouched, so it also keeps the cache warm for the main thread.

The same reasoning drives the cookbook's context engineering recipe (a Client SDK recipe, not Claude Code): memory, compaction and tool-result clearing are three different answers to "what should stay in the window", and the right one depends on whether the information is needed again. Anthropic's effective context engineering post frames the goal as the smallest set of high-signal tokens that gets the job done.

Exercise: measure, compact, branch

  1. Start a fresh session in a real repo and run /context before typing anything. Note the Memory files, MCP tools and Skills rows: that's your fixed overhead.
  2. Ask Claude to explain a subsystem (it will read 10+ files). Run /context again and note the Messages row.
  3. Run /compact focus on the module boundaries and open questions. Check /context and ask a question that needs a detail you didn't put in the focus.
  4. Run /branch try-alt, push the branch in a different direction for two turns, then /resume the original and confirm it's untouched.
  5. Mid-task, ask a /btw question and confirm with /context that Messages didn't grow.
Show a solution

Expected observations: the fixed overhead is usually a few percent of a 1M window, and Memory files plus skills are the parts you control. Exploration grows Messages fast, often by tens of thousands of tokens. After the focused compact, Messages drops sharply; up to five recently modified files come back (large ones as Referenced file), and details outside your focus may now need a re-read, which is the trade you made. The original session after /branch ends exactly where you branched. The /btw question leaves the Messages row unchanged because the exchange never enters history.

Docs: interactive mode: /btw

Key takeaways

  • /context first: classify rows by kind (used, free, buffer, deferred) and attack the biggest used row.
  • Compaction clears old tool output, then summarizes. Root CLAUDE.md, unscoped rules, auto memory, the skill listing and the plan come back; up to five recent files are re-read; path-scoped rules and chat-only instructions don't.
  • /compact is a large request that rewrites the cache; /clear is free. Compact at natural breaks; clear between tasks or after two failed corrections.
  • /branch switches you into a copy, /fork copies to a background session, /subtask runs a forked subagent that reports back.
  • @-mentions inline content within the Read limit; /btw asks about what's already in context without adding to it.

Settings

Memory shapes what Claude tries; settings decide what Claude Code allows. Settings files set the permission rules, mode, directories, environment and hooks that the harness enforces whatever the model thinks. They also decide which context sources load at all. Five scopes stack with one precedence rule, a few exceptions, and one trust gate.

Settings Files and Precedence

Claude Code reads four settings files plus managed policy, and each has a scope:

ScopeFileAffectsUse for
Managedmanaged-settings.json (macOS /Library/Application Support/ClaudeCode/, Linux and WSL /etc/claude-code/, Windows C:\Program Files\ClaudeCode\), MDM/OS policy, server-managed settingsEveryone the org deploys it toSecurity policy, compliance
Command line--settings <file-or-json>One sessionCI runs, experiments
Project local.claude/settings.local.jsonYou, one projectPersonal overrides, saved approvals
Shared project.claude/settings.json (commit it)Everyone in the repoTeam permissions, hooks, plugins, env
User~/.claude/settings.jsonYou, every projectPersonal defaults

Precedence runs top to bottom: managed → --settings → local → project → user. "When the same key appears in more than one place, Claude Code uses the value from the highest level that sets it." Three refinements matter in practice:

  • Lists merge. permissions.allow, deny, ask, claudeMdExcludes and other arrays combine across files, so each file adds entries. Exceptions: fallbackModel takes the whole chain from the highest file; modelPicker comes only from managed, --settings or user; a managed availableModels applies as-is.
  • Some security keys honor the stricter value from a lower level, even over managed: permissions.blockReadsOutsideWorkingDirectories: true from any file, disableClaudeAiConnectors: true from any file, a lower maxEffortLevel cap from any scope, remoteControlAtStartup: false from project or local.
  • Environment variables aren't a level. Each variable and key pair is decided on its own: ANTHROPIC_MODEL in your shell beats the model key in any file, while ANTHROPIC_DEFAULT_MODEL applies only when no file sets model. An env block inside a settings file is an ordinary key and follows the stack.
Scalar keys come from the highest file that sets them; list keys merge downward. A few security keys keep the strictest value from any level, and environment variables sit beside the stack, not in it. Each column is one key; a repository can't set auto or bypassPermissions as defaultMode, and the shared project's allow rules wait for workspace trust. The matrix under the drawing is the settings precedence resolver: pick a preset, or set a key's value at each level (or leave it unset), and see the effective value with the reason. Its rules come from the settings docs: highest level wins for scalars, lists merge, a few keys ignore repository files, security keys keep the strictest value, and some environment variables override files.

Gates that change what a file can do

  • Workspace trust. A project's permissions.allow rules, permissions.additionalDirectories, extraKnownMarketplaces and most env values apply only after you accept the trust dialog for that folder. Deny and ask rules apply immediately, because they only restrict. claude -p and the SDK never show the dialog, so in those runs project allow rules apply only if the folder was trusted before (interactively, or by hand: projects[…].hasTrustDialogAccepted in ~/.claude.json); in a folder that was never trusted they aren't used, and Claude Code prints a this workspace has not been trusted warning. The other half matters more for security: in an untrusted folder under -p or the SDK, the repository's settings hooks, its env block and helpers such as apiKeyHelper are used, its .mcp.json servers connect without asking, and its skills' allowed-tools apply. Before running claude -p in a repository you didn't write, pass --setting-sources user (which drops the project's settings files and .mcp.json entirely), start with --bare (no project hooks, skills, subagents, plugins or .mcp.json servers, though the project's env block and helpers such as awsAuthRefresh still apply), add --settings '{"disableAllHooks": true}', or reject servers with disabledMcpjsonServers (what runs before you trust a folder).
  • Keys a repository can't set. permissions.defaultMode values auto and bypassPermissions don't take effect from project or local files, and your user value doesn't replace them: a repository auto gives the built-in default, a repository bypassPermissions gives Manual. The autoMode block is read only from user settings, managed settings and --settings. Check the Scope line of a key in the settings reference.
  • Cloud sessions read the shared project file (in single-repo sessions) and server-managed settings, not your user or local files.

Format, reloads and verification

Installing Claude Code creates no settings file. Files are strict JSON ("a // comment or a trailing comma is a syntax error"); add "$schema": "https://json.schemastore.org/claude-code-settings.json" for editor validation. Interactive sessions show a Settings Error dialog for a broken file and a Settings Warning for a bad entry; a -p run silently skips them, so run claude doctor afterwards. Most edits hot-reload, including permissions, hooks and apiKeyHelper; model, effortLevel and modelSettings are read once at start (use /model and /effort). /status shows a Setting sources line listing the files that loaded; it doesn't show which file supplied each key.

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "allow": [
      "Bash(pnpm test *)",
      "Bash(pnpm lint *)",
      "Bash(git diff *)",
      "Bash(git commit *)",
      "WebFetch(domain:docs.stripe.com)"
    ],
    "ask": ["Bash(git push *)"],
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)",
      "Edit(**/generated/**)",
      "Bash(curl *)"
    ]
  },
  "env": {
    "CLAUDE_CODE_SUBAGENT_MODEL": "sonnet"
  },
  "claudeMdExcludes": ["**/vendor/**/CLAUDE.md"]
}
{
  "permissions": {
    "allow": ["Bash(docker compose up *)"],
    "additionalDirectories": ["../payments-sdk/"]
  },
  "model": "opus",
  "spinnerTipsEnabled": false
}
{
  "permissions": {
    "defaultMode": "auto",
    "deny": ["Read(~/.ssh/**)", "Read(~/.aws/**)"]
  },
  "autoMemoryEnabled": true,
  "env": { "BASH_MAX_OUTPUT_LENGTH": "60000" }
}

Claude Code keeps .claude/settings.local.json at the git repository root (v2.1.211+) so an approval made in a subdirectory or worktree applies across the repo, and adds **/.claude/settings.local.json to your global git excludes the first time it writes the file. If you create it by hand, gitignore it yourself.

Docs: settings · settings precedence · settings reference · managed settings

Permission Rules

A permission rule is Tool or Tool(specifier) in permissions.allow, ask or deny. "Rules are evaluated in order: deny, then ask, then allow. The first match in that order determines the outcome, and rule specificity doesn't change the order." So a broad Bash(aws *) deny blocks aws s3 ls even with a matching allow rule, and "an allow rule can't carve an exception out of a deny rule". The same order holds across files: a user-level deny blocks a project-level allow, and "if a tool is denied at any level, no other level can allow it." A bare deny (Bash, "mcp__*") removes the tool from Claude's context entirely; a scoped deny (Bash(rm *)) leaves the tool and blocks matching calls. "Permission rules are enforced by Claude Code, not by the model."

Bash rules

RuleMatchesDoesn't match
Bash(npm run build)npm run buildnpm run build --watch
Bash(npm run *)npm run test --watch, bare npm runnpm install
Bash(ls *)ls -la, lslsof
Bash(ls*)ls -la, lsof
Bash(git * main)git push origin main, git -c core.fsmonitor=<script> diff maingit log
  • Put the * after the subcommand. Everything before the first * is matched as written, so Bash(git log *) allows only git log while Bash(git *) allows every git command, including options like -c that run programs. Claude Code warns about an allow rule with a * before the subcommand. Bash(ls:*) equals Bash(ls *); :* works only at the end.
  • Compound commands are split on &&, ||, ;, |, |&, & and newlines. Deny and ask rules apply if any part matches (including inside $(...) and loops); allow needs every part covered. Approving a compound with "don't ask again" saves up to five per-subcommand rules.
  • Wrappers are stripped before matching: timeout, time, nice, nohup, stdbuf, command, builtin, noglob and flagless xargs. Runners such as npx, docker exec, direnv exec and devbox run aren't, so Bash(devbox run *) approves devbox run rm -rf .. A leading assignment of a known-safe variable (NODE_ENV=test npm test) is stripped for allow rules; deny and ask rules match past any assignment.
  • Built-in read-only commands (ls, cat, echo, pwd, head, tail, grep, find, wc, which, diff, stat, du, cd, read-only git) run without a prompt in every mode (in auto mode the classifier may still review them). Exceptions: a matching ask or deny rule (including a Read deny on a file argument, so cat .env is blocked by Read(./.env)), blockReadsOutsideWorkingDirectories for paths outside the working directories, and in Manual mode find -exec/-delete, a cd combined with git, and commands over 10,000 characters. Output redirects (> file) are checked against your Edit rules.
A Bash rule isn't a boundary around a programIt matches the command text Claude writes. Bash(rm *) in deny stops rm -rf build/, not /bin/rm -rf build/ or bash -c 'rm -rf build/'; Bash(git push *) doesn't stop git -C . push. For a hard limit on files and network, enable the sandbox (off by default; it covers shell commands only) or inspect commands in a PreToolUse hook. And "using WebFetch alone doesn't prevent network access. If Bash is allowed, Claude can still use curl".

Read and Edit rules

Path rules use gitignore syntax with four anchors. The single leading slash is the trap:

PatternAnchored atExample
//pathFilesystem rootRead(//Users/alice/secrets/**)
~/pathHome directoryRead(~/.zshrc)
/pathThe settings source: the primary working directory for project and local files, ~/.claude/ for user settingsEdit(/src/**/*.ts)
path or ./pathCurrent directoryRead(*.env)
  • A bare filename matches at any depth (Read(.env) = Read(**/.env)). A single-segment directory pattern such as src/** matches only ./src in an allow rule but any src directory in a deny or ask rule.
  • A Read deny also blocks Edit and Write on that path (Write needs v2.1.228+). An Edit allow also grants read. Only Read(...) and Edit(...) path rules are consulted: Write(docs/**) or Glob(src/**) are accepted but never checked, and Claude Code warns at startup.
  • In a deny list, a ! pattern carves out of the earlier patterns from the same file: Read(*.env) then Read(!sample.env).
  • "If your project has a .claudeignore file, it has no effect, so move its entries into Read deny rules."

Other tools

WebFetch(domain:example.com) (apex only) and WebFetch(domain:*.example.com) (subdomains only); mcp__github__* or mcp__github for a server, mcp__github__create_issue for one tool, "mcp__*" in deny for all MCP; Agent(Explore); Skill(deploy) and Skill(review-pr *); Cd(~/code/*) for /cd targets. Deny and ask rules can also match one top-level input parameter: Agent(model:opus), Agent(isolation:worktree), Bash(run_in_background:true). Unanchored allow globs such as "*" or "mcp__*" are skipped with a warning.

A sieve: the call drops as a token (a compound command splits into one token per subcommand), falls through the deny, ask and allow plates, and stops at the first rule that matches; anything no rule catches lands on the mode floor. Edit the three rule lists, pick a tool call and a mode, and evaluate. The matcher splits compound commands, strips the documented wrappers, applies deny → ask → allow per subcommand, honors read-only commands and path anchors, then falls back to the mode. Toy model of the documented behavior with the session in /work/app and rules from project settings; it skips hooks, the sandbox, workspace trust and the auto mode classifier's own judgment.

Where approvals go

In Manual mode, "Yes, and don't ask again" for a Bash command or a WebFetch domain is saved as an allow rule in .claude/settings.local.json at the git root and applies to future sessions anywhere in that repo. File-edit approvals last until the session ends. Two things trip people up: an allow rule saved locally doesn't outrank an ask rule from project or managed settings (ask beats allow), and "PreToolUse hook decisions don't bypass permission rules", while "a hook that exits with code 2 stops the tool call before permission rules are evaluated." Manage everything with /permissions (alias /allowed-tools), which lists each rule with the file it came from; /fewer-permission-prompts scans your transcripts for common read-only Bash and MCP calls and adds a prioritized allowlist to the project's .claude/settings.json, which you should review before committing.

Layered enforcement: what each layer actually guarantees

Think in layers, strongest last. CLAUDE.md shapes intent and guarantees nothing. Permission rules are deterministic, but Bash rules match text, so they cover "the invocation Claude usually produces". PreToolUse hooks see the full command and can parse it with your own logic; exit code 2 blocks even when an allow rule matches, and a hook deny "blocks the tool even in bypassPermissions mode". They fail open on timeout unless you set "onFailure": "block" (v2.1.295+), so don't use a timeout as policy. The sandbox is OS-level (Seatbelt on macOS, bubblewrap on Linux and WSL2) and applies to shell commands and their children whatever the command text says, but not to Claude's file tools, MCP servers or hooks. Read and Edit deny rules cover those file tools and the file commands Claude Code recognizes in Bash, not a script that opens files itself. "Use both for defense-in-depth."

One more boundary to know: a mod you install that handles tool.check answers after rules and hooks. With no managed settings and no Team or Enterprise /login, the docs say a mod can approve a call a deny rule refuses. On personal setups, audit mods like code you run, because they are. agents-5 · Guardrails builds a fail-closed guard hook on top of these layers.

Docs: permissions · rule syntax · sandboxing

Permission Modes

A permission mode sets the baseline for what runs without asking; rules layer on top. core-1 · First session introduces them; here is the configuration view.

Config valueStatus barRuns without asking
default (alias manual; labelled Manual)⏸ manual mode onReads only
acceptEdits⏵⏵ accept edits onReads, file edits, and mkdir, touch, rm, rmdir, mv, cp, sed in scope
plan⏸ plan mode onReads, plus classifier-approved commands when auto mode is available
auto⏵⏵ auto mode on"Everything, with background safety checks"
dontAsk⏵⏵ don't ask onReads in working directories and pre-approved tools; anything that would prompt is denied
bypassPermissions⏵⏵ bypass permissions onEverything. "Isolated containers and VMs only"

Which mode a session starts in

First match wins: --permission-mode (or --dangerously-skip-permissions for bypass) → permissions.defaultMode → the built-in default. The built-in default is auto for interactive terminal and VS Code sessions on v2.1.283+ (when auto mode is available to your plan, provider and model), and default for claude -p and the Agent SDK on v2.1.302+. For the SDK, the version of the Claude Code CLI it bundles decides this, not the SDK's own version number, so pass permission_mode / permissionMode explicitly (or point cli_path at a newer CLI); any settings file with disableAutoMode: "disable" forces default. Remember the file gates. defaultMode values auto and bypassPermissions don't take effect from project or local files, and the ignored value doesn't fall through to your user file: a repository "auto" leaves the session on the built-in default "rather than a defaultMode from ~/.claude/settings.json", and a repository "bypassPermissions" starts it in Manual. The VS Code extension reads only user, managed and --settings values for the starting mode, and cloud sessions honor only acceptEdits, plan, default and auto.

Press shift+tab to click the knob one detent; toggle bypass and auto availability to add or remove detents. From auto, the first press goes to Manual (default), then acceptEdits, then plan. Optional modes slot in after plan, bypass first and auto last; without bypass, plan goes straight back to auto, and when auto mode isn't available the cycle starts and ends at Manual. dontAsk never appears in the cycle: set it with --permission-mode dontAsk. To reach plan directly, type /plan.

How modes and rules combine

  • "Deny rules block in every mode, including bypassPermissions." "Allow rules have no effect in bypassPermissions."
  • No mode auto-approves an explicit ask-rule match, AskUserQuestion, MCP tools marked requiresUserInteraction, rm/rmdir of critical paths, or reads outside working directories under blockReadsOutsideWorkingDirectories. In dontAsk those are denied instead.
  • Entering auto mode drops broad allow rules: Bash(*), wildcarded interpreters such as Bash(python*), package-manager run commands, and Agent and Monitor allow rules, so the classifier sees those calls.
  • Protected paths (.git, .claude, .vscode, .husky, .mcp.json, .gitconfig, shell rc files and others) are never auto-approved except in bypass mode, and allow rules don't pre-approve them.
{
  "permissions": {
    "defaultMode": "acceptEdits",
    "disableBypassPermissionsMode": "disable"
  }
}
bypassPermissionsIt "offers no protection against prompt injection or unintended actions" and is refused when running as root on Linux and macOS. Use it only inside a container or VM with no credentials worth stealing. Auto mode is the middle ground for long tasks, and its docs say it "reduces permission prompts but does not guarantee safety". Lock bypass out with permissions.disableBypassPermissionsMode: "disable", ideally from managed settings.

Docs: permission modes · which mode a session starts in

Additional Directories

By default Claude's file tools work in the directory you launched from. Extend the working directories three ways: claude --add-dir ../shared at launch, /add-dir ../shared mid-session, or permissions.additionalDirectories in settings. Added directories follow the same rules as the original: reads without prompts, edits per the mode.

{
  "permissions": {
    "additionalDirectories": ["../payments-sdk/", "../docs/"]
  }
}

The key fact: adding a directory grants file access, not configuration. Most of its .claude/ isn't discovered, with a few exceptions that apply only to --add-dir and /add-dir, never to the settings key:

In the added directoryLoaded from --add-dir / /add-dir?
Skills in .claude/skills/Yes, with live reload
Commands in .claude/commands/, subagents in .claude/agents/Yes, without live reload
.claude/settings.json and settings.local.jsonOnly the enabledPlugins and extraKnownMarketplaces keys
CLAUDE.md, .claude/rules/, CLAUDE.local.mdOnly with CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1
  • A project file's additionalDirectories waits for workspace trust, like allow rules.
  • Resuming a session doesn't restore --add-dir or /add-dir directories; pass them again or use the settings key.
  • /cd <path> moves the session instead: the conversation stays, and (on v2.1.246+) the new directory's CLAUDE.md, project settings, hooks, .mcp.json, skills and agents apply, with a trust prompt if it's new. Cd(...) rules restrict where /cd may go.
  • permissions.blockReadsOutsideWorkingDirectories: true (v2.1.257+) makes the file tools refuse paths outside these directories in every mode, including bypass, and tells Claude to ask you for /add-dir. A true in any file applies.
  • Most network paths, such as a UNC share, can't be added; on Windows map them to a drive letter.
Sibling repos in a polyrepoTo work across app/ and sdk/ with both sets of instructions: CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../sdk. To share one team's skills with another repo, --add-dir is enough. For permanent cross-project configuration, prefer user-level files or a plugin.

Docs: working directories · what added directories load

Environment Variables

Set variables in your shell or in the env key of any settings file, which applies them to every session and every subprocess Claude Code starts. Precedence is per variable: a value in env overwrites the same variable exported in your shell, and when several files set it, the highest-precedence file wins. Set a variable to "" to cancel a shell export. When the Desktop app or a self-hosted runner launches the session, the launch environment wins instead.

  • Timing: user, --settings and managed values apply at startup; project and local values apply after you trust the workspace (at startup in -p, which never shows the dialog), except variables classified as safe, such as model selection and timeouts.
  • Repository files can't set some variables: CLAUDE_CONFIG_DIR, HOME, TMPDIR and the XDG_* family, OpenTelemetry exporter variables that turn telemetry on or point it elsewhere, CLAUDE_CODE_DISABLE_FILE_MENTIONS and others. Claude Code drops them with a warning visible in claude --debug.
  • No secrets in env: values are plain text and reach every subprocess. Use apiKeyHelper for API credentials and otelHeadersHelper for rotating telemetry tokens.
VariableContext effect
CLAUDE_CODE_AUTO_COMPACT_WINDOWCompaction threshold as a raw token count; beats /autocompact, --autocompact and autoCompactWindow
DISABLE_AUTO_COMPACT / DISABLE_COMPACTStop automatic compaction / all compaction
CLAUDE_CODE_DISABLE_1M_CONTEXTNative-1M models run a 200K window
CLAUDE_CODE_DISABLE_AUTO_MEMORYTurns auto memory off
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MDLoads CLAUDE.md and rules from --add-dir directories
ENABLE_TOOL_SEARCHtrue, auto, auto:N or false for MCP tool deferral
MAX_MCP_OUTPUT_TOKENSMCP result token cap (25,000 default)
BASH_MAX_OUTPUT_LENGTHCharacters read back from a command's output (30,000 default, 150,000 ceiling)
CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENSPer-call Read limit (25,000 default)
SLASH_COMMAND_TOOL_CHAR_BUDGETFixed character budget for the skill listing
CLAUDE_CODE_SUBAGENT_MODELModel for subagents that don't set one
CLAUDE_CODE_FORK_SUBAGENT0 turns fork mode off

Exercise: a team baseline plus your overrides

  1. Write a .claude/settings.json for your repo: allow your test, lint and read-only git commands; ask for git push; deny reads of .env* and secrets/**; add $schema.
  2. Write a .claude/settings.local.json that sets your preferred model and allows one personal command.
  3. Restart and run /status (Setting sources), then /permissions. Confirm each rule's source file.
  4. Ask Claude to cat .env, then to run git push. Note what happens in each case and why.
Show a solution

The cat .env request is refused by the Read(./.env) deny rule, because Read and Edit deny rules also apply to file commands Claude Code recognizes in Bash, such as cat. git push prompts even in auto mode, because no mode auto-approves an explicit ask rule. /permissions shows the deny and ask rules from .claude/settings.json and your personal allow from .claude/settings.local.json. If the team allow rules don't seem to apply, check workspace trust: in a fresh clone they wait for the trust dialog, and a claude -p run uses them only if the folder was trusted before (interactively, or by hand: projects[…].hasTrustDialogAccepted in ~/.claude.json).

What you run: a resolver over five sample files (managed, --settings, local, project, user) that applies the documented precedence: scalars from the highest file, merged lists with each entry's source, fallbackModel taken whole, the strict-value security keys, keys a repository file can't set, and the workspace-trust gate. It can also evaluate a tool call against the merged rules.

cd labs && python3 core-2/settings_resolver.py
python3 core-2/settings_resolver.py --session headless        # what a claude -p run in a repo you never trusted gets
python3 core-2/settings_resolver.py --permission-mode default --call "Bash: npm run lint"
python3 core-2/settings_resolver.py --repo /path/to/your/repo --user ~/.claude/settings.json
python3 core-2/settings_resolver.py --self-test                # 15 documented start-mode cases

Observe: model resolves to the --settings value; disableClaudeAiConnectors ends up true although managed says false; the project's defaultMode: bypassPermissions, its autoMode block and modelPicker are listed as ignored with reasons; the start mode is default (Manual), because the project's bypassPermissions doesn't take effect and the user file's acceptEdits doesn't fill in for it, so rm -rf build prompts; git push origin main prompts because your local allow loses to the project's ask rule; with --session headless the project's allow rules disappear while its deny rules and hooks still apply.

Open the lab walkthrough

Docs: the env key · environment variables

Key takeaways

  • Managed → --settings → local → project → user. Scalars from the highest file, lists merge, a few security keys keep the strictest value, env vars decide per pair.
  • Project allow rules, additional directories and most env wait for workspace trust; -p never shows the dialog.
  • deny → ask → allow, first match wins, across all files. A bare deny removes the tool; a Bash rule matches text, not the program.
  • Path rules: // absolute, ~/ home, / relative to the settings source, bare relative to cwd. Only Read and Edit path rules are consulted.
  • Modes set the baseline, rules refine it, and deny and ask rules hold in every mode. Added directories grant file access, not configuration.

Skills

A skill is context on demand. Its name and description sit in a small listing every session; its body enters the conversation only when you or Claude invoke it. That makes skills the right home for procedures and reference material that matter sometimes, and the wrong home for facts Claude needs every turn. This topic is the user's view: finding, choosing, invoking and budgeting skills. Authoring in depth is in agents-3, and workflow skills in core-5.

What Skills Are

A skill is a folder with a SKILL.md: YAML frontmatter plus Markdown instructions, optionally with supporting files and scripts. Claude Code skills follow the Agent Skills open standard and add Claude Code extensions such as invocation control, running in a subagent and dynamic context injection. The docs say when to make one: "when you keep pasting the same instructions, checklist, or multi-step procedure into chat, or when a section of CLAUDE.md has grown into a procedure rather than a fact."

Custom commands have been merged into skills (v2.1.3). "A file at .claude/commands/deploy.md and a skill at .claude/skills/deploy/SKILL.md both create /deploy and work the same way." Command files keep working and accept the same frontmatter except name and paths; when both exist with one name, the skill wins. Old posts that run project commands as /project:deploy are out of date.

---
name: release-notes
description: Draft release notes from merged PRs since the last tag. Use when the user asks for release notes, a changelog entry or "what shipped".
disable-model-invocation: true
argument-hint: [since-tag]
allowed-tools: Bash(git log *) Bash(git describe *) Bash(gh pr list *)
---

Draft release notes for changes since $ARGUMENTS (default: the latest tag).

1. List merged PRs with `gh pr list --state merged --search "merged:>DATE"`.
2. Group them under Features, Fixes and Internal. Skip dependency bumps.
3. Write one line per change in the user's language, with the PR number.
4. Show the draft. Don't commit or publish anything.

How a skill reaches the window

Invoke to unfold the body, read a file to unfold again, compact to refold to the first 5,000 tokens; the toggles hide the flap (disable-model-invocation) or deliver the card unfolded (preloaded in a subagent). Only the listing entry is paid every turn, and not even that for skills with disable-model-invocation: true. The body arrives once per invocation and stays in the conversation; supporting files load only when Claude reads them.
  • Listing: by default each skill's description is always in context so Claude knows it exists.
  • Body: on invocation "the rendered SKILL.md content enters the conversation as a single message and stays there across later turns." Claude Code doesn't re-read the file later, so write guidance as standing instructions ("run the tests after every edit") rather than one-time steps. Keep SKILL.md under 500 lines; push detail into supporting files the body links to.
  • Exceptions: subagents with preloaded skills get the full body at startup, and context: fork runs the skill in a new subagent of the type set in agent, with the skill body as its prompt. Despite the name, that subagent doesn't see your conversation history, unlike a fork; use /subtask when the task needs the history. It runs in the background by default (v2.1.218+; background: false waits for the result). When it runs in the background (the default), rewinding restores only the files Claude had already edited in your conversation, and its edits to other files stay; with background: false it edits your working tree during your own turn, so /rewind restores its edits as usual (checkpointing).
For each instruction, pick the mechanism you'd use, then check. The answers follow the docs' guidance on CLAUDE.md, rules, skills, hooks and permissions.

Docs: skills · extend Claude Code: which mechanism when

Discovery and Descriptions

Where a skill lives decides which sessions load it:

LocationPathLoads in
Enterprise.claude/skills/<name>/SKILL.md in the managed settings directoryEveryone the org deploys it to
Personal~/.claude/skills/<name>/SKILL.mdAll your local projects (not Cowork or cloud sessions)
Project.claude/skills/<name>/SKILL.mdThis repo; found from the working directory up to the repo root
Nested<subdir>/.claude/skills/<name>/SKILL.mdOnce Claude works on files in <subdir>; a name clash shows as /apps/web:deploy
Additional directory.claude/skills/ in an --add-dir directoryThat session
Plugin<plugin>/skills/<name>/SKILL.mdWherever the plugin is enabled, as /plugin-name:skill-name
claude.ai accountSynced into ~/.claude/skills/synced/Cowork, cloud, and terminal sessions signed in with that account

On a name clash, enterprise beats personal beats project; a skill beats a command file; plugin skills never clash because they are namespaced. A skill in an --add-dir directory that clashes with one of yours (or with one from a directory added earlier) stays reachable under a prefixed name, such as /cli:verify for --add-dir ../cli (v2.1.309+). Your skill can replace a bundled or built-in command but not its aliases. Skill directories are watched for edits; a nested skill below the working directory doesn't appear in the / menu until Claude touches files there, or until you run /add-dir on that subdirectory (v2.1.257+). Cloud scheduled tasks don't read ~/.claude/skills/, so a personal-only skill is "not found" there: commit it to the repo or enable it on your claude.ai account.

The description is the trigger

Claude decides whether to use a skill from its description (plus when_to_use, if present; the first non-empty body line if both are missing). Every model-invocable skill pays for its entry in the skill listing on every turn:

  • "The budget scales at 1% of the model's context window." Every skill name is always listed, but on overflow Claude Code drops descriptions, "starting with the skills you invoke least", which removes the keywords Claude needs to match.
  • Each entry's combined description and when_to_use is capped at 1,536 characters regardless of budget (skillListingMaxDescChars). Put the key use case first.
  • Raise the budget with skillListingBudgetFraction (for example 0.02) or a fixed SLASH_COMMAND_TOOL_CHAR_BUDGET; free it with skillOverrides: "on", "name-only", "user-invocable-only" (hidden from Claude, still in your / menu) or "off". The /skills menu writes overrides for you (Space cycles, Esc saves to .claude/settings.local.json). Plugin skills aren't affected; manage them through /plugin.
  • /skill-doctor reports each skill's context cost and usage and flags never-invoked skills (the commands page says v2.1.252+, the changelog adds it at v2.1.261; use v2.1.261+ to be safe). The Skills row in /context shows the listing after the budget.
The drawing is the listing printout itself: the words your request shares with it are underlined, and descriptions the budget drops are struck through. Type a request and see which listing entries share the most meaningful words with it. Shrink the listing budget and watch least-invoked skills lose their descriptions. Toy model: Claude reads the listing and judges relevance; it doesn't count keywords. The point is what information survives in the listing.
Skill not triggering
  • Put the words users actually say in the description
  • Ask "What skills are available?" to confirm it's listed
  • Malformed YAML loads the body with empty metadata: /name works, matching doesn't. claude plugin validate .claude/skills (v2.1.233+) finds it
  • Invoke it directly with /skill-name
Skill triggers too often
  • Make the description narrower; say what it's for, not everything it touches
  • Add disable-model-invocation: true if only you should run it
  • Deny it for Claude with Skill(name) in permissions.deny

Docs: where skills load · listing budget · skillOverrides

Invoking Skills

You invoke a skill by typing /name at the start of your message. The same name later in plain text ("go ahead and /deploy to staging") doesn't run anything directly: it counts as your permission for that message, and Claude judges from the wording whether you asked for it. Arguments fill $ARGUMENTS, $ARGUMENTS[N] or $N; if the skill has no placeholder, Claude Code appends ARGUMENTS: <your input> so nothing you typed is lost. At the terminal you can stack skills (/write-tests /fix-issue 123 loads both, up to the first plus five more); through claude -p or the SDK only the first loads.

Claude invokes skills through the Skill tool. Two frontmatter fields decide who may:

FrontmatterYou can invokeClaude can invokeIn context
(default)YesYesDescription always; body when invoked
disable-model-invocation: trueYesNot on its ownDescription not in context; body when invoked
user-invocable: falseNoYesDescription always; body when invoked

Use disable-model-invocation for anything with side effects: "You don't want Claude deciding to deploy because your code looks ready." If Claude tries anyway, Claude Code blocks the call and tells it not to reproduce the steps another way, so expect a suggestion to run /deploy yourself. user-invocable: false suits background knowledge such as a legacy system's quirks.

Permissions around skills

  • allowed-tools pre-approves the listed tools for the turn that invokes the skill; the grant clears with your next message even though the content stays. It doesn't restrict other tools. "Workspace trust doesn't gate this field", even in a -p run in a folder you never trusted, so review allowed-tools in repository skills before running Claude Code there. Organizations can neutralize it with managed allowManagedPermissionRulesOnly (v2.1.282+).
  • disallowed-tools removes tools while the skill is active, until your next message.
  • Rules: Skill in deny disables all skills for Claude; Skill(commit) matches exactly; Skill(review-pr *) matches with any arguments; Skill(skill:deploy) matches the skill under any of its names.
Skills, turns and compactionA skill's body is a message like any other. After compaction, Claude Code re-attaches "the most recent invocation of each skill after the summary, keeping the first 5,000 tokens of each", within 25,000 tokens total, filled from the most recently invoked. Long skills lose their tails and old skills can vanish. If Claude stops following a skill: move must-hold rules into a hook (a skill can define one in its hooks frontmatter), word guidance for the whole task, put critical instructions near the top, or invoke the skill again.

Docs: who invokes a skill · allowed-tools · skill content lifecycle

Bundled Skills

Bundled skills ship with Claude Code. They are prompt-based (they hand Claude instructions and let it orchestrate the work with its tools), unlike most built-in commands, which run fixed logic. The commands reference marks them Skill. Claude invokes some automatically when relevant; others, such as /verify, run only when you ask.

SkillWhat it does
/doctor [prompt-audit [path]] (/checkup)Setup checkup that diagnoses installation, settings, extensions and CLAUDE.md, and proposes fixes; prompt-audit audits instruction files (v2.1.283+)
/code-review [low|…|max|ultra] [--fix] [--comment] (/review)Reviews the diff or a PR for correctness bugs
/simplify [target]Cleanup review with four parallel review agents, then applies fixes
/batch <instruction>Splits a large change into 5 to 30 independent worktree-isolated units
/debug [description]Turns on debug logging and troubleshoots from the session debug log
/loop [interval] [prompt] (/proactive)Runs a prompt repeatedly while the session stays open
/run, /verify, /run-skill-generatorLaunch the app, confirm a change in the running app, and record the launch recipe as a project skill
/claude-api [subcommand]Claude API and Managed Agents reference for your language; migrate, prompt-audit, cost-optimize, build-eval and more
/fewer-permission-prompts, /update-configBuild an allowlist from your transcripts; edit settings from a description
  • Override: a project skill named code-review replaces /code-review, but the bundled alias /review still runs the bundled one.
  • Pre-commit checks: when a session starts with a skill named verify or simplify from the enterprise, personal, project or additional-directory location, Claude Code's commit instructions tell Claude to run it before each commit, except for docs and test changes (v2.1.286+). The recipe that /verify records at your repo root counts.
  • Turn off: disableBundledSkills. /doctor stays typable; hide it with DISABLE_DOCTOR_COMMAND or "skillOverrides": {"doctor": "off"}.
Budget math for the skill listing (illustrative)

The skills docs give the rule ("scales at 1% of the model's context window") and the per-entry cap (1,536 characters), not a token-to-character conversion. Anthropic's models overview gives a rough one: "1M tokens is roughly 555k words or 2.5M Unicode characters on the current tokenizer" (models overview), so about 2.5 characters per token. On a 1M window, 1% is about 10,000 tokens, or roughly 25,000 characters of listing: about 125 skills at 200 characters each, or 16 skills that each use the full cap. On a 200K window (for example with CLAUDE_CODE_DISABLE_1M_CONTEXT=1) the same listing gets about 5,000 characters, and 25 skills with 200-character descriptions already fill it. A plugin that ships 30 skills with long descriptions can push your own skills' descriptions out.

Two consequences. First, a long description is a tax on every other skill: write the one sentence that selects the skill, then stop. Second, overflow drops the least-invoked descriptions first, so rarely used skills with vague names become invisible to automatic matching. Give them distinctive names, set them to "name-only" on purpose, or make them user-only. Measure instead of guessing: /skill-doctor and the Skills row of /context.

Exercise: a personal skill you'll actually use

  1. Find a prompt you've pasted three times this month. Turn it into ~/.claude/skills/<name>/SKILL.md with a one-sentence description that starts with the use case.
  2. In a new session, check it appears in /skills and the Skills row of /context. Ask for the task in your own words, without the name, and see whether Claude picks it.
  3. If it has side effects, add disable-model-invocation: true and confirm Claude now suggests /name instead of running it.
  4. Run /skill-doctor and set one unused skill to "name-only" or "off" in skillOverrides.
Show a solution
---
name: pr-summary
description: Summarize the current branch's changes as a PR description with Why, What and Risk sections. Use when asked to write or update a PR description.
argument-hint: [base-branch]
allowed-tools: Bash(git diff *) Bash(git log *)
---

Base branch: $ARGUMENTS (use `main` if empty).
Compare the current branch to the base with `git diff <base>...HEAD --stat` and `git log <base>..HEAD --oneline`.
Write: **Why** (one paragraph), **What** (bullets by area), **Risk** (what could break, how it was verified).
Don't push, comment or open anything.

The listing entry is the description: short, starting with what it produces and when. allowed-tools pre-approves only read-only git for that turn. Because it has no side effects it stays model-invocable; a variant that runs gh pr edit should set disable-model-invocation: true.

Docs: bundled skills · commands reference

Key takeaways

  • Skills are context on demand: the listing entry every turn, the body once per invocation, supporting files only when read.
  • Commands merged into skills; .claude/commands/x.md still creates /x, and a skill of the same name wins.
  • The listing budget is 1% of the window and 1,536 characters per entry; overflow drops the least-invoked descriptions. /skill-doctor and skillOverrides manage it.
  • /name runs only at the start of a message. disable-model-invocation: true for side effects. allowed-tools pre-approves for one turn and isn't trust-gated.
  • Bundled skills (/doctor, /code-review, /batch, /verify, /simplify …) are prompts you can override, but aliases keep pointing at the bundled one.

Tools

Every tool costs context twice: its definition sits in the request, and every result it returns stays in the conversation. Claude Code's built-in tools are tuned for this. Search runs through a shell, MCP definitions are deferred, and large outputs are bounded or saved to files. Knowing those mechanics lets you predict what Claude will see and steer it toward cheaper paths.

Built-in Tools

The built-in tools have canonical names, and those exact strings are what permission rules, hook matchers and subagent tools lists accept. The label in the transcript can differ: the tool shown as Stop Task is TaskStop, and a rule written against the label matches nothing. The tools reference is the source of truth; this is the map.

The built-in tools as a periodic table: each family is an element group, each tool a tile with a made-up symbol and its exact name. A dashed tile is absent by default on macOS, Linux and WSL; a lock superscript marks the tools whose Permission required column in the tools reference says yes (Manual mode, paths inside the working directory). Ask Claude "What tools do you have access to?" for your session's set, and run /mcp for exact MCP tool names. Hover or tab to a tile.
Rule formatApplies to
Bash(npm run *)Bash, Monitor
Read(~/secrets/**)Read, Grep, Glob, LSP
Edit(/src/**)Edit, Write, NotebookEdit
WebFetch(domain:example.com)WebFetch
Skill(deploy *), Agent(Explore)Skill, Agent
WebSearch, ExitPlanModeBare name only

Availability versus approval. --tools Read,Edit,Bash decides which built-in tools exist in the session; --allowedTools only pre-approves. A bare deny rule ("deny": ["WebSearch"]) removes a tool from Claude's context, which saves its definition tokens but changes the tool list, and denying a whole tool with tool search off invalidates the prompt cache. Restrict tools at the start of a session, not in the middle.

Parallel tool callsClaude can issue several tool calls in one turn. In the agent loop, read-only tools (Read, Glob, Grep, read-only MCP tools) run concurrently while Edit, Write and Bash run one at a time, which is why "read these five files" is fast and "run these five commands" isn't. See agents-1 · Tools.

Docs: tools reference · rule formats per tool

Web Tools

WebFetch takes a URL and a prompt. It fetches the page, converts HTML to Markdown, 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." It is "lossy by design": "a result that says a page doesn't mention something may only mean the prompt didn't ask about it." Fetch again with a more specific prompt, or use curl through Bash for the unprocessed page.

  • Reads up to 100,000 characters of content per call; on v2.1.290+ it tells Claude how much went unread so it can fetch the next part.
  • Caches each response for 15 minutes (CLAUDE_CODE_WEBFETCH_CACHE_TTL_MS, v2.1.233+); upgrades HTTP to HTTPS; doesn't follow a redirect to another host but reports it, so Claude fetches the target in a second call.
  • Refuses localhost and dotless hostnames, telling Claude to use curl for local servers.
  • In Manual and acceptEdits, prompts except for allowed domains and a built-in set of preapproved documentation domains, after a domain safety check. "Yes, and don't ask again for <domain>" saves WebFetch(domain:…) to settings.local.json. Turn it off entirely with CLAUDE_CODE_DISABLE_WEB_FETCH=1 (v2.1.285+).

WebSearch returns result titles and URLs from Anthropic's search backend and "doesn't fetch the result pages"; Claude follows up with WebFetch. One call may run up to eight backend searches. Scope with allowed_domains or blocked_domains (not both). An interactive session gets 200 calls, shared with subagents; on v2.1.290+ the allowance refills at about 100 an hour, /clear resets it, and CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION raises it. It isn't available on Amazon Bedrock; for another provider, add an MCP server.

Web content is untrusted inputFetched pages can carry instructions aimed at Claude. WebFetch's extraction step and Claude Code's prompt-injection safeguards reduce the risk; they don't remove it. Network control also needs more than WebFetch rules: "If Bash is allowed, Claude can still use curl, wget, or other tools to reach any URL." curl and wget aren't auto-approved by default. For a real boundary, use deny rules for the network tools plus the sandbox's network allowlist (sandbox.network.allowedDomains), which a WebFetch(domain:…) rule also feeds.
{
  "permissions": {
    "allow": ["WebFetch(domain:docs.python.org)", "WebFetch(domain:*.readthedocs.io)", "WebSearch"],
    "deny":  ["Bash(curl *)", "Bash(wget *)"]
  }
}

Research workflows (search, fetch, research subagents, MCP context providers) are the subject of core-3 · Research.

Docs: WebFetch · WebSearch · WebFetch rules

Tool Output Limits

Tool results are the fastest-growing part of most sessions, so Claude Code bounds each one. The pattern is consistent: small results inline, large results saved to a file in the session directory with a short preview, so Claude can read or search the rest only if it needs to.

ToolInline limitBeyond itKnobs
Read25,000 tokens per callWhole file over the token limit: first page plus a PARTIAL view notice. Over 256KB: error telling Claude to page with offset/limit or use GrepCLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS; allow_large: true sizes the read against the remaining window (v2.1.296+)
Bash, valid result~30,000 charactersFile path (truncated past 64 MiB) plus a preview of the first 2,000 charactersbashOutputMaxChars up to 128,000 (v2.1.261+)
Bash, failure~10,000 charactersHead-and-tail excerpt of that size, no file pathBASH_MAX_OUTPUT_LENGTH widens the read-back window (30,000 default, 150,000 ceiling), not the inline ceiling
MCP toolWarning above 10,000 tokens; cap 25,000 tokensSaved to a file in the session's tool-results directory; text over 50,000 characters is saved whatever its token countMAX_MCP_OUTPUT_TOKENS; server-side anthropic/maxResultSizeChars up to 500,000
MCP error result~11,000 charactersFirst 5,000 and last 5,000 characters with a marker
WebFetch100,000 characters of page per callClaude is told how much went unread (v2.1.290+)The extraction prompt
Glob100 filesTruncation flagNarrow the pattern

A Bash command's output streams to a working file; a command whose output passes 5 GB is killed. Hook output (additionalContext, systemMessage, plain stdout) is capped at 10,000 characters and spilled to a file with a 2,000-character preview. Piped stdin to claude -p is capped at 10MB.

Every tool's cut points on one log ruler, from 1 character to 64 MiB; the output's size is the cursor, and the zone it lands in on your tool's row names what Claude gets. Choose a tool, an outcome and an output size. The simulator applies the documented thresholds and shows what lands in context. Token counts are estimated at about 2.5 characters per token, the models overview's rough figure for current models, so they're approximate.
Why spill-to-file beats truncation, and when it doesn't help

Truncating an output loses information silently: the model can't know what it didn't see. Saving the full result to a file and returning a path plus a preview keeps everything retrievable and lets Claude decide whether to grep the file, read a range, or ignore it. The same design appears in the API-level guidance on tool results and in the cookbook's context-engineering recipe: return references, not payloads.

Two cases defeat it. A failing Bash command gets a head-and-tail excerpt with no file path, so a 40,000-line stack trace keeps its beginning and end and loses the middle; rerun with a narrower command (one test, 2>&1 | grep -A20 Error). And a non-benign exit 1 (for example jq -e finding nothing, cmp on different files) is classified as a failure even when you consider it informational, so it takes the 10,000-character path. Raising limits is a trade: bashOutputMaxChars: 128000 means a single noisy command can add about 32K tokens to every later request in the session.

Exercise: measure the cost of your tools

  1. Run /context in a session with your usual MCP servers. Note the MCP tools and deferred rows.
  2. Exit and relaunch with ENABLE_TOOL_SEARCH=false claude. Run /context again and compare.
  3. Ask Claude to run your full test suite with default output. Check the Messages row. Then /rewind, and ask for the same run through a subagent that reports only failures. Compare again.
  4. On macOS or Linux, run claude --tools Read,Grep,Glob,Bash and ask for a codebase search; notice whether Claude now uses the Grep tool.
Show a solution

With tool search on, MCP servers contribute names and instructions (often under a few thousand tokens) and their schemas appear as deferred. With ENABLE_TOOL_SEARCH=false, every schema loads upfront, commonly tens of thousands of tokens for a few large servers, paid on every turn. The verbose test run usually adds more to Messages than all your memory files combined, while the subagent version adds only its summary. Naming Grep and Glob in --tools restores them, and hooks matching Grep start firing.

Docs: Bash output limits · Read limits · MCP output limits

Key takeaways

  • Rules, hooks and subagent tool lists use canonical tool names. --tools sets availability; --allowedTools only pre-approves.
  • Glob and Grep are absent by default on macOS, Linux and WSL: searches are Bash calls to embedded bfs and ugrep.
  • WebFetch returns an extraction, not the page; WebSearch returns titles and URLs. WebFetch rules don't stop curl.
  • Tool search defers MCP schemas by default; auto loads them upfront only under 10% of the window; alwaysLoad overrides per server.
  • Large results go to files with previews; failing Bash output gets an excerpt with no file. Shape output before it arrives.

Subagents

A subagent is context isolation you can call. It works in its own window and hands back a summary, so the file reads and logs it needed never enter yours. That is a context saving, not a cost saving: the subagent spends tokens of its own. This topic covers the built-in subagents, how delegation happens, exactly what crosses the boundary, and when staying in the main conversation is the better call. Writing your own agents is agents-4.

Built-in Subagents

Claude Code registers a set of subagents in every interactive session and delegates to them on its own. Each inherits the parent conversation's permission rules; most run with a restricted tool set.

AgentModelToolsUsed for
ExploreThe main conversation's model. When the main model is Fable, Explore runs on the opus alias model with a subscription, Console account or LLM gateway; it stays on the main model on Bedrock, Agent Platform, Foundry, Claude Platform on AWS or a Claude apps gatewayRead-only; Write and Edit deniedFile discovery and code search at a thoroughness of quick, medium or very thorough
PlanInherits the main modelRead-onlyCodebase research during plan mode, so exploration stays out of the read-only main thread
general-purposeCLAUDE_CODE_SUBAGENT_MODEL if set and nothing else assigns one, otherwise the main modelEvery tool available to subagentsMulti-step work that needs both exploration and changes
claudeNone of its ownEvery subagent toolCatch-all; default agent for dispatched background sessions
statusline-setupSonnet/statusline
claude-code-guideHaikuQuestions about Claude Code itself

Explore and Plan start without your CLAUDE.md files and the git status snapshot "to keep research fast and inexpensive". Other built-in and custom subagents load both, unless a custom one sets omitClaudeMd: true. A user or project subagent named Explore overrides the built-in and keeps its own model, which is the documented way to run exploration on a cheaper model. Your file's body then replaces the built-in system prompt, so write it carefully. The example lists Grep and Glob without Bash on purpose: on macOS, Linux and WSL those two tools exist only when a subagent leaves Bash out, and the agent stays strictly read-only.

---
name: Explore
description: Fast read-only codebase search. Use for finding files, symbols, callers and conventions without making changes.
tools: Read, Grep, Glob
model: haiku
---

You search and summarize; you never modify files.
Return: the answer first, then a list of `path:line` references, at most 300 words.
If the answer is uncertain, say what you checked and what you didn't.

Turning them off

  • One type: "permissions": {"deny": ["Agent(Explore)"]}. All delegation: deny Agent.
  • Only Explore and Plan: CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1 (v2.1.198+); Claude then reads files directly.
  • In -p and the SDK: CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1 removes all built-in types so only yours remain.
/agents is not a wizard anymore/agents now "prints a reminder to ask Claude or edit .claude/agents/ and ~/.claude/agents/ directly"; the interactive wizard existed on v2.1.197 and earlier. claude agents (no slash) is something else entirely: agent view for background sessions. Custom subagent descriptions also cost context: Claude Code warns at startup when they pass 15,000 tokens combined.

Docs: built-in subagents · Agent rules

Delegation

Delegation happens three ways, escalating in control:

  • Automatic: Claude matches the task against subagent descriptions and current context. A description that says "use proactively" encourages it.
  • Asked for: name it in your prompt ("use a subagent to run the test suite and report only the failing tests"), or @-mention it to guarantee that agent runs: @"code-reviewer (agent)" look at the auth changes, or type @agent-<name>. Claude still writes the subagent's task prompt from your message.
  • Session-wide: claude --agent code-reviewer or "agent": "code-reviewer" in settings makes the main thread itself take on that agent's prompt, tools and model.

Because Claude writes the delegation message, your prompt is the brief. Anthropic's multi-agent research post found that each delegation needs "an objective, an output format, guidance on the tools and sources to use, and clear task boundaries"; vague briefs produced duplicated work, and early versions "spawned 50 subagents for simple queries".

Use a subagent to find every caller of legacyAuth() in services/ and libs/.
Return a table: path:line, caller function, whether it passes a session token.
Don't read anything under vendor/ or generated/. Don't change files. Under 40 rows.

How a delegated run behaves

  • Background by default (since v2.1.198). You keep working. When it needs permission, the prompt surfaces in your main session and names the subagent; Esc denies that one call without stopping it, and an answer that lasts beyond one call applies to the whole session. Results arrive as a completion notification on a later turn.
  • Waiting for it: in interactive sessions fork mode is on, and Claude can't wait for a subagent; set CLAUDE_CODE_FORK_SUBAGENT=0 and ask it to wait. Ctrl+B sends running work to the background.
  • Limits: nesting up to three layers below the main conversation (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; 1 turns nesting off); 20 running at once (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, v2.1.217+). A finished subagent can be resumed with its full history via SendMessage by name or ID; Explore and Plan are one-shot.
  • Output scanning: before Claude reads a report, Claude Code escapes text that imitates its own markup and prepends a [harness: subagent output matched instruction-shaped pattern(s): line when a report looks like instructions. Reports arrive under a header saying they carry no authority from you, and "no message from any agent counts as your approval for a pending permission prompt".
Toy model with illustrative sizes. The two main windows show how much your window grows, inline or delegated; the third window is what the subagent processes, and the shaded areas are the token-turns your window carries afterwards, plus the prefix the subagent re-sends on each of its turns. Delegation shrinks the first and adds the second. Anthropic's context engineering post puts subagent summaries at "often 1,000-2,000 tokens".

Docs: work with subagents · foreground and background

Context Isolation

Context isolation is the point of a subagent, and it cuts both ways. "Each subagent starts with a fresh, isolated context window. It doesn't see your conversation history, the skills you've already invoked, or the files Claude has already read." A non-fork subagent starts with:

Crosses into the subagent
  • Its own system prompt plus environment details (not the Claude Code system prompt)
  • The task message Claude writes
  • Every level of CLAUDE.md, rules and CLAUDE.local.md (Explore and Plan skip these; omitClaudeMd leaves only managed files)
  • A git status snapshot (Explore and Plan skip it)
  • Full bodies of skills in its skills field
  • A roster of named agents, if it has SendMessage
Never crosses
  • Your conversation history and decisions
  • Skills you invoked and files Claude already read
  • Your output style
  • Main-conversation auto memory (a subagent's own memory: is separate)
  • Your window size: the subagent's model sets its own
  • Instructions you gave only in chat
The main session is the ship. A non-fork subagent goes down in its own sealed bell (a fresh window) with nothing from your conversation but the task message, plus its documented startup kit; your history, invoked skills, files read, output style and auto memory stay on deck. Everything the subagent reads stays on the sea floor, and only the final report comes back up the cable. A fork is the exception: it starts from a copy of the whole conversation. Toggle fork or Explore/Plan to change what goes down.

The practical rule from the docs: "If a rule must [reach the subagent], such as 'ignore the vendor/ directory,' restate it in the prompt you give Claude when delegating." Rules in CLAUDE.md reach most subagents automatically. Explore and Plan skip the startup CLAUDE.md files, though a subdirectory's CLAUDE.md and matching path-scoped rules still load when they work with files there. Conversation-only rules reach none.

Forks: isolation of output, not input

A fork "inherits everything the main session has at the moment it spawns": system prompt, tools, model and full history. Its own tool calls still stay out of your window and only its result returns. Because its system prompt and tools are identical, "its first request reuses the parent's prompt cache", so a fork is cheaper than a fresh subagent for tasks that need the same context. A fresh subagent has a separate cache. By default, on a Claude subscription within plan usage, subagent and fork requests get the 5-minute cache lifetime while the main conversation gets an hour (a fork's first request still reads the parent's cache); subagentPromptCacheTtl: "1h" (v2.1.242+) changes that bucket. See prompt caching. Start a fork with /subtask <task>; Claude starts them itself while fork mode is on (the default in interactive terminal sessions since v2.1.232). Forks can't spawn forks; block them with Agent(fork) in deny.

ForkFresh subagent
Starts withThe full conversationIts definition plus the task message
System prompt and toolsSame as mainFrom its definition
ModelSame as mainFrom its model field (or the documented order)
Prompt cacheShared with mainSeparate
Best forSide tasks that need everything said so far; parallel attempts from one pointNoisy, self-contained work; fresh-eyes review; tool restrictions
Delegation economics: context saved versus tokens spent

The research post reports that "agents typically use about 4× more tokens than chat interactions, and multi-agent systems use about 15× more tokens than chats", and the costs docs warn that "running several sessions or subagents at once multiplies token usage." Delegation pays off when the main thread would otherwise carry the subagent's reads for the rest of the session. A rough model (illustrative): exploring inline adds R tokens of reads that are re-sent on every later turn, so they cost about R × T over T remaining turns (mostly as cache reads). Delegating costs the subagent's own work (its system prompt, task message and the same R reads, about 65K of new input in this example) plus its own per-turn re-sends: the subagent also runs many turns and re-sends its growing prefix each time, mostly as cache reads on its own cache. The main thread then carries only a summary S for T turns. With R = 60K, S = 1.5K and T = 30, the main thread carries 45K instead of 1.8M token-turns. The saving in attention and window room is large; the saving in money depends on cache rates and is smaller than it looks.

Two qualitative costs don't show in the arithmetic. Summaries lose nuance (the research post's fix is to have subagents write full results to files and return references, to avoid "a game of telephone"). And the parent must verify what comes back: ask for path:line evidence or command output, not conclusions.

Docs: what loads at startup · forks

When Not to Delegate

The sub-agents docs give the decision directly. Use the main conversation when:

  • "The task needs frequent back-and-forth or iterative refinement"
  • "Multiple phases share significant context, such as planning, implementation, and testing"
  • "You're making a quick, targeted change"
  • "Latency matters. A subagent that isn't a fork starts fresh and may need time to gather context"

Use subagents when the task produces verbose output you don't need in the main context, when you want to enforce tool restrictions or permissions, and when the work is self-contained and can return a summary. Two neighbors cover the rest: skills "when you want reusable prompts or workflows that run in the main conversation context", and /btw "for a question about something already in your conversation."

✗ Delegation that backfires

"Have a subagent implement the feature we've spent an hour designing." It starts without the design discussion, re-reads half the repo, makes choices you already rejected, and returns a summary you must now verify line by line.

✓ Delegation that pays

"Run the integration suite and report only failures with their first error line." Or: "Review my diff against the spec in SPEC.md with fresh eyes; list only correctness issues with path:line." Self-contained, noisy or bias-prone work with a crisp return format.

  • Coupled work parallelizes poorly. Several subagents editing interdependent files produce merge conflicts and contradictory choices. Split along file boundaries or don't split (see core-4 · Parallel work).
  • Every report returns to your window. "Running many subagents that each return detailed results can consume significant context." Cap the length in the brief.
  • Usage is shared. Subagents count toward the same usage limits as your conversation.
  • Fresh eyes are a feature. A reviewer subagent that never saw the implementation discussion avoids the self-praise bias of reviewing your own work, which is one of the best uses of isolation.
For each task choose the main conversation, a subagent, a fork (/subtask), /btw or a skill, then check.

Exercise: one delegation, measured

  1. In a repo with a slow or verbose test suite, run /context and note Messages.
  2. Prompt: "Use a subagent to run the full test suite. Report only failing tests as file::name: first error line, max 30 lines." Keep working while it runs; answer any permission prompt it surfaces.
  3. When the report arrives, run /context again. Then ask Claude to verify one reported failure by running only that test.
  4. Finally, ask for a fresh-context review: "Use a subagent to review git diff main for correctness issues only; return path:line and a one-line reason each." Compare its findings to what you expected.
Show a solution

Messages grows by roughly the size of the report plus a little metadata, not by the test log. The verification run should reproduce at least one reported failure; if it doesn't, the report was wrong, which is why you verify. The review subagent works without your design conversation, so it may flag intentional choices; keep the brief to correctness against a written spec and cap review rounds (the best-practices guidance is about three) so the loop converges.

Docs: subagents vs main conversation · best practices

Key takeaways

  • Built-ins: Explore (read-only search, quick/medium/very thorough), Plan, general-purpose, claude, statusline-setup, claude-code-guide. Explore and Plan skip CLAUDE.md and git status.
  • Your prompt is the brief: objective, scope, exclusions, output format and a length cap.
  • Only the task message goes in and only the report comes out; chat-only rules don't cross. Forks inherit everything and share the parent's cache.
  • Subagents run in the background by default; their prompts surface in your session; their reports still land in your window.
  • Stay in the main conversation for iterative, shared-context, quick or latency-sensitive work; use /btw for questions about what's already known.

Session wrap-up

Every topic in this session controls the same object: the request Claude Code builds on each turn. Memory decides what stable instructions sit at the top of it. Session commands decide how much history it carries and what survives a rewrite. Settings decide what the harness enforces and which sources load at all. Skills, tools and subagents decide how much of the work's raw material enters the window, and when. The common discipline: load what every turn needs, load on demand what some turns need, push noisy work out, and enforce what must hold.

Three habits to keep
  • Look before you guess: /context, /status (Setting sources), /permissions and /memory answer most "why is it doing that?" questions.
  • Advice versus enforcement: CLAUDE.md, rules, skills and memory shape intent; permission rules, hooks and the sandbox guarantee outcomes. Put each instruction in the weakest layer that's strong enough.
  • Conclusions, not transcripts: shape tool output, delegate noisy work with a crisp brief, /clear between tasks and compact at natural breaks.
Where this goes next

Labs index

LabRunTopic
core-2/claudemd_lint.py: lint an instruction stack (length, imports, vague rules, must-rules that belong in hooks)cd labs && python3 core-2/claudemd_lint.pyMemory
core-2/rules_match.py: which .claude/rules files load for a given pathcd labs && python3 core-2/rules_match.pyPath-scoped rules
core-2/settings_resolver.py: merge five settings scopes and print effective permissions with sourcescd labs && python3 core-2/settings_resolver.pySettings

All three run offline with sample files and the Python standard library (no claude binary, no network). Point them at your own files with --repo (lint and settings) or --project (rules). They are read-only; settings_resolver.py --json writes its report to labs/core-2/out/.

What to do next

  1. Run /context at the start of your next three sessions and write down your fixed overhead. Cut the largest controllable row.
  2. Do the Memory and Settings exercises on your main repository; commit the reviewed .claude/settings.json and the trimmed CLAUDE.md together.
  3. Turn one repeated prompt into a skill, and route one noisy task to a subagent with a capped brief.
  4. Continue with core-3, which decides what content deserves the context you've just learned to manage.