Last updated: February 2026
- What is Claude Code?
- Installation & Setup
- How It Works — The Agentic Loop
- Core Interfaces
- Essential Commands & Shortcuts
- CLAUDE.md — Persistent Memory
- Skills — Custom Slash Commands
- MCP — Connecting External Tools
- Subagents — Specialized Assistants
- Hooks — Automation & Event Triggers
- Plugins — Bundled Extensions
- Best Practices
- Common Workflows
- Advanced Use — Automation & Scale
- Context Management
- Settings & Configuration
- Syncing Across Machines
- Quick Reference Card
Claude Code is an agentic AI coding assistant that runs in your terminal (and desktop/IDE/web). Unlike inline code completers that only see the current file, Claude Code sees your whole project and can act across it.
When you ask Claude to "fix the authentication bug," it:
- Searches for relevant files
- Reads multiple files to understand context
- Makes coordinated edits across them
- Runs tests to verify the fix
- Commits the changes if you ask
The key difference: It's a capable colleague who can do things, not just suggest them.
| Category | Examples |
|---|---|
| File operations | Read, edit, create, rename, reorganize files |
| Search | Find files by pattern, search content with regex, explore codebases |
| Execution | Run shell commands, start servers, run tests, use git |
| Web | Search the web, fetch documentation, look up error messages |
| Orchestration | Spawn subagents, ask clarifying questions, delegate tasks |
- Terminal (CLI) — primary interface, supports scripting and automation
- Desktop App — visual diff review, file attachments, session management
- VS Code / JetBrains — IDE-native integration
- Web — run on Anthropic's cloud infrastructure
- GitHub Actions / GitLab CI/CD — automated PR reviews and issue triage
- Slack — route bug reports to pull requests
- Chrome extension (beta) — browser automation, live debugging, form filling, and data extraction via
--chromeflag
macOS, Linux, WSL (Recommended — auto-updates):
curl -fsSL https://claude.ai/install.sh | bashWindows PowerShell:
irm https://claude.ai/install.ps1 | iexHomebrew (does NOT auto-update):
brew install --cask claude-codeWinGet:
winget install Anthropic.ClaudeCodeWindows users: Requires Git for Windows installed first.
claude # Starts interactive mode, prompts for login
/login # Switch accounts or log in again laterSupported account types:
- Claude.ai — Pro, Max, Teams, or Enterprise subscription
- Console — API access with pre-paid credits
- Cloud providers — Amazon Bedrock, Google Vertex AI
cd /path/to/your/project
claude # Opens interactive session
/init # Generates a starter CLAUDE.md from your project structure/init analyzes your build systems, test frameworks, and code patterns to create a solid CLAUDE.md foundation.
Claude Code operates as a Plan → Act → Reflect loop: it reasons about what to do, takes action with tools, observes the result, and repeats until the task is complete.
| Phase | What happens |
|---|---|
| Directive | You describe the task — a bug fix, a feature, a question |
| Plan | Claude understands the need, explores the codebase, and decides next steps |
| Act | Claude uses tools — reads files, runs commands, edits code, calls APIs |
| Reflect | Claude observes the result, adjusts its approach, and loops back |
| Outcome | Task complete — Claude responds with a summary |
The loop adapts to what you ask:
- A question → context gathering only
- A bug fix → cycles through all phases repeatedly
- A refactor → extensive exploration and verification
You're always in the loop. Press Esc to interrupt, type a correction, or steer Claude in a different direction at any point.
Each session is a conversation saved locally. Key facts:
- Sessions are tied to directories — each project has its own sessions
- Sessions start with a fresh context window (previous sessions don't bleed in)
- Sessions can be resumed, rewound, and forked
- Checkpoints are created before every file edit — fully reversible
- Use auto memory and CLAUDE.md to persist learnings across sessions
The primary interface. Full feature support, scripting, automation.
claude # Start interactive session
claude "do this task" # One-time task, then exit
claude -p "query" # Single query (headless/non-interactive)
claude -c / --continue # Resume most recent conversation
claude -r / --resume # Pick from recent sessions
claude --worktree # Start in an isolated git worktreeBest for: visual diff review, file attachments, managing parallel sessions.
To move a CLI session into Desktop:
/desktop # (from inside CLI) — saves session and opens in Desktop app
Desktop vs CLI:
| Use Desktop when... | Use CLI when... |
|---|---|
| Visual diff review | Scripting or automation |
| File attachments | Third-party providers |
| Session management sidebar | Prefer terminal workflow |
| PR monitoring | Headless/CI use |
Select model from the dropdown (Desktop) or /model command (CLI):
- Sonnet 4.6 — Fast, balanced for most tasks (default). 77.2% on SWE-bench Verified.
- Opus 4.6 — Most capable, best for complex reasoning. Extended thinking for deep, multi-step problems. 65.4% on Terminal-Bench 2.0.
- Haiku 4.5 — Fastest, cheapest, ideal for simple/repetitive tasks
Switch models mid-session with /model. Use Option/Alt + T to toggle extended thinking on/off.
| Command | What it does |
|---|---|
/help |
Show available commands |
/init |
Generate CLAUDE.md from project structure |
/clear |
Clear conversation history (fresh context) |
/compact |
Compress session for long context |
/compact focus on X |
Compact while preserving specific context |
/context |
Show what's using context space |
/memory |
Edit memory files (CLAUDE.md, auto memory) |
/mcp |
Manage MCP servers and authentication |
/permissions |
Manage tool permissions and allowlists |
/model |
Change model or effort level |
/agents |
View and manage subagents |
/hooks |
Configure event hooks |
/resume |
Open session picker |
/rename |
Name the current session |
/rewind |
Open checkpoint rewind menu |
/desktop |
Move CLI session to Desktop app |
/login |
Switch accounts |
/sandbox |
Enable OS-level isolation |
/statusline |
Configure terminal status line |
/commit-push-pr |
Commit, push, and open PR in one step |
| Shortcut | Action |
|---|---|
Esc |
Interrupt Claude (context preserved) |
Esc + Esc or /rewind |
Open rewind/checkpoint menu |
Shift + Tab |
Cycle permission modes (Normal → Auto-accept → Plan) |
Ctrl + G |
Open current plan in text editor |
Ctrl + B |
Background a running task |
Ctrl + O |
Toggle verbose mode (see Claude's reasoning) |
Option/Alt + T |
Toggle extended thinking on/off |
Tab |
Autocomplete filenames |
? |
Show all keyboard shortcuts |
@filename |
Reference a file in your prompt |
/ |
Browse skills and commands |
| Mode | Behavior |
|---|---|
| Normal (default) | Approves before every file edit |
| Auto-accept edits | Auto-accepts file edits, faster iteration |
| Plan mode | Read-only exploration, no file changes |
CLAUDE.md is the single most important configuration file. Claude reads it at the start of every session, giving it persistent context it can't infer from code alone.
| Type | Location | Scope |
|---|---|---|
| Managed policy | /Library/Application Support/ClaudeCode/CLAUDE.md (macOS) |
All users in org |
| Personal (all projects) | ~/.claude/CLAUDE.md |
All your projects |
| Project (shared) | ./CLAUDE.md or ./.claude/CLAUDE.md |
Team via git |
| Project (local only) | ./CLAUDE.local.md (auto-gitignored) |
Just you, current project |
| Auto memory | ~/.claude/projects/<project>/memory/ |
Auto-managed by Claude |
| Modular rules | ./.claude/rules/*.md |
Per-topic, path-scoped |
| ✅ Include | ❌ Exclude |
|---|---|
| Bash commands Claude can't guess | Anything Claude can figure out from code |
| Code style rules that differ from defaults | Standard language conventions |
| Testing instructions and preferred test runners | Detailed API documentation (link instead) |
| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |
| Architectural decisions specific to your project | Long explanations or tutorials |
| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |
| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |
# Code style
- Use ES modules (import/export), not CommonJS (require)
- Destructure imports when possible
# Workflow
- Run `npm test` to verify changes
- Prefer running single tests over full suite for performance
- Always typecheck after a series of code changes
# Architecture
- API routes live in src/routes/, models in src/models/
- Use the existing error handler pattern (see src/middleware/errors.js)
# Git
- Branch names: feature/_, bugfix/_, chore/\*
- PR titles: "[TYPE] short description"- Keep it short and human-readable — overly long files cause Claude to ignore rules
- For each line ask: "Would removing this cause Claude to make mistakes?" If not, cut it.
- Add
IMPORTANT:orYOU MUSTto improve adherence to critical rules - Check it into git so your team can contribute — it compounds in value over time. When Claude makes a mistake, add a rule so it doesn't repeat it.
- Import other files:
See @README.md for project overview - Run
/memoryto edit all memory files interactively
For larger projects, organize instructions into focused files:
.claude/rules/
├── code-style.md # Code style guidelines
├── testing.md # Testing conventions
└── api-design.md # API design patterns (scoped to src/api/**/*.ts)
Scope rules to specific file paths using frontmatter:
---
paths:
- "src/api/**/*.ts"
---
# API Rules
- All endpoints must include input validation
- Use standard error response formatClaude automatically saves useful context between sessions: project patterns, debugging insights, key commands, your preferences.
/memory # Open memory file selector and toggleAuto memory is stored in ~/.claude/projects/<project>/memory/MEMORY.md. You can tell Claude to save specific things: "remember that we use pnpm, not npm."
Skills are reusable prompts and workflows you invoke with /skill-name or that Claude uses automatically when relevant. They follow the Agent Skills open standard.
| Location | Scope |
|---|---|
~/.claude/skills/<name>/SKILL.md |
All your projects (personal) |
.claude/skills/<name>/SKILL.md |
Current project only |
<plugin>/skills/<name>/SKILL.md |
Where plugin is installed |
mkdir -p ~/.claude/skills/my-skill
# Create ~/.claude/skills/my-skill/SKILL.mdEvery skill needs a SKILL.md with YAML frontmatter and markdown instructions:
---
name: fix-issue
description: Fix a GitHub issue by number. Use when asked to work on a specific issue.
disable-model-invocation: true
argument-hint: "[issue-number]"
---
Fix GitHub issue: $ARGUMENTS
1. Run `gh issue view $ARGUMENTS` to understand the problem
2. Search the codebase for relevant files
3. Implement the fix following our coding standards
4. Write and run tests to verify
5. Ensure linting and typechecking passes
6. Commit with descriptive message
7. Open a PR with `gh pr create`Invoke with: /fix-issue 1234
| Field | Description |
|---|---|
name |
Creates /name slash command |
description |
Claude uses this to decide when to load automatically |
argument-hint |
Hint shown in autocomplete (e.g., [issue-number]) |
disable-model-invocation |
true = only YOU can invoke (Claude won't auto-trigger) |
user-invocable |
false = hidden from / menu, only Claude can use |
allowed-tools |
Tools Claude can use without asking when skill is active |
model |
Model to use when skill is active |
context |
fork = run in isolated subagent context |
agent |
Which subagent to use with context: fork |
| Variable | Description |
|---|---|
$ARGUMENTS |
All arguments after the skill name |
$ARGUMENTS[0], $0 |
First argument |
$ARGUMENTS[1], $1 |
Second argument |
${CLAUDE_SESSION_ID} |
Current session ID |
!`command` |
Runs shell command and injects output before Claude sees it |
# Only you can run this — Claude won't auto-trigger
disable-model-invocation: true
# Claude can auto-use but it's not a user command
user-invocable: falseUse skills/commands for workflows you repeat many times a day — committing, reviewing PRs, running tests. Pre-compute context with inline bash (!`git status`) so the command runs fast without back-and-forth. Check commands into git (.claude/commands/) so the whole team benefits.
---
name: deep-research
description: Research a topic thoroughly using isolated context
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Analyze the code
3. Summarize findings with file references# .claude/skills/generate-hook/SKILL.md
---
name: generate-hook
description: Scaffold a React custom hook
---
Create a React hook called $ARGUMENTS with proper TypeScript types,
a corresponding test file, and add it to the hooks index.# .claude/skills/pr-review/SKILL.md
---
name: pr-review
description: Comprehensive PR review
context: fork
agent: Explore
---
Review the current PR:
- Diff: !`gh pr diff`
- Comments: !`gh pr view --comments`
Check for: security issues, edge cases, test coverage, code style, performance.
Report findings organized by severity.Model Context Protocol (MCP) is an open standard for connecting Claude Code to external tools, databases, and APIs. With MCP, Claude can query your database, manage GitHub issues, check Slack, read Figma designs, and much more.
# Remote HTTP server (recommended)
claude mcp add --transport http notion https://mcp.notion.com/mcp
# Remote HTTP with auth header
claude mcp add --transport http secure-api https://api.example.com/mcp \
--header "Authorization: Bearer your-token"
# Local stdio server (runs as a process)
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
--dsn "postgresql://user:pass@host:5432/mydb"
# With environment variables
claude mcp add --transport stdio airtable \
--env AIRTABLE_API_KEY=YOUR_KEY -- npx -y airtable-mcp-serverclaude mcp list # List all configured servers
claude mcp get github # Details for a specific server
claude mcp remove github # Remove a server
/mcp # Check server status and authenticate (inside Claude Code)| Scope | Where stored | Use for |
|---|---|---|
local (default) |
~/.claude.json (per-project) |
Personal / sensitive credentials |
project |
.mcp.json (git-checked-in) |
Team-shared tools |
user |
~/.claude.json (global) |
Personal tools across all projects |
# Project-scoped (shared with team via .mcp.json)
claude mcp add --scope project --transport http github https://api.githubcopilot.com/mcp/
# User-scoped (available in all projects)
claude mcp add --scope user --transport http sentry https://mcp.sentry.dev/mcp# Add server then authenticate
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
/mcp # Follow browser login flowclaude mcp add-from-claude-desktop # Interactive selection of servers to import| Server | What it enables |
|---|---|
| GitHub | PR reviews, issue management, code search |
| Sentry | Error monitoring, stack traces, deployment tracking |
| Slack | Post messages, read channels, route issues |
| Notion | Read/write docs and databases |
| Figma | Access design files and components |
| PostgreSQL / Databases | Query data naturally in plain English |
| Playwright | Browser testing automation |
| Linear / Jira | Issue tracker integration |
> Analyze @github:issue://123 and suggest a fix
> Compare @postgres:schema://users with @docs:file://database/user-model
# 1. Add GitHub and Sentry MCP servers
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
# 2. Use them together
> "Check Sentry for the most common errors in the last 24 hours,
then create GitHub issues for the top 3 and assign them to me"Subagents are specialized AI assistants with their own context window, custom system prompt, and specific tool access. Claude delegates tasks to them automatically or on your request.
Key benefits:
- Context isolation — research stays out of your main conversation
- Enforce constraints — limit which tools a subagent can use
- Specialization — focused prompts for specific domains
- Cost control — route simple tasks to Haiku
| Agent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku (fast) | Read-only | File discovery, codebase search |
| Plan | Inherits | Read-only | Research during Plan Mode |
| General-purpose | Inherits | All | Complex multi-step tasks |
| Bash | Inherits | Bash | Terminal commands in separate context |
Using the /agents command (recommended):
/agents
Select → Create new agent → User-level → Generate with Claude → Configure tools & model
Manually (create .claude/agents/security-reviewer.md):
---
name: security-reviewer
description: Reviews code for security vulnerabilities. Use proactively after implementing auth or data handling code.
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling
Provide specific line references and suggested fixes.| Field | Description |
|---|---|
name |
Unique identifier (lowercase-with-hyphens) |
description |
When Claude should delegate to this agent (be descriptive!) |
tools |
Tools the agent can use (omit = inherits all) |
disallowedTools |
Tools to deny |
model |
sonnet, opus, haiku, or inherit |
permissionMode |
default, acceptEdits, dontAsk, bypassPermissions, plan |
maxTurns |
Max agentic turns before stopping |
skills |
Skills to preload into this agent's context |
mcpServers |
MCP servers available to this agent |
memory |
user, project, or local — enables cross-session learning |
isolation |
worktree = run in isolated git worktree |
background |
true = always run as background task |
Let Claude decide: Describe the task and Claude picks the right agent
Review my recent code changes for security issues
Request explicitly:
Use the security-reviewer subagent to check the auth module
Use a subagent to investigate how our authentication system handles token refresh
Parallel research:
Research the auth, database, and API modules in parallel using separate subagents
Chain agents:
Use the code-reviewer to find performance issues, then use the optimizer to fix them
---
name: code-reviewer
memory: user
---
You are a code reviewer. Update your memory with patterns and recurring issues you discover.Memory is stored in ~/.claude/agent-memory/<name>/ and builds institutional knowledge over time.
---
name: experimenter
isolation: worktree
---Each invocation gets its own git worktree — safe to make risky changes.
Hooks run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions (advisory), hooks are deterministic guarantees.
| Event | Fires when |
|---|---|
PreToolUse |
Before Claude uses any tool |
PostToolUse |
After Claude uses any tool |
Stop |
When Claude finishes responding |
Notification |
When Claude needs your attention |
SubagentStart |
When a subagent begins |
SubagentStop |
When a subagent completes |
/hooks # Interactive configuration menu
Or edit .claude/settings.json directly:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npm run lint -- $TOOL_INPUT_FILE"
}
]
}
],
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
}
]
}
]
}
}# Run linter after every file edit
"command": "eslint --fix $TOOL_INPUT_FILE"
# Run tests after edits
"command": "npm test"
# Desktop notification when Claude is waiting
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'" # macOS
"command": "notify-send 'Claude Code' 'Needs your attention'" # Linux
# Block writes to a protected folder
# (exit code 2 = block the action and report to Claude)
"command": "./scripts/check-protected-paths.sh"Write a hook that runs eslint after every file edit
Write a hook that blocks writes to the migrations folder
Write a hook that sends me a desktop notification when you're waiting for input
Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit. Install them from the marketplace or from the community.
+ button (next to prompt box) → Plugins → Browse and install
Or in CLI:
/plugin
- Skills — domain-specific prompts and workflows
- Subagents — specialized AI assistants
- MCP servers — external tool integrations (auto-started when plugin is enabled)
- Hooks — automation scripts
If you write TypeScript, Python, Go, or other typed languages, install a code intelligence plugin for your language. These give Claude:
- Precise "go to definition" navigation
- "Find all references" across files
- Automatic error detection after edits
Browse the official plugin marketplace for your language at the + menu in Desktop.
Most best practices exist because Claude's context window fills up fast, and performance degrades as it fills. Manage context aggressively.
This is the single highest-leverage thing you can do. Include tests, screenshots, or expected outputs.
| Strategy | Vague | Specific |
|---|---|---|
| Provide verification criteria | "implement email validation" | "write validateEmail. Test cases: user@example.com = true, invalid = false. Run tests after implementing" |
| Verify UI changes visually | "make dashboard look better" | "[paste screenshot] implement this design. Take screenshot of result, compare to original, list and fix differences" |
| Address root causes | "the build is failing" | "build fails with [paste error]. Fix it and verify build succeeds. Address root cause, don't suppress" |
For complex tasks:
- Explore → Enter Plan Mode (
Shift+Tabtwice). Read files, understand context. - Plan → Ask Claude to create a detailed implementation plan. Press
Ctrl+Gto edit it. - Implement → Switch back to Normal Mode. Let Claude code, verifying against the plan.
- Commit → Ask Claude to commit with a descriptive message and open a PR.
| Strategy | Vague | Specific |
|---|---|---|
| Scope the task | "add tests for foo.py" | "write a test for foo.py covering the case where the user is logged out. avoid mocks." |
| Reference existing patterns | "add a calendar widget" | "look at HotDogWidget.php as a pattern example. follow that pattern for a new calendar widget" |
| Describe the symptom | "fix the login bug" | "login fails after session timeout. check src/auth/ especially token refresh. write a failing test first, then fix" |
@filename— reference files directly in your prompt- Paste images — copy/paste or drag and drop screenshots and diagrams
- Pipe data —
cat error.log | claude -p "explain the root cause" - Give URLs — documentation and API references
- Let Claude fetch — "use gh cli to get the issue details"
Use explicit thinking modes:
think
think hard
think harder
ultrathink
Or use XML structure for complex prompts:
<instructions>Refactor the payment module</instructions>
<context>We use Stripe, the code is in src/payments/</context>
<constraints>Maintain backward compatibility with existing API</constraints>/clearbetween unrelated tasks — fresh context nearly always outperforms a long cluttered one- If you've corrected Claude twice on the same issue →
/clearand rewrite the prompt incorporating what you learned - Name sessions with
/rename oauth-migration— treat sessions like branches - Resume sessions with
claude --resume oauth-migration - Rewind checkpoints with
Esc+Escor/rewind— every action is reversible
- Prune regularly — if Claude already does something without the rule, delete it
- Too long = ignored — critical rules get lost in noise
- Convert stale rules to hooks — deterministic is better than advisory
- Test changes by observing whether Claude's behavior actually shifts
| Anti-pattern | Fix |
|---|---|
| Kitchen sink session — mixing unrelated tasks | /clear between tasks |
| Correction loop — fixing the same issue repeatedly | After 2 failures: /clear and write a better initial prompt |
| Bloated CLAUDE.md — too many rules, Claude ignores them | Ruthlessly prune. Convert rules to hooks where possible |
| Trust without verify — shipping code without testing | Always provide verification (tests, screenshots, scripts) |
| Infinite exploration — "investigate" without scope | Scope investigations narrowly OR use subagents |
give me an overview of this codebase
explain the main architecture patterns used here
what are the key data models?
how is authentication handled?
trace the login process from front-end to database
I'm seeing this error when I run npm test: [paste error]
suggest a few ways to fix the null pointer in user.ts
update user.ts to add the null check you suggested
run the tests and confirm the fix works
find functions in AuthService.ts not covered by tests
add tests for the notification service covering edge conditions
run the new tests and fix any failures
/commit-push-pr
Or step by step:
summarize the changes I've made to the authentication module
create a pr with a clear title and description
enhance the PR description with security improvement context
find deprecated API usage in our codebase
suggest how to refactor utils.js to use modern JavaScript features
refactor utils.js to ES2024 features while maintaining the same behavior
run tests for the refactored code
- Drag and drop image into Claude Code window, or paste with
Ctrl+V - Describe what you want:
generate CSS to match this design mockup
what HTML structure would recreate this component?
here's a screenshot of the error — what's causing it?
claude --permission-mode plan # Start in plan mode
# or press Shift+Tab twice during a session
> read src/auth/ and understand how we handle sessions
> create a detailed plan for adding OAuth support
> what about backward compatibility?Press Ctrl+G to open the plan in your editor and modify it directly.
claude --continue # Resume most recent conversation in current directory
claude --resume # Open session picker
claude --resume auth-refactor # Resume by name/hooks → Notification → + Match all → [enter notification command]
macOS: osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'
# One-off query
claude -p "What does this project do?"
# Structured output for scripts
claude -p "List all API endpoints" --output-format json
# Streaming real-time output
claude -p "Analyze this log file" --output-format stream-json
# Pipe data
cat error.log | claude -p "explain the root cause" > output.txtOutput formats: text (default), json, stream-json
// package.json
{
"scripts": {
"lint:claude": "claude -p 'look at changes vs. main and report typos. format: filename:line on line 1, description on line 2'"
}
}# In GitHub Actions
claude -p "Review this PR for security issues" --output-format json# Generate task list
claude -p "list all Python files needing migration" > files.txt
# Loop through tasks in parallel
for file in $(cat files.txt); do
claude -p "Migrate $file from Django 3 to Django 5. Return OK or FAIL." \
--allowedTools "Edit,Bash(git commit *)" &
done
wait| Session A (Writer) | Session B (Reviewer) |
|---|---|
Implement a rate limiter for our API endpoints |
— |
| — | Review the rate limiter in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with existing patterns. |
Here's the review feedback: [paste Session B output]. Address these issues. |
— |
# Start Claude in isolated worktree (auto-names it)
claude --worktree feature-auth
# Another session in a separate worktree
claude --worktree bugfix-123
# Auto-generate a random name
claude --worktreeWorktrees are created at <repo>/.claude/worktrees/<name>/. Add to .gitignore:
.claude/worktrees/
For sustained parallelism with shared tasks and messaging, use agent teams:
# See agent-teams documentation at code.claude.com/docs/en/agent-teams# For contained workflows like lint fixes or boilerplate generation
claude --dangerously-skip-permissions
# Or use /sandbox for OS-level isolation with similar autonomy but better security
/sandbox
⚠️ Only use--dangerously-skip-permissionsin a sandboxed environment without internet access.
For tasks that run unattended (large refactors, migrations, multi-file generation), combine autonomy with verification:
- Verify when done — prompt Claude to use a background agent to check its own work when finished, or use an agent
Stophook to run verification deterministically - Remove permission blockers — use
--permission-mode=dontAsk(less nuclear than--dangerously-skip-permissions) or run in a/sandboxso Claude isn't blocked waiting for approval - Isolate the work — use
--worktreeso long-running changes happen on an isolated branch
# Long-running autonomous task in a sandboxed worktree
claude --worktree --permission-mode=dontAskI want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs.
Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
Then start a fresh session to implement the spec with clean context.
Context is your most precious resource. Performance degrades as context fills.
Claude's context window holds:
- Your entire conversation history
- Every file Claude reads
- Every command output
- CLAUDE.md contents
- Loaded skills and subagents descriptions
- MCP server tool definitions
/context # See what's using context space
/mcp # Check per-server context costs (MCP servers add tool definitions)
Install a custom status line to track context usage continuously:
/statusline
Claude compacts automatically:
- Clears older tool outputs first
- Summarizes conversation if needed
- Preserves your requests and key code snippets
- May lose detailed instructions from early in the conversation
This is why CLAUDE.md exists. Don't rely on conversation history for persistent rules.
/compact # Manual compact
/compact focus on the API changes # Compact while preserving specific context
In CLAUDE.md:
# Compact Instructions
When compacting, always preserve: the full list of modified files, test commands, and API design decisions.| Strategy | How it helps |
|---|---|
/clear between tasks |
Resets context entirely |
| Subagents | Get their own fresh context window; return only a summary |
Skills with disable-model-invocation: true |
Don't add description to context until invoked |
| Scoped investigations | "only look at src/auth/" vs "investigate everything" |
| MCP Tool Search | Dynamically loads tools on demand vs all upfront |
| File | Purpose |
|---|---|
~/.claude/settings.json |
Personal settings across all projects |
.claude/settings.json |
Project settings (commit to git) |
.claude/settings.local.json |
Local project overrides (auto-gitignored) |
~/.claude.json |
OAuth tokens, machine state (don't sync!) |
{
"permissions": {
"defaultMode": "plan", // or "normal", "acceptEdits"
"allow": ["Bash(npm run lint)", "Bash(git commit *)"],
"deny": ["Bash(rm -rf *)"]
},
"autoMemoryEnabled": true,
"alwaysThinkingEnabled": true,
"env": {
"MAX_THINKING_TOKENS": "10000",
"CLAUDE_CODE_EFFORT_LEVEL": "high", // low, medium, high (Opus 4.6)
"ENABLE_TOOL_SEARCH": "auto" // for MCP tool search
}
}Reduce permission fatigue by pre-approving safe operations:
/permissions # Interactive permission management
Or add directly to settings.json:
{
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm test)",
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git push)"
]
}
}Prefer
/permissionsover--dangerously-skip-permissions. Pre-approve the specific commands you know are safe in your environment, and check them into.claude/settings.jsonso the whole team shares the same allowlist. This eliminates permission fatigue without disabling the safety model entirely.
| Variable | Purpose |
|---|---|
MAX_THINKING_TOKENS |
Limit thinking token budget |
CLAUDE_CODE_EFFORT_LEVEL |
Thinking depth for Opus 4.6 (low/medium/high) |
ENABLE_TOOL_SEARCH |
MCP tool search behavior (auto/true/false) |
MCP_TIMEOUT |
MCP server startup timeout in ms |
MAX_MCP_OUTPUT_TOKENS |
Max tokens for MCP tool output (default: 25000) |
CLAUDE_CODE_DISABLE_AUTO_MEMORY |
1 = disable auto memory |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS |
1 = disable background tasks |
SLASH_COMMAND_TOOL_CHAR_BUDGET |
Override skills context budget |
Store in a dotfiles repo or iCloud:
~/.claude/
├── settings.json # Permissions, hooks, env vars
├── CLAUDE.md # Personal instructions
├── agents/ # Custom subagents
├── rules/ # Personal rules
└── skills/ # Personal skills
~/.claude.json— contains OAuth tokens, machine-specific state. Each machine authenticates independently.
# Main machine
mkdir -p ~/.dotfiles/claude
cp ~/.claude/settings.json ~/.dotfiles/claude/
cp ~/.claude/CLAUDE.md ~/.dotfiles/claude/
git add && git commit && git push
# Other machines
git clone https://github.com/you/dotfiles ~/.dotfiles
ln -s ~/.dotfiles/claude/settings.json ~/.claude/settings.json
ln -s ~/.dotfiles/claude/CLAUDE.md ~/.claude/CLAUDE.mdmkdir -p ~/Library/Mobile\ Documents/com~apple~CloudDocs/claude-config
mv ~/.claude/settings.json ~/Library/Mobile\ Documents/.../claude-config/
ln -s ~/Library/Mobile\ Documents/.../claude-config/settings.json ~/.claude/settings.json.claude/
├── settings.json # Team settings
├── CLAUDE.md # Project instructions (committed)
├── CLAUDE.local.md # Personal overrides (gitignored)
├── agents/ # Team subagents
├── skills/ # Team skills
└── rules/ # Modular rules
.mcp.json # MCP server config (committed)
curl -fsSL https://claude.ai/install.sh | bash # Install
claude # Start session
/init # Generate CLAUDE.md
/help # Show commandsclaude # Start
@filename # Reference a file
Shift+Tab # Cycle permission modes
Esc # Interrupt Claude
Esc+Esc or /rewind # Undo / checkpoint
/clear # Fresh context
/compact # Compress context
claude --continue # Resume last sessionConversation instruction
→ CLAUDE.md rule
→ Skill (reusable prompt)
→ Hook (guaranteed execution)
→ Subagent (isolated context)
→ MCP server (external tool)
→ Plugin (bundled package)
CLAUDE.md → What Claude knows by default
.claude/agents/ → Custom subagents
.claude/skills/ → Custom slash commands
.claude/rules/ → Modular instruction files
.mcp.json → Shared MCP server config
~/.claude/ → Personal config (all projects)
| Need | Use |
|---|---|
| Persistent project instructions | CLAUDE.md |
| Personal instructions across projects | ~/.claude/CLAUDE.md |
| Reusable prompt or workflow | Skill (.claude/skills/) |
| Guaranteed action on every event | Hook |
| Task in isolated context | Subagent |
| External tool / database / service | MCP server |
| Bundled tools for distribution | Plugin |
| CI/CD / scripting | claude -p (headless) |
| Multiple tasks in parallel | Git worktrees + parallel sessions |
- Reference specific files (
@src/auth/login.ts) - Describe symptoms, not just requests ("login fails after session timeout")
- Include verification method ("run tests after implementing")
- Point to example patterns ("follow the pattern in HotDogWidget.php")
- State constraints ("maintain backward compatibility")
- Use Plan Mode for multi-file changes
- Give Claude a way to verify its work — tests, screenshots, expected outputs
- Explore first, then plan, then code — separate research from implementation
- Manage context aggressively —
/clearbetween unrelated tasks - Be specific — vague prompts work but specific prompts succeed on the first attempt
- Keep CLAUDE.md short — bloated = ignored; ruthlessly prune
- Commit CLAUDE.md — it compounds in value over time for your whole team
- Interrupt early — correct off-track work immediately, don't let it compound