The Complete Claude Code Guide
Everything you need to know — from first install to power-user mastery.
Built from a deep-dive conversation, March 2026. New here? Start with 15 Things I Wish I Knew Earlier.
What is Claude Code?
Claude Code is Anthropic's official CLI-based agentic coding assistant. Powered by Claude Opus 4.6, it lives in your terminal (and VS Code, JetBrains, desktop app, and the web). It can read your entire codebase, edit files, run commands, search the web, create git commits and PRs, spawn sub-agents for parallel work, and more — all through natural conversation.
It operates in a continuous agentic loop:
- Gather Context — Read files, search code, understand structure
- Take Action — Edit files, run commands, create commits
- Verify Results — Run tests, check output, iterate
You're always part of the loop: interrupt anytime to steer Claude in a different direction.
Installation
macOS / Linux / WSL
curl -fsSL https://claude.ai/install.sh | bash
Windows PowerShell
irm https://claude.ai/install.ps1 | iex
Homebrew
brew install --cask claude-code
WinGet
winget install Anthropic.ClaudeCode
After installation
claude --version # Verify install
claude auth login # Authenticate
cd your-project
claude # Start your first session
First Session
claude # Interactive session
claude "fix the login bug" # Start with a prompt
claude -p "explain this code" # Print mode (non-interactive)
claude -c # Continue last session
/init in your first session to generate a CLAUDE.md file for your project. This teaches Claude your build commands, conventions, and architecture.
Core Capabilities
| Category | What Claude Code Can Do |
|---|---|
| Files | Read, edit, create, rename, search by pattern (Glob) or content (Grep) |
| Shell | Run any command, start servers, background processes |
| Git | Commits, branches, PRs, diffs, log, push/pull |
| Web | Search the internet, fetch documentation |
| Subagents | Spawn specialized agents for parallel/isolated work |
| MCP | Connect to GitHub, Slack, databases, and more |
| Browser | Automate Chrome with --chrome |
Slash Commands
| Command | Purpose |
|---|---|
/model | Switch between Opus, Sonnet, Haiku |
/continue | Resume previous session |
/clear | Fresh start |
/compact | Compress context to free space |
/context | See what's consuming context window |
/cost | Token usage and costs |
/memory | View/edit persistent auto memory |
/init | Generate CLAUDE.md for your project |
/undo | Revert last code change |
/export [file] | Export conversation as text |
/hooks | Configure automation hooks |
/mcp | Manage MCP server connections |
/agents | Create/manage custom subagents |
/plugins | Browse and install plugins |
/doctor | Diagnose configuration issues |
/help | Help menu |
Keyboard Shortcuts
| Shortcut | Action |
|---|---|
| Enter | Submit message |
| Ctrl+C | Interrupt / cancel |
| Ctrl+D | Exit Claude Code |
| Shift+Tab | Cycle permission modes |
| Ctrl+P | Model picker |
| Ctrl+T | Toggle thinking / task list |
| Ctrl+G | Open external editor for prompts |
| Ctrl+O | Toggle verbose transcript |
| Ctrl+V | Paste image (Alt+V on Windows) |
| Ctrl+_ | Undo last action |
| Ctrl+R | Search command history |
| Ctrl+B | Background current task |
| Up / Down | Navigate history |
Customize keybindings in ~/.claude/keybindings.json. Supports chords like ctrl+k ctrl+s.
Permission Modes
Cycle with Shift+Tab:
| Mode | Behavior |
|---|---|
| Default | Ask permission for edits and commands |
| Auto-accept edits | File edits proceed without asking; commands still ask |
| Plan mode | Read-only — Claude can search and analyze but cannot change anything |
CLAUDE.md Files
Persistent instructions that Claude loads every session. Three layers (higher wins):
| File | Scope | Shared? |
|---|---|---|
.claude/CLAUDE.md | Project | Yes (git) |
.claude/CLAUDE.local.md | Project, personal | No |
~/.claude/CLAUDE.md | User (all projects) | No |
| System-wide path | Organization | Admin-deployed |
Example CLAUDE.md
# Build & Test
- Build: `npm run build`
- Test: `npm test`
- Dev: `npm run dev` (http://localhost:3000)
# Code Standards
- TypeScript strict mode, 2-space indent
- Always run tests before committing
# Architecture
- /src/routes/ — HTTP endpoints
- /src/services/ — Business logic
- /src/db/ — Database layer
@README.md or @docs/testing-guide.md in CLAUDE.md to reference other files.
Rules Files
Rules files provide context-sensitive instructions that load conditionally based on which files Claude is working with. They live in .claude/rules/.
How they work
Each rules file has a glob pattern in its frontmatter. When Claude reads or edits a file matching that pattern, the rules file is automatically loaded into context.
# .claude/rules/testing.md
---
globs: ["*.test.ts", "*.spec.ts", "**/__tests__/**"]
---
# Testing Rules
- Use vitest, not jest
- Always test edge cases: null, empty, boundary values
- Mock external services, never hit real APIs
- Follow Arrange-Act-Assert pattern
More examples
# .claude/rules/api-routes.md
---
globs: ["src/routes/**/*.ts", "src/api/**/*.ts"]
---
# API Route Rules
- Always validate request body with zod
- Return proper HTTP status codes (not just 200/500)
- Include error messages in response body
- Log all errors to the structured logger
# .claude/rules/database.md
---
globs: ["src/db/**", "*.sql", "migrations/**"]
---
# Database Rules
- Always use parameterized queries (never string interpolation)
- Migrations must be reversible (include down migration)
- Use transactions for multi-table operations
Rules vs CLAUDE.md
| CLAUDE.md | Rules Files | |
|---|---|---|
| Loaded | Always, every session | Only when working with matching files |
| Best for | Project-wide conventions | Context-specific standards |
| Context cost | Always in context | On-demand, saves tokens |
| Location | .claude/CLAUDE.md | .claude/rules/*.md |
settings.json
Configuration lives in settings.json at multiple scopes:
| File | Scope |
|---|---|
.claude/settings.json | Project (shared via git) |
.claude/settings.local.json | Project (local only) |
~/.claude/settings.json | User (all projects) |
{
"model": "claude-opus-4-6",
"env": {
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "50000"
},
"permissions": {
"allow": ["Bash(npm test)", "Bash(git *)", "Read", "Edit"],
"deny": ["Bash(rm -rf)"]
},
"hooks": { ... },
"autoMemoryEnabled": true
}
Permissions (Allow / Deny)
Control which tools Claude can use without asking:
{
"permissions": {
"allow": [
"Bash(npm test)", // Exact match
"Bash(git *)", // Wildcard
"Read", // All reads
"Edit" // All edits
],
"deny": [
"Bash(rm -rf *)",
"Bash(git push --force)"
]
}
}
Hooks: Why They Exist
Claude is intelligent but not deterministic. You can't rely on an LLM always remembering to run Prettier, or never touching .env files. Hooks solve this by giving you deterministic control at every lifecycle point — shell commands that fire automatically at specific events.
Permissions = "Here's what you CAN use" (access control)
Hooks = "Here's what MUST happen" (enforcement)
Rule of thumb: If it must always happen (or never happen), use a hook. If it requires judgment, use instructions.
All Hook Events
| Event | When It Fires | Matcher Matches On |
|---|---|---|
SessionStart | Session begins or resumes | startup, resume, clear, compact |
UserPromptSubmit | You submit a prompt | (none) |
PreToolUse | Before any tool executes | Tool name: Bash, Edit, mcp__* |
PermissionRequest | Permission dialog about to show | Tool name |
PostToolUse | After tool succeeds | Tool name |
PostToolUseFailure | After tool fails | Tool name |
Notification | Claude needs attention | permission_prompt, idle_prompt |
Stop | Claude finishes responding | (none) |
SubagentStart / Stop | Subagent lifecycle | Agent type |
ConfigChange | Settings file changes | user_settings, project_settings |
PreCompact | Before context compaction | manual, auto |
SessionEnd | Session terminates | clear, logout, etc. |
The Exit Code Protocol
This is the key to understanding hooks:
| Exit Code | Meaning | Effect |
|---|---|---|
| 0 | Allow / proceed | stdout = inject context (for SessionStart, UserPromptSubmit) |
| 2 | Block / deny | stderr = feedback sent to Claude explaining why |
| other | Proceed anyway | stderr logged, no blocking |
Hook Types
| Type | How It Works |
|---|---|
command | Run a shell command. Receives JSON on stdin. |
http | POST to a URL. Returns JSON with hookSpecificOutput. |
prompt | Ask a fast LLM (Haiku) to validate something. |
agent | Spawn a subagent for verification. |
Hook Configuration Format
{
"hooks": {
"EventName": [
{
"matcher": "regex_pattern",
"hooks": [
{
"type": "command",
"command": "your-shell-command",
"timeout": 30,
"async": false
}
]
}
]
}
}
Matchers use regex: Edit|Write matches both tools. mcp__github__.* matches all GitHub MCP tools. Empty string "" matches everything.
Hook Recipes
Auto-format with Prettier after edits
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write 2>/dev/null; exit 0"
}]
}]
}
}
Block dangerous commands
#!/bin/bash
# .claude/hooks/safety-check.sh
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if echo "$CMD" | grep -qE '(rm -rf /|DROP TABLE|git push --force)'; then
echo "Blocked: dangerous command" >&2
exit 2 # BLOCK
fi
exit 0 # ALLOW
Desktop notifications
{
"hooks": {
"Notification": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "notify-send 'Claude Code' 'Needs your attention!'"
}]
}]
}
}
Re-inject context after compaction
{
"hooks": {
"SessionStart": [{
"matcher": "compact",
"hooks": [{
"type": "command",
"command": "echo 'REMINDER: Use bun not npm. Current sprint: auth-refactor.'"
}]
}]
}
}
Force Claude to keep working until tests pass
{
"hooks": {
"Stop": [{
"hooks": [{
"type": "command",
"command": "ACTIVE=$(cat | jq -r '.stop_hook_active'); [ \"$ACTIVE\" = true ] && exit 0; npm test &>/dev/null || (echo 'Tests still failing' >&2 && exit 2); exit 0"
}]
}]
}
}
Protect sensitive files
{
"hooks": {
"PreToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "FILE=$(cat | jq -r '.tool_input.file_path'); case \"$FILE\" in *.env*|*secret*|*credential*) echo \"Protected file\" >&2; exit 2;; esac; exit 0"
}]
}]
}
}
Auto Memory
Auto memory is Claude taking notes for itself across sessions. As it works with you, it automatically saves useful patterns, commands, architecture insights, and debugging tricks to disk — so next session, it already "knows" your project.
What gets saved
- Build/test commands discovered
- Debugging patterns and workarounds
- Architecture insights from conversations
- Code style preferences inferred from corrections
- Environment setup quirks
What doesn't get saved
- General programming knowledge (Claude already knows)
- Temporary one-off debugging steps
- Secrets or credentials (never!)
- Session-specific context that won't matter tomorrow
Where it lives
~/.claude/projects/<project-key>/memory/
MEMORY.md ← Index (first 200 lines auto-loaded)
debugging.md ← Topic file (read on demand)
architecture.md ← Topic file
...
Project-scoped, machine-local, not synced across machines.
Interact with it
/memory— View, toggle, open folder- "Remember that we always use bun" — Claude saves it immediately
- "Forget the Redis note" — Claude finds and removes it
- Edit files directly:
~/.claude/projects/<project>/memory/
Disable
// In settings.json:
{ "autoMemoryEnabled": false }
Memory vs CLAUDE.md
| CLAUDE.md | Auto Memory | |
|---|---|---|
| Who writes it | You | Claude |
| Purpose | "Here's how I want you to work" | "Here's what you learned last time" |
| Nature | Prescriptive (rules) | Descriptive (knowledge) |
| Loaded | Full file, every session | First 200 lines only |
| Updated | Manually | Continuously |
The 200-Line Limit
MEMORY.md are loaded at session start. Content beyond line 200 is invisible until Claude explicitly reads it. Keep MEMORY.md as a concise index and move details into topic files.
Good pattern: MEMORY.md = 50-150 line index pointing to topic files. Topic files = deep details, read on demand.
Context Management
/context— See what's consuming space/compact [focus]— Manually compress with optional focus- Auto-compaction triggers at ~95% capacity
/exportafter compaction gives the compacted version only
/export after compaction gives you the summary, not the original messages. Export periodically during long sessions, or use /context to monitor usage.
Subagents
Specialized AI assistants that handle tasks in isolated contexts.
| Type | Model | Tools | Best For |
|---|---|---|---|
| Explore | Haiku | Read-only | Fast codebase search |
| Plan | Inherits | Read-only | Research & architecture |
| General-purpose | Inherits | All | Complex multi-step work |
Custom subagents
Create .claude/agents/my-agent.md:
---
name: code-reviewer
description: Review code for quality
tools: Read, Grep, Glob
model: sonnet
memory: user # Persistent learning!
maxTurns: 10
---
You are a code reviewer. Analyze code for quality,
security, and best practices.
memory: user to let subagents learn across sessions. A code reviewer that gets better over time!
MCP Servers (Integrations)
Model Context Protocol connects Claude to external tools.
# HTTP (recommended)
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
# Local stdio
claude mcp add --transport stdio postgres -- npx @anthropic/postgres-mcp
# With env vars
claude mcp add --transport stdio --env DATABASE_URL=postgres://... db -- npx server
# Manage
claude mcp list
claude mcp remove github
Use @server:resource syntax to reference MCP resources in prompts.
Skills
Reusable commands and workflows, invoked with /skill-name.
# .claude/skills/run-tests/SKILL.md
---
name: run-tests
description: Run the test suite
---
Run `npm test` and report results clearly.
Dynamic context injection
---
name: pr-analysis
description: Analyze current PR
---
## Context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
Analyze these changes...
The !command syntax executes before Claude sees the prompt.
Positional arguments
---
name: migrate
description: Migrate component between frameworks
---
Migrate $0 from $1 to $2.
Running /migrate Button React Vue expands to "Migrate Button from React to Vue."
Plan Mode
Read-only exploration — Claude can search and analyze but won't change anything.
- Activate: Shift+Tab twice
- Or:
claude --permission-mode plan - Perfect for: understanding before acting, complex refactors, architectural analysis
Extended Thinking
Extended thinking lets Claude "think harder" before responding — allocating more reasoning time for complex problems.
How to enable it
- Press Ctrl+T to toggle thinking on/off
- Or use the flag:
claude --thinking
What it does
When enabled, Claude performs an internal reasoning pass before generating its response. This shows as a "thinking" indicator in the UI. The thinking process:
- Analyzes the problem from multiple angles
- Plans its approach before acting
- Cross-checks its reasoning for errors
- Considers edge cases and implications
Adaptive reasoning
On Opus 4.6, thinking is adaptive — Claude automatically allocates more thinking time for harder problems. A simple "rename this variable" gets minimal thinking. A complex architectural question gets deep reasoning.
When to use it
| Use Thinking | Skip Thinking |
|---|---|
| Complex debugging with multiple possible causes | Simple file edits and renames |
| Architectural decisions with trade-offs | Running a build or test command |
| Code review that needs to find subtle bugs | Quick questions about code |
| Multi-step refactoring plans | Generating boilerplate |
| Security analysis | Git operations |
"Think harder" prompts
You can influence depth with your prompt:
> Think carefully about the security implications of this auth flow
> Reason step by step about why this test is flaky
> Consider all edge cases before implementing this
Git Worktrees
Run parallel Claude sessions on separate branches:
claude --worktree feature-auth # Isolated git worktree
claude -w # Auto-named worktree
Each worktree gets its own directory, branch, and file isolation. Changes don't collide.
Subagents can use them too:
---
name: parallel-refactor
isolation: worktree
---
IDE Integrations
| IDE | Install | Key Features |
|---|---|---|
| VS Code | Extensions marketplace: "Claude Code" | Inline diffs, file refs, plan mode, git integration |
| JetBrains | Settings → Plugins → "Claude Code" | Diff viewing, selection context, remote dev support |
| Desktop App | Download from claude.ai | Visual diff review, multi-session, background tasks |
| Web | claude.ai/code | Cloud-based, no local setup, mobile support |
Session Management
Every Claude Code conversation is a session that persists to disk. You can resume, fork, and manage them.
Starting sessions
claude # New interactive session
claude "fix the bug" # New session with initial prompt
claude -c # Continue the LAST session
claude --continue # Same as -c
claude -r "session-name" # Resume a specific named session
claude --resume "auth-refactor" # Same, with a name
claude --session-id "abc-123-..." # Resume by exact session ID
During a session
/fork-session # Branch off independently
/clear # Wipe conversation, start fresh
/compact # Compress context without clearing
Naming sessions
Give sessions meaningful names so you can find them later:
# When starting a session
claude --name "auth-refactor" # Start with a name
# During a session
/name auth-refactor # Name or rename the current session
# Resume by name
claude -r "auth-refactor" # Resume a named session
Without a name, sessions show up as their first message — often something unhelpful like "Boot up from ." Good names save you from scrolling through dozens of anonymous sessions.
Coloring terminal tabs
When running multiple Claude Code sessions at once, color your terminal tabs to tell them apart:
Windows Terminal: Right-click a tab → Color... → pick a color. Use different colors for different projects or tasks (e.g., red for production, green for experiments).
macOS Terminal / iTerm2: In iTerm2, right-click a tab → Edit Tab Title & Color. Combine with session naming for maximum clarity.
VS Code terminal: Right-click the terminal tab → Change Color.
/name to label the session inside Claude Code, and tab colors to distinguish them visually. A named, colored tab like auth-refactor — MyProject beats five identical "Windows PowerShell" tabs.
Session persistence
- Sessions are saved automatically to
~/.claude/sessions/ - Closing the terminal doesn't lose your session — resume anytime with
claude -c - Each session has a unique ID and optional name
- Session includes: conversation history, file changes, tool outputs
- Sessions survive across Claude Code updates
Session auto-deletion warning
The cleanupPeriodDays setting in ~/.claude/settings.json defaults to 30. After that, your sessions are gone forever. Worse: known bugs cause upgrades to reset this value, even if you changed it.
Fix it:
// In ~/.claude/settings.json — add:
{
"cleanupPeriodDays": 99999
}
Or use claude-chat.py's protect command to set this automatically. Its backup --watch mode also keeps versioned copies independently of Claude Code's storage.
Listing past sessions
claude --continue # Shows recent sessions to pick from
/resume # In-session: browse and resume
/fork-session before trying a risky approach. If it works, keep going. If not, resume the original. Like git branches, but for conversations.
Remote Control
Mirror your terminal session to a browser — on your phone, tablet, or another computer.
Setup
# Make sure you're on the latest version
claude update
# In an active session:
/remote
Claude generates a link (and optionally a QR code). Open it on any device — you'll see a live mirror of your terminal session.
How it works
- Creates a secure outbound HTTPS connection between your terminal and the web interface
- No credentials are exported from your terminal
- You can type commands from either the terminal or the remote browser
- Both see the same conversation in real-time
- The remote session ends when you close the terminal session
Use cases
| Scenario | How Remote Control Helps |
|---|---|
| Long-running agent task | Start on desktop, monitor from phone while away |
| Permission prompts | Approve permission requests from your phone when Claude needs input |
| Accept-edits mode | Don't come back hours later to find Claude was waiting for approval |
| Pair programming | Share the link with a colleague to watch/interact |
Teleport (reverse direction)
The opposite of Remote Control — bring a web session into your terminal:
/teleport # In web: generates a command
claude --teleport # In terminal: resume the web session locally
Background Tasks
Run long operations in the background while you continue working.
Background a running task
Press Ctrl+B while Claude is working to push it to the background. You'll get a notification when it completes.
Run commands in background
> Run the full test suite in the background while I work on something else
Claude uses the run_in_background parameter on Bash commands. The task runs asynchronously and Claude reports results when done.
Subagents as background workers
Subagents naturally run in isolated contexts. Spawn multiple for parallel work:
> Research the auth module, the payment module, and the notification module
> in parallel. Report findings for each.
Claude spawns three subagents that work simultaneously.
Checking on tasks
- Ctrl+T — Toggle the task list to see running/completed tasks
- Claude notifies you when background work finishes
- Use the
Notificationhook for desktop alerts on completion
Your First 10 Minutes with Claude Code
A step-by-step walkthrough from zero to productive. Assumes you've already installed Claude Code.
Minute 0-1: Start and authenticate
cd your-project
claude
If this is your first time, you'll be prompted to log in. Follow the browser flow.
Minute 1-2: Generate project instructions
/init
Claude scans your project and generates a CLAUDE.md with build commands, architecture notes, and conventions. Review it, edit if needed.
Minute 2-4: Ask Claude to understand your project
> What does this project do? Walk me through the architecture.
Claude reads your files, finds the entry points, and explains the structure. This also gives Claude context for future work.
Minute 4-6: Make your first edit
> Add input validation to the login endpoint
Claude will find the relevant file, show you a diff, and ask for permission to apply it. Review, approve, done.
Minute 6-8: Run tests
> Run the tests and fix anything that's broken
Claude runs your test suite, reads failures, edits code, re-runs until green.
Minute 8-10: Create a commit
> Commit this with a good message
Claude stages the changed files, writes a descriptive commit message, and creates the commit.
/model— Try switching between Opus (deep reasoning) and Sonnet (fast, cheaper)/cost— See how many tokens you've used/memory— Check what Claude learned about your project- Shift+Tab — Try Plan mode for safe exploration
Workflow: Debugging a Production Bug
A realistic end-to-end example showing how features combine.
1. Start in Plan mode (safe exploration)
# Press Shift+Tab twice for Plan mode
> Users report 500 errors on /api/checkout. The error log shows:
> "TypeError: Cannot read property 'price' of undefined"
> Investigate the root cause.
Claude searches the codebase, traces the data flow, finds the bug — without changing anything.
2. Switch to default mode and fix
# Press Shift+Tab to go back to default mode
> Fix it. The cart items array can contain null entries after deletion.
> Add a filter before the price calculation.
Claude edits the file and shows you the diff.
3. Verify with tests
> Write a test for this edge case and run the full test suite
4. Commit and create PR
> Commit and create a PR for this fix
Claude creates a branch, commits, pushes, and opens a PR with a description of the bug and fix.
Workflow: Refactor a Module and Create a PR
1. Plan the refactor
# Start in Plan mode
> The auth module in src/auth/ mixes JWT validation, session management,
> and password hashing. Plan a refactoring to separate these concerns.
Claude explores the code, identifies dependencies, and presents a plan.
2. Execute with worktree isolation
> Create a worktree and implement the plan
Claude creates an isolated git worktree, so your main branch stays clean while it works.
3. Spawn subagents for parallel work
> Split the JWT, session, and password modules in parallel
Claude spawns subagents that each handle one module simultaneously.
4. Run tests, commit, PR
> Run all tests, commit, and create a PR with a detailed description
Hidden Gems & Overlooked Features
1. Checkpoint + Summarize Strategy
Press Esc twice to open the rewind menu, then "Summarize from here." This compresses only from a point forward while keeping early context intact — unlike /compact which compresses everything.
2. Subagent Persistent Memory
Subagents can learn across sessions with memory: user. A code reviewer that builds institutional knowledge over time.
3. MCP Tool Search (Dynamic Loading)
When you have many MCP servers, tools consume context. Tool Search loads them on demand:
ENABLE_TOOL_SEARCH=auto:5 claude # Activate at 5% context
4. Skills with Dynamic Context
The !command syntax in skills executes shell commands and injects output into the prompt before Claude processes it.
5. --append-system-prompt vs --system-prompt
# WRONG: loses all Claude Code defaults
claude --system-prompt "You are a Python expert"
# RIGHT: adds to defaults
claude --append-system-prompt "Always use type hints"
6. Structured JSON Output
claude -p --output-format json "list endpoints"
claude -p --json-schema '{"type":"object",...}' "extract data"
7. Multi-Directory Work
claude --add-dir ../shared-lib --add-dir ../api
Claude sees and works across all specified directories.
8. Piping Into Claude
git diff | claude -p "Review for security issues"
cat error.log | claude -p "What went wrong?"
9. Budget Control
claude -p --max-budget-usd 5 "refactor auth module"
10. disable-model-invocation in Skills
| Setting | You invoke | Claude invokes |
|---|---|---|
| (default) | Yes (/skill) | Yes |
disable-model-invocation: true | Yes (/skill) | No |
user-invocable: false | No | Yes (background knowledge) |
Rewind & Checkpoints
Claude Code tracks every change and conversation state. You can rewind to any point.
Undo the last change
/undo # Revert last code change
# or press Ctrl+_
Rewind to any point
Press Esc twice to open the rewind menu. You'll see every conversation turn with options:
| Option | What It Does |
|---|---|
| Rewind here | Restore code and conversation to this exact point. All later changes undone. |
| Summarize from here | Keep everything before this point intact, compress everything after into a summary. Frees context without losing early instructions. |
/compact when you want to keep your initial setup and CLAUDE.md instructions intact but compress a verbose debugging phase. Much more surgical than global compaction.
Fork a conversation
/fork-session
Creates a branch of the current session. Explore a different approach without losing your current work. Both sessions continue independently.
Key insight: Rewind keeps the prompt
When you rewind, your original prompt stays in the input field. You can edit it and re-submit — perfect for trying a different instruction on the same starting point.
Browser Automation
Claude Code can control Chrome directly for testing, debugging, and scraping documentation.
Setup
# Launch with browser automation enabled
claude --chrome
# Or enable it in settings.json
{
"env": {
"CLAUDE_CODE_CHROME": "true"
}
}
You'll also need the Claude Code Chrome extension installed from the Chrome Web Store. This bridges Claude Code's terminal commands to your browser.
What Claude can do
| Action | Example Prompt |
|---|---|
| Navigate | "Open localhost:3000/login" |
| Click elements | "Click the 'Submit' button" |
| Fill forms | "Fill the email field with test@example.com" |
| Screenshot | "Take a screenshot of the current page" |
| Read page content | "What text is shown in the error banner?" |
| Check console | "Are there any JavaScript errors in the console?" |
| Wait for elements | "Wait for the loading spinner to disappear" |
Practical use cases
Visual debugging
> Open the app in Chrome, navigate to /dashboard, and screenshot the
> layout. The sidebar is overlapping the content on mobile width.
Claude opens Chrome, navigates, screenshots, identifies the CSS issue, then fixes it in your code.
End-to-end testing
> Test the full checkout flow: add an item to cart, go to checkout,
> fill in payment details, and verify the success page shows.
Scraping documentation
> Open the Stripe API docs and find the endpoint for creating
> payment intents. Summarize the required parameters.
Headless mode
For CI/CD or screenshotting without a visible browser:
claude --chrome --headless -p "Screenshot localhost:3000 and check for layout issues"
Cost Optimization
Model selection matters most
| Model | Best For | Relative Cost |
|---|---|---|
| Haiku | Simple edits, file search, quick questions | $ |
| Sonnet | Most coding tasks, balanced speed/quality | $$ |
| Opus | Complex architecture, deep reasoning, frontier research | $$$$ |
Switch with /model or Ctrl+P. Use Opus for the hard parts, Sonnet for everything else.
Token-saving strategies
- Use subagents for verbose operations — Their output stays in their context, not yours
- Keep CLAUDE.md under 200 lines — It loads every session
- Reduce MCP servers — Each adds tool definitions to context. Use
ENABLE_TOOL_SEARCH=auto:5for many tools - Use
/compactwith focus —/compact focus on the auth refactorpreserves what matters - Use Plan mode for exploration — Read-only operations before committing to changes
- Pipe for quick tasks —
git diff | claude -p "review"uses a single turn, no session overhead
Budget caps
# Hard stop at $5
claude -p --max-budget-usd 5 "refactor the auth module"
Monitor usage
/cost # Current session usage
/context # What's consuming context space
Set output token limit
// In settings.json:
{
"env": {
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "30000"
}
}
Headless / SDK Mode
# Non-interactive with JSON output
claude -p --output-format json --no-session-persistence "task"
# Streaming for real-time processing
claude -p --output-format stream-json --verbose "task"
# With schema validation
claude -p --json-schema '{"type":"object",...}' "extract data"
CI/CD Integration
Use Claude Code in automated pipelines with headless mode (-p).
Automated code review on PRs
# .github/workflows/claude-review.yml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: curl -fsSL https://claude.ai/install.sh | bash
- name: Review PR
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
DIFF=$(git diff origin/main...HEAD)
echo "$DIFF" | claude -p \
--model sonnet \
--max-budget-usd 2 \
"Review this PR diff for bugs, security issues, and code quality.
Be concise. Focus on actionable feedback only." \
> review.md
- name: Post review comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: review
});
Automated test generation
# Generate tests for changed files
CHANGED=$(git diff --name-only origin/main...HEAD | grep -E '\.(ts|js)$')
for file in $CHANGED; do
claude -p --model sonnet \
"Generate unit tests for $file. Output only the test file content." \
> "tests/$(basename $file .ts).test.ts"
done
Structured output for tooling
# Get JSON output for downstream processing
claude -p --output-format json \
--json-schema '{"type":"object","properties":{
"issues":{"type":"array","items":{"type":"object","properties":{
"file":{"type":"string"},
"line":{"type":"number"},
"severity":{"type":"string"},
"message":{"type":"string"}
}}}
}}' \
"Analyze src/ for security vulnerabilities" | jq '.issues[]'
Commit message generation
# In a git hook or CI step
MSG=$(git diff --cached | claude -p --model haiku \
"Write a concise conventional commit message for this diff.
Format: type(scope): description. One line only.")
git commit -m "$MSG"
--max-budget-usd in CI pipelines to prevent runaway costs. Use Haiku or Sonnet (not Opus) for automated tasks.
"YOLO Mode" (dangerously-skip-permissions)
"YOLO mode" is the community nickname for Claude Code's full-autonomy flag:
claude --dangerously-skip-permissions
This skips every permission prompt. Claude edits files, runs shell commands, deletes things, pushes to git — all without ever asking. Zero confirmations. Full autonomy.
--dangerously-skip-permissions to make you think twice.
The permission spectrum
| Mode | Claude does | You do |
|---|---|---|
Plan mode--permission-mode plan |
Read-only, can't change anything | Full control |
| Default | Asks before edits and commands | Approve/deny each action |
| Auto-accept edits | Edits freely, asks before commands | Approve commands only |
"YOLO mode"--dangerously-skip-permissions |
Everything, no questions asked | Watch |
Why people use it
- Speed — No interruptions, no clicking "approve" 50 times during a big refactor
- Trust — When you've worked with Claude Code enough to know it handles your project well
- CI/CD — Automated pipelines can't click "approve"
- Sandbox environments — When running in a container/VM where nothing matters
The risks
- Claude could
rm -rfsomething important - Could push to main without review
- Could run destructive database commands
- Could overwrite uncommitted work
- Could install packages or modify system files
- No undo for shell commands (file edits can still be
/undo'd)
The smart middle ground: Pre-approved permissions
Most power users don't go full YOLO. Instead, they pre-approve safe operations in settings.json:
{
"permissions": {
"allow": [
"Read", "Edit", "Write", "Glob", "Grep",
"Bash(npm test)", "Bash(npm run *)",
"Bash(git add *)", "Bash(git commit *)",
"Bash(git diff *)", "Bash(git status *)",
"Bash(git log *)", "Bash(git branch *)"
],
"deny": [
"Bash(rm -rf *)",
"Bash(git push --force *)",
"Bash(DROP *)",
"Bash(DELETE FROM *)"
]
}
}
This gives you ~90% of the YOLO speed with guardrails on the dangerous stuff. Claude breezes through reads, edits, tests, and git without asking — but still pauses before destructive operations.
PreToolUse hook that blocks specific dangerous patterns. You get speed AND safety:
{
"permissions": {
"allow": ["Read", "Edit", "Write", "Bash(npm *)", "Bash(git *)"],
"deny": ["Bash(git push --force *)"]
},
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "CMD=$(cat | jq -r '.tool_input.command'); echo \"$CMD\" | grep -qiE '(rm -rf /|drop table|truncate|format)' && echo 'Blocked' >&2 && exit 2; exit 0"
}]
}]
}
}
If you DO go full YOLO
- Use a sandbox — Container, VM, or at minimum a git branch you can throw away
- Commit first —
git commit -am "checkpoint before YOLO" - Watch the output — Don't walk away. YOLO means YOU are the guardrail now
- Set a budget —
claude --dangerously-skip-permissions --max-budget-usd 10 - Limit turns —
claude --dangerously-skip-permissions --max-turns 20
CLI Reference
# Session management
claude # Interactive
claude "task" # With prompt
claude -c # Continue last
claude -r "name" "prompt" # Resume specific
# Key flags
--model sonnet|opus|haiku # Choose model
--permission-mode plan # Read-only
--add-dir ../other # Extra directories
--chrome # Browser automation
--max-turns 5 # Limit loops
--append-system-prompt "text" # Add instructions
--output-format json|text|stream-json
# Auth
claude auth login|logout|status
# MCP
claude mcp add|list|get|remove
# Updates
claude update
Git Workflows
Claude Code has deep git integration that goes far beyond simple commits.
Commit workflow
> Commit this with a good message
Claude runs git status, git diff, reviews recent commit style, stages relevant files, writes a descriptive commit message, and commits. It follows conventional commit style if your project uses it.
PR workflow
> Create a PR for this feature
Claude creates a branch (if needed), pushes, and uses gh pr create with a structured description including summary and test plan. It reads the full diff from the base branch to write an accurate PR body.
Branch management
> Create a feature branch for the auth refactor
> Cherry-pick commit abc123 onto the release branch
> What commits are on this branch that aren't on main?
Conflict resolution
> Merge main into this branch and resolve any conflicts
Claude pulls, identifies conflicts, reads both sides, applies intelligent resolution (not just "pick ours"), and verifies the result compiles.
PR review
> Review PR #42 for security issues
Claude uses gh pr diff 42 and gh pr view 42 to read the full diff and description, then provides structured feedback.
Worktrees for parallel features
claude --worktree feature-a # First terminal: feature A
claude --worktree feature-b # Second terminal: feature B
Each worktree has its own branch, directory, and file state. Two Claude instances working on different features without conflicts.
Git safety behavior
Claude Code has built-in safety for git operations:
- Prefers new commits over amending (to avoid destroying work)
- Stages specific files rather than
git add -A(to avoid committing secrets) - Never force-pushes to main/master without explicit instruction
- Never skips hooks (
--no-verify) unless explicitly asked - Asks before destructive operations like
git reset --hard
Stop hook that runs tests:
{
"hooks": {
"Stop": [{
"hooks": [{
"type": "command",
"command": "npm test &>/dev/null || (echo 'Tests failing - keep going' >&2 && exit 2); exit 0"
}]
}]
}
}
Claude commits only when tests pass. Built-in CI.
Small Commands, Big Impact
The flashy features get all the attention. These don't — but together they transform your daily workflow.
Context awareness
| Command | What | Why it matters |
|---|---|---|
/context |
Show context window usage (%) | Know when you're about to hit the wall. Plan your /compact instead of being surprised |
/cost |
Show token costs for this session | Track spend per session. Big sessions can cost more than you think |
/compact |
Compress context without clearing | Keeps working memory but frees space. Use proactively, not after you've already hit the limit |
/export |
Export current conversation | Save before compaction eats the details. Compacted exports lose the original messages |
Session control
| Command | What | Why it matters |
|---|---|---|
/name my-task |
Name or rename the current session | Without this, sessions show up as their first message — often "fix the bug" or "boot up from ." |
/status |
Show active model, permissions, hooks | When something feels off, this tells you what's actually loaded |
/doctor |
Diagnose setup issues | First thing to try when stuff breaks. Checks Node, auth, permissions, hooks |
/memory |
View and manage auto-memory | See what Claude remembers about you and your project. Delete entries that are wrong or stale |
/init |
Generate a CLAUDE.md from your codebase | Seeds project instructions so Claude understands your repo from the first message |
Keyboard shortcuts
| Key | What | Why it matters |
|---|---|---|
Shift+Tab |
Cycle permission accept modes | Toggle between auto-accept and manual without restarting |
Esc |
Cancel current operation | Stop a runaway agent or long-running tool call immediately |
! + command |
Run shell command inline | Stay in the conversation, run a quick !git status or !ls without leaving |
Ctrl+O |
Expand collapsed output | Tool call results are collapsed by default. Expand to see full output |
/undo |
Undo last file changes | Claude tracks all edits. Undo fearlessly — it won't lose the conversation context |
CLI one-liners
| Command | What | Why it matters |
|---|---|---|
git diff | claude -p "review" |
Pipe data in for quick analysis | No session overhead. Get a review, explanation, or rewrite in one shot |
claude -p "explain" < file.py |
Quick file analysis | One-off understanding without starting a full session |
claude --model sonnet |
Start with a specific model | Use Sonnet for quick tasks, Opus for complex ones. Save cost where it doesn't matter |
claude -c |
Continue last session | Pick up exactly where you left off. Your context, files, and conversation are all there |
/name + tab colors + /context monitoring + proactive /compact + /export before key milestones = a workflow where you never lose work, never hit context limits by surprise, and can always find your sessions later. The little things compound.
Tips & Best Practices
- Start with
/initto create a CLAUDE.md for your project - Use Plan mode first for complex tasks — understand before changing
- Keep CLAUDE.md under 200 lines — link to external files
- Use subagents for verbose operations to protect context
- Set up hooks for formatting, linting, notifications
- Export periodically in long sessions before compaction
- Monitor context with
/contextand/cost - Use
/undofearlessly — Claude tracks all changes - Pipe data in for quick analysis:
git diff | claude -p "review" - Use worktrees for parallel feature development
Windows-Specific Gotchas
Claude Code on Windows uses Git Bash (MINGW64). This works well, but there are quirks.
PATH conflicts
Other software can inject executables into your PATH that break Claude Code or its tools. Known culprits:
| Software | Problem | Fix |
|---|---|---|
| Topaz Video AI | Bundles its own ffmpeg.exe that interferes with MiKTeX and other tools |
Use a clean PATH in your session: export PATH="/c/Users/You/AppData/.../bin:/usr/bin:/mingw64/bin" |
| Anaconda/Miniconda | Can shadow system Python and break pip |
Use full paths or deactivate conda: conda deactivate |
| Cygwin | Conflicts with Git Bash's Unix tools | Don't mix Cygwin and Git Bash in PATH |
Path format
Claude Code uses Unix-style paths in Git Bash:
/c/Users/Holger/Documents # Git Bash style (use this)
C:\Users\Holger\Documents # Windows style (avoid in commands)
D:/FromGitHubEtc/project # Forward slashes work too
LaTeX (MiKTeX) setup
# Install
winget install MiKTeX.MiKTeX
# Binary location
C:\Users\You\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe
# Add to PATH in .bashrc
export PATH="$PATH:/c/Users/You/AppData/Local/Programs/MiKTeX/miktex/bin/x64"
Line endings (CRLF vs LF)
Git on Windows defaults to CRLF. Claude Code writes LF. You'll see warnings like LF will be replaced by CRLF. This is harmless, but if it bothers you:
git config --global core.autocrlf input
Image paste shortcut
On Windows, use Alt+V to paste images (not Ctrl+V, which pastes text from clipboard).
Long file paths
Windows has a 260-character path limit by default. Node modules can exceed this. Fix:
# Run as admin in PowerShell:
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1
Claude Code vs Cursor vs Copilot vs Windsurf
| Claude Code | Cursor | Copilot | Windsurf | |
|---|---|---|---|---|
| Interface | Terminal CLI + IDE | Full IDE | IDE plugin | Full IDE |
| Model | Claude (Opus/Sonnet/Haiku) | Multiple | GPT-4o / Claude | Multiple |
| Agentic loop | Full | Yes | Limited | Yes |
| Shell access | Full | Yes | Limited | Yes |
| Git | Full | Basic | Full | Basic |
| Subagents | Yes | No | No | No |
| MCP | Full | Yes | Limited | Limited |
| Hooks | 12+ events | No | No | No |
| Skills | Yes | Rules | Instr. | Rules |
| Memory | Auto+manual | Notepad | Instr. | Rules |
| Headless | Full | No | CLI | No |
| Mobile | Termux | No | No | No |
| Plan mode | Yes | No | No | No |
| Pricing | Claude sub or API | $20/mo + API | $10-39/mo | $15/mo + credits |
When to choose Claude Code
- You want terminal-first workflow (or use multiple IDEs)
- You need automation — hooks, headless mode, CI/CD integration
- You need subagents for parallel work
- You want MCP integrations with external tools
- You work on mobile (Android/Termux)
- You need custom skills and persistent memory
- You prefer Claude models (especially Opus for complex reasoning)
When another tool might fit better
- You want inline autocomplete while typing (Copilot excels here)
- You want a full GUI IDE with AI built in (Cursor, Windsurf)
- You want to mix models from different providers in one tool (Cursor)
- You're a visual learner who prefers clicking over typing
Troubleshooting & FAQ
Common Errors
| Error | Cause | Fix |
|---|---|---|
command not found: claude |
Not in PATH | Reinstall: curl -fsSL https://claude.ai/install.sh | bash or check ~/.local/bin |
Authentication failed |
Token expired or invalid | claude auth logout && claude auth login |
Context window full |
Too much in conversation + files | /compact or start fresh with /clear |
MODULE_NOT_FOUND |
Node.js upgraded, npm packages broken | npm install -g @anthropic-ai/claude-code |
ENOENT: /tmp/... |
/tmp not writable (Termux) | Use proot: proot -b $PREFIX/tmp:/tmp claude |
| MCP server not connecting | Config issue or server down | claude mcp list and /mcp to diagnose |
| Hook never fires | Wrong matcher or event name | Check regex, enable verbose with Ctrl+O |
Rate limit exceeded |
Too many API requests | Wait, or switch to a different model: /model |
| Diff looks wrong in IDE | File changed outside Claude | /undo then re-apply, or refresh IDE |
FAQ
Q: Does Claude Code send my code to Anthropic's servers?
Claude Code sends file contents and commands to the Claude API for processing. Your data is subject to Anthropic's data policies. For sensitive projects, review the Anthropic privacy policy.
Q: Can I use Claude Code offline?
No. Claude Code requires an internet connection to communicate with the Claude API.
Q: How do I update Claude Code?
Native installs auto-update. For npm: npm update -g @anthropic-ai/claude-code. For Homebrew: brew upgrade claude-code.
Q: Can multiple people use the same CLAUDE.md?
Yes. .claude/CLAUDE.md is checked into git and shared with the team. Use .claude/CLAUDE.local.md for personal overrides.
Q: What happens to my session when I close the terminal?
Sessions are saved. Resume with claude -c (last session) or claude -r "name" (specific session).
Q: Can Claude Code work with monorepos?
Yes. Use --add-dir to include multiple packages: claude --add-dir packages/api --add-dir packages/web
Q: Is there a free tier?
Claude Code is included with Claude Pro, Team, and Enterprise subscriptions. You can also use it with Anthropic API credits (pay-per-token).
Q: Can I use it without VS Code?
Absolutely. Claude Code is terminal-first. VS Code and JetBrains are optional integrations. Many power users prefer the terminal exclusively.
Learning Resources
YouTube
Mark Kashef / Prompt Advisers
One of the few Claude Code YouTubers who consistently covers the WHY, WHAT, and HOW. Not just feature overviews — he opens the terminal and walks you through step by step. His videos typically follow a pattern: explain the concept, show the setup, then build something creative with it to demonstrate real-world value.
- "Claude Code Zero-to-Hero" playlist — Best starting point for beginners
- Remote control walkthrough — Shows
/remotesetup, then builds a pseudo personal assistant using soul files, memory, and skills — accessible from your phone - YOLO mode and operating system — How he built a Claude Code "operating system" managed from Telegram
- Covers MCP servers, skills, workspace design, and practical automation
Official Resources
| Resource | URL | Best For |
|---|---|---|
| Claude Code Docs | docs.anthropic.com | Authoritative reference |
| Claude Code GitHub | github.com/anthropics/claude-code | Bug reports, features |
| MCP Specification | modelcontextprotocol.io | Building MCP servers |
| Anthropic Cookbook | anthropics/anthropic-cookbook | Practical examples |
| Claude Code Best Practices | anthropic.com/engineering | Agentic-coding patterns from the team |
Courses & Certification
| Resource | URL | Best For |
|---|---|---|
| Anthropic Academy | anthropic.skilljar.com | Free official courses ("Claude Code in Action" & more) + certification track |
| freeCodeCamp: Claude Code Architect | youtube.com/watch?v=reDRM0tqhNs | Certification preparation, full-length walkthrough |
| DeepLearning.AI short course | Claude Code: A Highly Agentic Coding Assistant | Structured intro to agentic workflows |
Community
- masterclaudecode.com — Curated learning path
- awesome-claude-code — Community-curated list of skills, hooks, and tooling
- GitHub Issues — Where bugs get fixed and features get discussed
- r/ClaudeAI — Reddit community for tips, workflows, and troubleshooting
Key concepts to search for
When looking for more tutorials and guides, these terms will find the most useful content:
- "Claude Code hooks tutorial" — Automation and guardrails
- "Claude Code MCP setup" — External tool integration
- "Claude Code YOLO mode safe" — Permission strategies
- "Claude Code skills custom" — Building reusable workflows
- "Claude Code subagents parallel" — Multi-agent patterns
- "Claude Code CI/CD" — Pipeline automation
- "Claude Code Termux Android" — Mobile setup
Running Claude Code on Android (Termux)
Yes, Claude Code runs on your phone. It took hours of troubleshooting to figure out — here's everything you need to know, distilled into a guide and a one-command setup script.
Download setup-claude-termux.sh (included with this guide), copy it to Termux, and run:
cp ~/storage/downloads/setup-claude-termux.sh ~/
chmod +x ~/setup-claude-termux.sh
./setup-claude-termux.sh
The script handles everything: updates packages, installs Node.js, Python, proot, Claude Code, configures your shell, sets up Android storage access, and launches Claude Code at the end.
--all— Install everything without questions--status— See what's already installed--help— All options
Safe to re-run anytime. It detects what's already there and skips it.
If you want to understand what's happening under the hood, or if something goes wrong, read on.
Step-by-Step Installation
Step 1: Get Termux (Not From Play Store!)
The Play Store version has been abandoned since 2020. You need the GitHub release.
Go to: github.com/termux/termux-app/releases
Download the RELEASE build, not debug:
termux-app_v0.119.0+github-release_arm64-v8a.apk ← THIS ONE
termux-app_v0.119.0+github-debug_arm64-v8a.apk ← NOT this
Fix: Play Store → Profile → Play Protect → Settings → Turn OFF "Scan apps with Play Protect"
You can re-enable it after installing Termux.
Step 2: The Chicken-and-Egg Problem
Termux installed, but curl gives SSL errors. And pkg needs curl. Classic.
Run this immediately after first launch:
termux-change-repo
Select a mirror, then:
pkg update && pkg upgrade -y
Say Y to all config prompts. This syncs your libraries properly.
Step 3: Install Claude Code
pkg install nodejs -y
npm install -g @anthropic-ai/claude-code
Step 4: The /tmp Problem (Critical!)
This is where most people get stuck. Claude Code tries to create directories under /tmp, but on Termux, /tmp is read-only. You'll see errors like:
ENOENT: no such file or directory, mkdir '/tmp'
EACCES: permission denied
The fix is proot, which maps a writable directory onto /tmp:
pkg install proot
proot -b /data/data/com.termux/files/usr/tmp:/tmp claude
To make this permanent, add an alias to your .bashrc:
echo "alias claude='proot -b /data/data/com.termux/files/usr/tmp:/tmp claude'" >> ~/.bashrc
source ~/.bashrc
Now you just type claude and proot handles everything behind the scenes.
Step 5: Android Storage Access
Want Claude Code to save files to your Android Downloads folder?
termux-setup-storage
Tap Allow on the permission dialog. Now ~/storage/downloads maps to your phone's Downloads.
Step 6: The Node.js Update Trap
pkg can jump major Node.js versions (e.g. v22 to v25) in a single upgrade. When that happens, ALL globally installed npm packages break silently. The claude command exists but throws MODULE_NOT_FOUND.
Fix: reinstall Claude Code after any Node.js major version bump:
npm install -g @anthropic-ai/claude-code
The setup script handles this automatically — it checks if Claude Code actually works, not just if the binary exists.
Extras & Known Issues
Math & Science Packages
Claude Code can use these tools directly for computation:
# Math tools
pkg install pari maxima matplotlib python-scipy
pip install --break-system-packages sympy
# LaTeX
pkg install texlive-installer tectonic
# GitHub integration
pkg install gh
gh auth login
Known Issues & Workarounds
| Issue | Cause | Fix |
|---|---|---|
| Device full = broken packages | Running out of storage during pkg upgrade corrupts package state |
Free up space first. Need at least 500MB. |
| Background tasks fail | Even with TMPDIR set, background processes still try /tmp |
The proot alias is the only complete fix. |
claude update doesn't work |
Native updater downloads incompatible binary | pkg upgrade nodejs && npm install -g @anthropic-ai/claude-code |
| Android kills Claude Code | Android's aggressive background app killing | Disable battery optimization for Termux in Android settings |
| TMPDIR alone isn't enough | export TMPDIR=$HOME/tmp fixes some things but not all |
Use proot instead for complete /tmp mapping |
Why Bother?
The real reason: skills, workflows, git repos, and the full agentic loop — all on your phone. The Claude web interface can't use your custom skills, your CLAUDE.md, your hooks, or your MCP servers. With Termux, you get full Claude Code: terminal, git, file editing, subagents, everything. A complete mobile dev & research environment in your pocket.
git stash && git pull && git stash pop
Extending Claude Code — Field Notes from a Running Installation (July 2026)
What the March guide above documents as features, this section maps as attachment
points — each grounded in what a real four-box fleet (two Windows machines, Linux,
Android/Termux) actually runs daily. Full write-up with all the hook lessons and scar tissue:
extending-claude-code.md.
Surfaces in production
| Surface | What's attached |
|---|---|
SessionStart hooks | Boot scans (decayed resources, registry joins, config sanity) — silent when clean, fail-open; compact-source variant re-injects state after compaction |
PreToolUse — blocking | Contract gates: a document missing its required field is denied; a state-changing git command with silenced stderr is refused |
PreToolUse — reminders | First write in a sibling repo → "run the reuse scan"; heavyweight-process territory → proportionality nudge |
Stop hooks — blocking | Push-verify ("all pushed" while git is ahead → stop blocked), max_tokens truncation recovery, closeout enforcement |
| Speech hooks | Turn-end speech via a neural edge-tts voice (a Stop hook delegating to a sibling repo's proven speaker); a second, fully-offline Kokoro lane voices results and bus messages |
| Transcript JSONL | Post-hoc scanners over ~/.claude/projects/<slug>/ — per-session quality metrics no live hook could produce (and the reason claude-chat.py exists) |
| Monitor + background | Persistent watch on a git-file inter-session message bus — concurrent sessions on different machines collaborate without the human relaying |
.sh files (inline commands get MSYS-mangled on Windows) •
gate on CLAUDE_CODE_ENTRYPOINT=cli or you contaminate headless claude -p •
check the executable bit AND the git index mode — six correct hooks sat dead for days at 100644 •
every blocking gate ships a planted-positive control (a gate that has only ever passed has been shown to run, not to work) •
heuristics may warn; only authoritative signals (git state, stop_reason) may block.
Not yet attached (the catalog)
- Orchestration — custom subagents (
.claude/agents/), the Workflow tool + saved workflows (verification panels as ten-line scripts), worktree isolation for concurrent sessions - Time — CronCreate for scheduled headless sweeps,
/schedulecloud routines,/loopself-paced recurrence — nothing in most stacks fires without a human - Reach & presence — Notification hook + PushNotification (a blocked session pings your phone), statusline readouts, Artifacts as cross-device dashboards, Claude in Chrome
- Plumbing — plugins (package hooks+skills+agents against multi-machine drift), OpenTelemetry export (
CLAUDE_CODE_ENABLE_TELEMETRY=1— the work-timer dataset for one env var), MCP servers (deliberately skipped in this installation; documented why in the write-up)
Case studies — four ways to attach a thing
- Outside-in, no API — StickShift: a menu-bar H-pattern gearshift that changes the focused session's model/effort by proving the pane holds an idle agent (OS Accessibility), then typing
/modelas real keystrokes. Refuses with a reason code when unproven. - Inside-out — a speaking
Stophook: neural edge-tts voice, two-phase detach (the hook returns instantly), lock-serialized playback, kill-switch file, inert on machines without the speaker stack. Plus a fully-offline Kokoro lane. - Exhaust-watching — a zero-dependency CRT console that renders live lab state purely from files sessions already write (event store, bus JSONL, per-hook fire-logs). Integration cost to the observed sessions: zero.
- Contract-in-a-file — an avatar orb performing the assistant's own stage directions: any speaker writes
spool/latest.json, a browser page polls it. Second skin (140k-point GPU swarm) shipped with zero contract changes; a scene-painter canvas is next.
Adoption order picked here (2026-07-28): statusline + notification→push, verification panel as a saved workflow, OTel export. The one-line philosophy behind all of it: make the wiring refuse what the discipline used to merely discourage.
Prometheus v7.2 + Claude Code: Analysis & Recommendations
After analyzing the Prometheus v7.2 architecture installed at MilleniumProblems/.skills/Prometheus/ alongside your Claude Code setup, here's an honest assessment.
What Prometheus Does Well (Keep Doing)
- Cognitive architecture — The KERNEL (continuity, anticipation, holism, permission) provides genuine intellectual discipline that Claude Code has no native equivalent for
- Plugin hook system — DETECTION, KNOWN_STATE, TOOLS, STRATEGIES, LENS, CONTEXT — these are reasoning hooks, not automation hooks. They structure how Claude thinks, not what it executes
- Domain plugins — Mathematics, Physics plugins with KNOWN_STATE prevent rediscovering known results. Claude Code has no domain awareness natively
- GRIND/FRONTIER/PARALLAX — Research protocols with mandatory verification. No Claude Code equivalent
- State persistence —
.prometheus/state.mdandledger.mdprovide structured research continuity that auto-memory can't match - Dead-end tracking —
graveyard.mdwith failure reasons prevents revisiting closed routes
Where Prometheus and Claude Code Overlap (Streamline)
| Feature | Prometheus | Claude Code Native | Recommendation |
|---|---|---|---|
| Session memory | state.md + ledger.md | Auto memory + CLAUDE.md | Keep both — different purposes |
| Boot sequence | 8-step file loading | CLAUDE.md auto-load + skills | Consider making Prometheus a skill with context: fork |
| Mode detection | DETECTION_HEURISTICS.md | Claude's native classification | Prometheus adds value — keep |
| User prefs | user.md | Auto memory + ~/.claude/CLAUDE.md | Merge into auto-memory |
| Tool recs | TOOLS hook in plugins | Claude knows tools natively | Keep for domain-specific (PARI/GP) |
What You're Missing in Claude Code (Do More Of)
- No hooks configured! Your
settings.jsonhas permissions but zero hooks. Add at minimum:Notificationhook for desktop alertsSessionStart(compact)for context re-injection after compactionPreCompactto auto-save Prometheus state before compaction
- No custom subagents — You could create a
math-verifieragent that runs PARI/GP checks - No Claude Code skills (outside Prometheus) — Your DISTILL, GRIND, etc. live inside Prometheus but could also be native skills
- Permissions are overly specific — Your
settings.local.jsonhas 100+ individual Bash command allowances. Use wildcards instead - MEMORY.md is over 200 lines (215) — Last 15 lines are truncated. Move detailed sections into topic files
- No MCP servers — Consider GitHub MCP for your repos
Adapting Prometheus for Claude Code
Prometheus and Claude Code operate at different layers:
Prometheus = Cognition (how to think, what to verify, when to escalate)
They complement rather than compete.
Recommended adaptations:
- Add a
PreCompacthook that auto-saves.prometheus/state.mdbefore compaction:{ "hooks": { "PreCompact": [{ "matcher": "auto", "hooks": [{ "type": "command", "command": "echo 'Auto-saving Prometheus state before compaction' >&2" }] }] } } - Add a
SessionStart(compact)hook that re-injects critical Prometheus context:{ "hooks": { "SessionStart": [{ "matcher": "compact", "hooks": [{ "type": "command", "command": "cat .prometheus/state.md 2>/dev/null || echo 'No Prometheus state found'" }] }] } } - Wildcard your PARI/GP permissions instead of individual commands
- Trim MEMORY.md below 200 lines — move YM paper details, NS proof details, etc. into topic files
- Consider Prometheus commands as Claude Code skills —
/grind,/frontier,/parallaxcould be standalone skills
What to Do Less Of
- Stop accumulating one-off Bash permissions — your settings file has full PARI/GP scripts as individual allow entries. Use patterns instead.
- Reduce Prometheus boot overhead — 8 files loaded at boot consumes significant context. Consider lazy loading: boot KERNEL only, load plugins on demand via skills.
- Don't duplicate state —
Prometheus.env/user.md+ auto-memoryMEMORY.md+.prometheus/state.md= three places for similar info. Consolidate.