| title | The Ultimate Claude Code Guide |
| description | Comprehensive self-contained guide to mastering Claude Code from zero to power user |
| tags | ["guide","reference","workflows","agents","hooks","mcp","security"] |
The Ultimate Claude Code Guide
A comprehensive, self-contained guide to mastering Claude Code - from zero to power user.
Author: Florian BRUNIAUX | Founding Engineer @Méthode Aristote
Written with: Claude (Anthropic)
Reading time: ~30-40 hours (full) | ~15 minutes (Quick Start only)
Last updated: January 2026
Version: 3.29.0
Before You Start
This guide is not official Anthropic documentation. It's a community resource based on my exploration of Claude Code over several months.
What you'll find:
- Patterns that have worked for me
- Observations that may not generalize to your workflow
- Time estimates and percentages that are rough approximations, not measurements
What you won't find:
- Definitive answers (the tool is too new)
- Benchmarked performance claims
- Guarantees that any technique will work for you
Use critically. Experiment. Share what works for you.
⚠️ Note (Jan 2026): If you've heard about ClawdBot recently, that's a different tool. ClawdBot is a self-hosted chatbot assistant accessible via messaging apps (Telegram, WhatsApp, etc.), designed for personal automation and smart home use cases. Claude Code is a CLI tool for developers (terminal/IDE integration) focused on software development workflows. Both use Claude models but serve distinct audiences and use cases. More details in Appendix B: FAQ.
TL;DR - The 5-Minute Summary
If you only have 5 minutes, here's what you need to know:
Essential Commands
claude # Start Claude Code
/help # Show all commands
/status # Check context usage
/compact # Compress context when >70%
/clear # Fresh start
/plan # Safe read-only mode
Ctrl+C # Cancel operation
The Workflow
Describe → Claude Analyzes → Review Diff → Accept/Reject → Verify
Context Management (Critical!)
| Context % | Action |
|---|
| 0-50% | Work freely |
| 50-70% | Be selective |
| 70-90% | /compact now |
| 90%+ | /clear required |
These thresholds are based on my experience. Your optimal workflow may differ depending on task complexity and working style.
Memory Hierarchy
~/.claude/CLAUDE.md → Global (all projects)
/project/CLAUDE.md → Project (committed)
/project/.claude/ → Personal (not committed)
Power Features
| Feature | What It Does |
|---|
| Agents | Specialized AI personas for specific tasks |
| Skills | Reusable knowledge modules |
| Hooks | Automation scripts triggered by events |
| MCP Servers | External tools (Serena, Context7, Playwright...) |
| Plugins | Community-created extension packages |
The Golden Rules
- Always review diffs before accepting changes
- Use
/compact before context gets critical
- Be specific in your requests (WHAT, WHERE, HOW, VERIFY)
- Start with Plan Mode for complex/risky tasks
- Create CLAUDE.md for every project
Quick Decision Tree
Simple task → Just ask Claude
Complex task → Use TodoWrite to plan
Risky change → Enter Plan Mode first
Repeating task → Create an agent or command
Context full → /compact or /clear
Now read Section 1 for the full Quick Start, or jump to any section you need.
Table of Contents
1. Quick Start (Day 1)
Quick jump: Installation · First Workflow · Essential Commands · Permission Modes · Productivity Checklist · Migrating from Other Tools · Beginner Mistakes
Reading time: 15 minutes
Skill level: Beginner
Goal: Go from zero to productive
1.1 Installation
Choose your preferred installation method based on your operating system:
/*──────────────────────────────────────────────────────────────*/
/* Universal Method */ npm install -g @anthropic-ai/claude-code
/*──────────────────────────────────────────────────────────────*/
/* Windows (CMD) */ npm install -g @anthropic-ai/claude-code
/* Windows (PowerShell) */ irm https://claude.ai/install.ps1 | iex
/*──────────────────────────────────────────────────────────────*/
/* macOS (npm) */ npm install -g @anthropic-ai/claude-code
/* macOS (Homebrew) */ brew install claude-code
/* macOS (Shell Script) */ curl -fsSL https://claude.ai/install.sh | sh
/*──────────────────────────────────────────────────────────────*/
/* Linux (npm) */ npm install -g @anthropic-ai/claude-code
/* Linux (Shell Script) */ curl -fsSL https://claude.ai/install.sh | sh
Verify Installation
claude --version
Updating Claude Code
Keep Claude Code up to date for the latest features, bug fixes, and model improvements:
# Check for available updates
claude update
# Alternative: Update via npm
npm update -g @anthropic-ai/claude-code
# Verify the update
claude --version
# Check system health after update
claude doctor
Available maintenance commands:
| Command | Purpose | When to Use |
|---|
claude update | Check and install updates | Weekly or when encountering issues |
claude doctor | Verify auto-updater health | After system changes or if updates fail |
claude --version | Display current version | Before reporting bugs |
claude auth login | Authenticate from the command line | CI/CD, devcontainers, scripted setups |
claude auth status | Check current authentication state | Verify which account/method is active |
claude auth logout | Clear stored credentials | Shared machines, security cleanup |
Update frequency recommendations:
- Weekly: Check for updates during normal development
- Before major work: Ensure latest features and fixes
- After system changes: Run
claude doctor to verify health
- On unexpected behavior: Update first, then troubleshoot
Platform-Specific Paths
| Platform | Global Config Path | Shell Config |
|---|
| macOS/Linux | ~/.claude/ | ~/.zshrc or ~/.bashrc |
| Windows | %USERPROFILE%\.claude\ | PowerShell profile |
Windows Users: Throughout this guide, when you see ~/.claude/, use %USERPROFILE%\.claude\ or C:\Users\YourName\.claude\ instead.
First Launch
cd your-project
claude
On first launch:
- You'll be prompted to authenticate with your Anthropic account
- Accept the terms of service
- Claude Code will index your project (may take a few seconds for large codebases)
Note: Claude Code requires an active Anthropic subscription. See claude.com/pricing for current plans and token limits.
1.2 First Workflow
Let's fix a bug together. This demonstrates the core interaction loop.
Step 1: Describe the Problem
You: There's a bug in the login function - users can't log in with email addresses containing a plus sign
Step 2: Claude Analyzes
Claude will:
- Search your codebase for relevant files
- Read the login-related code
- Identify the issue
- Propose a fix
Step 3: Review the Diff
- const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
+ const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
💡 Critical: Always read the diff before accepting. This is your safety net.
Step 4: Accept or Reject
- Press
y to accept the change
- Press
n to reject and ask for alternatives
- Press
e to edit the change manually
Step 5: Verify
You: Run the tests to make sure this works
Claude will run your test suite and report results.
Step 6: Commit (Optional)
You: Commit this fix
Claude will create a commit with an appropriate message.
1.3 Essential Commands
These 7 commands are the ones I use most frequently:
| Command | Action | When to Use |
|---|
/help | Show all commands | When you're lost |
/clear | Clear conversation | Start fresh |
/compact | Summarize context | Running low on context |
/status | Show session info | Check context usage |
/exit or Ctrl+D | Exit Claude Code | Done working |
/plan | Enter Plan Mode | Safe exploration |
/rewind | Undo changes | Made a mistake |
Quick Actions & Shortcuts
| Shortcut | Action | Example |
|---|
!command | Run shell command directly | !git status, !npm test |
@file.ts | Reference a specific file | @src/app.tsx, @README.md |
Ctrl+C | Cancel current operation | Stop long-running analysis |
Ctrl+R | Search command history | Find previous prompts |
Esc | Stop Claude mid-action | Interrupt current operation |
Shell Commands with !
Execute commands immediately without asking Claude to do it:
# Quick status checks
!git status
!npm run test
!docker ps
# View logs
!tail -f logs/app.log
!cat package.json
# Quick searches
!grep -r "TODO" src/
!find . -name "*.test.ts"
When to use ! vs asking Claude:
Use ! for... | Ask Claude for... |
|---|
Quick status checks (!git status) | Git operations requiring decisions |
View commands (!cat, !ls) | File analysis and understanding |
| Already-known commands | Complex command construction |
| Fast iteration in terminal | Commands you're unsure about |
Example workflow:
You: !git status
Output: Shows 5 modified files
You: Create a commit with these changes, following conventional commits
Claude: [Analyzes files, suggests commit message]
File References with @
Reference specific files in your prompts for targeted operations:
# Single file
Review @src/auth/login.tsx for security issues
# Multiple files
Refactor @src/utils/validation.ts and @src/utils/helpers.ts to remove duplication
# With wildcards (in some contexts)
Analyze all test files @src/**/*.test.ts
# Relative paths work
Check @./CLAUDE.md for project conventions
Why use @:
- Precision: Target exact files instead of letting Claude search
- Speed: Skip file discovery phase
- Context: Signals Claude to read these files on-demand via tools
- Clarity: Makes your intent explicit
Example:
# Without @
You: Fix the authentication bug
Claude: Which file contains the authentication logic? [Wastes time searching]
# With @
You: Fix the authentication bug in @src/auth/middleware.ts
Claude: [Reads file on-demand and proposes fix]
Working with Images and Screenshots
Claude Code supports direct image input for visual analysis, mockup implementation, and design feedback.
How to use images:
-
Paste directly in terminal (macOS/Linux/Windows with modern terminal):
- Copy screenshot or image to clipboard (
Cmd+Shift+4 on macOS, Win+Shift+S on Windows)
- In Claude Code session, paste with
Cmd+V / Ctrl+V
- Claude receives the image and can analyze it
-
Drag and drop (some terminals):
- Drag image file into terminal window
- Claude loads and processes the image
-
Reference with path:
Analyze this mockup: /path/to/design.png
Common use cases:
# Implement UI from mockup
You: [Paste screenshot of Figma design]
Implement this login screen in React with Tailwind CSS
# Debug visual issues
You: [Paste screenshot of broken layout]
The button is misaligned. Fix the CSS.
# Analyze diagrams
You: [Paste architecture diagram]
Explain this system architecture and identify potential bottlenecks
# Code from whiteboard
You: [Paste photo of whiteboard algorithm]
Convert this algorithm to Python code
# Accessibility audit
You: [Paste screenshot of UI]
Review this interface for WCAG 2.1 compliance issues
Supported formats: PNG, JPG, JPEG, WebP, GIF (static)
Best practices:
- High contrast: Ensure text/diagrams are clearly visible
- Crop relevantly: Remove unnecessary UI elements for focused analysis
- Annotate when needed: Circle/highlight specific areas you want Claude to focus on
- Combine with text: "Focus on the header section" provides additional context
Example workflow:
You: [Paste screenshot of error message in browser console]
This error appears when users click the submit button. Debug it.
Claude: I can see the error "TypeError: Cannot read property 'value' of null".
This suggests the form field reference is incorrect. Let me check your form handling code...
[Reads relevant files and proposes fix]
Limitations:
- Images consume significant context tokens (equivalent to ~1000-2000 words of text)
- Use
/status to monitor context usage after pasting images
- Consider describing complex diagrams textually if context is tight
- Some terminals may not support clipboard image pasting (fallback: save and reference file path)
💡 Pro tip: Take screenshots of error messages, design mockups, and documentation instead of describing them textually. Visual input is often faster and more precise than written descriptions.
Wireframing Tools for AI Development
When designing UI before implementation, low-fidelity wireframes help Claude understand intent without over-constraining the output. Here are recommended tools that work well with Claude Code:
| Tool | Type | Price | MCP Support | Best For |
|---|
| Excalidraw | Hand-drawn style | Free | ✓ Community | Quick wireframes, architecture diagrams |
| tldraw | Minimalist canvas | Free | Emerging | Real-time collaboration, custom integrations |
| Pencil | IDE-native canvas | Free* | ✓ Native | Claude Code integrated, AI agents, git-based |
| Frame0 | Low-fi + AI | Free | ✓ | Modern Balsamiq alternative, AI-assisted |
| Paper sketch | Physical | Free | N/A | Fastest iteration, zero setup |
Excalidraw (excalidraw.com):
- Open-source, hand-drawn aesthetic reduces over-specification
- MCP available:
github.com/yctimlin/mcp_excalidraw
- Export: PNG recommended (1000-1200px), also SVG/JSON
- Best for: Architecture diagrams, quick UI sketches
tldraw (tldraw.com):
- Infinite canvas with minimal UI, excellent SDK for custom apps
- Agent starter kit available for building AI-integrated tools
- Export: JSON native, PNG via screenshot
- Best for: Collaborative wireframing, embedding in custom tools
Frame0 (frame0.app):
- Modern Balsamiq alternative (2025), offline-first desktop app
- Built-in AI: text-to-wireframe, screenshot-to-wireframe conversion
- Native MCP integration for Claude workflows
- Best for: Teams wanting low-fi wireframes with AI assistance
Pencil (pencil.dev):
- IDE-native infinite canvas (Cursor/VSCode/Claude Code)
- AI multiplayer agents running in parallel for collaborative design
- Format:
.pen JSON, git-versionnable with branch/merge support
- MCP: Bi-directional read+write access to design files
- Founded by Tom Krcha (ex-Adobe XD), funded a16z Speedrun
- Export: .pen JSON native, PNG via screenshot, Figma import (copy-paste)
- Best for: Engineer-designers wanting design-as-code paradigm, teams on Cursor/Claude Code workflows
⚠️ Note: Launched January 2026, strong traction (1M+ views, FAANG adoption) but still maturing. Currently free; pricing model TBD. Recommended for early adopters comfortable with rapid iteration.
Paper + Photo:
- Seriously, this works extremely well
- Snap a photo with your smartphone → paste directly in Claude Code
- Tips: Good lighting, tight crop, avoid reflections/shadows
- Claude handles rotations and hand-drawn artifacts well
Recommended export settings: PNG format, 1000-1200px on longest side, high contrast
Figma MCP Integration
Figma provides an official MCP server (announced 2025) that gives Claude direct access to your design files, dramatically reducing token usage compared to screenshots alone.
Setup options:
# Remote MCP (all Figma plans, any machine)
claude mcp add --transport http figma https://mcp.figma.com/mcp
# Desktop MCP (requires Figma desktop app with Dev Mode)
claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp
Available tools via Figma MCP:
| Tool | Purpose | Tokens |
|---|
get_design_context | Extracts React+Tailwind structure from frames | Low |
get_variable_defs | Retrieves design tokens (colors, spacing, typography) | Very low |
get_code_connect_map | Maps Figma components → your codebase | Low |
get_screenshot | Captures visual screenshot of frame | High |
get_metadata | Returns node properties, IDs, positions | Very low |
Why use Figma MCP over screenshots?
- 3-10x fewer tokens: Structured data vs. image analysis
- Direct token access: Colors, spacing values are extracted, not interpreted
- Component mapping: Code Connect links Figma → actual code files
- Iterative workflow: Small changes don't require new screenshots
Recommended workflow:
1. get_metadata → Understand overall structure
2. get_design_context → Get component hierarchy for specific frames
3. get_variable_defs → Extract design tokens once per project
4. get_screenshot → Only when visual reference needed
Example session:
You: Implement the dashboard header from Figma
Claude: [Calls get_design_context for header frame]
→ Returns: React structure with Tailwind classes, exact spacing
Claude: [Calls get_variable_defs]
→ Returns: --color-primary: #3B82F6, --spacing-md: 16px
Claude: [Implements component matching Figma exactly]
Prerequisites:
- Figma account (Free tier works for remote MCP)
- Dev Mode seat for desktop MCP features
- Design file must be accessible to your account
MCP config file (examples/mcp-configs/figma.json):
{
"mcpServers": {
"figma": {
"transport": "http",
"url": "https://mcp.figma.com/mcp"
}
}
}
Image Optimization for Claude Vision
Understanding Claude's image processing helps optimize for speed and accuracy.
Resolution guidelines:
| Range | Effect |
|---|
| < 200px | Loss of precision, text unreadable |
| 200-1000px | Sweet spot for most wireframes |
| 1000-1568px | Optimal quality/token balance |
| 1568-8000px | Auto-downscaled (wastes upload time) |
| > 8000px | Rejected by API |
Token calculation: (width × height) / 750 ≈ tokens consumed
| Image Size | Approximate Tokens |
|---|
| 200×200 | ~54 tokens |
| 500×500 | ~334 tokens |
| 1000×1000 | ~1,334 tokens |
| 1568×1568 | ~3,279 tokens |
Format recommendations:
| Format | Use When |
|---|
| PNG | Wireframes, diagrams, text, sharp lines |
| WebP | General screenshots, good compression |
| JPEG | Photos only—compression artifacts harm line detection |
| GIF | Avoid (static only, poor quality) |
Optimization checklist:
💡 Token tip: A 1000×1000 wireframe uses ~1,334 tokens. The same information as structured text (via Figma MCP) might use 200-400 tokens. Use screenshots for visual context, structured data for implementation.
Session Continuation and Resume
Claude Code allows you to continue previous conversations across terminal sessions, maintaining full context and conversation history.
Two ways to resume:
-
Continue last session (--continue or -c):
# Automatically resumes your most recent conversation
claude --continue
# Short form
claude -c
-
Resume specific session (--resume <id> or -r <id>):
# Resume a specific session by ID
claude --resume abc123def
# Short form
claude -r abc123def
-
Link to a GitHub PR (--from-pr <number>, v2.1.49+):
# Start a session linked to a specific PR
claude --from-pr 123
# Sessions created via gh pr create during a Claude session
# are auto-linked to that PR — use --from-pr to resume them
gh pr create --title "Add auth" --body "..."
# Later:
claude --from-pr 123 # Resumes the session context for this PR
Useful for continuing work on a feature exactly where you left off relative to a specific PR — no need to remember session IDs.
Finding session IDs:
# Native: Interactive session picker
claude --resume
# Native: List via Serena MCP (if configured)
claude mcp call serena list_sessions
# Recommended: Fast search with ready-to-use resume commands
# See examples/scripts/session-search.sh (bash, zero dependencies, 15ms list, 400ms search)
# See examples/scripts/cc-sessions.py (Python, incremental index, partial resume, branch filter)
cs # List 10 most recent sessions
cs "authentication" # Full-text search across all sessions
# Sessions are also shown when you exit
You: /exit
Session ID: abc123def (saved for resume)
Session Search Tools: For fast session search, see session-search.sh (bash, lightweight) and cc-sessions.py (Python, advanced features: incremental index, partial ID resume, branch filter). Also: Observability Guide.
Common use cases:
| Scenario | Command | Why |
|---|
| Interrupted work | claude -c | Pick up exactly where you left off |
| Multi-day feature | claude -r abc123 | Continue complex task across days |
| After break/meeting | claude -c | Resume without losing context |
| Parallel projects | claude -r <id> | Switch between different project contexts |
| Code review follow-up | claude -r <id> | Address review comments in original context |
Example workflow:
# Day 1: Start implementing authentication
cd ~/project
claude
You: Implement JWT authentication with refresh tokens
Claude: [Analysis and initial implementation]
You: /exit
Session ID: auth-feature-xyz (27% context used)
# Day 2: Continue the work
cd ~/project
claude --continue
Claude: Resuming session auth-feature-xyz...
You: Add rate limiting to the auth endpoints
Claude: [Continues with full context of Day 1 work]
Best practices:
- Use
/exit properly: Always exit with /exit or Ctrl+D (not force-kill) to ensure session is saved
- Descriptive final messages: End sessions with context ("Ready for testing") so you remember the state when resuming
- Proactive context management: Monitor with
/status and use research-backed thresholds:
- 70%: Warning - Start planning cleanup or handoff
- 85%: Manual handoff recommended - Prevent auto-compact degradation (research-backed)
- 95%: Force handoff - Severe quality degradation
- Session naming: Use meaningful session IDs when available to identify different work streams
Resume vs. fresh start:
| Use Resume When... | Start Fresh When... |
|---|
| Continuing a specific feature/task | Switching to unrelated work |
| Building on previous decisions | Previous session went off track |
| Context is still relevant (<75%) | Context is bloated (>90%) |
| Multi-step implementation in progress | Quick one-off questions |
Limitations:
- Sessions are stored locally (not synced across machines)
- Very old sessions may be pruned (depends on local storage limits)
- Corrupted sessions can't be resumed (start fresh with
/clear)
- Cannot resume sessions started with different model or MCP config
Context preservation:
When you resume, Claude retains:
- ✅ Full conversation history
- ✅ Files previously read/edited
- ✅ CLAUDE.md and project settings
- ✅ MCP server state (if Serena is used)
- ✅ Uncommitted code changes awareness
Combining with MCP Serena:
For advanced session management with project memory and symbol tracking:
# Initialize Serena memory for the project
claude mcp call serena initialize_session
# Work with full session persistence
You: Implement user authentication
Claude: [Works with Serena tracking symbols and context]
# Exit and resume later with full project memory
claude -c
Claude: [Resumes with Serena's persistent project understanding]
💡 Pro tip: Use claude -c as your default way to start Claude Code in active projects. This ensures you never lose context from previous sessions unless you explicitly want a fresh start with claude (no flags).
Source: DeepTo Claude Code Guide - Context Resume Functions
1.4 Permission Modes
Claude Code has five permission modes that control how much autonomy Claude has:
Default Mode
Claude asks permission before:
- Editing files
- Running commands
- Making commits
This is the safest mode for learning.
Auto-accept Mode (acceptEdits)
You: Turn on auto-accept for the rest of this session
Claude auto-approves file edits but still asks for shell commands. Use when you trust the edits and want speed.
⚠️ Warning: Only use auto-accept for well-defined, reversible operations.
Plan Mode
/plan
Claude can only read and analyze, no modifications allowed. Perfect for:
- Understanding unfamiliar code
- Exploring architectural options
- Safe investigation before changes
Exit with /execute when ready to make changes.
Don't Ask Mode (dontAsk)
Auto-denies tools unless pre-approved via /permissions or permissions.allow rules. Claude never interrupts with permission prompts: if a tool isn't explicitly allowed, it's silently denied.
Use for restrictive workflows where you want tight control over which tools run, without interactive confirmation.
Bypass Permissions Mode (bypassPermissions)
Auto-approves everything, including shell commands. No permission prompts at all.
⚠️ Warning: Only use in sandboxed CI/CD environments. Requires --dangerously-skip-permissions to enable from CLI. Never use on production systems or with untrusted code.
1.5 Productivity Checklist
You're ready for Day 2 when you can:
1.6 Migrating from Other AI Coding Tools
Switching from GitHub Copilot, Cursor, or other AI assistants? Here's what you need to know.
Why Claude Code is Different
| Feature | GitHub Copilot | Cursor | Claude Code |
|---|
| Interaction | Inline autocomplete | Chat + autocomplete | CLI + conversation |
| Context | Current file | Open files | Entire project |
| Autonomy | Suggestions only | Edit + chat | Full task execution |
| Customization | Limited | Extensions | Agents, skills, hooks, MCP |
| Cost Model | $10-20/month flat | $20/month flat | Pay-per-use ($0.10-$0.50/hour) |
Key mindset shift: Claude Code is a structured context system, not a chatbot or autocomplete tool. You build persistent context (CLAUDE.md, skills, hooks) that compounds over time — see §2.5.
Migration Guide: GitHub Copilot → Claude Code
What Copilot Does Well
- Inline suggestions - Fast autocomplete as you type
- Familiar workflow - Works inside your editor
- Low friction - No context switching
What Claude Code Does Better
- Multi-file refactoring - Copilot: one file at a time | Claude: reads and edits across files
- Complex tasks - Copilot: suggests lines | Claude: implements features
- Understanding context - Copilot: current file | Claude: can search and read project-wide
- Explaining code - Copilot: limited | Claude: detailed explanations
- Debugging - Copilot: weak | Claude: systematic root cause analysis
Hybrid Approach (Recommended)
Use Copilot for:
- Quick autocomplete while typing
- Boilerplate code generation
- Simple function completions
Use Claude Code for:
- Feature implementation (multi-file changes)
- Debugging complex issues
- Code reviews and refactoring
- Understanding unfamiliar codebases
- Writing tests for entire modules
Workflow example:
# Morning: Plan feature with Claude Code
claude
You: "I need to add user authentication. What's the best approach for this codebase?"
# Claude analyzes project, suggests architecture
# During coding: Use Copilot for inline completions
# Type in VS Code, Copilot autocompletes
# Afternoon: Debug with Claude Code
claude
You: "Login fails on mobile but works on desktop. Debug this."
# Claude systematically investigates
# End of day: Review with Claude Code
claude
You: "Review my changes today. Check for security issues."
# Claude reviews all modified files
Migration Guide: Cursor → Claude Code
What Cursor Does Well
- Inline editing - Direct code modifications in editor
- GUI interface - Familiar VS Code experience
- Chat + autocomplete - Both modalities in one tool
What Claude Code Does Better
- Terminal-native workflow - Better for CLI-heavy developers
- Advanced customization - Agents, skills, hooks, commands
- MCP servers - Extensibility beyond what Cursor offers
- Cost efficiency - Pay for what you use vs. flat $20/month
- Git integration - Native git operations, commit generation
- CI/CD integration - Headless mode for automation
When to Switch
Stick with Cursor if:
- You strongly prefer GUI over CLI
- You want all-in-one IDE experience
- You use it >4 hours/day (flat rate is better)
- You don't need advanced customization
Switch to Claude Code if:
- You're comfortable with terminal workflows
- You want deeper customization (agents, hooks)
- You work with complex, multi-repo projects
- You want to integrate AI into CI/CD
- You prefer pay-per-use pricing
Running Both
You can use both tools simultaneously:
# Cursor for editing and quick changes
# Claude Code in terminal for complex tasks
# Example workflow:
# 1. Use Cursor to explore and make quick edits
# 2. Open terminal: claude
# 3. Ask Claude Code: "Review my changes and suggest improvements"
# 4. Apply suggestions in Cursor
# 5. Use Claude Code to generate tests
Migration Checklist
Week 1: Learning Phase
□ Complete Quick Start (Section 1)
□ Understand context management (critical!)
□ Try 3-5 small tasks (bug fixes, small features)
□ Learn when to use /plan mode
□ Practice reviewing diffs before accepting
Week 2: Establishing Workflow
□ Create project CLAUDE.md file
□ Set up 1-2 custom commands for frequent tasks
□ Configure MCP servers (Serena, Context7)
□ Define your hybrid workflow (when to use Claude Code vs. other tools)
□ Track costs and optimize based on usage
Week 3-4: Advanced Usage
□ Create custom agents for specialized tasks
□ Set up hooks for automation (formatting, linting)
□ Integrate into CI/CD if applicable
□ Build team patterns if working with others
□ Refine CLAUDE.md based on learnings
Common Migration Issues
Issue 1: "I miss inline suggestions"
- Solution: Keep using Copilot/Cursor for autocomplete, use Claude Code for complex tasks
- Alternative: Request Claude to generate code snippets you can paste
Issue 2: "Context switching is annoying"
- Solution: Use split terminal (editor on left, Claude Code on right)
- Tip: Set up keyboard shortcut to toggle terminal focus
Issue 3: "I don't know when to use which tool"
- Rule of thumb:
- <5 lines of code → Use Copilot/autocomplete
- 5-50 lines, single file → Either tool works
- >50 lines or multi-file → Use Claude Code
Issue 4: "Claude Code is slower than autocomplete"
- Reality check: Claude Code solves different problems
- Don't compare: Autocomplete vs. full task execution
- Optimize: Use specific queries, manage context well
Issue 5: "Costs are unpredictable"
- Solution: Track costs in Anthropic Console
- Budget: Set mental budget per session ($0.10-$0.50)
- Optimize: Use
/compact, be specific in queries
Transition Strategies
Strategy 1: Gradual (Recommended)
Week 1: Use Claude Code 1-2 times/day for specific tasks
Week 2: Use Claude Code for all debugging and reviews
Week 3: Use Claude Code for feature implementation
Week 4: Full workflow integration
Strategy 2: Cold Turkey
Day 1: Disable Copilot/Cursor, force yourself to use only Claude Code
Day 2-3: Frustration period (learning curve)
Day 4-7: Productivity recovery
Week 2+: Full proficiency
Strategy 3: Task-Based
Use Claude Code exclusively for:
- All new features
- All debugging sessions
- All code reviews
Keep Copilot/Cursor for:
- Quick edits
- Autocomplete
Measuring Success
You know you've successfully migrated when:
Subjective productivity indicators (your experience may vary):
- Feeling more productive on complex tasks
- Spending less time on boilerplate and debugging
- Catching more issues through Claude reviews
- Better understanding of unfamiliar code
1.7 Trust Calibration: When and How Much to Verify
AI-generated code requires proportional verification based on risk level. Blindly accepting all output or paranoidly reviewing every line both waste time. This section helps you calibrate your trust.
The Problem: Verification Debt
Research consistently shows AI code has higher defect rates than human-written code:
Key insight: AI produces code faster but verification becomes the bottleneck. The question isn't "does it work?" but "how do I know it works?"
Nuance on downstream maintainability: A 2-phase blind RCT (Borg et al., 2025, n=151 professional developers) found no significant difference in the time needed for downstream developers to evolve AI-generated vs. human-generated code. The defect rates above are real — but they do not systematically translate into higher maintenance burden for the next developer. The risk is more narrowly scoped than commonly assumed. (arXiv:2507.00788)
The Verification Spectrum
Not all code needs the same scrutiny. Match verification effort to risk:
| Code Type | Verification Level | Time Investment | Techniques |
|---|
| Boilerplate (configs, imports) | Light skim | 10-30 sec | Glance, trust structure |
| Utility functions (formatters, helpers) | Quick test | 1-2 min | One happy path test |
| Business logic | Deep review + tests | 5-15 min | Line-by-line, edge cases |
| Security-critical (auth, crypto, input validation) | Maximum + tools | 15-30 min | Static analysis, fuzzing, peer review |
| External integrations (APIs, databases) | Integration tests | 10-20 min | Mock + real endpoint test |
Solo vs Team Verification
Solo Developer Strategy:
Without peer reviewers, compensate with:
- High test coverage (>70%): Your safety net
- Vibe Review: An intermediate layer between "accept blindly" and "review every line":
- Read the commit message / summary
- Skim the diff for unexpected file changes
- Run the tests
- Quick sanity check in the app
- Ship if green
- Static analysis tools: ESLint, SonarQube, Semgrep catch what you miss
- Time-boxing: Don't spend 30 min reviewing a 10-line utility
Solo workflow:
Generate → Vibe Review → Tests pass? → Ship
↓
Tests fail? → Deep review → Fix
Team Strategy:
With multiple developers:
- AI first-pass review: Let Claude or Copilot review first (catches 70-80% of issues)
- Human sign-off required: AI review ≠ approval
- Domain experts for critical paths: Security code → security-trained reviewer
- Rotate reviewers: Prevent blind spots from forming
Team workflow:
Generate → AI Review → Human Review → Merge
↓ ↓
Flag issues Final approval
The "Prove It Works" Checklist
Before shipping AI-generated code, verify:
Functional correctness:
Security baseline:
Integration sanity:
Code quality:
Anti-Patterns to Avoid
| Anti-Pattern | Problem | Better Approach |
|---|
| "It compiles, ship it" | Syntax ≠ correctness | Run at least one test |
| "AI wrote it, must be secure" | AI optimizes for plausible, not safe | Always review security-critical code manually |
| "Tests pass, done" | Tests might not cover the change | Check test coverage of modified lines |
| "Same as last time" | Context changes, AI may generate different code | Each generation is independent |
| "Senior dev wrote the prompt" | Seniority doesn't guarantee output quality | Review output, not input |
| "It's just boilerplate" | Even boilerplate can hide issues | At minimum, skim for surprises |
Calibrating Over Time
Your verification strategy should evolve:
- Start cautious: Review everything when new to Claude Code
- Track failure patterns: Where do bugs slip through?
- Tighten critical paths: Double-down on areas with past incidents
- Relax low-risk areas: Trust AI more for stable, tested code types
- Periodic audits: Spot-check "trusted" code occasionally
Mental model: Think of AI as a capable junior developer. You wouldn't deploy their code unreviewed, but you also wouldn't rewrite everything they produce.
Putting It Together
┌─────────────────────────────────────────────────────────┐
│ TRUST CALIBRATION FLOW │
├─────────────────────────────────────────────────────────┤
│ │
│ AI generates code │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ What type? │ │
│ └──────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Boiler Business Security │
│ -plate logic critical │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Skim Test + Full review │
│ only review + tools │
│ │ │ │ │
│ └──────┴────────┘ │
│ │ │
│ ▼ │
│ Tests pass? ──No──► Debug & fix │
│ │ │
│ Yes │
│ │ │
│ ▼ │
│ Ship it │
│ │
└─────────────────────────────────────────────────────────┘
"AI lets you code faster—make sure you're not also failing faster."
— Adapted from Addy Osmani
Attribution: This section draws from Addy Osmani's "AI Code Review" (Jan 2026), research from ACM, Veracode, CodeRabbit, and Cortex.io.
1.8 Eight Beginner Mistakes (and How to Avoid Them)
Common pitfalls that slow down new Claude Code users:
1. ❌ Skipping the Plan
Mistake: Jumping straight into "fix this bug" without explaining context.
Fix: Use the WHAT/WHERE/HOW/VERIFY format:
WHAT: Fix login timeout error
WHERE: src/auth/session.ts
HOW: Increase token expiry from 1h to 24h
VERIFY: Login persists after browser refresh
2. ❌ Ignoring Context Limits
Mistake: Working until context hits 95% and responses degrade.
Fix: Watch Ctx(u): in the status line. /compact at 70%, /clear at 90%.
3. ❌ Using Vague Prompts
Mistake: "Make this code better" or "Check for bugs"
Fix: Be specific: "Refactor calculateTotal() to handle null prices without throwing"
4. ❌ Accepting Changes Blindly
Mistake: Hitting "y" without reading the diff.
Fix: Always review diffs. Use "n" to reject, then explain what's wrong.
5. ❌ No Version Control Safety
Mistake: Making large changes without commits.
Fix: Commit before big changes. Use feature branches. Claude can help: /commit
6. ❌ Overly Broad Permissions
Mistake: Setting Bash(*) or --dangerously-skip-permissions
Fix: Start restrictive, expand as needed. Use allowlists: Bash(npm test), Bash(git *)
7. ❌ Mixing Unrelated Tasks
Mistake: "Fix the auth bug AND refactor the database AND add new tests"
Fix: One focused task per session. /clear between different tasks.
8. ❌ Treating Claude Code Like a Chatbot
Mistake: Typing ad-hoc instructions every session. Repeating project conventions, re-explaining architecture, manually enforcing quality checks.
Fix: Build structured context that compounds over time:
- CLAUDE.md: Your conventions, stack, and patterns — loaded every session automatically
- Skills: Reusable workflows (
/review, /deploy) for consistent execution
- Hooks: Automated guardrails (lint, security, formatting) — zero manual effort
Start with CLAUDE.md in Week 1. See §2.6 Mental Model for the full framework.
Quick Self-Check
Before your next session, verify:
Tip: Bookmark Section 9.11 for detailed pitfall explanations and solutions.
2. Core Concepts
Quick jump: The Interaction Loop · Context Management · Plan Mode · Rewind · Model Selection · Mental Model · Config Decision Guide · Data Flow & Privacy
📌 Section 2 TL;DR (2 minutes)
What you'll learn: The mental model and critical workflows for Claude Code mastery.
Key Concepts:
- Interaction Loop: Describe → Analyze → Review → Accept/Reject cycle
- Context Management 🔴 CRITICAL: Watch
Ctx(u): — /compact at 70%, /clear at 90%
- Plan Mode: Read-only exploration before making changes
- Rewind: Undo with Esc×2 or /rewind
- Mental Model: Claude = expert pair programmer, not autocomplete
The One Rule:
Always check context % before starting complex tasks. High context = degraded quality.
Read this section if: You want to avoid the #1 mistake (context overflow)
Skip if: You just need quick command reference (go to Section 10)
Reading time: 20 minutes
Skill level: Day 1-3
Goal: Understand how Claude Code thinks
2.1 The Interaction Loop
Every Claude Code interaction follows this pattern:
┌─────────────────────────────────────────────────────────┐
│ INTERACTION LOOP │
├─────────────────────────────────────────────────────────┤
│ │
│ 1. DESCRIBE ──→ You explain what you need │
│ │ │
│ ▼ │
│ 2. ANALYZE ──→ Claude explores the codebas │
│ │ │
│ ▼ │
│ 3. PROPOSE ──→ Claude suggests changes (diff) │
│ │ │
│ ▼ │
│ 4. REVIEW ──→ You read and evaluate │
│ │ │
│ ▼ │
│ 5. DECIDE ──→ Accept / Reject / Modify │
│ │ │
│ ▼ │
│ 6. VERIFY ──→ Run tests, check behavior │
│ │ │
│ ▼ │
│ 7. COMMIT ──→ Save changes (optional) │
│ │
└─────────────────────────────────────────────────────────┘
Key Insight
The loop is designed so that you remain in control. Claude proposes, you decide.
2.2 Context Management
🔴 This is the most important concept in Claude Code.
📌 Context Management Quick Reference
The zones:
- 🟢 0-50%: Work freely
- 🟡 50-75%: Be selective
- 🔴 75-90%:
/compact now
- ⚫ 90%+:
/clear required
When context is high:
/compact (saves context, frees space)
/clear (fresh start, loses history)
Prevention: Load only needed files, compact regularly, commit frequently
What is Context?
Context is Claude's "working memory" for your conversation. It includes:
- All messages in the conversation
- Files Claude has read
- Command outputs
- Tool results
The Context Budget
Claude has a 200,000 token context window. Think of it like RAM - when it fills up, things slow down or fail.
Reading the Statusline
The statusline shows your context usage:
Claude Code │ Ctx(u): 45% │ Cost: $0.23 │ Session: 1h 23m
| Metric | Meaning |
|---|
Ctx(u): 45% | You've used 45% of context |
Cost: $0.23 | API cost so far |
Session: 1h 23m | Time elapsed |
Custom Statusline Setup
The default statusline can be enhanced with more detailed information like git branch, model name, and file changes.
Option 1: ccstatusline (recommended)
Add to ~/.claude/settings.json:
{
"statusLine": {
"type": "command",
"command": "npx -y ccstatusline@latest",
"padding": 0
}
}
This displays: Model: Sonnet 4.6 | Ctx: 0 | ⎇ main | (+0,-0) | Cost: $0.27 | Session: 0m | Ctx(u): 0.0%
Option 2: Custom script
Create your own script that:
- Reads JSON data from stdin (model, context, cost, git info)
- Outputs a single formatted line to stdout
- Supports ANSI colors for styling
{
"statusLine": {
"type": "command",
"command": "/path/to/your/statusline-script.sh",
"padding": 0
}
}
Use /statusline command in Claude Code to auto-generate a starter script.
Context Zones
| Zone | Usage | Action |
|---|
| 🟢 Green | 0-50% | Work freely |
| 🟡 Yellow | 50-75% | Start being selective |
| 🔴 Red | 75-90% | Use /compact or /clear |
| ⚫ Critical | 90%+ | Must clear or risk errors |
Context Recovery Strategies
When context gets high:
Option 1: Compact (/compact)
- Summarizes the conversation
- Preserves key context
- Reduces usage by ~50%
Option 2: Clear (/clear)
- Starts fresh
- Loses all context
- Use when changing topics
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"
Context Triage: What to Keep vs. Evacuate
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.
Session vs. Persistent Memory
Claude Code has two distinct memory systems. Understanding the difference is crucial for effective long-term work:
| Aspect | Session Memory | Persistent Memory |
|---|
| Scope | Current conversation only | Across all sessions |
| Managed by | /compact, /clear | /memory command, CLAUDE.md files |
| Lost when | Session ends or /clear | Explicitly deleted from files |
| Use case | Immediate working context | Long-term decisions, patterns |
Session Memory (short-term):
- Everything in your current conversation
- Files Claude has read, commands run, decisions made
- Managed with
/compact (compress) and /clear (reset)
- Disappears when you close Claude Code
Persistent Memory (long-term):
- Requires Serena MCP server installed
- 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
- Persistent memory: Decisions you'll need in future sessions
- CLAUDE.md: Team conventions, project structure (versioned with git)
Fresh Context Pattern (Ralph Loop)
The Problem: Context Rot
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 Claude models
- 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.
The Pattern
# Canonical "Ralph Loop" (Geoffrey Huntley)
while :; do cat TASK.md PROGRESS.md | claude -p ; done
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.
| Traditional | Fresh Context |
|---|
| Accumulate in chat history | Reset per task |
/compact to compress | State in files + git |
| Context bleeds across tasks | Each task gets full attention |
When to Use
| Situation | Use |
|---|
| Context 70-90%, staying interactive | /compact |
| Context 90%+, need fresh start | /clear then continue |
| Long autonomous run, task-based | Fresh Context Pattern |
| Overnight/AFK execution | Fresh Context Pattern |
Good fit:
- Autonomous sessions >1 hour
- Migrations, large refactorings
- 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.
Practical Implementation
Option 1: Manual loop
# Simple fresh-context loop
for i in {1..10}; do
echo "=== Iteration $i ==="
claude -p "$(cat TASK.md PROGRESS.md)"
git diff --stat # Check progress
read -p "Continue? (y/n) " -n 1 -r
[[ ! $REPLY =~ ^[Yy]$ ]] && break
done
Option 2: Script (see examples/scripts/fresh-context-loop.sh)
./fresh-context-loop.sh 10 TASK.md PROGRESS.md
Option 3: External orchestrators
- AFK CLI — Zero-config orchestration across task sources
Task Definition Template
# TASK.md
## Current Focus
[Single atomic task with clear deliverable]
## Acceptance Criteria
- [ ] Tests pass
- [ ] Build succeeds
- [ ] [Specific verification]
## Context
- Related files: [paths]
- Constraints: [rules]
## Do NOT
- Start other tasks
- Refactor unrelated code
Key Insight
/compact preserves conversation flow. Fresh context maximizes per-task attention at the cost of continuity.
Sources: Chroma Research - Context Rot | Ralph Loop Origin | METR - Long Task Capability | Anthropic - Context Engineering
What Consumes Context?
| Action | Context Cost |
|---|
| Reading a small file | Low (~500 tokens) |
| Reading a large file | High (~5K+ tokens) |
| Running commands | Medium (~1K tokens) |
| Multi-file search | High (~3K+ tokens) |
| Long conversations | Accumulates |
Context Depletion Symptoms
Learn to recognize when context is running out:
| Symptom | Severity | Action |
|---|
| Shorter responses than usual | 🟡 Warning | Continue with caution |
| Forgetting CLAUDE.md instructions | 🟠 Serious | Document state, prepare checkpoint |
| Inconsistencies with earlier conversation | 🔴 Critical | New session needed |
| Errors on code already discussed | 🔴 Critical | New session needed |
| "I can't access that file" (when it was read) | 🔴 Critical | New session immediately |
Context Inspection
Check your context usage in detail:
/context
Example output:
┌─────────────────────────────────────────────────────────────┐
│ CONTEXT USAGE 67% used │
├─────────────────────────────────────────────────────────────┤
│ System Prompt ████████░░░░░░░░░░░░░░░░ 12,450 tk │
│ System Tools ██░░░░░░░░░░░░░░░░░░░░░░ 3,200 tk │
│ MCP Tools (5 servers) ████████████░░░░░░░░░░░░ 18,600 tk │
│ Conversation ████████████████████░░░░ 89,200 tk │
├─────────────────────────────────────────────────────────────┤
│ TOTAL 123,450 tk │
│ REMAINING 76,550 tk │
└─────────────────────────────────────────────────────────────┘
💡 The Last 20% Rule: Reserve ~20% of context for:
- Multi-file operations at end of session
- Last-minute corrections
- Generating summary/checkpoint
Cost Awareness & Optimization
Claude Code isn't free - you're using API credits. Understanding costs helps optimize usage.
Pricing Model (as of February 2026)
The default model depends on your subscription: Max/Team Premium subscribers get Opus 4.6 by default, while Pro/Team Standard subscribers get Sonnet 4.6. If Opus usage hits the plan threshold, it auto-falls back to Sonnet.
| Model | Input (per 1M tokens) | Output (per 1M tokens) | Context Window | Notes |
|---|
| Sonnet 4.6 | $3.00 | $15.00 | 200K tokens | Default model (Feb 2026) |
| Sonnet 4.5 | $3.00 | $15.00 | 200K tokens | Legacy (same price) |
| Opus 4.6 (standard) | $5.00 | $25.00 | 200K tokens | Released Feb 2026 |
| Opus 4.6 (1M context beta) | $10.00 | $37.50 | 1M tokens | Requests >200K context |
| Opus 4.6 (fast mode) | $30.00 | $150.00 | 200K tokens | 2.5x faster, 6x price |
| Haiku 4.5 | $0.80 | $4.00 | 200K tokens | Budget option |
Reality check: A typical 1-hour session costs $0.10 - $0.50 depending on usage patterns.
Model deprecations (Feb 2026): claude-3-haiku-20240307 (Claude 3 Haiku) was deprecated on February 19, 2026 with retirement scheduled for April 20, 2026. If your CLAUDE.md, agent definitions, or scripts hardcode this model ID, migrate to claude-haiku-4-5-20251001 (Haiku 4.5) before April 2026. Source: platform.claude.com/docs/model-deprecations
200K vs 1M Context: Performance, Cost & Use Cases
The 1M context window (beta, API + usage tier 4 required) is a significant capability jump — but community feedback consistently frames it as a niche premium tool, not a default.
Retrieval accuracy at scale (MRCR v2 8-needle 1M variant)
| Model | 256K accuracy | 1M accuracy | Source |
|---|
| Opus 4.6 | 93% | 76% | Anthropic blog + independent analysis (Feb 2026) |
| Sonnet 4.5 | — | 18.5% | Anthropic blog (Feb 2026) |
| Sonnet 4.6 | Not yet published | Not yet published | — |
The benchmark is the "8-needle 1M variant" — finding 8 specific facts in a 1M-token document. Opus 4.6 drops from 93% to 76% when scaling from 256K to 1M; Sonnet 4.5 collapses to 18.5%. Community validation: a developer loaded ~733K tokens (4 Harry Potter books) and Opus 4.6 retrieved 49/50 documented spells in a single prompt (HN, Feb 2026). Sonnet 4.6 MRCR not yet published, but community reports suggest it "struggles with following specific instructions and retrieving precise information" at full 1M context.
Cost per session (approximate)
Above 200K input tokens, all tokens in the request are charged at premium rates — not just the excess. Applies to both Sonnet 4.6 and Opus 4.6.
| Session type | ~Tokens in | ~Tokens out | Sonnet 4.6 | Opus 4.6 |
|---|
| Bug fix / PR review (≤200K) | 50K | 5K | ~$0.23 | ~$0.38 |
| Module refactoring (≤200K) | 150K | 20K | ~$0.75 | ~$1.25 |
| Full service analysis (>200K, 1M beta) | 500K | 50K | ~$4.13 | ~$6.88 |
For comparison: Gemini 1.5 Pro offers a 2M context window at $3.50/$10.50/MTok — significantly cheaper for pure long-context RAG. Community advice: use Gemini for large-document RAG, Claude for reasoning quality and agentic workflows.
When to use which
| Scenario | Recommendation |
|---|
| Bug fix, PR review, daily coding | Sonnet 4.6 @ 200K — fast and cheap |
| Full-repo audit, entire codebase load | Opus 4.6 @ 1M — worth the cost for precision |
| Cross-module refactoring | Sonnet 4.6 @ 1M — but weigh cost vs. chunking + RAG |
| Architecture analysis, Agent Teams | Opus 4.6 @ 1M — strongest retrieval at scale |
| Large-document RAG (PDFs, legal, books) | Consider Gemini 1.5 Pro — cheaper at this scale |
Key facts
- Opus 4.6 max output: 128K tokens; Sonnet 4.6 max output: 64K tokens
- 1M context ≈ 30,000 lines of code / 750,000 words
- 1M context is beta — requires
anthropic-beta: context-1m-2025-08-07 header, usage tier 4 or custom rate limits
- Above 200K input tokens: Sonnet 4.6 doubles to $6/$22.50/MTok; Opus 4.6 doubles to $10/$37.50/MTok
- If input stays ≤200K, standard pricing applies even with the beta flag enabled
- Practical workaround: check context at ~70% and open a new session rather than hitting compaction (HN pattern)
- Community consensus: 200K + RAG is the default; 1M Opus is reserved for cases where loading everything at once is genuinely necessary
What Costs the Most?
| Action | Tokens Consumed | Estimated Cost |
|---|
| Read a 100-line file | ~500 | $0.0015 |
| Read 10 files (1000 lines) | ~5,000 | $0.015 |
| Long conversation (20 messages) | ~30,000 | $0.090 |
| MCP tool call (Serena, Context7) | ~2,000 | $0.006 |
| Running tests (with output) | ~3,000-10,000 | $0.009-$0.030 |
| Code generation (100 lines) | ~2,000 output | $0.030 |
The expensive operations:
- Reading entire large files - 2000+ line files add up fast
- Multiple MCP server calls - Each server adds ~2K tokens overhead
- Long conversations without
/compact - Context accumulates
- Repeated trial and error - Each iteration costs
Cost Optimization Strategies
Strategy 1: Be specific in queries
# ❌ Expensive - reads entire file
"Check auth.ts for issues"
# ~5K tokens if file is large
# ✅ Cheaper - targets specific location
"Check the login function in auth.ts:45-60"
# ~500 tokens
Strategy 2: Use /compact proactively
# Without /compact - conversation grows
Context: 10% → 30% → 50% → 70% → 90%
Cost per message increases as context grows
# With /compact at 70%
Context: 10% → 30% → 50% → 70% → [/compact] → 30% → 50%
Frees significant context space for subsequent messages
Strategy 3: Choose the right model
# Use Haiku for simple tasks (4x cheaper input, 3.75x cheaper output)
claude --model haiku "Fix this typo in README.md"
# Use Sonnet (default) for standard work
claude "Refactor this module"
# Use Opus only for critical/complex tasks
claude --model opus "Design the entire authentication system"
Strategy 4: Limit MCP servers
// ❌ Expensive - 5 MCP servers loaded
{
"mcpServers": {
"serena": {...},
"context7": {...},
"sequential": {...},
"playwright": {...},
"postgres": {...}
}
}
// ~10K tokens overhead per session
// ✅ Cheaper - load only what you need
{
"mcpServers": {
"serena": {...} // Only for this project
}
}
// ~2K tokens overhead
Strategy 5: Batch operations
# ❌ Expensive - 5 separate prompts
"Read file1.ts"
"Read file2.ts"
"Read file3.ts"
"Read file4.ts"
"Read file5.ts"
# ✅ Cheaper - single batched request
"Read file1.ts, file2.ts, file3.ts, file4.ts, file5.ts and analyze them together"
# Shared context, single response
Strategy 6: Use prompt caching for repeated context (API)
If you call the Anthropic API directly (e.g., for custom agents or pipelines), prompt caching cuts costs by up to 90% on repeated prefixes.
# Mark stable sections with cache_control
response = client.messages.create(
model="claude-sonnet-4-6-20250514",
max_tokens=1024,
system=[
{
"type": "text",
"text": "<your large system prompt / codebase context>",
"cache_control": {"type": "ephemeral"} # Cache this prefix
}
],
messages=[{"role": "user", "content": "Fix the bug in auth.ts"}]
)
Prompt caching economics:
| Operation | Cost multiplier | TTL |
|---|
| Cache write | 1.25x base price | 5 minutes (default) |
| Cache write (extended) | 2x base price | 1 hour |
| Cache read (hit) | 0.1x base price | — |
| Latency reduction | Up to 85% for long prompts | — |
Break-even: 2 cache hits with 5-minute TTL. After that, pure savings.
Rules:
- Max 4 cache breakpoints per request
- Cache key = exact prefix match (single character change = cache miss)
- Place breakpoints after large stable sections: system prompt, tool definitions, codebase context
- For Claude Code itself: caching is handled automatically by the CLI — this applies to API-based workflows you build on top of Claude
Docs: prompt caching
Tracking Costs
Real-time tracking:
The status line shows current session cost:
Claude Code │ Ctx(u): 45% │ Cost: $0.23 │ Session: 1h 23m
↑ Current session cost
Advanced tracking with ccusage:
The ccusage CLI tool provides detailed cost analytics beyond the /cost command:
ccusage # Overview all periods
ccusage --today # Today's costs
ccusage --month # Current month
ccusage --session # Active session breakdown
ccusage --model-breakdown # Cost by model (Sonnet/Opus/Haiku)
Example output:
┌──────────────────────────────────────────────────────┐
│ USAGE SUMMARY - January 2026 │
├──────────────────────────────────────────────────────┤
│ Today $2.34 (12 sessions) │
│ This week $8.91 (47 sessions) │
│ This month $23.45 (156 sessions) │
├──────────────────────────────────────────────────────┤
│ MODEL BREAKDOWN │
│ Sonnet 3.5 85% $19.93 │
│ Opus 4.6 12% $2.81 │
│ Haiku 3.5 3% $0.71 │
└──────────────────────────────────────────────────────┘
Why use ccusage over /cost?
- Historical trends: Track usage patterns over days/weeks/months
- Model breakdown: See which model tier drives costs
- Budget planning: Set monthly spending targets
- Team analytics: Aggregate costs across developers
For a full inventory of community cost trackers, session viewers, config managers, and alternative UIs, see Third-Party Tools.
Monthly tracking:
Check your Anthropic Console for detailed usage:
Cost budgeting:
# Set a mental budget per session
- Quick task (5-10 min): $0.05-$0.10
- Feature work (1-2 hours): $0.20-$0.50
- Deep refactor (half day): $1.00-$2.00
# If you're consistently over budget:
1. Use /compact more often
2. Be more specific in queries
3. Consider using Haiku for simpler tasks
4. Reduce MCP servers
Cost vs. Value
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)
Cost-Conscious Workflows
For solo developers on a budget:
1. Start with Haiku for exploration/planning
2. Switch to Sonnet for implementation
3. Use /compact aggressively (every 50-60% context)
4. Limit to 1-2 MCP servers
5. Be specific in all queries
6. Batch operations when possible
Monthly cost estimate: $5-$15 for 20-30 hours
For professional developers:
1. Use Sonnet as default (optimal balance)
2. Use /compact when needed (70%+ context)
3. Use full MCP setup (productivity matters)
4. Don't micro-optimize queries
5. Use Opus for critical architectural decisions
Monthly cost estimate: $20-$50 for 40-80 hours
For teams:
1. Shared MCP infrastructure (Context7, Serena)
2. Standardized CLAUDE.md to avoid repeated explanations
3. Agent library to avoid rebuilding patterns
4. CI/CD integration for automation
5. Track costs per developer in Anthropic Console
Monthly cost estimate: $50-$200 for 5-10 developers
Red Flags (Cost Waste Indicators)
| Indicator | Cause | Fix |
|---|
| Sessions consistently >$1 | Not using /compact | Set reminder at 70% context |
| Cost per message >$0.05 | Context bloat | Start fresh /clear |
| >$5/day for hobby project | Over-using or inefficient queries | Review query specificity |
| Haiku failing simple tasks | Using wrong model tier | Use Sonnet for anything non-trivial |
Subscription Plans & Limits
Note: Anthropic's plans evolve frequently. Always verify current pricing and limits at claude.com/pricing.
How Subscription Limits Work
Unlike API usage (pay-per-token), subscriptions use a hybrid model that's deliberately opaque:
| Concept | Description |
|---|
| 5-hour rolling window | Primary limit; resets when you send next message after 5 hours lapse |
| Weekly aggregate cap | Secondary limit; resets every 7 days. Both apply simultaneously |
| Hybrid counting | Advertised as "messages" but actual capacity is token-based, varying by code complexity, file size, and context |
| Model weighting | Opus consumes 8-10× more quota than Sonnet for equivalent work |
Approximate Token Budgets by Plan (Jan 2026, community-verified)
| Plan | 5-Hour Token Budget | Weekly Sonnet Hours | Weekly Opus Hours | Claude Code Access |
|---|
| Free | 0 | 0 | 0 | ❌ None |
| Pro ($20/mo) | ~44,000 tokens | 40-80 hours | N/A (Sonnet only) | ✅ Limited |
| Max 5x ($100/mo) | ~88,000-220,000 tokens | 140-280 hours | 15-35 hours | ✅ Full |
| Max 20x ($200/mo) | ~220,000+ tokens | 240-480 hours | 24-40 hours | ✅ Full |
Warning: These are community-measured estimates. Anthropic does not publish exact token limits, and limits have been reduced without announcement (notably Oct 2025). The 8-10× Opus/Sonnet ratio means Max 20x users get only ~24-40 Opus hours weekly despite paying $200/month.
Why "Hours" Are Misleading
The term "hours of Sonnet 4" refers to elapsed wall-clock time during active processing, not calendar hours. This is not directly convertible to tokens without knowing:
- Code complexity (larger files = higher per-token overhead)
- Tool usage (Bash execution adds ~245 input tokens per call; text editor adds ~700)
- Context re-reads and caching misses
Tier-Specific Strategies
| If you have... | Recommended approach |
|---|