The context window depends on the selected model and provider. Opus 5.5, Sonnet 5.5 and Fable 5.1 have native 1M-token windows on the direct API; Haiku 4.5 has 200K. Inspect /context for the active session. Capacity does not guarantee that every detail will be retrieved reliably.
These are workflow heuristics, not product states or automatic-compaction triggers. Inspect /context; recovery depends on the model, settings and retained content.
Zone
Usage
Action
🟢 Green
0-50%
Work freely
🟡 Yellow
50-75%
Start being selective
🔴 Red
75-90%
Review relevance and consider /compact
⚫ Critical
90%+
Preserve state and assess compaction or a new session
Aims to preserve relevant context, but can omit details
Reduction varies with the conversation; no fixed percentage is guaranteed
When /compact goes wrong: Compaction fires when the model has the most accumulated context, meaning it is also at its most distracted point. If the model cannot predict where the work is heading (e.g., auto-compact fires mid-debugging and your next message is “now fix that warning in bar.ts”), it may drop future-relevant info from the summary. Mitigate by compacting proactively and with context: /compact focus on the auth refactor, drop the test debugging guides the summary toward what matters next. (Source: Anthropic internal guidance)
Option 2: Clear (/clear)
Resets the active conversation
Does not delete saved session history or project instruction files
“One Task, One Chat”: mixing unrelated topics across turns degrades model accuracy by ~39%. Context accumulates noise (“context rot”) that distorts judgment even when total token usage stays low. Use /clear aggressively between distinct tasks, not just when the context bar turns red.
Option 3: Summarize from here (v2.1.32+)
Use /rewind (or Esc + Esc) to open the checkpoint list
Select a checkpoint and choose “Summarize from here”
Claude summarizes everything from that point forward, keeping earlier context intact
Frees space while keeping critical context
More precise than full /compact
Option 4: Targeted Approach
Be specific in queries
Avoid “read the entire file”
Use symbol references: “read the calculateTotal function”
When approaching the red zone (75%+), /compact alone may not be enough. You need to actively decide what information to preserve before compacting.
Priority: Keep
Keep
Why
CLAUDE.md content
Core instructions must persist
Files being actively edited
Current work context
Tests for the current component
Validation context
Critical decisions made
Architectural choices
Error messages being debugged
Problem context
Priority: Evacuate
Evacuate
Why
Files read but no longer relevant
One-time lookups
Debug output from resolved issues
Historical clutter
Long conversation history
Summarized by /compact
Files from completed tasks
No longer needed
Large config files
Can be re-read if needed
Pre-Compact Checklist:
Document critical decisions in CLAUDE.md or a session note
Commit pending changes to git (creates restore point)
Note the current task explicitly (“We’re implementing X”)
Run /compact to summarize and free space
Pro tip: If you know you’ll need specific information post-compact, tell Claude explicitly: “Before we compact, remember that we decided to use Strategy A for authentication because of X.” Claude will include this in the summary.
Explicitly saved with write_memory("key", "value")
Survives across sessions
Ideal for: architectural decisions, API patterns, coding conventions
Pattern: End-of-Session Save
# Before ending a productive session:
"Save our authentication decision to memory:
- Chose JWT over sessions for scalability
- Token expiry: 15min access, 7d refresh
- Store refresh tokens in httpOnly cookies"
# Claude calls: write_memory("auth_decisions", "...")
# Next session:
"What did we decide about authentication?"
# Claude calls: read_memory("auth_decisions")
When to use which:
Session memory: Active problem-solving, debugging, exploration
Auto-memory: Decisions and context you want Claude to rediscover next session without manual effort (v2.1.59+)
Persistent memory (Serena): Structured key-value store for architectural decisions across many projects
CLAUDE.md: Team conventions, project structure (versioned with git)
Auto-compact and PostToolUse memory capture: a conflict to know about:
Claude Code auto-compacts the conversation when the remaining context drops below a fixed buffer threshold (roughly the last 6-7% of the context window, or about 13K tokens from the effective limit). In practice, this triggers somewhere in the 90-95% usage range depending on the model’s context window and reserved output tokens. Before full compaction runs, Claude Code also applies micro-compaction: a lighter pass that selectively compresses older tool results (file reads, bash outputs, search results) to free space incrementally without summarizing the whole conversation. If auto-compact fails (e.g., due to a rate limit), it retries up to 3 consecutive times before giving up for that session.
If you use a hook-based memory capture tool (like claude-mem) that saves session history via PostToolUse, auto-compact can fire and discard conversation history before the save pipeline has a chance to capture it.
Two ways to handle this:
// Option 1: disable auto-compact in your project settings.json
// (you manage compaction manually via /compact)
{
"autoCompactEnabled": false
}
Terminal window
# Option 2: keep auto-compact on, but set your tool's save threshold
# to trigger well below 80% (e.g., at 60% context usage)
# — check your memory plugin's cooldowns/threshold config
Option 1 gives full control but requires discipline. Option 2 is safer if you forget to compact manually. The general guide advice (use /compact proactively at 75%) still applies. Auto-compact disabled just means you own the timing.
Research shows LLM performance degrades significantly with accumulated context:
20-30% performance gap between focused and polluted prompts (Chroma, 2025)
Degradation starts at ~16K tokens for older Claude models (Chroma, 2025); Anthropic reports noticeable degradation around 300-400K tokens on the 1M context window (task-dependent, not a fixed threshold)
Failed attempts, error traces, and iteration history dilute attention
Instead of managing context within a session, you can restart with a fresh session per task while persisting state externally.
Naming note: “Ralph Loop” is used in two distinct ways in the community. Geoffrey Huntley’s original pattern (above) is about context rotation: spawning fresh sessions to avoid context rot. A separate usage, popularized by Addy Osmani and others in 2026, applies the same term to atomic task iteration in multi-agent teams: pick task → implement → validate → commit → reset context → repeat. Both share the same core mechanic (stateless loop with external state), but the scope differs. When the term appears without attribution, clarify which variant is meant.
State persists via:
TASK.md: Current task definition with acceptance criteria
PROGRESS.md: Learnings, completed tasks, blockers
Git commits: Each iteration commits atomically
Variant: tasks/lessons.md
A lightweight alternative for interactive sessions (no loop required): after each user correction, Claude updates tasks/lessons.md with the rule to avoid the same mistake. Reviewed at the start of each new session.
tasks/
├── todo.md # Current plan (checkable items)
└── lessons.md # Rules accumulated from corrections
The difference from PROGRESS.md: lessons.md captures behavioral rules (“always diff before marking done”, “never mock without asking”) rather than task state. It compounds over time. The mistake rate drops as the ruleset grows.
Tasks with clear success criteria (tests pass, build succeeds)
Poor fit:
Interactive exploration
Design without clear spec
Tasks with slow/ambiguous feedback loops
Variant: Session-per-Concern Pipeline
Instead of looping the same task, dedicate a fresh session to each quality dimension:
Plan session: Architecture, scope, acceptance criteria
Test session: Write unit, integration, and E2E tests first (TDD)
Implement session: Code until all linters and tests pass
Review sessions: Separate sessions for security audit, performance, code review
Repeat: Iterate with scope adjustments as needed
This combines Fresh Context (clean 200K per phase) with OpusPlan (Opus for review/strategy sessions, Sonnet for implementation). Each session generates progress artifacts that feed the next.
Note: Anthropic announced a separate monthly credit for programmatic usage (claude -p, the Agent SDK, third-party apps) due on June 15, 2026, then paused it. As verified on 2026-09-30, that usage still draws from your subscription’s usage limits. See §9.13: The Interactive/Programmatic Billing Split for the announced plan and audit steps, and AI FinOps for the cost section as a whole.
Claude Code usage can draw from a subscription allowance, usage credits or API billing. Check the active account and billing path before interpreting a token-cost estimate.
Claude Code v2.1.280 and later defaults to Opus 5.5 on Pro, Max, Team, Enterprise, the Anthropic API, Claude Platform on AWS, Bedrock, and Google Cloud’s Agent Platform. Microsoft Foundry retains Sonnet 4.5 as its account default. Organization policy, model settings, and environment overrides can change the result. Check /model and /status for your session.
Model
Input / MTok
Output / MTok
Cache read / MTok
Context
Default effort in Claude Code
Opus 5.5
$4
$20
$0.20
1M
medium
Sonnet 5.5
$2
$10
$0.20
1M
high
Haiku 4.5
$1
$5
$0.10
200K
No effort parameter
Fable 5.1
$10
$50
$0.25
1M
high
These are standard Anthropic API rates in USD, checked October 6, 2026. Subscription allowances, usage credits, cache writes, batch discounts, data residency, and partner-operated cloud pricing are separate. Sonnet 5.5 (claude-sonnet-5-5) replaced Sonnet 5 as the default Sonnet on the Anthropic API in Claude Code v2.1.284 (September 28, 2026) at the same $2/$10; Sonnet 5 is now a legacy model, and the September increase once announced for it did not occur. Official model pricing.
Fast mode supports Opus 5.5 ($8/$40 per MTok), Opus 5 and Opus 4.8 ($10/$50). It is unavailable on Sonnet and Haiku. Anthropic describes up to 2.5 times faster output; this is not a guarantee for every request. Subscription fast mode uses usage credits. Fast mode reference.
Fable 5.1 is available by explicit selection, subject to account and organization access. It is not an account-type default. Previous-generation model prices belong to the official legacy pricing table, not to the current default rows above.
Opus 5.5, Sonnet 5.5, and Fable 5.1 have native 1M context on the Anthropic API. The older Opus 4.6 and Sonnet 4.6 use a [1m] variant with plan-specific access. Gateway and cloud-provider settings can expose a different window; inspect /context and the provider rules.
The current native 1M models use their standard rates beyond 200K input tokens. Old beta-header and long-context premium advice for Sonnet 4/4.5 must not be applied to them. Maximum output is 128K for Opus 5.5, Sonnet 5.5, and Fable 5.1, and 64K for Haiku 4.5. Model specifications.
Illustrative token bills, not measured session costs, without caching or retries:
Example
Input
Output
Sonnet 5.5
Opus 5.5
Bounded review
50K
5K
$0.15
$0.30
Module refactoring
150K
20K
$0.50
$1.00
Large-context analysis
500K
50K
$1.50
$3.00
A larger window is capacity, not a guarantee of retrieval or reasoning quality. Load relevant context and evaluate the complete task. Earlier Opus 4.6 and Sonnet 4.5 retrieval measurements describe those models and their benchmark conditions; they do not establish performance for the current lineup.
Native 1M sessions normally auto-compact around 967K tokens. Use /autocompact auto to restore the model default, or /autocompact 500k to choose a smaller window. Compact or start a new session when accumulated context hurts the task, rather than treating a fixed percentage as a universal accuracy threshold.
Claude Code manages prompt caching without any configuration on your part. Understanding the mechanics helps you make decisions that keep cache hit rates high and costs low.
Cache prefix hierarchy
Every API call Claude Code makes structures content in this fixed order: tools → system → messages. Cache matching always starts from the beginning of this prefix. A stable tool list + stable CLAUDE.md + growing conversation history means the first two layers are almost always cache hits, while only new message turns require fresh computation.
The 20-block lookback: the long-session trap
Cache matching uses a bounded lookback of approximately 20 blocks. In a long session with many tool calls and exchanges, blocks from early in the conversation fall outside this window and become cache misses. Practical consequence: very long sessions gradually lose cache efficiency at the message layer. The fix is /compact: it compresses the conversation history into a single summary block, resetting the lookback window and restoring high hit rates.
Minimum token thresholds by model
A block must meet a minimum size to be eligible for caching. Blocks smaller than the threshold are never cached, regardless of how stable they are:
Model family
Minimum tokens
Claude Opus 5, Fable 5
512
Claude Sonnet 5, Opus 4.8
1,024
Claude Opus 4.7, Opus 4.6, Opus 4.5, Haiku 4.5
4,096
Claude Sonnet 4.6
2,048
Claude Sonnet 4.5, Sonnet 4, Sonnet 3.7, Opus 4.1, Opus 4
1,024
Claude Haiku 3.5, Haiku 3
2,048
Short CLAUDE.md files (under ~1,000 tokens) may not be cached at all on Sonnet models. If cost optimization matters, make sure your system prompt crosses the threshold for your target model.
Tool result size and cache economics
Tool results land in the message history and stay there for the rest of the session. Every subsequent API call re-reads that history, at cache read price (0.1x), but still proportional to size. A git status output of 500 tokens costs 500 × 0.1x to read on every turn that follows. The same output at 50 tokens (filtered by a tool like RTK) costs 50 × 0.1x: 90% less, compounding across every turn in the session. Compact tool outputs are not just faster to process; they make the entire cached prefix cheaper to maintain.
The same logic applies to cache writes: a smaller history prefix means cheaper initial writes (1.25x × fewer tokens).
Monitoring cache performance in your own pipelines
When building agents or pipelines on top of the Anthropic API, the response usage object exposes cache metrics directly:
response = client.messages.create(...)
print(response.usage.cache_creation_input_tokens) # Tokens written to cache this request
print(response.usage.cache_read_input_tokens) # Tokens read from cache (hits)
Calculate your hit rate as cache_read / (cache_read + cache_creation) across requests. A ratio above 0.8 means your prompt structure is working well. Low ratios usually mean content in the stable prefix is changing between requests: check for timestamps, random IDs, or dynamic content embedded in your system prompt.
/usage includes prompt-cache statistics for the main conversation on supported current versions. For custom API pipelines, inspect the response fields above. See the cost and cache documentation.
Practical rules
Keep CLAUDE.md stable between sessions: edits invalidate the system cache one-shot, then it re-warms on the next request
Run /compact before the conversation gets very long, not after performance degrades
Avoid dynamic content in stable sections (dates, random values, per-request context)
Larger CLAUDE.md = more expensive cache write, but also more tokens saved per read, profitable after ~2 hits
Known cache bugs (v2.1.69+)
Two active bugs silently break caching on v2.1.69+. Apply these workarounds immediately:
—resume/—continue causes a full cache rebuild (0% hit ratio) on every resume because session JSONL strips deferred tool records before write. Workaround: avoid --resume until fixed.
Per-session billing header injects a unique hash as the first system prompt block, causing a cold miss on every session start and subagent call. Workaround: "CLAUDE_CODE_ATTRIBUTION_HEADER": "false" in ~/.claude/settings.json.
Estimate from measured input, output, cache usage and retries for representative accepted tasks. Use the provider’s billing records for charged amounts; local tools provide estimates. See the ccusage command guide for available reports.
Perspective on costs: If Claude Code saves you meaningful time on a task, the API cost is usually negligible compared to your hourly rate. Don’t over-optimize for token costs at the expense of productivity.
When to optimize:
✅ You’re on a tight budget (student, hobbyist)
✅ High-volume usage (>4 hours/day)
✅ Team usage (5+ developers)
When NOT to optimize:
❌ Your time is more expensive than API costs
❌ You’re spending more time optimizing than the savings
❌ Optimization hurts productivity (being too restrictive)
Choose a model and effort level that meet the task’s acceptance criteria, then compare total cost including retries and review. Route repetitive work to a cheaper model only when the measured result justifies it. A team pilot should record accepted tasks, model usage, failures and human review effort before setting a budget.
Observation
Investigation
Cost rises during long sessions
Inspect context growth and cache misses with /usage
Repeated tool calls return the same material
Narrow the request and reuse an explicit result
A cheaper model needs many retries
Compare cost per accepted task with a stronger model
Many agents repeat repository discovery
Give each a bounded scope and shared written context
Check current plans and the usage information for the signed-in account. Subscription allowances are not fixed published token budgets; API price ratios do not determine quota consumption. Model access and organization policy can change independently of the plan label. Pro is not limited to Sonnet: current defaults and available selections are described in the model table above.
Monitoring Your Usage
/usage # Session estimates, subscription limits and usage breakdown
/model # Available models for this account and provider
/status # Active account and session configuration
The session dollar estimate does not by itself represent a subscriber’s bill. /usage includes plan bars for subscription accounts and, when enabled, usage-credit information. Use the relevant Claude or provider billing page for authoritative charged amounts. Cost tracking documentation.
If you choose opusplan, Opus handles planning and Sonnet handles execution. Haiku requires separate explicit selection. Evaluate this routing policy against your work; it does not promise a fixed saving or a guaranteed number of usable hours.
When a limit interrupts work, inspect its reset information and current account policy. Preserve the task state before switching model, account or execution mode. Historical reports of quotas and peak-hour behavior are not reliable current limits.
You: "Create a session handoff document for what we accomplished today"
Claude will analyze git status, conversation history, and generate a structured handoff.
Handoff Triad Pattern: For teams or multi-session workflows, a three-command protocol adds explicit merge semantics on top of the basic handoff. Three commands work together:
Command
Job
/handoff:create
Generates the structured document from current session context
/handoff:resume
Loads a handoff document, confirms understanding, and waits for approval before starting
/handoff:update
Updates an existing handoff with section-specific merge rules (see below)
The critical addition is per-section merge rules in update:
Section
Merge Rule
Task, Scope
Keep or refine
Files
Merge: combine original with new files touched
Discoveries
Append: add new findings, never remove prior ones
Work Done
Append only: add new entries, never delete history, include commit hashes
Status
Replace: write current state
Next Steps
Replace: write updated checklist
The append-only Work Done section creates an audit trail across sessions. Even if earlier work was revised, the revision appears as a new entry rather than an overwrite.
Fork-ready templates at examples/commands/handoff/ in this repo.
Recommended frequency: Boris Cherny (Head of Claude Code at Anthropic) starts approximately 80% of tasks in Plan Mode, letting Claude plan before writing a single line of code. Once the plan is approved, execution is almost always correct on the first try.
Lenny’s Newsletter, February 19, 2026
Press Shift+Tab to toggle back to Normal Mode (Act Mode). You can also type a message and Claude will ask: “Ready to implement this plan?”
Note: Shift+Tab toggles between Plan Mode and Normal Mode during a session. Use Shift+Tab twice from Normal Mode to enter Plan Mode, once from Plan Mode to return.
Expected benefit: reviewing a plan can catch misunderstandings before implementation. Token savings and defect reduction depend on the task and must be measured; no general percentage is established here.
Aliases resolve by provider and can be remapped by configuration. Verified against the official model configuration on September 24, 2026:
Provider
opus
sonnet
Anthropic API
Opus 5.5
Sonnet 5.5 (since v2.1.284)
Claude Platform on AWS
Opus 5.5
Sonnet 4.6
Amazon Bedrock / Google Cloud’s Agent Platform
Opus 5.5
Sonnet 4.5
Microsoft Foundry
Opus 4.6
Sonnet 4.5
Selection
Meaning
default
Clear the override and use the account or organization default
haiku
Haiku family alias; current direct-service model is Haiku 4.5
fable
Fable 5.1, except Fable 5 through the Claude apps gateway
best
Same as fable where available, otherwise opus
opus[1m], sonnet[1m]
Request a 1M variant where the provider/model needs one
opusplan
opus for planning, sonnet for execution
opusplan[1m]
Request 1M in both phases where not native; /model accepts it from v2.1.265
Pin a version with its exact provider ID, such as claude-opus-5-5, or the appropriate ANTHROPIC_DEFAULT_*_MODEL variable. A provider alias resolving to an older model does not mean newer explicit IDs are unavailable.
/model <name> saves a default for new sessions. In the picker, press s for this session only. claude --model <name> and ANTHROPIC_MODEL apply to the launched session. Project and managed settings can reapply on the next launch; resumed sessions usually restore their recorded model. ANTHROPIC_DEFAULT_MODEL is a lower-priority default, not a replacement for these overrides.
Use the status line, /model, or the API response metadata to identify the active model. Model self-reports are not reliable identification. The current reliable knowledge cutoffs are June 2026 for Opus 5.5, Sonnet 5.5 and Fable 5.1, and February 2025 for Haiku 4.5. Model specifications.
Concept: Use Opus for planning (superior reasoning) and Sonnet for implementation (cost-efficient).
Why OpusPlan?
Cost optimization: Opus tokens cost more than Sonnet
Best of both worlds: Opus-quality planning + Sonnet-speed execution
Token savings: Planning is typically shorter than implementation
Activation:
/model opusplan
Or in ~/.claude/settings.json:
{
"model": "opusplan"
}
How It Works:
In Plan Mode (/plan or Shift+Tab twice) → Uses Opus
In Act Mode (normal execution) → Uses Sonnet
Automatic switching based on mode
Recommended Workflow:
1. /model opusplan → Enable OpusPlan
2. Shift+Tab × 2 → Enter Plan Mode (Opus)
3. Describe your task → Get Opus-quality planning
4. Shift+Tab → Exit to Act Mode (Sonnet)
5. Execute the plan → Sonnet implements efficiently
Alternative Approach with Subagents:
You can also control model usage per agent:
.claude/agents/planner.md
---
name: planner
model: opus
tools: Read, Grep, Glob
---
# Strategic Planning Agent
.claude/agents/implementer.md
---
name: implementer
model: haiku
tools: Write, Edit, Bash
---
# Fast Implementation Agent
Pro Users Note: OpusPlan is particularly valuable for Pro subscribers with limited Opus tokens. It lets you use Opus reasoning for critical planning while preserving tokens for more sessions.
Budget Variant: SonnetPlan (Community Hack)
opusplan is hardcoded to Opus+Sonnet. There’s no native sonnetplan alias. But you can remap what the opus and sonnet aliases resolve to via environment variables, effectively creating a Sonnet→Haiku hybrid:
Caveat: The model’s self-report (what model are you?) is unreliable: models don’t always know their own identity. Trust the status bar (Model: Sonnet 5 in plan mode) or verify via billing dashboard. GitHub issue #9749 tracks native support.
Pinning Opus 4.6 (Community Hack)
Opus 4.7 ships with a new tokenizer that maps the same input to roughly 1.0-1.35x more tokens depending on content type, and at higher effort levels it produces more output tokens (more reasoning steps). For workflows where that extra spend doesn’t translate into better results, pinning to Opus 4.6 keeps an older model and tokenizer; measure the cost and quality tradeoff on your task.
Option A: Opus 4.6 everywhere (simplest)
~/.claude/settings.json
{
"model": "claude-opus-4-6"
}
All sessions use Opus 4.6. No hybrid. Add [1M] if you need the 1M context window: "claude-opus-4-6[1M]".
Option B: Keep OpusPlan, intentionally pin the older Opus side
~/.claude/settings.json
{
"model": "opusplan",
"env": {
"ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-6"
}
}
opusplan still switches between Plan and Act modes, but Plan Mode now routes to Opus 4.6 instead of the provider’s current Opus alias. Sonnet stays unchanged in Act Mode.
Shell variant (non-persistent, useful for testing):
Resets on the next session. Useful before committing to a config change.
Verification: check the status bar in Plan Mode. Verify the resolved Opus 4.6 model ID. The billing dashboard confirms which model was charged.
Trade-offs: Opus 4.6 does not support xhigh, but does support max. Pinning keeps an older model, tokenizer, and knowledge cutoff. Compare accepted outcomes and total tokens with the current default before treating the older model as a cost optimization.
Unfamiliar domain where first instincts are often wrong
Pattern:
## Round 1: Initial analysis
User: /plan
User: Analyze the current auth system. What are the key components,
dependencies, and potential risks of migrating to OAuth2?
Claude: [Initial analysis]
## Round 2: Deep challenge
User: Now use extended thinking. Challenge your own analysis:
- What assumptions did you make?
- What failure modes did you miss?
- What would a senior security engineer flag?
Claude: [Deeper analysis with self-correction]
## Round 3: Final plan
User: Based on both rounds, write the definitive migration plan.
Include rollback strategy and risk mitigation for each step.
Claude: [Refined plan incorporating both rounds]
## Execute
[approve the plan, or Shift+Tab to leave plan mode]
User: Implement the plan from round 3.
Purpose: a second round challenges assumptions and a third consolidates the plan. Repetition does not guarantee new findings or correctness; keep independent tests and explicit acceptance criteria.
📊 Empirical backing: Anthropic AI Fluency Index (Feb 2026)
In 9,830 Claude.ai conversations sampled during one week in January 2026, conversations with iteration/refinement were 5.6 times more likely to show users questioning reasoning and four times more likely to show users identifying missing context. These are associations between observed behaviors, not measured bug-detection rates.
The report explicitly does not establish causality. It does not test the three-round pattern above or prove that another review round improves a plan.
Cloud-based parallel multi-agent code review. Multiple review agents read through your changes simultaneously and surface bugs and design issues that careful reviewers would catch.
Activation:
Terminal window
/ultrareview# Review current branch (diff from base)
/ultrareview<PR#># Review a specific GitHub PR
Ultrareview operates on diffs, not the full codebase: it reviews what changed on the current branch, or the changes in a given PR. The cloud session dispatches parallel agents to analyse the diff; results arrive in the browser and can optionally be teleported back to the terminal.
Launch offer: Pro and Max subscribers receive three free ultrareviews to try the feature.
Long or ambiguous work that misses the quality bar
Evaluate Fable 5.1
Start at high
Multi-agent workflow
Assign by role and measured task results
Per supported model
No fixed cost per task follows from a model name. Measure input, output, cache tokens, retries, and review effort against the same acceptance criteria. See the pricing table.
Fable 5.1 (claude-fable-5-1, Claude Code v2.1.257+) is an explicit option when evaluations on Opus 5.5 still fall short. /model fable normally selects it; Claude apps gateway sessions map that alias to Fable 5, so use a full supported ID to pin the newer model. Availability and usage-credit billing depend on the account. A stronger model does not remove the need to verify security or production decisions. Fable access and billing.
Effort controls adaptive reasoning and can change tool use, response length, latency, and cost. It is not an accuracy guarantee.
Models
Supported Claude Code effort levels
Default
Opus 5.5
low, medium, high, xhigh, max
medium
Sonnet 5, Opus 5 / 4.8, Fable 5 / 5.1
low, medium, high, xhigh, max
high
Opus 4.7
low, medium, high, xhigh, max
xhigh
Opus 4.6, Sonnet 4.6
low, medium, high, max
high
Haiku 4.5
No effort parameter
Not applicable
/effort or the /model picker saves supported low through xhigh choices per model when confirmed with Enter; s makes the choice session-only. /effort max is session-only. Persistent modelSettings and effortLevel do not accept max. CLAUDE_CODE_EFFORT_LEVEL can override the session, and organization policy can cap available levels.
/effort ultracode enables dynamic workflow orchestration with xhigh reasoning. It is a Claude Code setting, not a sixth model effort level. The prompt keyword ultrathink adds an instruction to reason more deeply without changing the effort value sent to the API.
Opus 5.5 starts at medium and does not inherit the old top-level effortLevel from user settings. A per-model choice, an explicit runtime override, or project/local/managed effort settings can still change it. Official effort rules.
Skills can declare their own effort level in frontmatter. The skill’s value overrides the session setting for the duration of that skill’s execution, then reverts. This eliminates the need to manually toggle effort between mechanical and analytical tasks.
# Mechanical skill — always fast, never wastes reasoning budget
# Analytical skill — always deep, regardless of session setting
---
name: architecture-review
description: Full architectural analysis with trade-off evaluation
effort: high
---
Decision table for common skill types:
Skill type
Recommended effort
Reasoning
Commit, push, sync
low
Sequential steps, no design decisions
Changelog, release notes
low
Reads git + formats, mécanique
Scaffolding, boilerplate
low
Template instantiation
Code review (single PR)
medium
Pattern recognition, bounded scope
Issue triage, backlog
medium
Categorization + some analysis
Security audit
high
Threat modeling, adversarial thinking
Architecture review
high
Design decisions, cross-component reasoning
Multi-agent orchestration
high
Coordination + planning
Cost model: low effort means fewer tool calls, no preamble, direct output. high effort means more tool calls with explanations, detailed summaries, deeper exploration. Match effort to where analysis adds value, not to “effort = quality” uniformly.
description: Mechanical execution agent. Scope must be defined explicitly in the task.
model: haiku
tools: Write, Edit, Bash, Read, Grep, Glob
---
Note: Haiku is for mechanical tasks only. If the implementation requires design decisions or complex business logic, use Sonnet, and state this in the task prompt.
Thinking toggle: Option+T on macOS or Alt+T elsewhere, where supported. Opus 5.5 and Fable always use thinking; lower their effort for bounded work instead.
External Services: Claude can’t access your databases directly
Your Intent: Claude needs clear instructions
Hidden Files: Claude respects .gitignore by default
⚠️ Pattern Amplification: Claude mirrors the patterns it finds. In well-structured codebases, it produces consistent, idiomatic code. In messy codebases without clear abstractions, it perpetuates the mess. If your code lacks good patterns, provide them explicitly in CLAUDE.md or use semantic anchors (Section 2.9).
The most common mistake is treating Claude Code like a chatbot: typing ad-hoc requests and hoping for good output. What separates casual usage from production workflows is a shift in thinking:
Chatbot mode: You write good prompts. Context system: You build structured context that makes every prompt better.
“Stop treating it like a chatbot. Give it structured context. CLAUDE.md, hooks, skills, project memory. Changes everything.”Robin Lorenz, AI Engineer (comment)
This guide groups four mechanisms into a conceptual learning model, not an exhaustive runtime architecture:
These are not independent features. They are layers of the same system:
CLAUDE.md teaches Claude what your project needs (conventions, stack, patterns)
Skills teach Claude how to perform specific workflows (review, deploy, test)
Hooks enforce guardrails automatically (block secrets, auto-format, run linting)
Memory preserves decisions across sessions (architectural choices, resolved tradeoffs)
Before (chatbot mode):
“Use pnpm, not npm. And remember our naming convention is…”
(Every session. Every time. Copy-pasting context.)
After (context system):
Applicable CLAUDE.md files supply conventions. Skills provide reusable workflows.
Configured hooks run checks for supported events. Memory records decisions for later use.
These mechanisms improve available context; they do not guarantee instruction adherence, complete recall or a successful quality check.
XML-structured prompts provide semantic organization for complex requests, helping Claude distinguish between different aspects of your task for clearer understanding and better results.
The Claude Code team internally treats prompts as challenges to a peer, not instructions to an assistant. This subtle shift produces higher-quality outputs because it forces Claude to prove its reasoning rather than simply comply.
Three challenge patterns from the team:
1. The Gatekeeper: Force Claude to defend its work before shipping:
"Grill me on these changes and don't make a PR until I pass your test"
Claude reviews your diff, asks pointed questions about edge cases, and only proceeds when satisfied. This catches issues that passive review misses.
2. The Proof Demand: Require evidence, not assertions:
"Prove to me this works — show me the diff in behavior between main and this branch"
Claude runs both branches, compares outputs, and presents concrete evidence. Eliminates the “trust me, it works” failure mode.
3. The Reset: After a mediocre first attempt, invoke full-context rewrite:
"Knowing everything you know now, scrap this and implement the elegant solution"
This forces a substantive second attempt with accumulated context rather than incremental patches on a weak foundation. The key insight: Claude’s second attempt with full context consistently outperforms iterative fixes.
Why this works: Provocation triggers deeper reasoning paths than polite requests. When Claude must convince rather than comply, it activates more thorough analysis and catches its own shortcuts.
A semantic anchor is the name of an established method, pattern, or framework used as shorthand in a prompt. It gives Claude a more specific reference than a request such as “write good tests.” Recognition and correct application still depend on the model, the task, and the surrounding instructions.
“Write good tests” leaves the testing approach open. “Use TDD, London School; start with an outside-in behavior test” names a particular approach and states the part you need. The added instruction matters: a model may recognize the term without applying it well to your code.
Vague request
Anchor with task-specific direction
What to check
”Handle errors"
"Use Railway Oriented Programming with Result for expected failures”
"Apply Deep Modules: hide implementation detail behind a small interface”
Callers depend on fewer details without losing needed behavior
”Modernize this feature"
"Use Strangler Fig: replace one behavior behind a boundary”
Old and new paths coexist safely during migration
”Design the API"
"Target Richardson Maturity Model Level 2”
Resources, HTTP methods, and status codes match the API contract
An anchor should fit the problem. State the relevant behavior, boundaries, and acceptance checks alongside it. For example, CQRS and Event Sourcing are separate choices; naming either one does not justify adopting both.
The Semantic Anchors project’s evaluation plan separates recognition from application and compares anchor prompts with ordinary descriptions. It describes an evaluation method, not a measured quality gain for the examples in this guide. If a model applies a term incorrectly, expand it into explicit instructions and verify the result.
- Error handling: Use a Result type for expected payment failures; keep unexpected failures observable.
- Testing: Use TDD, London School at the service boundary; add an integration test for the provider adapter.
- Documentation: Record the provider-boundary decision in an ADR.
These are project choices, not defaults to copy into every repository. An XML-structured prompt (Section 2.8) can group the same instructions, but the tags alone do not make the anchor more reliable.
Two prompt-level techniques that close the gap between well-structured prompts and reliably accurate outputs: few-shot examples for calibrating format and style, and validation retry loops for catching and correcting extraction failures.
Few-shot examples show the model what correct output looks like before it processes the actual input. They are most effective for establishing output format, tone calibration, and input-specific processing style. They cannot enforce business rules or guarantee compliance; use schema validation for that.
Optimal count: 2-4 examples. Below 2, the pattern is too weak to anchor behavior. Above 4, the examples consume context budget without proportional improvement, and the model may pattern-match too literally on superficial features.
Message-pair format for tool use:
When the task involves tool calls, examples must include the full exchange, not just user inputs and final text outputs:
messages =[
# Example 1
{"role": "user", "content": "Invoice: Acme Corp, 15 Jan 2025, $4,200.00"},
The second example above demonstrates null handling explicitly. Without it, the model may invent a vendor name rather than returning null for an ambiguous field.
Calibrating false positive rates:
In CI-style review tasks (security scanning, code quality checks, compliance checks), false positives destroy trust faster than false negatives. A few-shot example set that includes a near-miss that should NOT trigger an alert teaches the boundary explicitly:
# In the system prompt or early in the conversation:
CALIBRATION_EXAMPLES="""
Examples of what triggers a HIGH severity flag vs what does not:
Example 1 (HIGH, triggers):
Input: SELECT * FROM users WHERE id = ' + user_input + '
Reason: Direct string concatenation in SQL, classic injection vector.
Example 2 (NOT flagged, near-miss):
Input: query = f"SELECT * FROM users WHERE id = {user_id}"
Reason: f-string with a typed integer variable. No injection risk if user_id is
Reason: Direct shell execution from unsanitized request parameter.
"""
Near-miss examples reduce false positive rates by teaching the model where the actual boundary sits, not just what a clear violation looks like.
Limits of few-shot:
Few-shot examples teach style and format. They cannot enforce schema constraints (use strict: true for that), guarantee business rule compliance (use a programmatic validator), or replace explicit instructions. If the rule needs to hold without exception, state it as a rule, not just as an example.
The validation retry loop catches structured extraction failures programmatically and feeds specific error feedback back to the model for regeneration, rather than silently discarding bad output or failing the whole task.
f"The extraction has {len(errors)} validation error(s):\n\n"
f"{error_feedback}\n\n"
f"Please correct these specific issues and re-extract."
)
}
])
returnExtractionResult(
success=False,data=None,
error=f"Failed after {max_attempts} attempts: {errors}",
attempts=max_attempts
)
defformat_errors(errors, raw_output):
lines =[]
for err in errors:
lines.append(f"- Field `{err.field}`: {err.message}")
if err.field in raw_output:
lines.append(f" Got: {raw_output[err.field]!r}")
return"\n".join(lines)
The feedback triple matters. Effective retry feedback includes (1) the original document excerpt where the issue occurred, (2) the failed JSON the model produced, and (3) a specific error list per field. Vague feedback (“please try again, there were errors”) degrades into random variation. Specific feedback (“field date expected ISO 8601, got ‘15th January’”) almost always resolves on the second attempt.
When source data is absent:
If the document genuinely does not contain the required field, a retry loop will not help. The model will keep hallucinating or oscillating between null and invented values. Exit condition: if the same field fails twice with different invented values, mark it as absent_from_source and move on. Do not burn the full 3-attempt budget on a field that isn’t there.
Asking the same model instance that generated an output to review its own output produces results with a 15-30% self-preference bias: the model tends to agree with itself, finding the generated content “correct” at rates above what independent reviewers would. The context window shared between generation and review is the contamination vector.
Mitigation: independent review instance
# Generation pass
generation_response = client.messages.create(
model="claude-opus-4-5",
max_tokens=2048,
messages=[
{"role": "user", "content": f"Analyze this contract:\n\n{contract_text}"}
]
)
analysis = generation_response.content[0].text
# Review pass: fresh conversation, no generation context
review_response = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
system="You are a critical reviewer. Identify gaps, errors, and unsupported claims.",
messages=[
{
"role": "user",
"content": (
f"Review this contract analysis for accuracy:\n\n"
f"CONTRACT:\n{contract_text}\n\n"
f"ANALYSIS TO REVIEW:\n{analysis}\n\n"
f"Identify any errors, gaps, or claims not supported by the contract text."
)
}
]
)
The review instance receives the source document and the generated analysis but has no memory of generating it. This eliminates the self-preference bias almost entirely. Use it for high-stakes extraction (legal, financial, medical), customer-facing content where errors damage trust, and any task where undetected hallucination is not acceptable.
For borderline classifications, a reasoning field in the output schema surfaces the evidence chain that produced the classification. This is not chain-of-thought prompting; it is a structured output field that forces the model to articulate the key evidence before committing to a label.
"description": "The specific evidence from the input that determined this classification"
},
"confidence": {"type": "number"}
}
When classification: "urgent" and reasoning: "customer explicitly states production outage affecting 10,000 users", a downstream filter can verify the classification in one read. When reasoning is vague or circular (“classified as urgent because it seems urgent”), that is a reliable signal to escalate for human review regardless of the confidence score.
Schema design determines how much of the extraction burden falls on the model versus on downstream validation. Good schemas express what the model genuinely knows; bad schemas force the model to invent values for fields it cannot find.
A confidence score of 0.9 means nothing without a labeled validation set showing that fields labeled 0.9 by this model are actually correct 90% of the time. Uncalibrated confidence scores create a false sense of accuracy.
Different fields have different error costs. A wrong vendor name on an invoice is annoying; a wrong total amount is a financial error. Set per-field confidence thresholds that route to human review when not met:
Plot model confidence on the x-axis against actual accuracy on the y-axis. A perfectly calibrated model follows the diagonal. Systematic overconfidence shows up as a curve below the diagonal; systematic underconfidence shows as a curve above it. Both can be corrected with temperature adjustment or post-hoc calibration (Platt scaling).
Calibrate on at least 200 labeled examples per field to get statistically meaningful buckets. Below 100 examples, bucket accuracy estimates are too noisy to act on.
Important: Everything you share with Claude Code is sent to Anthropic servers. Understanding this data flow is critical for protecting sensitive information.
2. Never connect production databases to MCP servers. Use dev/staging with anonymized data.
3. Use security hooks to block reading of sensitive files (see Section 7.4).
Full guide: For complete privacy documentation including known risks, community incidents, and enterprise considerations, see Data Privacy & Retention Guide.
Reading time: 5 minutes
Goal: Understand the core architecture that powers Claude Code
This section provides a summary of Claude Code’s internal mechanisms. For the complete technical deep-dive with diagrams and source citations, see the Architecture & Internals Guide.
The diagram describes the basic model/tool loop. It does not inventory every current product feature: auto mode can add a permission classifier, and dynamic workflows can coordinate additional agents. The model selects actions within the tools, policy checks and execution controls exposed by the runtime.
The following is a selection of built-in tools, not the complete current inventory:
Tool
Purpose
Bash
Execute shell commands (universal adapter)
Read
Read file contents (max 2000 lines)
Edit
Modify existing files (diff-based)
Write
Create/overwrite files
Grep
Search file contents (ripgrep-based)
Glob
Find files by pattern
Agent
Spawn subagents; Task remains a compatibility alias in settings and agent definitions
TodoWrite
Track progress (legacy, see below)
How tool execution works: Claude Code can start executing tools marked as concurrency-safe (read-only operations like Read, Grep, Glob) while the model is still generating its response, reducing total turn time. Non-concurrent tools (writes, bash commands) wait for the response to complete and run serially. When multiple read-only tools appear in a single response, they run in parallel, up to 10 concurrent by default.
⚠️ Important: Use repository-specific task list IDs to avoid cross-project contamination. Tasks with the same ID are shared across all sessions using that ID.
Illustrative task record (not a complete tool-call schema):
{
"id": "task-auth-login",
"subject": "Implement login endpoint",
"description": "POST /auth/login with JWT token generation",
The Diagnostic Principle: When Claude’s task list doesn’t match your intent, the problem sits in your instructions, not in Claude.
Task lists act as a mirror for instruction clarity. If you ask Claude to plan a feature and the resulting tasks surprise you, that divergence is diagnostic information:
Your instruction: "Refactor the auth system"
Claude's task list:
- [ ] Read all auth-related files
- [ ] Identify code duplication
- [ ] Extract shared utilities
- [ ] Update imports
- [ ] Run tests
Your reaction: "That's not what I meant—I wanted to switch from session to JWT"
Diagnosis: Your instruction was ambiguous. "Refactor" ≠ "replace".
Divergence patterns and what they reveal:
Divergence Type
What It Means
Fix
Tasks too broad
Instructions lack specificity
Add WHAT, WHERE, HOW, VERIFY
Tasks too narrow
Instructions too detailed, missing big picture
State the goal, not just the steps
Wrong priorities
Context missing about what matters
Add constraints and priorities
Missing tasks
Implicit knowledge not shared
Make assumptions explicit in prompt
Extra tasks
Claude inferred requirements you didn’t intend
Add explicit scope boundaries
Using task divergence as a workflow:
## Step 1: Seed with loose instruction
User: "Improve the checkout flow"
## Step 2: Review Claude's task list (don't execute yet)
Claude generates: [task list]
## Step 3: Compare against your mental model
- Missing: payment retry logic? → Add to instructions
User: "Actually, here's what I need: [refined instruction with specifics]"
Pro tip: Run TaskList after initial planning as a sanity check before execution. If more than 30% of tasks surprise you, your prompt needs work. Iterate on the prompt, not the tasks.
Context is model/provider dependent: current Opus, Sonnet and Fable models have native 1M windows on the direct API; Haiku 4.5 has 200K. Older variants have separate access rules. See 200K vs 1M comparison. The following sizes are illustrative, not fixed reservations:
Component
Approximate Size
System prompt
5-15K tokens
CLAUDE.md files
1-10K tokens
Conversation history
Variable
Tool results
Variable
Reserved for response
40-45K tokens
Native 1M sessions normally auto-compact around 967K tokens. /autocompact can choose a smaller window. Compaction can omit information needed later, so save decisions and verification commands before a handoff. Use /compact at logical breakpoints; a fixed percentage is not a universal quality threshold. See [Session Handoffs](line 2140) and Auto-Compaction Research.
This limits transcript accumulation in the parent. Ordinary subagents start with fresh context; forked subagents can inherit history. Separate conversation context does not isolate filesystem changes, credentials or external effects. Use a worktree or other isolation when needed; see subagent context.
Agent Teams provide a lead, independently working teammates, shared tasks and direct mailbox messages. Enable them with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1; choose an available model for each teammate.
Task state lives under ~/.claude/tasks/<team-name>/, with team configuration and inboxes under ~/.claude/teams/<team-name>/. File locking prevents simultaneous claims of one task. It does not merge source changes or prevent two agents editing the same file.
Use separate file ownership or worktrees for edits. Ask the lead to stop or redirect teammates when their scope changes. Display modes include in-process and terminal split panes; use Shift+Down to cycle teammates in-process.
Older community material uses the name TeammateTool and inferred operations such as spawnTeam. Treat those as historical implementation notes, not the current documented interface. See Agent Teams and §9.20 for current operation and limitations.
A small model/tool loop is a useful starting point for reasoning about the system. More capable models and additional orchestration still need explicit tool boundaries and verification.
Use that simplified model to locate decisions, tool results and failures. It does not prove that fewer components always improve reliability or that a model-selected action is correct.