Claude Code Reference: CLI Flags, Shortcuts, CLAUDE.md Templates & Troubleshooting
Last updated:
Quick jump: Commands Table · Keyboard Shortcuts · Configuration Reference · Troubleshooting · Cheatsheet · Daily Workflow
📌 Section 10 TL;DR (1 minute)
Section titled “📌 Section 10 TL;DR (1 minute)”What’s inside: Complete command reference, troubleshooting guides, and daily checklists.
Quick Navigation by Need:
Section titled “Quick Navigation by Need:”| I need to… | Go to |
|---|---|
| Look up a command | 10.1 Commands Table |
| Find keyboard shortcut | 10.2 Keyboard Shortcuts |
| Configure settings | 10.3 Configuration Reference |
| Fix an error | 10.4 Troubleshooting |
| Quick daily reference | 10.5 Cheatsheet |
| Set up workflow | 10.6 Daily Workflow |
| Copy ready-to-use templates | examples/ directory: Commands, hooks, agents |
Most Common Lookups:
Section titled “Most Common Lookups:”- Context full? → 10.4.1 Context Issues
- MCP not working? → 10.4.4 MCP Troubleshooting
- Need clean reinstall? → 10.4.3 Full Reinstall
Usage tip: Bookmark this section: you’ll reference it often.
Purpose: Quick lookup for all Claude Code information
10.1 Commands Table
Section titled “10.1 Commands Table”Source of truth: code.claude.com/docs/en/commands is the official reference and always lists the current set. The tables below mirror it as of October 27, 2026 (tracked CLI v2.1.310), with the guide’s own notes and cross-references added. When the two disagree, the official page wins. For launch-time flags rather than in-session commands, see code.claude.com/docs/en/cli-reference and §10.3.
Not every command shows up for every user. Availability depends on platform, plan, and provider: /desktop only appears on macOS and x64 Windows with a Claude subscription, /setup-bedrock only when CLAUDE_CODE_USE_BEDROCK=1 is set, /upgrade never on Enterprise. Type / in a session to see what you actually have.
Notation: <arg> is required, [arg] is optional, aliases follow the command in parentheses.
Session lifecycle
Section titled “Session lifecycle”| Command | Action |
|---|---|
/clear [name] (/reset, /new) | Start a new conversation with empty context. A name labels the previous one in the /resume picker |
/resume [session] (/continue) | Resume a conversation by ID or name, or open the picker. Background sessions appear marked bg |
/branch [name] | Branch the conversation at this point and switch into the copy. The original stays reachable via /resume (v2.1.77+) |
/fork [prompt] | Copy the conversation into a new background session and keep working here. On v2.1.161 to v2.1.211 this launched a forked subagent instead (now /subtask); before that it aliased /branch |
/subtask <task> | Spawn a forked subagent that inherits the full conversation, works in the background, and reports its result back here (v2.1.212+) |
/background [prompt] (/bg) | Detach this session to run as a background agent and free the terminal. Monitor with claude agents |
/stop | Stop the attached background session. Transcript and worktree are kept. Use /exit to detach without stopping |
/rename [name] | Name the session and show it on the prompt bar. Without an argument, generates a name from history |
/recap | One-line summary of the current session on demand |
/rewind (/checkpoint, /undo) | Rewind conversation and/or code to a checkpoint, or summarize from a selected message |
/copy [N] | Copy the Nth-latest assistant response. With code blocks, opens a picker; press w to write to a file instead |
/export [filename] | Export the conversation as plain text, to a file or the clipboard |
/teleport (/tp) | Pull a Claude Code on the web session into this terminal, branch and conversation included. Requires a claude.ai subscription |
/remote-control (/rc) | Make this session drivable from claude.ai or the mobile app |
/desktop (/app) | Continue the session in the Claude Code Desktop app |
/exit (/quit) | Exit the CLI. In an attached background session, detaches and leaves it running |
Context
Section titled “Context”| Command | Action |
|---|---|
/compact [instructions] | Summarize the conversation to free context. Optional instructions focus the summary |
/autocompact [auto|<tokens>] | Set and save the auto-compaction window, or restore the model default |
/context [all] | Colored grid of context usage with optimization suggestions. all expands the per-item breakdown in fullscreen |
/btw [question] | Side question in an ephemeral read-only overlay, no tools, no history pollution. Without a question, shows your most recent side question (v2.1.212+) |
/memory | Edit CLAUDE.md files, toggle auto-memory, browse auto-memory entries |
/add-dir <path> | Add a working directory for file access this session. Most .claude/ config is not discovered from it |
/cd <path> | Move the session to a new working directory without losing the prompt cache (v2.1.169+) |
Model, effort, and permission modes
Section titled “Model, effort, and permission modes”| Command | Action |
|---|---|
/model [model] | Switch model and save it as the default. Left/right arrows adjust effort. Press s on a row for session-only |
/effort [level|auto|status|ultracode [on|off]] | Set effort: low, medium, high, xhigh, max, or auto; status prints it. max is session-only; auto clears the saved model level. ultracode enables dynamic workflows at xhigh for the session, and ultracode on|off needs v2.1.284+ |
/fast [on|off] | Toggle fast mode (same model, faster output, higher price). Available on Fable 5.2 and Opus 5.5, and in research preview on Opus 5 |
/plan [description] | Enter plan mode, optionally with the task to start on |
/goal [condition|clear] | Set a completion condition. Claude works across turns until an evaluator confirms it, with a live overlay showing elapsed time, turns, and tokens (v2.1.139+) |
/advisor [model|off] | Enable the advisor tool: a second model consulted for guidance at key moments. Accepts fable when available, opus, sonnet, or a model ID |
/permissions (/allowed-tools) | Manage allow, ask, and deny rules; working directories; recent auto mode denials |
/fewer-permission-prompts | Bundled skill. Scan transcripts for common read-only Bash and MCP calls, then propose an allowlist for .claude/settings.json. Shipped as /less-permission-prompts in v2.1.111, renamed since |
/sandbox | Toggle sandbox mode on supported platforms |
Parallel and scheduled work
Section titled “Parallel and scheduled work”| Command | Action |
|---|---|
/tasks (/bashes) | View and manage this session’s background work, finished subagents included |
/batch <instruction> | Bundled skill. Decompose a codebase-wide change into 5 to 30 units, then run one background subagent per unit in its own worktree, each opening a PR. Needs a git repository or a WorktreeCreate hook (outside git: v2.1.281+) |
/list-agents (/peers) | List messageable subagents, teammates, and other sessions when cross-session messaging is enabled (v2.1.224+) |
/workflow-authoring | Bundled skill. Load the reference for writing dynamic workflow scripts, where workflows are enabled (v2.1.248+) |
/workflows | Open the workflow progress view to watch, pause, resume, or save runs |
/loop [interval] [prompt] (/proactive) | Bundled skill. Run a prompt repeatedly while the session stays open. No interval means Claude self-paces; no prompt runs the maintenance check or .claude/loop.md |
/schedule [description] (/routines) | Create, update, list, or run cloud scheduled tasks (formerly routines) on Anthropic-managed cloud infrastructure |
/deep-research <question> | Bundled workflow. Fan out web searches, cross-check sources, synthesize a cited report. Manual-only since v2.1.218 |
/autofix-pr [prompt] | Spawn a cloud session that watches the current branch’s PR and pushes fixes when CI fails or reviewers comment. Needs the gh CLI |
/remote-env | Choose the default cloud environment for cloud sessions started from the CLI |
Review and ship
Section titled “Review and ship”| Command | Action |
|---|---|
/diff | Interactive viewer for uncommitted changes and per-turn diffs |
/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [--max-findings n|all|default] [target] | Bundled skill. Review the diff for correctness bugs; since v2.1.328, most models report only bugs and CLAUDE.md violations (use /simplify for cleanups). With no target, most models review the whole branch against the default branch (v2.1.329 changelog). Follows the root REVIEW.md on the default branch (v2.1.333 changelog). --fix applies findings, --comment posts them on the GitHub PR or GitLab merge request (GitLab: v2.1.257+), ultra runs the cloud review. --max-findings caps or lifts the number of findings until you pass default (v2.1.288). Runs as a background subagent since v2.1.218 |
/review [level] [--fix] [--comment] [target] | Alias of /code-review since v2.1.223; accepts the same targets, effort levels, and flags |
/ultrareview [PR or branch] | Deep multi-agent cloud review. Now an alias of /code-review ultra. 3 free runs on Pro, Max, and Ultra, then usage credits |
/security-review | Analyze the branch diff against origin’s default branch for injection, auth, and data-exposure risks. Needs an origin remote |
/ship [level] [pr] [+bot] | Bundled skill (v2.1.330+). Commits and pushes your work where it can, opens a GitHub pull request if needed, reviews it, then watches it in the session and pushes fixes. It can proceed without a confirmation prompt; read what it commits and pushes first. You merge. /ship stop ends the watch. On other code hosts it only watches a branch. Not available in cloud sessions. Where it is available, Claude Code does not load a custom ship skill, including the ship example skill unless you rename it |
/steward [pr] [+bot] | Bundled skill (v2.1.330+). Watches your open pull request in the session and pushes fixes, without the initial review. /steward stop ends the watch |
/simplify [target] | Bundled skill. Four parallel agents review the changed code for reuse, simplification, efficiency, and altitude, then apply fixes. Since v2.1.154 it no longer hunts correctness bugs, that is /code-review |
/verify | Bundled skill, runs only when invoked. Confirm a change works by building the app, running it, and observing the result instead of trusting tests (v2.1.145+) |
/run | Bundled skill. Launch and drive the project’s app to see a change working (v2.1.145+) |
/run-skill-generator | Bundled skill. Write a per-project skill that teaches /run and /verify how to build, launch, and drive your app (v2.1.145+) |
Configuration and extensions
Section titled “Configuration and extensions”| Command | Action |
|---|---|
/output-style [style] | List or select Default, Proactive, Concise, Explanatory, Learning, or a custom style (v2.1.269+) |
/auto-mode-setup | Draft auto-mode environment entries from the project and recent sessions, then review before saving. Needs v2.1.228+ on Pro, Max, or Team, v2.1.283+ on Enterprise or with a Console API key |
/update-config [request] | Bundled skill. Ask Claude to edit the appropriate settings file for a described change |
/import [codex|gemini|cursor] [--dry-run] [--yes] | Import another local agent configuration; use --dry-run to inspect first. Provider and feature-flag restrictions apply |
/artifacts | Browse, attach, or open accessible artifacts where the feature is available (v2.1.208+) |
/artifact-capabilities | Bundled skill. Load the reference for runtime capabilities a published artifact can use, such as calling connectors or offering a file download |
/artifact-diagramming | Bundled skill. Load diagramming guidance for artifacts: when a diagram helps and how to keep inline SVG legible in light and dark themes (v2.1.221+) |
/design [brief] | Bundled skill. Draft editable design artboards as a Claude Design artifact on supported Anthropic sessions (v2.1.265+). Unavailable on Bedrock, Agent Platform, Foundry, and Claude Platform on AWS |
/design consent, /design revoke | Grant Claude access to Claude Design, or withdraw it. Type /design consent yourself when asked |
/slides [brief] | Bundled skill. Make a new presentation as a Claude Slides artifact from your brief (v2.1.265+, where artifacts are available) |
/config [key=value ...] (/settings) | Open the settings interface, or set a key directly: /config theme=dark. /config --help lists every settable key |
/init | Generate a starter CLAUDE.md. Review the generated instructions and test their usefulness before committing; context-file effects vary by configuration. CLAUDE_CODE_NEW_INIT=1 adds an interactive flow covering skills, hooks, personal memory |
/hooks | View hook configurations for tool events |
/mcp [reconnect (<server>|all)|enable|disable [<server>|all]] | Manage MCP connections and OAuth. In -p mode, prints a text status summary |
/plugin [subcommand] | Manage plugins. Subcommands: list, install, enable, disable |
/plugin-authoring | Load the reference Claude uses to write a mod; a skill from a built-in plugin that you can turn off in /plugin (v2.1.287+) |
/reload-plugins [--force] | Reload active plugins without restarting. Skips and warns when the reload would invalidate the prompt cache, unless forced |
/reload-skills | Re-scan skill and command directories so on-disk changes take effect mid-session (v2.1.152+) |
/skills | List skills. Filter by typing, sort by token count with t, cycle visibility with Space |
/agents | Prints a reminder to ask Claude to manage subagents, or edit .claude/agents/ directly. Was an interactive manager before v2.1.198 |
/keybindings | Open ~/.claude/keybindings.json |
/statusline | Configure the status line, or auto-configure it from your shell prompt |
/terminal-setup | Install a Shift+Enter newline binding in VS Code, Cursor, Devin Desktop, Alacritty, or Zed; Option+Enter in Apple Terminal; clipboard access for /copy in iTerm2. Only appears in terminals that need it |
/setup-bedrock | Interactive Amazon Bedrock wizard. Visible only with CLAUDE_CODE_USE_BEDROCK=1 |
/setup-vertex | Interactive Google Cloud Agent Platform wizard. Visible only with CLAUDE_CODE_USE_VERTEX=1 |
/web-setup | Connect your GitHub account to Claude Code on the web using local gh credentials |
/install-github-app | Install the Claude GitHub App for a repo, optionally wiring up GitHub Actions workflows and secrets. github.com repositories only |
/install-slack-app | Install the Claude Slack app through a browser OAuth flow |
/chrome | Configure Claude in Chrome settings |
/claude-in-chrome [task] | Bundled skill. Carry out a task in your browser through Claude in Chrome, such as testing a page or reading console logs. Available when Chrome integration is enabled, for example with claude --chrome |
/design-login | Authorize design-system access for /design-sync with your claude.ai account. The standalone claude.ai/design site closes by December 14, 2026 |
/design-sync [hint] | Bundled skill. Convert the repo’s React design system and upload it to Claude Design so generated designs use your real components. First sync can take hours on a large repo. Anthropic API only. The standalone claude.ai/design site closes by December 14, 2026 |
/claude-api [subcommand] | Bundled skill. API reference and workflows: migrate, upgrade, api-version, managed-agents-onboard, managed-agents-secure, prompt-audit, cost-optimize, build-eval, hillclimb, preserved-thinking-migration |
/dataviz [request] | Bundled skill. Chart and dashboard design guidance with a runnable colorblind and contrast validator (v2.1.198+) |
Interface and display
Section titled “Interface and display”| Command | Action |
|---|---|
/theme | Change the color theme: auto, light, dark, daltonized, ANSI, or custom themes from ~/.claude/themes/ |
/color [color|default] | Set the prompt bar color for the session. No argument picks one at random |
/tui [classic|fullscreen] | Set the terminal renderer and relaunch into it with the conversation intact |
/focus | Toggle focus view: last prompt, a one-line tool-call summary with diffstats, final response. Fullscreen only |
/scroll-speed | Interactive slider for mouse wheel speed, with a scrollable ruler for live preview. Fullscreen only, not in the JetBrains terminal |
/voice [hold|tap|off] | Toggle voice dictation or set its mode. Requires a claude.ai account |
/ide | Manage IDE integrations and show status |
Diagnostics and support
Section titled “Diagnostics and support”| Command | Action |
|---|---|
/doctor [prompt-audit [path]] (/checkup) | Bundled skill. Full setup checkup: install health, PATH, unparseable settings, unused skills and MCP servers versus their context cost, slow hooks, CLAUDE.md bloat, version drift. Reports first, asks before changing anything (v2.1.205+). prompt-audit audits your instructions instead (v2.1.283+) |
/skill-doctor | Report visible skill context cost and never-invoked skills. Excludes bundled and enterprise skills, requires feature-flag fetching, and is unavailable through Remote Control. Run it in the terminal (v2.1.252+) |
/debug [description] | Bundled skill. Turn on debug logging for the session and troubleshoot from the debug log |
/heapdump | Write a heap snapshot and memory breakdown to ~/Desktop for diagnosing high memory use. ⚠️ contains the full conversation and credentials, never share it. Hidden from the command menu, type it in full |
/status | Settings interface on the Status tab: version, model, account, connectivity. Works while Claude is responding |
/usage (/cost, /stats) | Session cost, plan limits, activity stats. On paid plans, breaks usage down by skill, subagent, plugin, and MCP server |
/insights | Report analyzing your sessions: project areas, interaction patterns, friction points. Not available in cloud sessions |
/release-notes | Interactive changelog picker. Since v2.1.208 the notes stay out of the conversation Claude sees |
/help | Show help and available commands |
/bug [report] (/share) | Report a bug or share the conversation, with a consent screen. Falls back to a local archive under ~/.claude/feedback-bundles/ on third-party providers (v2.1.212+) |
/feedback [report] | Send product feedback. Same dialog and sending rules as /bug |
/team-onboarding | Generate a teammate ramp-up guide from 30 days of sessions, commands, and MCP usage |
/powerup | Interactive lessons with animated demos for discovering features |
Account and platform
Section titled “Account and platform”| Command | Action |
|---|---|
/login | Sign in to your Anthropic account |
/logout | Sign out |
/upgrade | Open the plan upgrade page. Hidden on Enterprise |
/rate-limit-options | Show wait-and-continue, usage-credit, and upgrade options when a claude.ai usage limit blocks a request. Requires a claude.ai subscription; the wait rows need v2.1.234+ |
/usage-credits | Configure usage credits, or request them from your admin when you hit a limit. Previously /extra-usage |
/privacy-settings | View and update privacy settings. Pro and Max only |
/passes | Share a free week of Claude Code. Only visible if your account is eligible |
/mobile (/ios, /android) | QR code for the Claude mobile app |
/stickers | Check Claude Code sticker availability |
/radio | Open Claude FM lo-fi radio, or print the stream URL. Not on Bedrock, Agent Platform, Foundry, or Claude Platform on AWS |
MCP servers add their own commands as /mcp__<server>__<prompt>, discovered from connected servers.
Removed, renamed, and commands that never existed
Section titled “Removed, renamed, and commands that never existed”| Command | Status |
|---|---|
/ultraplan | Removed; use /plan instead |
/execute | Not a Claude Code command. Absent from the official commands reference and from the entire CHANGELOG. Earlier versions of this guide listed it by mistake. Exit plan mode by approving the plan or pressing Shift+Tab |
/less-permission-prompts | Renamed /fewer-permission-prompts. The old name is what shipped in v2.1.111 and still appears in that release’s notes |
/extra-usage | Renamed /usage-credits |
/pr-comments | Removed in v2.1.91. Ask Claude to fetch PR comments instead |
/vim | Removed in v2.1.92. Use /config → Editor mode |
Ctrl+D | Not a command, the keyboard shortcut for exiting. See §10.2 |
Quick Actions
Section titled “Quick Actions”| Action | Shortcut |
|---|---|
| Run shell command | !command |
| Reference file | @filename |
| Cancel operation | Ctrl+C |
| Search history | Ctrl+R |
| Dismiss suggestion | Esc |
10.2 Keyboard Shortcuts
Section titled “10.2 Keyboard Shortcuts”Session Control
Section titled “Session Control”| Shortcut | Action |
|---|---|
Enter | Send message |
Shift+Enter | New line in message |
Ctrl+C | Cancel current operation |
Ctrl+D | Exit Claude Code |
Ctrl+R | Search command history |
Ctrl+L | Clear screen (keeps context) |
Ctrl+B | Run command in background |
Esc | Stop Claude mid-action (context preserved) |
Esc×2 (double-tap) | Open rewind menu (same as /rewind) |
Input & Navigation
Section titled “Input & Navigation”| Shortcut | Action |
|---|---|
Ctrl+A | Jump to beginning of line |
Ctrl+E | Jump to end of line |
Ctrl+W | Delete previous word |
Ctrl+U | Delete from the cursor to the line start (kept for pasting) |
Ctrl+Y | Paste the text last deleted with Ctrl+K, Ctrl+U or Ctrl+W |
Alt+B / Alt+F | Move back / forward one word (Option as Meta on macOS) |
Alt+D | Delete to the end of the word |
Ctrl+_ / Ctrl+Shift+- | Undo the last input edit |
Ctrl+Z | Suspend Claude Code to the shell (Unix); fg resumes |
Left / Right arrows | Switch tabs in permission dialogs and menus |
Ctrl+G / Ctrl+X Ctrl+E | Edit the current prompt or dialog response in an external editor |
Tab | Autocomplete file paths |
↑ / ↓ | Navigate command history |
Mode & Model Toggles
Section titled “Mode & Model Toggles”| Shortcut | Action |
|---|---|
Alt+T (Option+T on macOS) | Toggle thinking where supported; no effect on Opus 5.5, Sonnet 5.5, Haiku 5.5 or Fable |
Alt+P (Option+P on macOS) | Open the model picker |
Ctrl+X Ctrl+K | Stop running background subagents |
Ctrl+Enter / Ctrl+X Ctrl+S | Interrupt and send queued messages now |
Ctrl+O | View thinking blocks |
Voice Input
Section titled “Voice Input”| Shortcut | Action |
|---|---|
Space (hold) | Push-to-talk: hold to speak, release to send (default binding) |
Rebinding: The voice:pushToTalk binding is configurable in ~/.claude/keybindings.json (v2.1.71+). Add a custom binding if Space conflicts with your workflow:
{ "voice:pushToTalk": "ctrl+space"}Toggle voice on/off with /voice. The push-to-talk binding only activates when voice mode is active.
Agent Teams Navigation
Section titled “Agent Teams Navigation”| Shortcut | Action |
|---|---|
Shift+Down | Cycle through active teammates (in-process mode) |
Ctrl+T | Toggle task list visibility |
Enter | View selected teammate’s session |
Escape | Interrupt current turn, return to prompt |
Custom Keybindings
Section titled “Custom Keybindings”Run /keybindings to create or open ~/.claude/keybindings.json. Changes apply without a restart. Each block names a context and maps keystrokes to actions; null unbinds a default (official keybindings reference, checked October 27, 2026):
{ "$schema": "https://www.schemastore.org/claude-code-keybindings.json", "bindings": [ { "context": "Chat", "bindings": { "ctrl+e": "chat:externalEditor", "meta+g": "command:compact", "ctrl+s": null } } ]}| Element | Rule |
|---|---|
| Contexts | Global, Chat, Autocomplete, Confirmation, Transcript, HistorySearch, Task, DiffPanel, ModelPicker, EffortSlider, Select, Plugin, Agents, Scroll, and others listed in the reference |
| Actions | namespace:action, for example chat:modelPicker, chat:fastMode, chat:sendNow, chat:queueSubmit, chat:killAgents, app:toggleTodos, history:search, task:background. command:<name> runs /<name> |
| Modifiers | ctrl, shift, alt/opt/meta, cmd/super. cmd only works in terminals that report the Super modifier, so prefer ctrl or meta |
| Chords | Space-separated keystrokes, each within 3 seconds: ctrl+k ctrl+s. Default chords use the ctrl+x prefix; unbind all of them in each defining context to reclaim ctrl+x |
| Reserved | Ctrl+C, Ctrl+D, Ctrl+M (Enter), Ctrl+[ (Escape), Ctrl+I (Tab), Ctrl+H, and Caps Lock cannot be rebound |
| Layouts | Key names are case-insensitive; write Ctrl shortcuts with Latin letters. AZERTY matches the letter the key types |
Invalid entries are skipped with a warning in the debug log, not an error: a misspelled modifier such as ctl+k binds plain k, and a space next to + (ctrl+ k) creates a chord that never fires. Start with claude --debug to see the warnings. Watch for terminal multiplexer conflicts: Ctrl+B (tmux), Ctrl+A (GNU screen), Ctrl+Z (suspend).
Useful Flag Combinations
Section titled “Useful Flag Combinations”| Flags | Purpose | Example |
|---|---|---|
-c -p "msg" | Resume session + single prompt | claude -c -p "run tests" |
-r <id> -p | Resume specific session + prompt | claude -r abc123 -p "check status" |
-p | Non-interactive automation | claude -p "lint fix" < errors.txt |
Note: Combine resume flags with
-pfor scripting and CI/CD workflows.
10.3 Configuration Reference
Section titled “10.3 Configuration Reference”CLAUDE.md Locations
Section titled “CLAUDE.md Locations”| Location | Scope | Committed |
|---|---|---|
~/.claude/CLAUDE.md | All projects (global) | N/A |
/project/CLAUDE.md | This project (shared) | ✅ Yes |
/project/CLAUDE.local.md | This project (local overrides) | ❌ No (.gitignored) |
/project/CLAUDE.local.md | Personal project instructions; add to .gitignore | ❌ No |
| Parent/child directories | Auto-loaded in monorepos | Depends on location |
Settings Files
Section titled “Settings Files”| File | Purpose | Committed |
|---|---|---|
settings.json | Hook configuration | ✅ Yes |
settings.local.json | Permission overrides | ❌ No |
Permission Patterns
Section titled “Permission Patterns”| Pattern | Matches |
|---|---|
Bash(git *) | Any git command |
Bash(npm test) | Exactly npm test |
Edit | All file edits |
Write | All file writes |
WebSearch | Web search |
mcp__serena__* | All Serena tools |
Read(*.env*) | Block reading any .env* file path |
Edit(*.pem) | Block editing .pem certificates |
Bash(rm -rf *) | Block destructive bash commands |
CLI Flags Reference
Section titled “CLI Flags Reference”Complete reference for all Claude Code command-line flags, subcommands, and startup environment variables.
Session & Context
Section titled “Session & Context”| Flag | Short | Description |
|---|---|---|
--continue | -c | Continue the most recent conversation in the current directory |
--resume <ID> | -r | Resume a specific session by UUID or name, or show interactive picker |
--from-pr <NUMBER|URL> | Open the session picker filtered to sessions linked to a pull request. Accepts a PR number or a GitHub, GitLab, or Bitbucket URL | |
--fork-session | Create a new session ID when resuming (use with --resume or --continue) | |
--session-id <UUID> | Use a specific session UUID | |
--no-session-persistence | Disable session persistence (print mode only) | |
--name <NAME> | -n | Set a display name for the session, shown in /resume and the terminal title |
--remote | Deprecated alias for --cloud | |
--cloud | With a task description, create a cloud session. With a session ID or claude.ai/code URL and -p, queue a message into that session | |
--teleport | Resume a web session in your local terminal | |
--bg, --background | Start the session as a background agent and return immediately. Prints session ID and management commands. Combine with --exec or --agent. Cannot be combined with -p | |
--exec <CMD> | Run a shell command as a PTY-backed background job instead of starting a Claude session. Use with --bg |
Model & Configuration
Section titled “Model & Configuration”| Flag | Short | Description |
|---|---|---|
--model <NAME> | Set model with alias (sonnet, opus, haiku, fable) or full model ID. Overrides the model setting | |
--fallback-model <NAME> | Auto-fallback model(s) when the primary is overloaded or unavailable. Comma-separated list, tried in order | |
--effort <LEVEL> | Set effort level: low, medium, high, xhigh, max, ultracode (v2.1.203+). Available levels depend on the model | |
--betas <LIST> | Beta headers to include in API requests (API key users only) |
Output & Format
Section titled “Output & Format”| Flag | Short | Description |
|---|---|---|
--print | -p | Print response and exit without interactive mode (headless/SDK mode) |
--output-format <FORMAT> | Output format: text, json, stream-json | |
--input-format <FORMAT> | Input format: text, stream-json | |
--json-schema <SCHEMA> | Get validated JSON matching schema (print mode only) | |
--include-partial-messages | Include partial streaming events (requires --print and stream-json) | |
--include-hook-events | Include hook lifecycle events in output stream. Requires --output-format stream-json | |
--prompt-suggestions | Emit a predicted next prompt after each turn. Requires --print, --output-format stream-json, --verbose | |
--replay-user-messages | Re-emit user messages from stdin back on stdout for acknowledgment. Requires --input-format stream-json and --output-format stream-json | |
--verbose | Enable verbose logging with full turn-by-turn output |
Permissions & Security
Section titled “Permissions & Security”| Flag | Short | Description |
|---|---|---|
--dangerously-skip-permissions | Skip ALL permission prompts (use with extreme caution) | |
--allow-dangerously-skip-permissions | Add bypassPermissions to the Shift+Tab cycle without starting in it | |
--permission-mode <MODE> | Begin in specified mode: default, plan, acceptEdits, auto, dontAsk, bypassPermissions (manual is an alias for default, v2.1.200+) | |
--allowedTools <TOOLS> | Tools that execute without prompting (permission rule syntax) | |
--disallowedTools <TOOLS> | Deny rules. A bare tool name removes the tool from context; a scoped rule such as Bash(rm *) denies only matching calls | |
--tools <TOOLS> | Restrict which built-in tools Claude can use (use "" to disable all) | |
--permission-prompt-tool <TOOL> | MCP tool to handle permission prompts in non-interactive mode |
System Prompt
Section titled “System Prompt”| Flag | Short | Description |
|---|---|---|
--system-prompt <TEXT> | Replace entire system prompt with custom text | |
--system-prompt-file <PATH> | Load system prompt from file, replacing default | |
--append-system-prompt <TEXT> | Append custom text to default system prompt | |
--append-system-prompt-file <PATH> | Append file contents to default prompt | |
--exclude-dynamic-system-prompt-sections | Move per-user context (such as the auto memory location) into the first user message. Improves prompt-cache reuse across users and machines running the same task. Default system prompt only. Use with -p for scripted multi-user workloads |
Agent & Subagent
Section titled “Agent & Subagent”| Flag | Short | Description |
|---|---|---|
--agent <NAME> | Specify an agent for the current session | |
--agents <JSON> | Define custom subagents dynamically via JSON | |
--advisor <model> | Enable the server-side advisor tool for the session with fable, opus, sonnet or a full model ID; overrides advisorModel | |
--autocompact <auto|tokens> | Set the auto-compact window for this session without changing saved settings, e.g. --autocompact 500k (v2.1.221+) | |
--append-subagent-system-prompt | Append custom text to the end of every subagent’s system prompt, nested subagents included, apart from a forked subagent, which reuses the conversation’s own prompt. | |
--append-subagent-system-prompt-file | Load text from a file and append it to subagent system prompts. | |
--ax-screen-reader | Render screen-reader friendly output: flat text without decorative borders or animations. | |
--desktop | Open the Claude Desktop app on the current directory and exit without starting a session in the terminal. | |
--environment <environment-id> | Create a new cloud session that runs on the self-hosted environment with the given ID. | |
--ref <branch> | With --environment, base the new session’s checkout on a named ref instead of local HEAD | |
--restricted | Start in restricted mode. | |
--safe-mode | Start with all customizations disabled to troubleshoot a broken configuration: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto memory do not load. | |
--system-prompt-snapshot | Pass off to rebuild the system prompt on every request instead of reusing the prompt recorded on the conversation’s first request, for example while you iterate on --append-system-prompt text across --continue runs. | |
--forward-subagent-text | Emit subagent text and thinking blocks in the output stream as assistant and user messages with parent_tool_use_id set, so you can reconstruct each subagent’s transcript. | |
--permission-prompts | Set who answers permission prompts in print mode. | |
--teammate-mode <MODE> | Set agent team display: in-process (default), auto, tmux, iterm2 |
MCP & Plugins
Section titled “MCP & Plugins”| Flag | Short | Description |
|---|---|---|
--mcp-config <PATH|JSON> | Load MCP servers from JSON file or inline JSON string | |
--strict-mcp-config | Only use MCP servers from --mcp-config, ignore all others | |
--plugin-dir <PATH> | Load plugins from a directory or .zip archive for this session only (repeatable). Multiple --plugin-dir flags supported. (.zip since v2.1.128) | |
--plugin-url <url> | Fetch a plugin .zip archive from a URL and load it for the current session. Useful for CI pipelines sharing plugins via artifact storage. (v2.1.129) |
Directory & Workspace
Section titled “Directory & Workspace”| Flag | Short | Description |
|---|---|---|
--add-dir <PATH> | Add additional working directories for Claude to access | |
--worktree | -w | Start Claude in an isolated git worktree at <repo>/.claude/worktrees/<name>. #<number> or a PR/MR URL branches it from that PR/MR |
--tmux | Create a tmux session for the worktree. Requires --worktree. Uses iTerm2 native panes when available. Pass --tmux=classic for traditional tmux |
Budget & Limits
Section titled “Budget & Limits”| Flag | Short | Description |
|---|---|---|
--max-budget-usd <AMOUNT> | Maximum dollar amount for API calls before stopping (print mode only) | |
--max-turns <NUMBER> | Limit number of agentic turns (print mode only) |
Integration
Section titled “Integration”| Flag | Short | Description |
|---|---|---|
--chrome | Enable Chrome browser integration for web automation | |
--no-chrome | Disable Chrome browser integration for this session | |
--ide | Automatically connect to IDE on startup if exactly one valid IDE is available | |
--channels | MCP servers whose channel notifications Claude should listen for (Research Preview). Space-separated plugin:<name>@<marketplace> entries. Needs claude.ai or Console API key auth. Managed orgs require channelsEnabled: true in managed-settings (v2.1.128) | |
--remote-control | --rc | Start an interactive session with Remote Control enabled so you can also control it from claude.ai or the Claude app. Optionally pass a session name |
--remote-control-session-name-prefix <PREFIX> | Prefix for auto-generated Remote Control session names. Defaults to machine hostname |
Initialization & Maintenance
Section titled “Initialization & Maintenance”| Flag | Short | Description |
|---|---|---|
--init | Run Setup hooks with the init matcher before the session (print mode only) | |
--init-only | Run Setup and SessionStart hooks, then exit without starting a conversation | |
--maintenance | Run Setup hooks with the maintenance matcher before the session (print mode only) |
Debug & Diagnostics
Section titled “Debug & Diagnostics”| Flag | Short | Description |
|---|---|---|
--debug <CATEGORIES> | Enable debug mode with optional category filtering (e.g., --debug="api,hooks"; the filter binds only in the = form) | |
--debug-file <PATH> | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over CLAUDE_CODE_DEBUG_LOGS_DIR | |
--dangerously-load-development-channels | Enable channels not on the approved allowlist, for local development. Requires confirmation |
Settings Override
Section titled “Settings Override”| Flag | Short | Description |
|---|---|---|
--bare | Minimal mode: skip auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory, and CLAUDE.md. Scripted calls start faster. Sets CLAUDE_CODE_SIMPLE | |
--settings <PATH|JSON> | Path to settings JSON file or inline JSON string to load | |
--setting-sources <LIST> | Comma-separated sources to load: user, project, local | |
--disable-slash-commands | Disable all skills and slash commands for this session |
Version & Help
Section titled “Version & Help”| Flag | Short | Description |
|---|---|---|
--version | -v | Output the current version number |
--help | -h | Show help information |
Subcommands
Section titled “Subcommands”Top-level commands run as claude <subcommand>:
| Subcommand | Description |
|---|---|
claude "query" | Start REPL with an initial prompt |
claude agents | Open Agent View: lists all sessions (running / waiting / done) with peek and inline reply; --json prints active sessions for scripting (v2.1.139+) |
claude attach <id|name> | Attach to a background session in the current terminal. Partial names need v2.1.290+ |
claude auto-mode defaults | Print the built-in auto mode classifier rules as JSON; --label <prefix> filters rules. Use claude auto-mode config to see effective config with settings applied |
claude auto-mode reset | Restore the default auto mode configuration by removing the autoMode section from your user settings file. |
claude auth login / logout / status | Manage Claude Code authentication |
claude daemon status | Print the background-session supervisor state, version, socket directory, and worker count. Exits 1 if supervisor is not running |
claude daemon stop --any | Stop the background-session supervisor and the sessions it hosts. Pass --keep-workers to leave background sessions running |
claude daemon logs | Follow the background-session supervisor’s log file (~/.claude/daemon.log) until Ctrl+C |
claude daemon run | Run the background-session supervisor in the foreground of this terminal, printing its log |
claude doctor | Print read-only installation and settings diagnostics without starting a session. The in-session /doctor can also apply fixes |
claude gateway | Start the self-hosted Claude apps gateway server, for administrators deploying SSO and policy in front of Claude Code on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. |
claude install [version] | Install or reinstall the native binary. Accepts a version, stable, or latest |
claude import [source] | Start an interactive session that runs /import to bring configuration from other coding agents; accepts --dry-run and --yes. Not on Bedrock, Vertex, Foundry or Claude Platform on AWS, or with feature-flag fetching off. Requires v2.1.213+ |
claude logs <id|name> | Print recent output from a background session. Partial names need v2.1.290+ |
claude purge [path] | Delete all local Claude Code state for a project (transcripts, task lists, debug logs, file-edit history, prompt history, its ~/.claude.json entry). Omit [path] to pick interactively. --dry-run previews, -y/--yes skips confirmation, -i/--interactive confirms each item, --all covers every project. Irreversible |
claude mcp add / remove / list / get / enable | Configure MCP servers |
claude mcp login <name> | Run a configured MCP server’s OAuth flow without opening the interactive /mcp panel. |
claude mcp logout <name> | Clear stored OAuth credentials for an MCP server |
claude self-hosted-runner | Start a runner process that registers this machine or container with a self-hosted environment and hosts Claude Code cloud sessions on your infrastructure. |
claude plugin | Manage Claude Code plugins (alias claude plugins) |
claude remote-control | Start a Remote Control server to control Claude Code from claude.ai or the Claude app |
claude respawn <ID> | Restart a background session (running or stopped) with its conversation intact. Use --all to restart all running sessions |
claude rm <ID> | Remove a background session from the list. The conversation transcript stays on disk for /resume |
claude setup-token | Generate a long-lived OAuth token for CI and scripts. Prints it without saving. Requires a Claude subscription |
claude stop <ID> | Stop a background session (alias: claude kill) |
claude update / claude upgrade | Update to the latest version (claude upgrade is not in the official CLI reference, checked 2026-10-27) |
claude project purge [path] | Not in the official commands reference (checked 2026-10-27); the official command is claude purge above. Earlier guide text: delete all Claude Code state for a project, options --dry-run, -y/--yes, -i/--interactive, --all (v2.1.126) |
claude ultrareview [target] | Run /ultrareview non-interactively from CI/scripts. target: PR number, branch, or current branch if omitted. --json for machine-readable output, --timeout <minutes> to override the 45-minute default, --post to post findings to a github.com PR as one comment (v2.1.227+). Exits 0 on completion, 1 on failure. (v2.1.120) |
claude plugin prune | Remove orphaned auto-installed plugin dependencies. Cascade with claude plugin uninstall --prune. (v2.1.121) |
claude plugin details <name> | Show plugin component inventory (skills, agents, commands, hooks, MCP servers) and projected per-session token cost. (v2.1.139) |
Startup Environment Variables
Section titled “Startup Environment Variables”Set these in your shell before launching Claude Code (these cannot be configured via settings.json):
| Variable | Description |
|---|---|
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 | Enable experimental agent teams |
CLAUDE_CODE_TMPDIR | Override temp directory for internal files |
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 | Enable additional directory CLAUDE.md loading |
DISABLE_AUTOUPDATER=1 | Disable automatic updates |
CLAUDE_CODE_EFFORT_LEVEL | Control thinking depth for extended thinking models |
USE_BUILTIN_RIPGREP=0 | Use system ripgrep instead of built-in (useful on Alpine Linux) |
CLAUDE_CODE_SIMPLE | Enable simple mode (Bash + Edit tools only, no agents/hooks/MCP) |
CLAUDE_BASH_NO_LOGIN=1 | Skip login shell invocation for BashTool |
CLAUDE_CODE_SESSION_ID | Unique identifier for the current Claude Code session. Passed to all Bash tool subprocess environments. Matches session_id in hook stdin JSON. Use for correlating tool output with sessions in observability pipelines. (v2.1.132) |
CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1 | Opt out of the fullscreen alternate-screen renderer. Terminal output stays in the native scrollback buffer instead of the alternate screen. Use in environments that don’t support alternate screen (some log-capture setups, embedded terminals). (v2.1.132) |
CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1 | When set, Homebrew or WinGet auto-upgrades Claude Code in the background and prompts to restart when a new version is available. (v2.1.129) |
For the full environment variable reference (190+ vars across 17 categories, including all ANTHROPIC_*, CLAUDE_CODE_*, DISABLE_*, and OTEL_* vars), see Settings Reference: Environment Variables.
Common Combinations:
# CI/CD mode - non-interactive with auto-acceptclaude -p "fix linting errors" --dangerously-skip-permissions
# JSON output for scriptingclaude -p "analyze code quality" --output-format json
# Economic analysis with Haikuclaude -p "review this file" --model haiku
# Allow access to a directory outside CWDclaude --add-dir ./src/components
# Plan mode for safetyclaude --permission-mode plan
# Multi-directory projectclaude --add-dir ../shared-lib ../utils ../config
# Limit agentic turns in automationclaude -p "refactor this module" --max-turns 10
# Resume specific session non-interactivelyclaude -r abc123 -p "summarize progress"Safety Guidelines:
| Flag | Risk Level | Use When |
|---|---|---|
--dangerously-skip-permissions | High | Only in CI/CD, never on production |
--allowedTools | Safe | Restricting tool access |
--disallowedTools | Safe | Blocking specific tools |
--permission-mode plan | Safe | Read-only exploration |
--debug | Medium | Troubleshooting (verbose logs) |
10.4 Troubleshooting
Section titled “10.4 Troubleshooting”Interactive Troubleshooting: Use the
/diagnosecommand for guided, interactive problem-solving. It auto-scans your environment and provides targeted solutions. See examples/skills/diagnose/SKILL.md.
Quick Diagnostic Guide
Section titled “Quick Diagnostic Guide”Use this symptom-based guide for rapid issue identification and resolution:
| Symptom | Likely Cause | Quick Fix | Prevention |
|---|---|---|---|
| ”Context too long” error | Session accumulated too much context | /compact first, then /clear if needed | Compact regularly at 70% |
| Slow/delayed responses | High context usage (>75%) | Check /context, run /compact | Monitor context with /context |
| ”Rate limit exceeded” | API throttling from frequent requests | Wait 2 minutes, use --model haiku for simple tasks, or use cc-copilot-bridge for flat-rate access | Batch operations, use /compact, consider Copilot Pro |
| Claude forgets instructions | Context overflow, CLAUDE.md lost | Create checkpoint, /clear, reload CLAUDE.md | Keep CLAUDE.md concise (<500 lines) |
| MCP server not connecting | Server crashed or config error | claude mcp list, check paths, restart server | Test servers after config changes |
| Permission prompts every time | Tool not in permissions.allow | Add pattern to permissions.allow in settings.json (or run /permissions) | Use wildcards: Bash(git *) |
| Changes not taking effect | Cached configuration | Restart Claude Code session | Use /exit before config changes |
| Session won’t resume | Corrupted session file | Start fresh with /clear | Exit cleanly with /exit or Ctrl+D |
Quick Diagnosis Flow:
- Check context:
/context→ If >70%, run/compact - Check connectivity: Try simple command → If fails, check network
- Check configuration:
claude mcp list→ Verify MCP servers - Check permissions: Review error message → Add to
permissions.allowif needed - Still failing:
/doctor→ Run diagnostics and verify system health
Common Issues Reference
Section titled “Common Issues Reference”| Symptom | Cause | Solution |
|---|---|---|
| ”Context too long” | Used 100% context | /clear or /compact |
| Slow responses | High context usage | /compact |
| ”Permission denied” | Security settings | Check settings.local.json |
| Hook not running | Registration error | Check settings.json matcher |
| MCP tool not found | Server not running | Check mcp.json config |
| Agent not found | File naming | Check .claude/agents/ |
| Command not found | Path error | Check .claude/skills/<name>/SKILL.md (legacy: .claude/commands/) |
| Unexpected API charges despite active subscription | ANTHROPIC_API_KEY set in shell or .env bypasses subscription | Run echo $ANTHROPIC_API_KEY: if it returns a value, Claude Code is billing at API rates. Unset it from your shell profile to restore subscription billing. Run claude /cost to check spend in the current session. |
Context Recovery
Section titled “Context Recovery”| Context Level | Recommended Action |
|---|---|
| 0-50% | Continue normally |
| 50-75% | Be more specific in queries |
| 75-90% | Use /compact |
| 90%+ | Use /clear |
Common Errors
Section titled “Common Errors”“Tool execution failed”
- Check tool permissions in
settings.local.json - Verify command syntax
- Check for missing dependencies
“Agent not available”
- Verify agent file exists in
.claude/agents/ - Check YAML frontmatter syntax
- Restart Claude Code session
“Hook blocked operation”
- Check hook exit code (2 = blocked)
- Review hook error message
- Adjust hook rules if needed
“Unexpected API charges despite subscription”
- Run
echo $ANTHROPIC_API_KEYin your shell: any output means Claude Code is routing via API billing, not your subscription - Remove the key from
~/.zshrc,~/.bashrc, or.envfiles if subscription billing is intended - Use
claude /cost(or/usagesince v2.1.118) to check real-time spend in the current session - Use
npx ccusageto review cross-session historical spend - See §9.13: The Interactive/Programmatic Billing Split for the announced programmatic credit, paused before it took effect
MCP Server Issues
Section titled “MCP Server Issues”Common MCP Errors and Solutions
Error 1: Tool Name Validation Failed
Section titled “Error 1: Tool Name Validation Failed”API Error 400: "tools.11.custom.name: String should match pattern '^[a-zA-Z0-9_-]{1,64}'"Cause: MCP server name contains invalid characters.
Solution:
- Server names must only contain: letters, numbers, underscores, hyphens
- Maximum 64 characters
- No special characters or spaces
Example:
# ❌ Wrongclaude mcp add my-server@v1 -- npx server
# ✅ Correctclaude mcp add my-server-v1 -- npx serverError 2: MCP Server Not Found
Section titled “Error 2: MCP Server Not Found”MCP server 'my-server' not foundCause: Server not properly registered or wrong scope.
Solution:
- Check scope settings (local/user/project)
Terminal window claude mcp list # Verify server is listed - Ensure you’re in the correct directory for local scope
- Restart Claude Code session
- Re-add server if needed:
Terminal window claude mcp add my-server -s user -- npx @my/server
Error 3: Windows Path Issues
Section titled “Error 3: Windows Path Issues”Error: Cannot find module 'C:UsersusernameDocuments'Cause: Backslashes in Windows paths not properly escaped.
Solution:
# ❌ Wrongclaude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Documents
# ✅ Correct - Use forward slashesclaude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem C:/Users/username/Documents
# ✅ Correct - Escape backslashesclaude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem "C:\\Users\\username\\Documents"MCP Debugging Techniques
Section titled “MCP Debugging Techniques”Enable Debug Mode:
# Debug all MCP connectionsclaude --debug='mcp'
# View MCP status inside Claude Code/mcpView Log Files:
# macOStail -f ~/Library/Logs/Claude/mcp*.log
# Linuxtail -f ~/.local/share/claude/logs/mcp*.log
# Windows (PowerShell)Get-Content "$env:APPDATA\Claude\logs\mcp*.log" -Wait -Tail 50Manual Server Test:
# Test if server works standalonenpx -y @modelcontextprotocol/server-filesystem ~/Documents
# Expected: Server should start and output JSON-RPC messages# If it crashes immediately, check server logsQuick Diagnostic Commands:
# List all configured serversclaude mcp list
# Test specific serverclaude --debug='mcp' -p "List available tools"
# Remove and re-add serverclaude mcp remove my-serverclaude mcp add my-server -s user -- npx @my/serverConnection Failed: Common Causes
| Error | Cause | Solution |
|---|---|---|
ECONNREFUSED | Server not running | Check mcp.json command is correct |
Timeout after 30s | Slow initialization | Increase timeout or check server logs |
Module not found | Missing dependencies | Run npm install in server directory |
Permission denied | File access | Check file permissions on server executable |
ENOENT | Server binary not found | Verify npx/npm is in PATH |
Invalid JSON | Server output malformed | Check server version compatibility |
Serena MCP specific issues:
# Index not foundserena list-memories# If empty, re-index:# In your project, ask Claude: "Index this project with Serena"
# Session not persisting# Check that mcp.json launches the uv-installed Serena (PyPI package serena-agent):{ "mcpServers": { "serena": { "command": "serena", "args": ["start-mcp-server", "--context", "claude-code", "--project-from-cwd"] } }}Context7 MCP issues:
# Documentation not found# Ensure you're searching for official libraries:# ✅ "React useState documentation"# ❌ "my-custom-lib documentation" (not in context7)
# Slow lookups# Context7 fetches from official docs - network dependent# Check your internet connectionSequential Thinking MCP issues:
# "Sequential not responding"# Sequential uses significant compute - expect 10-30s responses# Not an error, just be patient
# Quality seems off# Sequential works best with specific, well-defined problems# ✅ "Debug why user authentication fails on mobile"# ❌ "Make the app better"Permission Issues
Section titled “Permission Issues”Pattern matching problems:
// ❌ Wrong - too specific{ "permissions": { "allow": ["Bash(npm test)"] }}// This ONLY allows exactly "npm test"
// ✅ Right - use wildcards{ "permissions": { "allow": ["Bash(npm *)"] }}// This allows any npm commandCommon permission patterns:
{ "permissions": { "allow": [ "Bash(git *)", // All git commands "Bash(npm *)", // All npm commands "Bash(pytest *)", // All pytest commands "Edit", // All file edits "Write", // All file writes "Read", // All file reads "mcp__serena__*", // All Serena tools "mcp__context7__*", // All Context7 tools "Task" // Allow agent delegation ] }}Timeout Issues
Section titled “Timeout Issues”Claude stops responding mid-task:
Possible causes:
- Network interruption - Check your internet connection
- API rate limit - Wait 1-2 minutes and retry
- Context exhausted - Use
/compactor/clear - Long-running operation - Some MCP operations take 30s+
Workaround for long operations:
# Instead of:"Analyze all 500 files in the codebase"
# Break into chunks:"Analyze files in /src/components/ first""Now analyze /src/utils/""Finally analyze /src/services/"Installation Issues
Section titled “Installation Issues”Windows-specific problems:
# npm global install fails# Run PowerShell as administratornpm install -g @anthropic-ai/claude-code
# PATH not updated# Manually add to PATH:$env:Path += ";$env:APPDATA\npm"
# Permission errors# Check antivirus isn't blocking Node.jsmacOS-specific problems:
# "Command not found" after install# Check shell config loaded:source ~/.zshrc # or ~/.bashrc
# Permission denied on /usr/local# Don't use sudo with npm# Fix permissions:sudo chown -R $(whoami) /usr/local
# curl install blocked# Check firewall/VPN settingsLinux-specific problems:
# npm not found# Install Node.js first:curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -sudo apt-get install -y nodejs
# Global install permission issues# Configure npm to use home directory:mkdir ~/.npm-globalnpm config set prefix '~/.npm-global'echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrcsource ~/.bashrcOne-Shot Health Check Scripts
Section titled “One-Shot Health Check Scripts”Diagnostic scripts for instant troubleshooting. Get them from:
- Windows:
examples/scripts/check-claude.ps1 - macOS/Linux:
examples/scripts/check-claude.sh - Bridge health:
python examples/scripts/bridge.py --health(LM Studio connectivity)
Full Clean Reinstall Procedures
Section titled “Full Clean Reinstall Procedures”⚠️ Nuclear option for corrupted installations. Use when all else fails.
Get the scripts from:
- Windows:
examples/scripts/clean-reinstall-claude.ps1 - macOS/Linux:
examples/scripts/clean-reinstall-claude.sh
When to use clean reinstall:
- Mysterious errors that persist after normal troubleshooting
- Corrupted configuration files
- Breaking changes after Claude Code updates
- Migration to new machine (export/import workflow)
What gets deleted:
- ✓ Claude Code binary and npm packages
- ✓ Downloaded models and cache
- ✓ Local session data
- ⚠️ Config file (optional - backed up by default)
What survives:
- ✓ Project-level
.claude/folders - ✓ Project
CLAUDE.mdfiles - ✓ Custom agents, skills, commands, hooks (in projects)
- ✓ MCP server configurations (in
mcp.json)
10.5 Cheatsheet
Section titled “10.5 Cheatsheet”One-Page Quick Reference
Section titled “One-Page Quick Reference”╔══════════════════════════════════════════════════════════╗║ CLAUDE CODE CHEATSHEET ║╠══════════════════════════════════════════════════════════╣║ ║║ ESSENTIAL COMMANDS ║║ ───────────────── ║║ /help Show commands /clear Fresh start ║║ /context Context usage /compact Save context ║║ /plan Safe mode /rewind Undo changes ║║ /exit Quit Ctrl+C Cancel ║║ ║║ QUICK ACTIONS ║║ ───────────── ║║ !command Run shell @file Reference file ║║ Ctrl+R Search ↑/↓ History ║║ ║║ CONTEXT MANAGEMENT ║║ ────────────────── ║║ 🟢 0-50% Work freely ║║ 🟡 50-75% Be selective ║║ 🔴 75-90% /compact now ║║ ⚫ 90%+ /clear required ║║ ║║ PERMISSION MODES ║║ ──────────────── ║║ Default Ask before changes ║║ Auto-accept Execute without asking ║║ Plan Mode Read-only exploration ║║ ║║ CONFIGURATION ║║ ───────────── ║║ ~/.claude/CLAUDE.md Global settings ║║ /project/CLAUDE.md Project settings ║║ .claude/settings.json Hooks config ║║ .claude/settings.local.json Permission overrides ║║ ║║ .claude/ FOLDER ║║ ─────────────── ║║ agents/ Custom agents commands/ Slash commands ║║ hooks/ Event scripts rules/ Auto-load rules ║║ skills/ Knowledge modules ║║ ║║ THINKING MODE (model-specific effort and defaults) ║║ ───────────────────────────────────────── ║║ Alt+T Toggle on/off Current session ║║ /config Global setting Persists across sessions ║║ ultrathink adds guidance; /effort controls API effort ║║ ║║ MCP SERVERS ║║ ─────────── ║║ Serena Semantic code analysis ║║ Context7 Library documentation ║║ Sequential Structured reasoning ║║ Postgres Database queries ║║ Playwright Browser automation ║║ ║║ HOOKS (events) ║║ ────────────── ║║ PreToolUse Before tool (security) ║║ PostToolUse After tool (format, log) ║║ UserPromptSubmit On message (enrich context) ║║ ║║ WORKFLOW ║║ ──────── ║║ Describe → Analyze → Review → Accept/Reject → Verify ║║ ║║ BEST PRACTICE: Always read the diff before accepting! ║║ ║╚══════════════════════════════════════════════════════════╝10.6 Daily Workflow & Checklists
Section titled “10.6 Daily Workflow & Checklists”Daily Workflow Pattern
Section titled “Daily Workflow Pattern”┌─────────────────────────────────────────────────────────────┐│ DAILY WORKFLOW │├─────────────────────────────────────────────────────────────┤│ ││ MORNING (Setup) ││ ─────────────── ││ □ Git pull latest changes ││ □ Review context with /context ││ □ Load project memory (/sc:load if using Serena) ││ □ Review yesterday's progress ││ ││ WORK SESSION ││ ──────────── ││ □ Define task clearly before starting ││ □ Use TodoWrite for multi-step work ││ □ Commit after each completed task ││ □ /compact when context >70% ││ □ Take breaks every 90 minutes ││ ││ END OF DAY ││ ────────── ││ □ Commit all work in progress ││ □ Save session (/sc:save) ││ □ Note blockers or next steps ││ □ Push to remote ││ │└─────────────────────────────────────────────────────────────┘Prompt Quality Checklist
Section titled “Prompt Quality Checklist”Use this before sending complex requests:
□ WHAT: Clear deliverable described?□ WHERE: File paths/locations specified?□ HOW: Constraints/approach mentioned?□ WHY: Context for decision-making?□ VERIFY: Success criteria defined?Example applying checklist:
❌ Vague: "Add user authentication"
✅ Complete:"Add JWT authentication to the /api/login endpoint.- WHERE: src/api/auth/login.ts- HOW: Use jsonwebtoken library (already in deps), bcrypt for password comparison- CONSTRAINTS: Token expires in 24h, include userId and role- VERIFY: Test with wrong password, expired token, invalid token"Appendix: Templates Collection
Section titled “Appendix: Templates Collection”💡 Production-Ready Examples: For complete, battle-tested templates including advanced commands (
/pr,/release-notes,/sonarqube) and security hooks, see theexamples/directory. The templates below are minimal starting points.
A.1 Agent Template
Section titled “A.1 Agent Template”---name: your-agent-namedescription: Use this agent when [specific trigger]model: sonnettools: Read, Write, Edit, Bash, Grep, Globskills: []---
# Agent name
## Role definitionYou are an expert in [domain].
## Activation triggersUse this agent when:- [Trigger 1]- [Trigger 2]
## Methodology1. [Step 1]2. [Step 2]3. [Step 3]
## Output format[Expected deliverables]
## Examples[Concrete usage examples]A.2 Skill Template
Section titled “A.2 Skill Template”---name: skill-namedescription: Expert guidance for [domain]allowed-tools: Read Grep Bashargument-hint: "[--option] <required_arg>" # if the skill accepts $ARGUMENTS---
# Skill name
## Expertise areas- [Area 1]- [Area 2]
## Methodology1. [Step 1]2. [Step 2]
## Checklists- [ ] [Check 1]- [ ] [Check 2]
## Examples[Good and bad patterns]A.3 Command Template
Section titled “A.3 Command Template”---description: Brief description of what this command doesargument-hint: "<first_arg> [second_arg] [--flag]"---# Command name
## Purpose[What this command does]
## Process1. **Step 1**: [Instructions]2. **Step 2**: [Instructions]
## Arguments- $ARGUMENTS[0] (or $0): First argument - [How to handle]- $ARGUMENTS[1] (or $1): Second argument - [How to handle]
## Output format[Expected output]A.4 Hook Templates
Section titled “A.4 Hook Templates”PreToolUse (Security)
Section titled “PreToolUse (Security)”#!/bin/bashINPUT=$(cat)COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')
# Block dangerous patterns[[ "$COMMAND" =~ "dangerous-pattern" ]] && { echo "BLOCKED" >&2; exit 2; }
exit 0PostToolUse (Formatting)
Section titled “PostToolUse (Formatting)”#!/bin/bashINPUT=$(cat)FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""')
# Auto-format[[ "$FILE_PATH" =~ \.(ts|tsx)$ ]] && npx prettier --write "$FILE_PATH" 2>/dev/null
exit 0UserPromptSubmit (Context)
Section titled “UserPromptSubmit (Context)”#!/bin/bashCONTEXT="[Custom context here]"cat << EOF{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"$CONTEXT"}}EOFexit 0A.5 settings.json Template
Section titled “A.5 settings.json Template”{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [{"type": "command", "command": ".claude/hooks/security.sh", "timeout": 5}] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [{"type": "command", "command": ".claude/hooks/format.sh"}] } ], "UserPromptSubmit": [ { "matcher": "", "hooks": [{"type": "command", "command": ".claude/hooks/context.sh"}] } ] }}A.6 settings.local.json Template
Section titled “A.6 settings.local.json Template”{ "permissions": { "allow": [ "Bash(git *)", "Bash(npm test)", "Bash(pnpm *)", "Edit", "Write" ], "deny": [ "Bash(rm -rf *)", "Bash(sudo *)" ], "ask": [ "Bash(npm publish)", "Bash(git push --force)" ] }}A.7 CLAUDE.md Template
Section titled “A.7 CLAUDE.md Template”# Project name
## Tech stack- [Technology 1]- [Technology 2]
## Code conventions- [Convention 1]- [Convention 2]
## Architecture- [Pattern 1]- [Pattern 2]
## Commands- `npm run dev` - Start development- `npm test` - Run tests