Claude Code Mastery Guide
Everything you need to become highly proficient with Claude Code. From essential commands to advanced automation patterns, this guide covers it all.
Start with Quick Reference for immediate productivity gains, then explore each section as you need those features. You don't need to memorize everything upfront.
Quick Reference
The most important commands and shortcuts to memorize first.
Essential Commands
| Command | Purpose | When to Use |
|---|---|---|
/clear |
Reset conversation | Between unrelated tasks |
/compact |
Summarize context | When context is filling up |
/context |
Visualize usage | Check how full context is |
/cost |
Show token usage | Monitor spending |
/model |
Change model | Switch between Sonnet/Opus/Haiku |
/memory |
Edit CLAUDE.md | Update project instructions |
/resume |
Resume session | Continue previous work |
Essential Shortcuts
File References
Use @ to reference files in your prompts:
Explain @src/auth/login.ts
What's the structure of @src/components?
Compare @file1.js with @file2.js
Slash Commands
All commands you can run in Claude Code, organized by category.
Session Management
| Command | Description | Example |
|---|---|---|
/clear |
Clear conversation history | /clear |
/compact [focus] |
Summarize conversation with optional focus | /compact Focus on API changes |
/rename <name> |
Name current session | /rename auth-refactor |
/resume [id/name] |
Resume previous session | /resume auth-refactor |
/rewind |
Rewind conversation or code | /rewind |
/export [file] |
Export conversation | /export session.md |
/copy |
Copy last response to clipboard | /copy |
/exit |
Exit Claude Code | /exit |
Configuration & Status
| Command | Description |
|---|---|
/config |
Open settings interface |
/model |
Select/change AI model |
/permissions |
View/update permissions |
/memory |
Edit CLAUDE.md files |
/status |
Show version, model, account |
/statusline |
Configure status line UI |
/theme |
Change color theme |
/vim |
Enable vim-style editing |
/terminal-setup |
Configure Shift+Enter for multiline |
Monitoring & Debugging
| Command | Description |
|---|---|
/context |
Visualize context usage as grid |
/cost |
Show token usage statistics |
/stats |
Visualize daily usage and streaks |
/usage |
Show plan limits (subscription) |
/tasks |
List background tasks |
/todos |
List current TODO items |
/doctor |
Check installation health |
/debug [desc] |
Troubleshoot session |
Project & Planning
| Command | Description |
|---|---|
/init |
Initialize project with CLAUDE.md |
/plan |
Enter plan mode from prompt |
/mcp |
Manage MCP server connections |
/help |
Get usage help |
Special Commands
| Command | Description |
|---|---|
/teleport |
Resume remote session from claude.ai |
!command |
Run bash command directly (bypass Claude) |
/mcp__server__prompt |
Run MCP server prompts as commands |
Keyboard Shortcuts
General Controls
Rewind & Recovery
The rewind menu offers three options:
- Restore code - Revert file changes, keep conversation
- Restore conversation - Revert messages, keep code
- Summarize from here - Compress from selected point forward
Permission Modes
Modes cycle: Normal → Auto-Accept → Plan → (Delegate if teams active)
Model & Thinking
Navigation & History
Images & Pasting
On iTerm2, use Cmd+V. On Windows, use Alt+V.
Multiline Input
| Method | Shortcut | Compatibility |
|---|---|---|
| Quick escape | \ + Enter | All terminals |
| macOS default | Option+Enter | macOS |
| Shift+Enter | Shift+Enter | iTerm2, WezTerm, Ghostty, Kitty |
| Control sequence | Ctrl+J | Line feed character |
Text Editing
For Alt shortcuts to work on macOS, set Option as Meta Key in your terminal: iTerm2 → Settings → Profiles → Keys → Set Left/Right Option to "Esc+"
Enable with /vim. Then use standard vim keys:
Mode Switching
- Esc - Enter NORMAL mode
- i / I / a / A / o / O - Enter INSERT mode
Navigation (NORMAL mode)
- h/j/k/l - Move left/down/up/right
- w/e/b - Word navigation
- 0/$ - Line start/end
- gg/G - File start/end
Editing (NORMAL mode)
- x - Delete character
- d - Delete
- c - Change
- y - Yank/copy
- p/P - Paste after/before
- . - Repeat last change
CLAUDE.md Files
CLAUDE.md files provide persistent instructions Claude reads at the start of every session. They're the primary way to customize Claude's behavior for your project.
File Locations & Priority
Claude loads CLAUDE.md files in order of precedence (highest first):
| Location | Scope | Shareable (git) |
|---|---|---|
managed-settings.json |
Organization-wide (admin) | Via IT/DevOps |
./CLAUDE.md or ./.claude/CLAUDE.md |
Project (team) | Yes |
./.claude/rules/*.md |
Project (modular rules) | Yes |
~/.claude/CLAUDE.md |
User (all projects) | No |
./.claude/CLAUDE.local.md |
Project (personal) | No (auto-gitignored) |
What to Include
- Build commands Claude can't guess
- Code style rules that differ from defaults
- Testing instructions & runners
- Repository etiquette (branches, PRs)
- Architectural decisions
- Developer environment quirks
- Things Claude figures out from code
- Standard language conventions
- Detailed API documentation
- Information that changes frequently
- Long tutorials or explanations
- Self-evident practices
Example CLAUDE.md
# Code Style
- Use ES modules (import/export) not CommonJS (require)
- Destructure imports when possible
- 2-space indentation
# Workflow
- Typecheck: `npm run typecheck`
- Run single test: `npm test -- <filename>`
- Create PRs from feature branches only
# Architecture
- API routes in `/src/routes/`
- Database models in `/src/models/`
- Utilities in `/src/utils/`
# Environment
- Requires `.env` with API_KEY
- Run `npm install` before first session
Importing Other Files
Reference other files using @path/to/import:
See @README.md for overview and @package.json for commands.
# Git Workflow
@docs/git-instructions.md
Paths resolve relative to the CLAUDE.md file location.
Modular Rules with .claude/rules/
Break instructions into topic-specific files:
.claude/
├── CLAUDE.md
└── rules/
├── code-style.md
├── testing.md
├── security.md
└── frontend/
└── react.md
Path-Specific Rules
Apply rules only to matching files using YAML frontmatter:
---
paths:
- "src/api/**/*.ts"
- "src/**/*.{ts,tsx}"
---
# API Development Rules
- All endpoints require input validation
- Use standard error format
Aim for <500 lines in CLAUDE.md. Longer files consume context and may have instructions ignored. Move detailed content to skills (loaded on-demand) or link to external docs.
Memory System
Claude has multiple memory layers that persist across sessions.
Memory Types
| Type | Location | Purpose |
|---|---|---|
| Project memory | ./CLAUDE.md |
Shared team conventions |
| User memory | ~/.claude/CLAUDE.md |
Personal preferences (all projects) |
| Local project | ./.claude/CLAUDE.local.md |
Personal project preferences |
| Auto memory | ~/.claude/projects/<project>/memory/ |
Claude's auto-saved learnings |
Auto Memory
Claude automatically saves learnings without you writing anything:
- Project patterns and debugging insights
- Architecture notes and your preferences
- First 200 lines loaded automatically
- Topic files (debugging.md, patterns.md) loaded on-demand
Control auto memory with environment variable:
# Force on
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=0
# Force off
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
Using /memory Command
Run /memory to open any memory file in your editor for extensive additions or organization.
Load Memory from Additional Directories
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config
Settings & Configuration
Settings Files (Precedence Order)
managed-settings.json(admin/organization)- Command-line arguments
.claude/settings.local.json(local project).claude/settings.json(shared project)~/.claude/settings.json(user)
Example settings.json
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "claude-sonnet-4-5-20250929",
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(git *)",
"Read"
],
"deny": [
"Read(./.env)",
"Read(./.env.*)"
],
"defaultMode": "acceptEdits"
},
"sandbox": {
"enabled": true,
"network": {
"allowedDomains": ["github.com", "npmjs.org"]
}
},
"hooks": {
"PostToolUse": []
},
"outputStyle": "Explanatory",
"alwaysThinkingEnabled": true
}
Key Environment Variables
| Variable | Purpose |
|---|---|
ANTHROPIC_API_KEY |
API authentication |
CLAUDE_CODE_EFFORT_LEVEL |
Thinking depth: low, medium, high |
MAX_THINKING_TOKENS |
Extended thinking budget |
MCP_TIMEOUT |
MCP server startup timeout (ms) |
DISABLE_TELEMETRY |
Opt out of telemetry |
HTTP_PROXY / HTTPS_PROXY |
Proxy configuration |
Permission System
Permission Modes
| Mode | Behavior | Use Case |
|---|---|---|
default |
Prompt on each tool use | Safety-first |
acceptEdits |
Auto-accept file edits | Reduce interruptions |
plan |
Read-only, planning | Safe analysis |
dontAsk |
Auto-deny unless pre-approved | CI/CD automation |
bypassPermissions |
Skip all checks | Sandboxed only |
Toggle modes with Shift+Tab
Permission Rule Syntax
"permissions": {
"allow": [
"Bash(npm run *)", // Glob patterns
"Bash(git commit *)", // Specific commands
"Read(./.env)", // Specific file
"Edit(/src/**/*.ts)", // Glob in paths
"WebFetch(domain:github.com)", // Domain filter
"Task(Explore)" // Specific subagent
],
"deny": [
"Bash(curl *)"
]
}
Rule Precedence
Rules evaluated in order: deny → ask → allow. First match wins.
Bash(npm *) requires a space before * (word boundary).
Bash(ls*) without space matches both ls and lsof.
Context Management
Your entire conversation lives in the context window. As it fills, performance degrades. Managing context is crucial for long sessions.
Monitor Context Usage
/context- Visualize usage as colored grid/cost- See token counts- Configure custom status line for continuous monitoring
Context Reduction Strategies
1. Clear Between Tasks
/rename auth-work # Name for later
/clear # Start fresh
2. Use Compact
/compact Focus on API changes and test results
Claude summarizes the conversation, preserving critical context.
3. Use Rewind
Press Esc Esc to:
- Restore code - Undo file changes, keep conversation
- Restore conversation - Undo messages, keep code
- Summarize from here - Compress from selected point
4. Isolate with Subagents
Delegate verbose operations (tests, logs) to subagents. Results return as summaries.
5. Use Skills Instead of CLAUDE.md
Keep CLAUDE.md <500 lines. Move specialized instructions to skills (loaded on-demand).
6. Reduce MCP Overhead
/mcp # Check active servers
/context # See what consumes space
Disable unused servers. Use CLI tools when available instead of MCP.
7. Choose Right Model
- Sonnet - Most tasks, lower cost
- Opus - Complex reasoning, architecture
- Haiku - Subagent tasks, budget-conscious
Plan Mode
Plan Mode enables Claude to analyze your codebase without making changes. It's read-only and prompts for clarifications before proposing a plan.
When to Use Plan Mode
- Multi-file implementations
- Complex refactoring
- Understanding unfamiliar code
- Interactive feature development
How to Use
# Start in plan mode
claude --permission-mode plan
# Switch during session
Shift+Tab (cycle modes)
# One-shot query
claude --permission-mode plan -p "Analyze auth system"
# Configure as default
{
"permissions": {
"defaultMode": "plan"
}
}
Plan Mode Workflow
- Claude analyzes codebase (read-only)
- Claude asks clarifying questions
- Claude proposes detailed plan
- Press Ctrl+G to edit plan in editor
- Switch to Normal Mode (Shift+Tab) to implement
Use plan mode for complex tasks, then switch to normal mode to implement. This separates thinking from doing and reduces wasted effort.
Session Management
Naming Sessions
/rename auth-refactor
Named sessions are easier to find later.
Resume Sessions
claude --continue # Most recent in cwd
claude --resume # Show picker
claude --resume auth-refactor # By name
claude --from-pr 123 # From GitHub PR
Session Persistence
- Stored locally per project directory
- Include full message history
- Tool results preserved
- Persist across system restarts
Checkpointing with Rewind
Press Esc Esc or /rewind to access:
- Restore code - Revert file changes
- Restore conversation - Revert messages
- Summarize from here - Compress from selected point
Git Integration
Common Operations
# Create commits
"Create a commit for the auth changes"
# Create PRs
"Create a PR with a descriptive message"
# Resume from PR
claude --from-pr 123
Git Permissions
{
"permissions": {
"allow": [
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git push *)"
]
}
}
Attribution
{
"attribution": {
"commit": "Generated with Claude Code\n\nCo-Authored-By: Claude <[email protected]>",
"pr": "Generated with Claude Code"
}
}
MCP Servers
MCP (Model Context Protocol) lets Claude connect to external tools, databases, and APIs.
Why Use MCP?
- Implement features from JIRA/GitHub issues
- Query databases directly
- Analyze Sentry errors
- Integrate Figma designs
- Automate workflows (Slack, Gmail)
Installation Methods
HTTP Server (Recommended for Remote)
claude mcp add --transport http notion https://mcp.notion.com/mcp
Local Stdio Server
claude mcp add --transport stdio airtable \
--env AIRTABLE_API_KEY=YOUR_KEY \
-- npx -y airtable-mcp-server
Managing Servers
claude mcp list # List all servers
claude mcp get github # Details for specific server
claude mcp remove github # Remove server
/mcp # Check status in Claude Code
Installation Scopes
| Scope | Location | Visibility |
|---|---|---|
| Local | ~/.claude.json |
Current project only |
| Project | .mcp.json |
Team-shared (git) |
| User | ~/.claude.json |
All projects |
MCP Resources
Reference MCP resources with @ mentions:
Can you analyze @github:issue://123 and suggest a fix?
When MCP tools exceed 10% of context, Claude defers them and loads on-demand.
Control with ENABLE_TOOL_SEARCH=auto:5 (trigger at 5%).
Hooks
Hooks are shell commands that execute at specific lifecycle points. Unlike prompts, hooks are deterministic and guaranteed to run.
Lifecycle Events
| Event | When | Use Case |
|---|---|---|
SessionStart |
Session begins | Re-inject context after compaction |
UserPromptSubmit |
Before processing prompt | Pre-validate input |
PreToolUse |
Before tool executes | Validate/block commands |
PostToolUse |
After tool succeeds | Auto-format files |
Notification |
When idle | Desktop notifications |
SessionEnd |
Session terminates | Cleanup |
Example: Auto-format After Edits
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}
Example: Desktop Notifications (macOS)
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
Example: Block Protected Files
#!/bin/bash
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path')
if [[ "$FILE" == *".env"* ]]; then
echo "Blocked: Protected file" >&2
exit 2
fi
exit 0
Exit Codes
0- Action proceeds (stdin output added to context)2- Action blocked (stderr becomes feedback to Claude)
Skills
Skills are custom commands that extend Claude's capabilities. They're loaded on-demand, keeping your context lean.
Create a Skill
mkdir -p ~/.claude/skills/my-skill
Create ~/.claude/skills/my-skill/SKILL.md:
---
name: my-skill
description: What this skill does
---
Instructions for Claude to follow when skill is invoked.
Skill Types
Reference Content (Knowledge)
---
name: api-conventions
description: API design patterns
---
When writing API endpoints:
- Use RESTful naming
- Return consistent errors
Task Content (Workflows)
---
name: deploy
description: Deploy to production
disable-model-invocation: true
---
1. Run tests
2. Build
3. Deploy
Skill Locations
~/.claude/skills/- Personal (all projects).claude/skills/- Project (git-shared)
Skill Arguments
---
name: migrate-component
description: Migrate component framework
---
Migrate $0 from $1 to $2 while preserving behavior.
Run: /migrate-component SearchBar React Vue
Control Invocation
disable-model-invocation: true # Manual invocation only
user-invocable: false # Claude-only
allowed-tools: Read, Grep, Glob # Restrict tools
Subagents
Subagents are specialized AI assistants that handle specific types of tasks.
Built-In Subagents
| Agent | Tools | Purpose |
|---|---|---|
| Explore | Read-only | Fast codebase searching |
| Plan | Read-only | Planning & research |
| General-purpose | All | Complex multi-step tasks |
Create Custom Subagent
Using /agents command or create manually:
# ~/.claude/agents/code-reviewer.md
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Grep, Glob
model: sonnet
---
You are a senior code reviewer. Analyze code and provide specific feedback.
Configuration Options
| Field | Purpose |
|---|---|
name |
Unique identifier |
description |
When Claude should delegate |
tools |
Allowed tools |
model |
sonnet, opus, haiku, inherit |
permissionMode |
default, acceptEdits, plan |
When to Use Subagents
- Isolate verbose operations (tests, logs)
- Enforce tool restrictions
- Parallel research
- Control costs (use cheaper models)
Extended Thinking
Claude uses internal reasoning tokens to think through problems before responding.
Enable/Disable
- Toggle: Alt+T
- Default:
/configto set default - Environment:
CLAUDE_CODE_EFFORT_LEVEL=high
Effort Levels (Opus 4.6)
Use /model and left/right arrows to adjust:
- Low - Minimal thinking, fast
- Medium - Balanced
- High - Deep reasoning, thorough
Thinking Token Budget
# Set budget
export MAX_THINKING_TOKENS=10000 claude
# Disable entirely
export MAX_THINKING_TOKENS=0 claude
View Thinking
Press Ctrl+O to toggle verbose mode and see thinking as gray italic text.
Effective Prompting
How you communicate with Claude dramatically affects results.
1. Give Verification Criteria
Include tests, screenshots, expected outputs:
implement email validator
implement validateEmail function. Test: [email protected]=true, invalid=false. Run tests.
2. Explore → Plan → Implement → Commit
# Step 1 (Plan Mode): Explore
"Analyze our auth system and explain the flow"
# Step 2 (Plan Mode): Plan
"Create a detailed plan to add OAuth2"
# Step 3 (Normal Mode): Implement
"Implement OAuth2 from your plan, write tests, verify"
# Step 4 (Normal Mode): Commit
"Create a PR with a descriptive message"
3. Provide Specific Context
why does this have a weird API?
look at ExecutionFactory git history and explain why the API became this way
4. Reference Files with @
Explain @src/utils/auth.js logic
What's the structure of @src/components?
5. Use Rich Content
- Paste screenshots/images (Ctrl+V)
- Reference files with @
- Pipe data:
cat error.log | claude - Provide documentation URLs
6. Point to Source Examples
"Look at how existing widgets implement X pattern in home.js and follow it"
7. Be Specific About Scope
add tests
write tests for logout edge case where session expires. Avoid mocks.
Cost Optimization
Track Costs
/cost
Shows total cost, token count, code changes, and timing.
Reduction Strategies
Manage Context
- Use
/clearbetween tasks - Use
/compactwith focus - Use subagents for verbose ops
Choose Right Model
- Sonnet - Most work
- Opus - Complex reasoning
- Haiku - Subagent tasks
Reduce MCP Overhead
- Disable unused servers
- Use CLI tools when available
- Check with
/mcp
Use Skills
- Keep CLAUDE.md <500 lines
- Move specialized content to skills
- Skills load on-demand
Adjust Thinking
- Reduce effort level in
/model - Disable thinking in
/config - Set MAX_THINKING_TOKENS budget
Write Better Prompts
- Be specific, not vague
- Include verification criteria
- Use plan mode for complex tasks
Power User Tips
Efficient Workflows
- Start with Plan Mode - Understand before implementing
- Monitor context - Use
/contextcontinuously - Clear aggressively -
/clearbetween unrelated tasks - Name sessions early -
/renamefor future reference - Specify deeply - More specific = fewer corrections needed
- Verify everything - Include tests, screenshots, expected output
- Rewind on mistakes - Esc Esc to undo and retry
- Delegate exploration - Use subagents for research
- Use hooks - Automate repetitive validations
- Build skills library - Reuse workflows across projects
Advanced Patterns
Parallel Sessions with Worktrees
git worktree add ../project-feature -b feature
cd ../project-feature
claude
Each worktree has isolated state, allowing parallel Claude instances.
Piping & Scripting
cat logs.txt | claude -p "Find error patterns"
claude -p "analyze code" --output-format json > output.json
CI/CD Integration
claude -p "Review code changes for issues" --output-format json
Fan Out Across Files
for file in $(cat files-to-migrate.txt); do
claude -p "Migrate $file from React to Vue" \
--allowedTools "Edit,Bash(git commit *)"
done
Claude as Unix Utility
{
"scripts": {
"lint:claude": "claude -p 'check for typos in changes vs main'"
}
}
Common Mistakes to Avoid
| Mistake | Solution |
|---|---|
| Context filling with irrelevant data | Use /clear between tasks |
| Correcting same issue repeatedly | Rewrite prompt better, then /clear |
| CLAUDE.md too long, instructions ignored | Ruthlessly prune; move to skills |
| No way to verify implementation | Always include tests/screenshots |
| Deep exploration fills context | Use subagents for investigation |
| Trusting implementation without testing | Always verify: run tests, check output |
| Starting implementation without understanding | Use Plan Mode first |
| Not naming sessions | Use /rename to find later |
Headless Mode & Automation
One-Off Queries
claude -p "explain this function" # Text output
claude -p "analyze code" --output-format json # JSON output
claude -p "query data" --output-format stream-json # Streaming
In Scripts
cat error.log | claude -p "find root cause"
Structured Output
claude -p "list endpoints" --json-schema '{"type":"object","properties":...}'
Key Flags
| Flag | Purpose |
|---|---|
-p, --print |
Non-interactive mode |
--output-format |
text, json, stream-json |
--max-turns |
Limit agentic turns |
--max-budget-usd |
Stop at budget |
-c, --continue |
Resume last session |
IDE Integration
VS Code
- Install "Claude Code" extension from Marketplace
- Use
/configto configure settings - Run CLI from VS Code terminal with
claude - Switch between extension and CLI with
--ideflag
Key features: Prompt box in sidebar, resume conversations, work with git
JetBrains IDEs
- Install from Plugin Marketplace (IntelliJ, PyCharm, WebStorm)
- Run Claude Code from External Terminals
- Configure ESC key behavior in plugin settings
Debugging & Troubleshooting
Check Installation Health
/doctor
View Debug Log
/debug "description of issue"
Verbose Output
claude --verbose
Shows full turn-by-turn reasoning.
Enable Debug Mode
claude --debug "api,mcp"
- Slow responses: Check context size with
/context - Instructions ignored: Trim CLAUDE.md, use skills
- MCP errors: Check
/mcpstatus - Permission issues: Review
/permissions
Claude Code Mastery Guide • Keep this open as a reference while you work