Skip to content
Back to search

claude-code-guide

SkillWorks with Claude CodeGitHub

Claude Code Guide - Setup, Commands, workflows, agents, skills & tips-n-tricks from beginner to power user!

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/zebbern/claude-code-guide with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/zebbern/claude-code-guide'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/zebbern--claude-code-guide/badge.svg)](/listings/zebbern--claude-code-guide)

HTML

<a href="/listings/zebbern--claude-code-guide"><img src="/api/listings/zebbern--claude-code-guide/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

> **For a remote HTTP server, add the URL and complete OAuth separately:**

claude mcp add --transport http -s user sentry https://mcp.sentry.dev/mcp
claude mcp login sentry

# Verify connection and tool discovery
claude mcp list

For a local stdio server, put its executable and arguments after `--` so Claude Code flags cannot consume server flags. Replace the paths with a server you have reviewed and installed:

claude mcp add -s local local-tools -- /absolute/path/to/mcp-server --workspace "$PWD"

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 3,073 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. <h2 id="claude-code-community-guide">Claude Code Guide</h2>
  3. _For reference and contributions, visit the [official Claude Code documentation](https://code.claude.com/docs/en/overview)_
  4. _Commands and provider model mappings change quickly; the linked official references remain authoritative._
  5. ![Claude Code](https://img.shields.io/npm/v/@anthropic-ai/claude-code?label=Claude%20Code&logo=anthropic)
  6. [![Status](https://img.shields.io/badge/Status-Active-brightgreen)](https://github.com/anthropics/claude-code)
  7. [![License](https://img.shields.io/badge/License-MIT-blue)](LICENSE)
  8. </div>
  9. <div align="center">
  10. <kbd>
  11. | Section | Status | Other Resources |
  12. | ------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------- |
  13. | Getting Started | ✅ | **Claude-Code** [Docs](https://code.claude.com/docs/en/overview) |
  14. | Configuration & Environment Variables | ✅ | **Claude-Code via** [**Discord**](https://github.com/zebbern/claude-code-discord) |
  15. | Commands & Usage | ✅ | 70+ [Skills](https://github.com/zebbern/claude-code-guide/tree/main/skills) & [Agent pack](https://github.com/zebbern/claude-code-guide/tree/main/agents) |
  16. | Interface & Input | ✅ | Goal Creator [SKILL.md](https://github.com/zebbern/skills) |
  17. | Advanced Features | ✅ | 1,900+ Agent [Skills](https://github.com/zebbern/antigravity-awesome-skills) |
  18. | Automation & Integration | ✅ | No cost ai [resources](https://github.com/zebbern/no-cost-ai) |
  19. | Help & Troubleshooting | ✅ | 240+ Mermaid [templates](https://github.com/zebbern/mermaid-templates) |
  20. | Third-Party Integrations | ✅ | Discord Communication [MCP](https://github.com/zebbern/discord-mcp-agent) |
  21. </kbd>
  22. </div>
  23. ---
  24. <h3 id="content">Contents</h3>
  25. **Fast paths:** [Install](#quick-start) · [Commands](#claude-commands) · [Config](#configuration--environment) · [MCP](#mcp-integration) · [Agents](#sub-agents) · [Troubleshoot](#help--troubleshooting)
  26. | Area | Start here | Also useful |
  27. | --- | --- | --- |
  28. | [Getting Started](#getting-started) | [Quick Start](#quick-start) | [Initial Setup](#initial-setup), [System Requirements](#system-requirements) |
  29. | [Configuration](#configuration--environment) | [Environment Variables](#environment-variables) | [Configuration Files](#configuration-files) |
  30. | [Commands](#commands--usage) | [Slash Commands](#claude-commands) | [Command Line Flags](#command-line-flags), [CLI Quick Reference](#cheat-sheet) |
  31. | [Interface](#interface--input) | [Keyboard Shortcuts](#keyboard-shortcuts) | [Vim Mode](#vim-mode) |
  32. | [Advanced Features](#advanced-features) | [Plan Mode](#plan-mode), [Auto Mode](#auto-mode), [MCP](#mcp-integration) | [Sub Agents](#sub-agents), [Skills](#skills), [Hooks](#hooks-system) |
  33. | [Security](#security--permissions) | [Security & Permissions](#security--permissions) | [Dangerous Mode](#dangerous-mode), [Best Practices](#security-best-practices-main) |
  34. | [Automation](#automation--integration) | [Automation & Scripting](#automation--scripting-with-claude-code) | [PR Review](#auto-pr-review-inline-comments), [Issue Triage](#issue-triage-suggest-labels--severity) |
  35. | [Help](#help--troubleshooting) | [Troubleshooting](#help--troubleshooting) | [Best Practices](#best-practices), [Monitoring](#monitoring--alerting) |
  36. | [Third-Party Integrations](#third-party-integrations) | [DeepSeek Integration](#deepseek-integration) | [Provider Setup Examples](#provider-setup-examples), [Cloud Providers and Gateways](#cloud-providers-and-gateways) |
  37. <details>
  38. <summary>Full content map</summary>
  39. - **[Getting Started](#getting-started)**
  40. - [Quick Start](#quick-start)
  41. - [System Requirements](#system-requirements)
  42. - [Initial Setup](#initial-setup)
  43. - **[Configuration & Environment](#configuration--environment)**
  44. - [Environment Variables](#environment-variables)
  45. - [Global Config Options](#global-config-options)
  46. - [Configuration Files](#configuration-files)
  47. - **[Commands & Usage](#commands--usage)**
  48. - [Slash Command Reference](#claude-commands)
  49. - [Command Line Flags](#command-line-flags)
  50. - [CLI Quick Reference](#cheat-sheet)
  51. - **[Interface & Input](#interface--input)**
  52. - [Keyboard Shortcuts](#keyboard-shortcuts)
  53. - [Vim Mode](#vim-mode)
  54. - [Command History](#command-history)
  55. - **[Advanced Features](#advanced-features)**
  56. - [Thinking Mode](#thinking-keywords)
  57. - [Effort Levels](#effort-levels)
  58. - [Advisor Tool](#advisor-tool)
  59. - [Fast Mode](#fast-mode)
  60. - [Auto Mode](#auto-mode)
  61. - [Plan Mode](#plan-mode)
  62. - [Background Tasks](#background-tasks)
  63. - [Workflows & Scheduling](#workflows--scheduling)
  64. - [Cloud Sessions](#remote-sessions)
  65. - [Claude in Chrome](#claude-in-chrome)
  66. - [Desktop and IDEs](#desktop-and-ides)
  67. - [Sandbox Mode](#sandbox-mode)
  68. - [LSP Tool](#lsp-tool)
  69. - [Sub Agents](#sub-agents)
  70. - [Agent Teams](#agent-teams)
  71. - [Skills](#skills)
  72. - [Plugin System](#plugin-system)
  73. - [Worktree Isolation](#worktree-isolation)
  74. - [Native Installer](#native-installer)
  75. - [Authentication CLI](#claude-auth)
  76. - [Agent Management CLI](#claude-agents-cli)
  77. - [Remote Control](#remote-control)
  78. - [Managed Settings](#managed-settings)
  79. - [Model Updates](#model-updates)
  80. - [Theming & Customization](#theming--customization)
  81. - [Code Review](#code-review)
  82. - [Insights](#insights)
  83. - [Artifacts](#artifacts)
  84. - [MCP Integration](#mcp-integration)
  85. - [Hooks System](#hooks-system)
  86. - **[Security & Permissions](#security--permissions)**
  87. - [Dangerous Mode](#dangerous-mode)
  88. - [Security Best Practices](#security-best-practices-main)
  89. - **[Automation & Integration](#automation--integration)**
  90. - [Automation & Scripting](#automation--scripting-with-claude-code)
  91. - [Auto PR Review](#auto-pr-review-inline-comments)
  92. - [Security Review on Every PR](#security-review-on-every-pr)
  93. - [Issue Triage](#issue-triage-suggest-labels--severity)
  94. - **[Help & Troubleshooting](#help--troubleshooting)**
  95. - [Debug Quick Commands](#debug-quick-commands)
  96. - [Path Temp Fix](#linuxpath)
  97. - [Windows Path Perm Fix](#windowspath)
  98. - [Installation Issues](#installation--nodejs-issues)
  99. - [Authentication Issues](#authentication-issues)
  100. - [Permission Issues](#permission--allowed-tools-issues)
  101. - [MCP Issues](#mcp-model-context-protocol-issues)
  102. - [Repair or Reinstall](#full-clean-reinstall-windows--powershell)
  103. - [One-Shot Health Check](#one-shot-health-check-copypaste)
  104. - [Useful Paths](#appendix-useful-paths)
  105. - [Best Practices](#best-practices)
  106. - [Effective Prompting](#effective-prompting)
  107. - [Performance Tips](#performance-tips)
  108. - [Monitoring & Alerting](#monitoring--alerting)
  109. - [Collaboration Best Practices](#collaboration-best-practices)
  110. - [Common Pitfalls to Avoid](#common-pitfalls-to-avoid)
  111. - **[Third-Party Integrations](#third-party-integrations)**
  112. - [Provider Setup Examples](#provider-setup-examples)
  113. - [Cloud Providers and Gateways](#cloud-providers-and-gateways)
  114. - [DeepSeek Integration](#deepseek-integration)
  115. </details>
  116. ---
  117. <h1 id="getting-started">Getting Started</h1>
  118. **Enable completion alerts:** Ghostty, Kitty, and iTerm2 (once its alert settings are on) show desktop notifications by default. Elsewhere, choose **Terminal bell** under `/config` → **Local notifications**, or set `"preferredNotifChannel": "terminal_bell"` in `~/.claude/settings.json`.
  119. <h2 id="quick-start">Quick Start</h2>
  120. > [!TIP]
  121. > **Run <mark>claude</mark> in a project directory to start the interface.**
  122. >
  123. > **Go to [Help & Troubleshooting](#help--troubleshooting) to fix issues...**
  124. **Native installer (recommended; no Node.js required)**
  125. macOS, Linux, or WSL:
  126. ```bash
  127. curl -fsSL https://claude.ai/install.sh | bash
  128. ```
  129. Windows PowerShell:
  130. ```powershell
  131. irm https://claude.ai/install.ps1 | iex
  132. ```
  133. Windows CMD:
  134. ```bat
  135. curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
  136. ```
  137. Supported package managers (manual updates by default):
  138. ```bash
  139. brew install --cask claude-code # stable channel; claude-code@latest tracks latest
  140. winget install Anthropic.ClaudeCode
  141. ```
  142. npm distribution (supported; Node.js 22+ is required to install):
  143. ```bash
  144. npm install -g @anthropic-ai/claude-code
  145. ```
  146. > [!Warning]
  147. > npm 12 skips Claude Code's postinstall step by default, leaving a placeholder `claude` that prints `Error: claude native binary not installed.` (on Windows, the shell can't run it at all). Use the native installer, or allow the step as shown in [Installation / Node.js Issues](#installation--nodejs-issues). The binary ships as an optional dependency, so don't use `--omit=optional` or `optional=false` in `.npmrc`.
  148. Verify the installation, then start Claude Code:
  149. ```bash
  150. claude --version
  151. claude doctor
  152. claude
  153. ```
  154. Native installs update themselves. Homebrew, WinGet, and the signed `apt`, `dnf`, and `apk` repositories follow their package manager's update flow; set `CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1` to let Claude Code run the Homebrew or WinGet upgrade itself. See the [official setup guide](https://code.claude.com/docs/en/setup) for channels, version pinning, Linux repository setup, and signature verification. For an npm install, upgrade with `npm install -g @anthropic-ai/claude-code@latest`; do not use `sudo npm install -g`.
  155. ---
  156. > [!Tip]
  157. > <ins>**Open Project Via Terminal Into VS Code / Cursor**</ins>
  158. >
  159. > ### $ - <kbd>cd /path/to/project</kbd>
  160. >
  161. > ### $ - <kbd>code .</kbd>
  162. >
  163. > **Make sure you have the <mark>(Claude Code extension)</mark> installed in your VS Code / Cursor**
  164. ---
  165. <h2 id="system-requirements">System Requirements</h2>
  166. > - OS: macOS 13+, Windows 10 1809+/Windows Server 2019+, Ubuntu 20.04+, Debian 10+, or Alpine Linux 3.19+. Native Windows, WSL 1, and WSL 2 are supported.
  167. > - Hardware: 4 GB+ RAM and an x64 or ARM64 processor
  168. > - Shell: Bash, Zsh, PowerShell, or CMD
  169. > - Software: Git is optional on native Windows; without Git for Windows, Claude uses the PowerShell tool instead of Bash, and the Monitor tool is unavailable. Node.js 22+ is required only to install through npm; the installed CLI is a native binary.
  170. > - Alpine/musl: run `apk add bash curl libgcc libstdc++ ripgrep` (ripgrep is in the community repository), then set `"USE_BUILTIN_RIPGREP": "0"` under `env` in `settings.json`.
  171. > - Internet: Connection for API calls from an [Anthropic supported region](https://www.anthropic.com/legal/supported-regions)
  172. ---
  173. <h2 id="initial-setup">Initial Setup</h2>
  174. Claude Code requires a Pro, Max, Team, Enterprise, or Console account, or access through Amazon Bedrock, Google Cloud's Agent Platform (Vertex AI), or Microsoft Foundry; the free Claude.ai plan does not include Claude Code. The normal first-party flow is browser sign-in:
  175. ```bash
  176. claude auth login # Claude subscription
  177. claude auth login --console # Anthropic Console/API billing
  178. claude auth status # Verify the active login
  179. ```
  180. At the `/login` prompt, Console users can pick **Sign in with your Console account** to skip creating an API key; Bedrock and Agent Platform users can pick **3rd-party platform** (or run `/setup-bedrock` / `/setup-vertex`) for a setup wizard.
  181. For API automation or a provider/gateway deployment, inject credentials from an OS key store or secret manager instead of committing them:
  182. ```bash
  183. export ANTHROPIC_API_KEY="$SECRET_FROM_YOUR_STORE" # bash/zsh: current process only
  184. ```
  185. ```powershell
  186. $env:ANTHROPIC_API_KEY = $secretFromYourStore # PowerShell: current process only
  187. ```
  188. To run CI or scripts on a Pro, Max, Team, or Enterprise subscription, run `claude setup-token` once and store the one-year token it prints (it is not saved) as `CLAUDE_CODE_OAUTH_TOKEN`. It only makes model requests (no Remote Control or claude.ai connectors), and `--bare` ignores it; see [Authentication CLI](#claude-auth).
  189. > [!Important]
  190. > `ANTHROPIC_AUTH_TOKEN`, an approved `ANTHROPIC_API_KEY`, `apiKeyHelper`, and `CLAUDE_CODE_OAUTH_TOKEN` take precedence over your `/login` sign-in. Interactive sessions ask once before using `ANTHROPIC_API_KEY` (change the answer with **Use custom API key** in `/config`); `-p` always uses it. While an API key, auth token, or credential helper is in use, subscription-only features such as Remote Control, `/schedule`, claude.ai MCP connectors, and notification preferences remain unavailable. [Authentication Issues](#authentication-issues) lists the full precedence order; run `/status` to see which credential is active. Do not commit credentials; use your platform's secret storage.
  191. ---
  192. <h1 id="configuration--environment">Configuration & Environment</h1>
  193. <h2 id="environment-variables">Environment Variables</h2>
  194. > **Environment values can also be stored as strings under the `env` key in a `settings.json` file. The [official environment-variable reference](https://code.claude.com/docs/en/env-vars) is the exhaustive source.**
  195. > [!Important]
  196. > **On PowerShell, use `$env:NAME = "value"` for the current process. Persist secrets through an OS key store or secret manager, not a checked-in settings file.**
  197. ```bash
  198. # Authentication and routing: set only when API/provider billing is intentional
  199. export ANTHROPIC_API_KEY="$SECRET_FROM_YOUR_STORE"
  200. export ANTHROPIC_AUTH_TOKEN="$TOKEN_FROM_YOUR_STORE"
  201. export ANTHROPIC_BASE_URL="https://gateway.example.com"
  202. export ANTHROPIC_CUSTOM_HEADERS="X-Trace-Id: 12345"
  203. # Model selection and provider alias overrides
  204. export ANTHROPIC_MODEL="sonnet" # Wins over the model setting and a saved /model choice
  205. # export ANTHROPIC_DEFAULT_MODEL="sonnet" # Alternative: starting model only; any model setting or saved /model choice wins
  206. export ANTHROPIC_DEFAULT_FABLE_MODEL="<provider-fable-model-id>"
  207. export ANTHROPIC_DEFAULT_OPUS_MODEL="<provider-opus-model-id>"
  208. export ANTHROPIC_DEFAULT_SONNET_MODEL="<provider-sonnet-model-id>"
  209. export ANTHROPIC_DEFAULT_HAIKU_MODEL="<provider-haiku-model-id>"
  210. # Third-party provider selection (enable one deployment path; only Bedrock and Mantle combine)
  211. # export CLAUDE_CODE_USE_BEDROCK=1
  212. # export ANTHROPIC_BEDROCK_REGION_PREFIX=eu # Prefer eu/us/apac/jp/au/global cross-region inference on Bedrock
  213. # export CLAUDE_CODE_USE_MANTLE=1 # Amazon Bedrock Mantle endpoint; may be combined with CLAUDE_CODE_USE_BEDROCK
  214. # export CLAUDE_CODE_USE_ANTHROPIC_AWS=1 # Claude Platform on AWS; also set ANTHROPIC_AWS_WORKSPACE_ID and AWS_REGION
  215. # export CLAUDE_CODE_USE_VERTEX=1 # Google Cloud's Agent Platform (formerly Vertex AI)
  216. # export CLAUDE_CODE_USE_FOUNDRY=1
  217. # export CLAUDE_CODE_MODEL_CATALOG=off # Cloud providers: don't fetch signed model settings from downloads.claude.ai
  218. # export CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT=0 # Full system prompt on any model, including custom deployment names/ARNs
  219. # Timeouts, retries, and output budgets, in milliseconds/tokens
  220. export API_TIMEOUT_MS=1200000
  221. export BASH_DEFAULT_TIMEOUT_MS=120000
  222. export BASH_MAX_TIMEOUT_MS=600000
  223. export MCP_TIMEOUT=30000
  224. export MCP_TOOL_TIMEOUT=600000 # Overall MCP tool limit (default ~28h); above 60000 it also raises remote servers' 60 s per-request limit
  225. export MAX_MCP_OUTPUT_TOKENS=25000
  226. export MAX_THINKING_TOKENS=0 # 0 disables thinking on the Anthropic API, except Opus/Sonnet/Haiku 5.5 and Fable; adaptive models ignore a positive budget (use effort)
  227. # export CLAUDE_CODE_RETRY_WATCHDOG=1 # Unattended runs (CI, workers): keep retrying 429/529 capacity errors
  228. # export CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS=1800000 # Cap each request's 429/529 wait under the watchdog
  229. # Session, context, agents, and accessibility
  230. # export CLAUDE_CODE_SIMPLE=1
  231. # export CLAUDE_CODE_SAFE_MODE=1
  232. export CLAUDE_CODE_DISABLE_1M_CONTEXT=1 # Clamp native-1M models to 200K via autocompaction; warns if the clamp is not enforced
  233. export CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1 # Opt out of enforcing the assumed context window for unknown model IDs
  234. export CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS=20
  235. export CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=3
  236. export CLAUDE_CODE_FORWARD_SUBAGENT_TEXT=1
  237. export CLAUDE_AX_SCREEN_READER=1
  238. # Feature and administration controls
  239. export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
  240. export CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1
  241. export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1
  242. export CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1
  243. export ENABLE_CLAUDEAI_MCP_SERVERS=false
  244. # Network routing
  245. export HTTP_PROXY="http://proxy.example.com:8080"
  246. export HTTPS_PROXY="http://proxy.example.com:8080"
  247. export NO_PROXY="localhost,127.0.0.1"
  248. export NODE_EXTRA_CA_CERTS="/path/to/corporate-ca.pem" # Only if a TLS-inspecting proxy's CA isn't in the OS trust store (or npm installs on Node < 22.15)
  249. # Privacy/network reduction: these are presence-based; unset them to turn them off
  250. export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
  251. export DISABLE_TELEMETRY=1
  252. export DISABLE_ERROR_REPORTING=1
  253. ```
  254. The block is a catalog, not a recommended profile—do not enable mutually exclusive provider variables together. Boolean variables usually accept `1`/`true` and `0`/`false`, but the three presence-based variables shown at the end treat any non-empty value, including `0`, as enabled. `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` and `DISABLE_TELEMETRY` also stop [feature-flag fetching](https://code.claude.com/docs/en/env-vars#features-that-need-feature-flag-fetching), which disables `/import`, the advisor tool, claude.ai skill and plugin sync, and idle compaction; the first also turns off Remote Control, auto-updates, and `/feedback`.
  255. An `env` value in `settings.json` replaces the shell's value; set it to `""` to cancel a stale shell export (removing the key takes effect at the next launch). Most values from `.claude/settings.json` and `.claude/settings.local.json` apply only after you trust the workspace, and those files cannot set variables a repository shouldn't control, such as `CLAUDE_CONFIG_DIR`, `TMPDIR`, OpenTelemetry exporter variables, or `CLAUDE_AX_SCREEN_READER`; put those in your shell, user, or managed settings (`claude --debug` logs any it drops). Sessions launched by the Claude Desktop app keep the app's launch value for variables it sets.
  256. <h2 id="global-config-options">Global Config Options</h2>
  257. Use `/config` for interactive settings, or pass one or more `key=value` pairs. Run `/config --help` for the keys supported by your installed build.
  258. ```bash
  259. /config # Open the settings UI
  260. /config theme=dark model=sonnet # Update supported keys directly
  261. ```
  262. For version-controlled or managed configuration, edit JSON settings files directly:
  263. | Scope | File |
  264. | :---- | :--- |
  265. | User | `~/.claude/settings.json` |
  266. | Project (shared) | `.claude/settings.json` |
  267. | Project (private) | `.claude/settings.local.json` |
  268. | Managed | macOS: `/Library/Application Support/ClaudeCode/`<br />Linux/WSL: `/etc/claude-code/`<br />Windows: `C:\Program Files\ClaudeCode\` |
  269. ```json
  270. {
  271. "model": "sonnet",
  272. "theme": "dark",
  273. "autoUpdatesChannel": "stable",
  274. "permissions": {
  275. "defaultMode": "default"
  276. }
  277. }
  278. ```
  279. Settings-file precedence is **managed policy → `--settings` → local → project → user**. Other flags and environment variables are not levels in this stack; each key decides whether they win (`--model` and `ANTHROPIC_MODEL` beat any `model` setting, even a managed one, which is only a starting default). List keys such as `permissions.allow` merge across files, so read [settings precedence](https://code.claude.com/docs/en/settings#settings-precedence) before relying on last-writer-wins behavior; [All settings](https://code.claude.com/docs/en/settings-reference) lists every key. With no permission mode configured, interactive sessions start in auto mode; `permissions.defaultMode` overrides that, but `auto` and `bypassPermissions` apply only from user or managed settings (or `--settings` / `--permission-mode`). `~/.claude.json` stores global state, session/trust data, and local/user MCP configuration; it is not the user settings file.
  280. To hide all commit and PR attribution, set `"attribution": false`. Versions before v2.1.281 skip a settings file that contains it, so in files they also read use `"attribution": { "commit": "", "pr": "", "sessionUrl": false }`.
  281. <h2 id="configuration-files">Configuration Files</h2>
  282. Claude Code combines human-authored instructions from several locations:
  283. | Memory Type | Location | Purpose | Use Case Examples | Shared With |
  284. | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |
  285. | **Enterprise policy** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />Linux: `/etc/claude-code/CLAUDE.md`<br />Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |
  286. | **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |
  287. | **User memory** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |
  288. | **Project memory (local)** | `./CLAUDE.local.md` | Personal project preferences (add to `.gitignore`) | Your sandbox URLs, preferred test data, personal overrides | Just you (current project) |
  289. | **Project rules** | `.claude/rules/**/*.md` | Modular project rules (loaded alongside CLAUDE.md) | Linting rules, API conventions, path-scoped standards | Team members via source control |
  290. | **User rules** | `~/.claude/rules/**/*.md` | Personal rules, loaded before project rules | Preferred tools, personal workflow conventions | Just you (all projects) |
  291. > Instruction files are concatenated rather than overriding one another. User and ancestor-project files load at startup; `CLAUDE.md` files in subdirectories load lazily when Claude works there. In monorepos, skip other teams' or unrelated ancestor files with the `claudeMdExcludes` setting (glob patterns; a managed `CLAUDE.md` can't be excluded). `CLAUDE.md` is context, not an enforcement boundary. Run `/doctor prompt-audit` for a report of outdated, broken, or conflicting instructions; it edits nothing until you approve.
  292. Use `@path` to import another file. When no `CLAUDE.md`, `.claude/CLAUDE.md`, or `CLAUDE.local.md` exists in the working directory or above it, Claude Code reads `AGENTS.md` instead; user and managed `CLAUDE.md` files and `.claude/rules/` still load. If any of those project files exists (even just `CLAUDE.local.md`), `AGENTS.md` is skipped: import it with `@AGENTS.md`, or set **Project instructions** to `claude-md-and-agents-md` in `/config` to load both.
  293. #### `.claude/rules/` Directory
  294. The `.claude/rules/` directory lets you break project instructions into separate Markdown files instead of one large `CLAUDE.md`. Markdown files are discovered recursively. Add `paths` frontmatter with glob patterns when a rule should load only for matching files. This is useful for:
  295. - **Modular organization**: Separate concerns (e.g., `api-conventions.md`, `testing-rules.md`)
  296. - **Per-directory scoping**: `paths`-scoped rules and rules in a subdirectory's `.claude/rules/` load on demand when Claude reads, writes, or edits files they cover, adding to other rules rather than overriding them
  297. - **Team collaboration**: Different team members can own different rule files via PR review
  298. #### Auto-Memory
  299. Claude can save useful working context under `~/.claude/projects/<project>/memory/`. It loads the first 200 lines or 25 KB of `MEMORY.md`; use `/memory` to inspect, edit, disable, or remove saved memories. Auto-memory is machine-local and shared across worktrees for the same repository. Turn it off for one project with `"autoMemoryEnabled": false` in that project's settings, or everywhere with `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`; `autoMemoryDirectory` moves where it is stored.
  300. Auto-memory is most useful for context you would otherwise repeat across sessions:
  301. - Preferred build, test, and lint commands
  302. - Local conventions that are not obvious from code alone
  303. - Architecture decisions that influence future edits
  304. - Team preferences that should shape how Claude proposes changes
  305. Keep durable team rules in `CLAUDE.md` or `.claude/rules/`. Treat auto-memory as helpful working context, not as the only source of truth.
  306. ---
  307. <h1 id="commands--usage">Commands & Usage</h1>
  308. <h2 id="claude-commands">Slash Command Reference</h2>
  309. Type `/` to see what your installed build, plan, platform, plugins, MCP servers, and skills actually provide. The table below is a high-value snapshot; use the [official command reference](https://code.claude.com/docs/en/commands) for the live list.
  310. | Command | Purpose |
  311. | :------ | :------ |
  312. | `/add-dir <path>` | Grant this session access to another working directory |
  313. | `/advisor [model\|off]` | Configure the experimental second-model advisor, save the selection, or turn it off |
  314. | `/agents` | Explain how to create or edit subagents; hidden from the `/` menu, and the old interactive wizard was removed in v2.1.198 |
  315. | `/artifacts` | List artifacts you own or that are shared with you; attach one to the session, open it, or copy its link |
  316. | `/auto-mode-setup` | Draft `autoMode.environment` entries from your project and recent sessions, then review and save them to user settings |
  317. | `/autocompact [auto\|tokens]` | Set the auto-compact window per model (e.g. `/autocompact 200k` if your gateway stops at 200K); `auto` restores the default |
  318. | `/background [prompt]` | Detach the current conversation as a background session (`/bg` alias) |
  319. | `/batch <instruction>` | Decompose a large change into worktree-isolated background units (bundled skill) |
  320. | `/branch [name]` | Switch into a new branch of the current conversation while preserving the original |
  321. | `/btw [question]` | Ask an ephemeral side question without adding it to conversation history |
  322. | `/cd <path>` | Move the current session to another working directory; its project settings, hooks, skills, agents, and `.mcp.json` servers (after approval) apply immediately |
  323. | `/clear [name]` | Start a new conversation with empty context while preserving project memory |
  324. | `/code-review [level] [--fix] [--comment] [--max-findings n\|all\|default] [target]` | Run a local background review, or use level `ultra` for cloud review; levels run from `low` through `max`. `--comment` posts to a GitHub PR or GitLab MR; a `--max-findings` choice sticks until you pass `default` |
  325. | `/compact [instructions]` | Summarize the conversation to free context |
  326. | `/config [key=value ...]` | Open settings or update supported keys directly (`/settings` alias) |
  327. | `/context [all]` | Visualize what is using the context window |
  328. | `/copy [N]` | Copy the last (or Nth-latest) response; a picker selects single code blocks, and `w` writes to a file instead (useful over SSH) |
  329. | `/diff` | Open the interactive current/per-turn diff viewer; in fullscreen mode, toggle a panel of uncommitted changes beside the conversation |
  330. | `/doctor [prompt-audit [path]]` | Diagnose setup, configuration, hooks, memory, plugins, and MCP; can offer fixes (`/checkup` alias). `prompt-audit` checks CLAUDE.md, skills, agents, and commands for stale paths and prompting patterns written for older models |
  331. | `/effort [level\|auto\|status\|ultracode [on\|off]]` | Set model-dependent effort (`low` to `xhigh` save per model; `max`, or `s` in the picker, is session-only). `status` prints the level; `ultracode [on\|off]` toggles ultracode at any effort level |
  332. | `/fast [on\|off]` | Toggle fast mode where the selected Opus model and plan support it |
  333. | `/focus` | Toggle focus view (fullscreen rendering only): your last prompt, a one-line tool summary, and the final response |
  334. | `/fork [prompt]` | Copy this conversation into a worktree-isolated background session and keep working here |
  335. | `/goal [condition\|clear]` | Keep working across turns until a completion condition is met |
  336. | `/hooks` | Inspect configured hooks in the read-only hook browser |
  337. | `/import [codex\|gemini\|cursor] [--dry-run] [--yes]` | Bring instruction files, MCP servers, commands, subagents, and skills over from OpenAI Codex, Gemini CLI, or Cursor; `--dry-run` previews and `--yes` skips the picker |
  338. | `/init` | Generate a starter `CLAUDE.md` for the project |
  339. | `/keybindings` | Open `~/.claude/keybindings.json` to customize shortcuts (see [Keyboard Shortcuts](#keyboard-shortcuts)) |
  340. | `/loop [interval] [prompt]` | Run a prompt repeatedly while the session remains open |
  341. | `/mcp [reconnect\|enable\|disable] [server\|all]` | Inspect, authenticate, enable, disable, or reconnect MCP servers; `/mcp reconnect all` retries every server that failed or needs authentication |
  342. | `/memory` | Manage `CLAUDE.md`, rules, and auto-memory |
  343. | `/model [model]` | Switch model and normally save it as the default; press `s` in the picker for session-only selection |
  344. | `/output-style [style]` | List output styles or switch to one, such as `/output-style concise` |
  345. | `/permissions` | Manage allow, ask, and deny rules (`/allowed-tools` alias) |
  346. | `/plan [description]` | Enter plan mode, optionally with a task |
  347. | `/plugin [subcommand]` | Discover, install, enable, disable, and manage plugins |
  348. | `/reload-plugins [--force]` | Apply plugin changes without restarting when safe |
  349. | `/remote-control [name]` | Expose this local session to claude.ai/code or the Claude mobile app |
  350. | `/resume [session]` | Resume by ID/name or open the session picker |
  351. | `/review ...` | Alias for `/code-review` as of v2.1.223 |
  352. | `/rewind` | Restore or summarize code and conversation from a checkpoint; Bash edits such as `sed -i` are not checkpointed unless Claude already edited that file with its file tools (`/undo` alias) |
  353. | `/sandbox` | View and configure OS-level filesystem/network sandboxing for Bash, PowerShell, and Monitor commands on supported platforms |
  354. | `/schedule [description]` | Create, update, list, or run cloud scheduled tasks, formerly routines (`/routines` alias) |
  355. | `/security-review` | Review the current branch diff for security vulnerabilities |
  356. | `/simplify` | Review changed code for reuse, quality, and efficiency improvements |
  357. | `/skill-doctor` | Show what each skill costs in context and how often it is used, so you can turn off unused ones |
  358. | `/skills` | List skills; press `t` to sort by token cost and `Space`/`Enter` to change a skill's visibility |
  359. | `/status` | Show version, model, account, and connectivity on the Settings Status tab; works while Claude is responding |
  360. | `/statusline [description]` | Configure the status line from a description, or from your shell prompt when run without arguments |
  361. | `/subtask [prompt]` | Run the former in-session fork behavior as a subagent that reports back here |
  362. | `/tasks` | List the current session's background shells, subagents, and tool calls |
  363. | `/teleport [session]` | Pull a cloud session's branch and conversation into this terminal (`/tp` alias) |
  364. | `/tui [default\|fullscreen]` | Switch the terminal renderer and relaunch with the conversation intact; with no argument, print the active renderer |
  365. | `/usage` | Show session cost and prompt-cache hits, plan usage limits, and activity stats, with one-line fixes for warnings (`/cost`, `/stats` aliases) |
  366. | `/usage-credits` | Configure usage credits, or on Team/Enterprise request them from your admin, when you hit a limit (formerly `/extra-usage`) |
  367. | `/verify` | Build, run, and observe your app to confirm a change works beyond tests and type checks (bundled skill; Claude runs it only when you invoke it) |
  368. | `/voice [hold\|tap\|off]` | Toggle voice dictation or choose its mode; needs a Claude.ai login |
  369. | `/workflows` | Inspect dynamic workflow runs and background orchestration |
  370. <h2 id="command-line-flags">Command Line Flags</h2>
  371. | Flag / Command | Description | Example |
  372. | :--------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------- |
  373. | `-d, --debug` | Enable debug mode (shows detailed debug output). | `claude -d -p "query"` |
  374. | `--include-partial-messages` | Include partial streaming events; requires print mode and `stream-json`. | `claude -p --output-format stream-json --verbose --include-partial-messages "query"` |
  375. | `--include-hook-events` | Include hook lifecycle events in `stream-json` output. | `claude -p --output-format stream-json --verbose --include-hook-events "query"` |
  376. | `--forward-subagent-text` | Forward subagent text/thinking with `parent_tool_use_id` in `stream-json`. | `claude -p --output-format stream-json --verbose --forward-subagent-text "query"` |
  377. | `--verbose` | Override verbose mode setting from config (shows expanded logging / turn-by-turn output). | `claude --verbose` |
  378. | `-p, --print` | Print response and exit (useful for piping output). | `claude -p "query"` |
  379. | `--output-format <format>` | Output format (only works with `--print`): `text` (default), `json` (single result), or `stream-json` (realtime streaming; requires `--verbose`). | `claude -p "query" --output-format json` |
  380. | `--input-format <format>` | Input format (only works with `--print`): `text` (default) or `stream-json` (realtime streaming input). | `claude -p --verbose --output-format stream-json --input-format stream-json` |
  381. | `--replay-user-messages` | Re-emit user messages from stdin back to stdout for acknowledgment — **only works with** print mode plus `stream-json` input and output. | `claude -p --verbose --input-format stream-json --output-format stream-json --replay-user-messages` |
  382. | `--allowedTools`, `--allowed-tools <tools...>` | Comma/space-separated permission rules to allow. | `claude --allowed-tools "Bash(git *)" "Edit"` |
  383. | `--disallowedTools`, `--disallowed-tools <tools...>` | Comma/space-separated permission rules to deny. | `claude --disallowed-tools "Edit"` |
  384. | `--mcp-config <configs...>` | Load MCP servers from JSON files or strings (space-separated). | `claude --mcp-config ./mcp-servers.json` |
  385. | `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring other MCP configurations; exits at startup if a `managed-mcp.json` is deployed. | `claude --mcp-config ./a.json --strict-mcp-config` |
  386. | `--append-system-prompt <prompt>` | Append a system prompt to the default system prompt (useful in print mode). | `claude -p --append-system-prompt "Do X then Y"` |
  387. | `--autocompact <auto\|tokens>` | Override the auto-compaction window for this session. | `claude --autocompact 500k` |
  388. | `--ax-screen-reader` | Use a flat, screen-reader-friendly renderer without decorative borders or animations. | `claude --ax-screen-reader` |
  389. | `--bare` | Minimal scripted mode: skip discovered hooks, skills, plugins, MCP, auto-memory, and `CLAUDE.md`. | `claude --bare -p "query"` |
  390. | `--permission-mode <mode>` | Start in `default`/`manual`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, or `plan`. | `claude --permission-mode plan` |
  391. | `--permission-prompt-tool <tool>` | Specify an MCP tool to handle permission prompts in non-interactive mode; pass the full `mcp__<server>__<tool>` name of a tool on an MCP server the run loads. | `claude -p --mcp-config ./mcp.json --permission-prompt-tool mcp__permissions__approve "query"` |
  392. | `--permission-prompts <host\|none>` | Print mode: `host` (default) sends prompts to the SDK host or `--permission-prompt-tool`; `none` denies anything that would prompt, while the permission mode decides the rest. | `claude -p --permission-mode auto --permission-prompts none "query"` |
  393. | `--fallback-model <models>` | Comma-separated fallback chain for when the primary model is overloaded or unavailable (interactive or print mode); the primary is retried each turn. Overrides `fallbackModel`. | `claude --fallback-model sonnet,haiku` |
  394. | `--effort <level>` | Set effort to `low`, `medium`, `high`, `xhigh`, or `max`; `ultracode` starts at `xhigh` with ultracode turned on. | `claude --effort high` |
  395. | `--model <model>` | Model for the current session. Accepts aliases like `sonnet`/`opus` or a full model ID when pinning. | `claude --model sonnet` |
  396. | `--advisor <model>` | Set the experimental advisor for this session without changing `advisorModel`; intentionally omitted from `claude --help`. | `claude --advisor opus` |
  397. | `--settings <file-or-json>` | Load additional settings from a JSON file or a JSON string. | `claude --settings ./settings.json` |
  398. | `--add-dir <directories...>` | Additional directories to allow tool access to. Most network paths (UNC shares, `/net` automounts) are refused; on Windows, use a mapped drive letter. | `claude --add-dir ../apps ../lib` |
  399. | `--ide` | Automatically connect to an IDE on startup if exactly one valid IDE is available. | `claude --ide` |
  400. | `-c, --continue` | Continue the most recent conversation in the current directory. | `claude --continue` |
  401. | `-r, --resume [id\|name]` | Resume by session ID, name, or `.jsonl` transcript path, or open the picker; resuming a still-running background session attaches to it. | `claude -r auth-refactor` |
  402. | `--session-id <uuid>` | Use a specific session ID for the conversation (must be a valid UUID). | `claude --session-id 123e4567-e89b-12d3-a456-426614174000` |
  403. | `--agents <json\|file>` | Define custom subagents dynamically via inline JSON or, with `-p`, a path to a JSON file (see subagent docs for format). | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"..."}}'` |
  404. | `--agent <name>` | Specify a specific agent for the current session. | `claude --agent my-custom-agent` |
  405. | `--bg` | Start or continue work as a background session that can be viewed from `claude agents`. | `claude --bg "fix failing tests"` |
  406. | `--bg --exec <command>` | Run a shell command as an attachable background session. | `claude --bg --exec "npm test"` |
  407. | `-n, --name <name>` | Set a display name for any session (prompt box, `/resume` picker, terminal title); resume it later with `claude --resume <name>`. | `claude -n auth-refactor` |
  408. | `--chrome` | Enable Chrome browser integration for web automation and testing. | `claude --chrome` |
  409. | `--no-chrome` | Disable Chrome browser integration for this session. | `claude --no-chrome` |
  410. | `--cloud [description\|session\|url]` | Create a cloud session on claude.ai; with `-p` and a session ID or URL, queue a message into an existing one. | `claude --cloud "Fix the login bug"` |
  411. | `--remote` | Deprecated alias for `--cloud`. | `claude --remote "Fix the login bug"` |
  412. | `--remote-control`, `--rc` | Start an interactive local session that can also be controlled from claude.ai or the Claude app. | `claude --remote-control "My Project"` |
  413. | `--teleport [session]` | Pull a cloud session into your local terminal; with no ID it opens a picker. | `claude --teleport <session-id>` |
  414. | `--fork-session` | When resuming, create a new session ID instead of reusing the original. | `claude --resume abc123 --fork-session` |
  415. | `--json-schema <schema>` | Get validated JSON output matching a JSON Schema after agent completes (print mode only). | `claude -p --json-schema '{"type":"object",...}' "query"` |
  416. | `--max-budget-usd <amount>` | Maximum dollar amount to spend on API calls before stopping (print mode only). | `claude -p --max-budget-usd 5.00 "query"` |
  417. | `--max-turns <n>` | Limit the number of agentic turns (print mode only). Exits with error when limit reached. | `claude -p --max-turns 3 "query"` |
  418. | `--betas <headers>` | Beta headers to include in API requests (API key users only). | `claude --betas interleaved-thinking` |
  419. | `--tools <tools>` | Restrict which built-in tools Claude can use. Use "" to disable all, "default" for all, or specific tool names. | `claude --tools "Bash,Edit,Read"` |
  420. | `--system-prompt <prompt>` | Replace the entire system prompt with custom text (works in interactive and print modes). | `claude --system-prompt "You are a Python expert"` |
  421. | `--system-prompt-file <file>` | Load a system prompt from a file, replacing the default in interactive or print mode. | `claude --system-prompt-file ./custom-prompt.txt` |
  422. | `--append-system-prompt-file <file>` | Load additional system-prompt text from a file in interactive or print mode; can be combined with `--append-system-prompt` (the file's text comes first). | `claude --append-system-prompt-file ./extra-rules.txt` |
  423. | `--system-prompt-snapshot <on\|off>` | `on` (default) reuses the prompt recorded on the first request, even after `--resume`/`--continue`, until compaction; `off` rebuilds it each request (for iterating on prompt flags). | `claude -c --append-system-prompt "Draft rules" --system-prompt-snapshot off` |
  424. | `--plugin-dir <path>` | Load a plugin directory, a `.zip`, or a folder of plugins (each child with a manifest loads) for this session only (repeatable). | `claude --plugin-dir ./my-plugin --plugin-dir ./other.zip` |
  425. | `--plugin-url <url>` | Fetch a plugin `.zip` URL for this session only (repeatable). | `claude --plugin-url https://example.com/plugin.zip` |
  426. | `--setting-sources <sources>` | Comma-separated list of setting sources to load (user, project, local). | `claude --setting-sources user,project` |
  427. | `--no-session-persistence` | Disable session persistence so sessions are not saved to disk (print mode only). | `claude -p --no-session-persistence "query"` |
  428. | `--disable-slash-commands` | Disable all skills and slash commands for this session. | `claude --disable-slash-commands` |
  429. | `--dangerously-skip-permissions` | Skip normal permission prompts, subject to non-bypassable safety checks and managed policy. | `claude --dangerously-skip-permissions` |
  430. | `--allow-dangerously-skip-permissions` | Add bypass mode to the `Shift+Tab` cycle without starting in it. | `claude --permission-mode plan --allow-dangerously-skip-permissions` |
  431. | `--safe-mode` | Disable customizations (CLAUDE.md, skills, plugins and installed mods, hooks, MCP servers, and more) for troubleshooting; authentication, models, built-in tools, permissions, and managed policy still apply. | `claude --safe-mode` |
  432. | `--restricted` | Locked-down session (also `CLAUDE_CODE_RESTRICTED=1`): removes built-in tools that run commands or code, and WebFetch, unless named in `--tools`; confines file tools to the working directories; ignores user/project/local settings; refuses `bypassPermissions`. | `claude --restricted -p "query"` |
  433. | `--worktree [name]`, `-w [name]` | Start in `<repo>/.claude/worktrees/<name>`; omit the name to generate one, or pass `#<number>` or a GitHub PR / GitLab MR URL to branch from it. Add `--tmux` for a tmux session. | `claude -w feature-auth` |
  434. | `--from-pr [value]` | Filter/resume sessions by PR number or GitHub/GitLab/Bitbucket PR/MR URL, or open the picker. | `claude --from-pr 123` |
  435. | `--init` | Run Setup hooks with the `init` matcher before a print-mode session. | `claude -p --init "query"` |
  436. | `--init-only` | Run Setup and `SessionStart` hooks, then exit without starting a conversation. | `claude --init-only` |
  437. | `--maintenance` | Run Setup hooks with the `maintenance` matcher before a print-mode session. | `claude -p --maintenance "query"` |
  438. | `-v, --version` | Show the installed `claude` CLI version. | `claude --version` |
  439. | `-h, --help` | Display help / usage. | `claude --help` |
  440. > This table highlights common and recently changed options; `claude --help` and the [live CLI reference](https://code.claude.com/docs/en/cli-reference) are authoritative. `--output-format json` is useful for one-shot automation; use `stream-json` for event-level integrations.
  441. For programmatic integrations, the former **Claude Code SDK** is now the [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview): TypeScript uses `@anthropic-ai/claude-agent-sdk`, and Python uses `claude-agent-sdk` / `claude_agent_sdk`. Use `claude -p` for headless CLI calls; `--bare` removes discovered customization and keychain/OAuth access for low-overhead API/provider automation.
  442. <h2 id="cheat-sheet">CLI Quick Reference & Configuration Examples</h2>
  443. ```md
  444. ## Claude Cheat Sheet
  445. # Start and resume
  446. claude # Start interactive REPL
  447. claude "explain this project" # Start REPL seeded with a prompt
  448. claude -p "summarize README.md" # Non-interactive headless print mode
  449. cat logs.txt | claude -p "explain" # Pipe input to Claude and exit
  450. claude -c # Continue most recent conversation
  451. claude -r "<session-id>" "finish this" # Resume by ID or name
  452. claude --model sonnet # Pick the Sonnet alias for this run
  453. claude --model opus # Pick the Opus alias for harder tasks
  454. # Install, update, and auth
  455. claude update # Manually update Claude Code
  456. claude doctor # Diagnose install/version & setup
  457. claude install stable # Install/reinstall the native binary on the stable channel
  458. claude auth login # Log in to your Anthropic account
  459. claude auth status # Check authentication status
  460. claude auth logout # Log out
  461. claude setup-token # Generate a long-lived OAuth token for CI and scripts (subscription)
  462. # Background, cloud, and Remote Control sessions
  463. claude agents # Open the live session dashboard: running, blocked, completed
  464. claude agents --json # Scriptable JSON list of live/background sessions
  465. claude --bg "run the integration suite and summarize failures" # Start a background session
  466. claude --bg --exec "npm test" # Run a shell command as an attachable background session
  467. claude attach <id|name> # Attach to a background session (part of its name works)
  468. claude logs <id|name> # Print recent background-session output
  469. claude stop <id> # Stop a background session
  470. claude rm <id> # Remove it from agent view and delete its worktree; transcript remains resumable
  471. claude remote-control # Serve local sessions to web/mobile while this process stays alive
  472. claude --cloud "Fix the bug" # Start a cloud session on claude.ai
  473. claude --teleport <session-id> # Pull a cloud session into this terminal
  474. # Config essentials
  475. /config # Interactive settings
  476. /config model=sonnet # Set a supported key directly
  477. /config theme=dark
  478. /config --help # Show settable keys and values
  479. # For shared or managed settings, edit the appropriate settings.json file.
  480. # MCP essentials
  481. claude mcp list # List configured MCP servers
  482. claude mcp get <name> # Show details for a server
  483. claude mcp add <name> -- <command> [args...] # Add local stdio server; `--` separates Claude's options from the server's
  484. claude mcp add --transport http <name> <url> # Add remote HTTP server
  485. claude mcp login <name> # Complete OAuth without opening /mcp
  486. claude mcp logout <name> # Clear saved OAuth credentials
  487. claude mcp reset-project-choices # Reset approvals for project .mcp.json servers
  488. claude mcp serve # Run Claude Code itself as an MCP stdio server
  489. # High-value flags
  490. claude --add-dir ../apps ../lib # Add additional working directories
  491. claude --allowed-tools "Bash(git log *)" "Read" # Allow listed tools without permission prompts
  492. claude --disallowed-tools "Edit" # Deny listed tools
  493. claude -p "query" --output-format json # Structured one-shot output
  494. claude --verbose # Verbose logging (turn-by-turn)
  495. claude --dangerously-skip-permissions # Skip permission prompts (use with caution)
  496. claude --permission-mode plan # Start in plan mode without source edits
  497. claude --effort high # Set reasoning effort for this session
  498. claude --bare -p "query" # Fast scripted call without discovered customization
  499. claude --safe-mode # Troubleshoot with user/project customization disabled
  500. claude --ax-screen-reader # Use the accessible flat-text renderer
  501. claude --max-turns 3 -p "query" # Limit agentic turns (print mode only)
  502. claude --json-schema '{"type":"object"}' -p "query" # Get validated JSON output
  503. claude --chrome # Enable Chrome browser integration
  504. claude --agent code-reviewer # Run this session with a named agent
  505. claude ultrareview 123 --trust-workspace --json # Non-interactive cloud review of PR 123; in scripts/CI, --trust-workspace trusts an untrusted folder for this run
  506. # Slash shortcuts
  507. claude --fork-session -r abc123 # Fork instead of reusing original
  508. claude -w feature-auth "implement feature" # Start in an isolated git worktree
  509. /rename auth-refactor # Name current session
  510. /resume # Open session picker
  511. /export output.md # Export conversation to file
  512. /branch experiment-name # Branch the current conversation
  513. /fork "investigate the flaky test" # Copy conversation into a background session
  514. /subtask "trace the regression" # Fork a subagent that reports back here
  515. /cd ../other-project # Move the current session to another directory, keeping the conversation
  516. /review high --fix # Run /code-review via its current alias
  517. /goal "all tests pass and README is updated" # Keep working until the completion condition is met
  518. /loop 30m "check deploy health and summarize anomalies" # Schedule recurring work
  519. /workflows # View dynamic workflows and background orchestration
  520. # Settings precedence: managed policy > CLI/--settings > local > project > user.
  521. ```
  522. ---
  523. <h1 id="interface--input">Interface & Input</h1>
  524. <h2 id="keyboard-shortcuts">Keyboard Shortcuts</h2>
  525. | Shortcut | Description | Context |
  526. | :--------------------------- | :--------------------------------- | :--------------------------------------- |
  527. | `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation; when idle, clears the prompt (`Up` restores it), and a second press exits |
  528. | `Ctrl+D` | Exit Claude Code session | Press twice on an empty prompt; with text, deletes the next character |
  529. | `Ctrl+G` | Open in default text editor | Edit your prompt or custom response |
  530. | `Ctrl+L` | Redraw the screen | Keeps your input and conversation; `/clear` starts a new conversation |
  531. | `Ctrl+O` | Toggle transcript viewer | Shows detailed tool usage, timestamps, and model |
  532. | `Ctrl+R` | Reverse search command history | Search through previous commands |
  533. | `Ctrl+V` (`Cmd+V` in iTerm2); `Alt+V` on Windows/WSL | Paste image from clipboard | Inserts an image chip at the cursor |
  534. | `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents |
  535. | `Ctrl+X`, then `Ctrl+K` | Stop all background agents | Press the chord twice within 3 seconds to confirm |
  536. | `Ctrl+T` | Toggle task checklist | Stays empty on models newer than Opus 4.7/Sonnet 4.6/Haiku 4.5 unless `CLAUDE_CODE_ENABLE_TODO_TOOLS=1`; `/tasks` is the background-work view |
  537. | `Ctrl+S` | Stash or restore the current prompt | Preserves text, cursor, and pasted content |
  538. | `Ctrl+Enter` or `Ctrl+X Ctrl+S` | Send queued messages now | Sends queued messages and your draft now; running shells and subagents move to the background, otherwise the turn is interrupted; use `Ctrl+X Ctrl+S` if `Ctrl+Enter` arrives as Enter |
  539. | `Ctrl+Z` | Suspend Claude Code | Unix only; `fg` resumes (undo is `Ctrl+_`) |
  540. | `Up/Down arrows` | Navigate command history | Recall previous inputs |
  541. | `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in dialogs |
  542. | `←` on an empty prompt | Open agent view | Backgrounds the session and opens `claude agents`; detaches an attached session |
  543. | `Esc` | Interrupt Claude, or close a dialog | Stops the current response or tool call, keeping work so far; declines a permission prompt |
  544. | `Esc` + `Esc` | Clear the draft, or rewind | With text, clears it (`Up` recalls it); on an empty prompt, opens the rewind menu to restore or summarize code and conversation |
  545. | `Shift+Tab` (or `Alt+M`) | Cycle enabled permission modes | Includes Manual, Accept Edits, Plan, and enabled Auto/Bypass modes; `Alt+M` is a Windows fallback |
  546. | `Option+P` (macOS) / `Alt+P` | Switch model | Switch models without clearing prompt |
  547. | `Option+T` (macOS) / `Alt+T` | Toggle extended thinking | No effect on Opus 5.5, Sonnet 5.5, Haiku 5.5, or Fable models, which always think; works on macOS without Option as Meta |
  548. | `Option+O` (macOS) / `Alt+O` | Toggle fast mode | Enable/disable supported fast mode |
  549. > [!Tip]
  550. > **Custom shortcuts:** run `/keybindings` to open `~/.claude/keybindings.json`, whose `bindings` array holds blocks like `{ "context": "Chat", "bindings": { "ctrl+e": "chat:externalEditor", "ctrl+s": null } }` (`null` unbinds). Changes apply without a restart; `Ctrl+C`/`Ctrl+D` are reserved and vim keys can't be remapped.
  551. > [!Note]
  552. > **Fullscreen rendering** (flicker-free, with mouse support) is the default for most new installs. Switch with `/tui fullscreen` or `/tui default` (`/tui` alone shows the active renderer), or set `CLAUDE_CODE_NO_FLICKER=1`/`0` per launch. In its transcript viewer, `?` lists the extra keys.
  553. <h3 id="text-editing">Text Editing</h3>
  554. | Shortcut | Description | Context |
  555. | :--------------------- | :--------------------------- | :------------------------------------ |
  556. | `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |
  557. | `Ctrl+U` | Delete to start of line | Stores deleted text; repeat to clear across lines in multiline input |
  558. | `Ctrl+W` | Delete back to whitespace | Removes a whole path or `--flag=value` in one press |
  559. | `Ctrl+Y` | Paste deleted text | Pastes text last deleted with Ctrl+K/U/W or Alt+D |
  560. | `Alt+Y` (after Ctrl+Y) | Cycle paste history | Cycle through previously deleted text |
  561. | `Alt+B` | Move cursor back one word | Requires Option as Meta on macOS |
  562. | `Alt+F` | Move cursor forward one word | Stops at word end (`_`, `.`, `/` separate words); requires Option as Meta on macOS |
  563. | `Alt+D` | Delete to end of word | Stores deleted text; requires Option as Meta on macOS |
  564. | `Ctrl+_` | Undo last input edit | Also `Ctrl+Shift+-` |
  565. <h3 id="multiline-input">Multiline Input</h3>
  566. | Method | Shortcut | Context |
  567. | :--------------- | :------------- | :-------------------------------- |
  568. | Quick escape | `\` + `Enter` | Works in all terminals |
  569. | Option key | `Option+Enter` | macOS, after enabling Option as Meta (see tip below) |
  570. | Shift+Enter | `Shift+Enter` | Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, and Windows Terminal; see tip below for others |
  571. | Control sequence | `Ctrl+J` | Line feed character for multiline |
  572. | Paste mode | Paste directly | For code blocks, logs |
  573. > [!Tip]
  574. > Run `/terminal-setup` once for Shift+Enter in VS Code, Cursor, Zed, and Alacritty before 0.16 (foot, Alacritty 0.16+, and other kitty-protocol terminals work natively); gnome-terminal and JetBrains terminals have none, so use `Ctrl+J`. In tmux, add `set -s extended-keys on` and `set -as terminal-features 'xterm*:extkeys'` to `~/.tmux.conf`. `Option+` shortcuts on macOS need Option as Meta (Terminal.app: Settings → Profiles → Keyboard; iTerm2: Option keys to "Esc+"; VS Code: `"terminal.integrated.macOptionIsMeta": true`).
  575. <h3 id="quick-commands">Quick Commands</h3>
  576. | Shortcut | Description | Notes |
  577. | :----------- | :---------------- | :------------------------------------ |
  578. | `/` at start | Command or skill | See built-in commands and skills |
  579. | `!` at start | Shell mode | Runs the command and Claude responds to its output; `"respondToBashCommands": false` only adds it to context |
  580. | `@` | File or session mention | Autocompletes file paths; after a letter, also suggests your other live sessions for Claude to message |
  581. | `?` on empty input | Shortcut help | Toggles the shortcut help panel |
  582. > [!Tip]
  583. > **PDF Page Ranges:** For PDFs over 10 pages, the Read tool takes one page or range per call in its `pages` parameter (e.g., `pages: "1-5"`, up to 20 pages; comma lists like `"6,9,15"` error). Page reads need `pdftoppm` (`brew install poppler` / `apt-get install poppler-utils`). Large PDFs (>10 pages) return a lightweight reference when @-mentioned instead of being inlined.
  584. > [!Tip]
  585. > **Voice and spelling:** `/voice` turns on dictation (hold `Space` to record, or `/voice tap` to tap to start and again to send); it needs a Claude.ai login and a local mic, so not API-key/Bedrock/Agent Platform/Foundry auth, SSH, or cloud sessions. `"spellcheck": { "enabled": true }` in `~/.claude/settings.json` underlines misspellings (needs `aspell`, `hunspell`, or `ispell`).
  586. <h2 id="vim-mode">Vim Mode</h2>
  587. > [!Note]
  588. > Enable vim-style editing from `/config` -> Editor mode, or set `"editorMode": "vim"` in `~/.claude/settings.json`. Add `"vimInsertModeRemaps": { "jj": "<Esc>" }` to make a two-key INSERT sequence act as Escape (ignored in project settings).
  589. <h3 id="vim-mode-switching">Vim Mode Switching</h3>
  590. | Command | Action | From mode |
  591. | :------ | :-------------------------- | :-------- |
  592. | `Esc` or `Ctrl+[` | Enter NORMAL mode | INSERT, VISUAL |
  593. | `i` | Insert before cursor | NORMAL |
  594. | `I` | Insert at beginning of line | NORMAL |
  595. | `a` | Insert after cursor | NORMAL |
  596. | `A` | Insert at end of line | NORMAL |
  597. | `o` | Open line below | NORMAL |
  598. | `O` | Open line above | NORMAL |
  599. | `v` / `V` | Visual selection (character / line); `d`, `y`, `c`, `p`, `>`/`<`, `~`/`u`/`U`, `J` act on it | NORMAL |
  600. <h3 id="vim-navigation">Vim Navigation</h3>
  601. | Command | Action |
  602. | :-------------- | :------------------------ |
  603. | `h`/`j`/`k`/`l` | Move left/down/up/right |
  604. | `w` | Next word |
  605. | `e` | End of word |
  606. | `b` | Previous word |
  607. | `0` | Beginning of line |
  608. | `$` | End of line |
  609. | `^` | First non-blank character |
  610. | `gg` | Beginning of input |
  611. | `G` | Beginning of last line |
  612. | `f`/`F`/`t`/`T` + char | Jump to, or just before/after, a character on the line; `;` / `,` repeat / reverse |
  613. | `%` | Matching `()`, `[]`, or `{}` bracket (also with `d`/`c`/`y`) |
  614. | `/` | Reverse history search (same as `Ctrl+R`) |
  615. <h3 id="vim-editing">Vim Editing</h3>
  616. | Command | Action |
  617. | :------------- | :---------------------- |
  618. | `x` | Delete character |
  619. | `dd` | Delete line |
  620. | `D` | Delete to end of line |
  621. | `dw`/`de`/`db` | Delete word/to end/back |
  622. | `cc` | Change line |
  623. | `C` | Change to end of line |
  624. | `cw`/`ce`/`cb` | Change word/to end/back |
  625. | `r{char}`, `s`/`S` | Replace character; substitute character/line |
  626. | `yy`/`Y`, `yw`/`ye`/`yb` | Yank line, word/to end/back |
  627. | `p` / `P` | Paste after / before cursor |
  628. | `>>` / `<<`, `J` | Indent / dedent line; join lines |
  629. | `ciw`, `di"`, `ya(` … | Text objects: `i`/`a` + `w`, `W`, `"`, `'`, `(`, `[`, or `{`, with `d`/`c`/`y` |
  630. | `u` / `.` | Undo / repeat last change |
  631. > [!Tip]
  632. > Enter still submits your prompt in INSERT mode, unlike standard Vim. Use `o`/`O` in NORMAL mode, or `Ctrl+J`, to insert a newline.
  633. <h2 id="command-history">Command History</h2>
  634. Claude Code keeps a history of the prompts you type (in `~/.claude/history.jsonl`), and Up-arrow recall also reaches earlier sessions of the same project:
  635. * History is stored per working directory
  636. * `/clear` doesn't erase history; recall lists the new session's prompts first, then earlier ones
  637. * Up/Down (or `Ctrl+P`/`Ctrl+N`) first move the cursor within a multiline prompt, then step through history
  638. * **Ctrl+R** is built in and works in any terminal: the inline search covers all projects (`Ctrl+R` again for older matches, `Tab`/`Esc` to accept, `Enter` to accept and run). In fullscreen it opens a dialog where `Ctrl+S` cycles the scope (session, project, all projects)
  639. * **Drafts cleared with `Ctrl+C`** come back with `Up`; the last ten, with pasted text and images, are kept until you exit
  640. * History expansion with `!` is disabled by default
  641. ---
  642. <h1 id="advanced-features">Advanced Features</h1>
  643. <h2 id="thinking-keywords">Thinking Keywords</h2>
  644. > [!Note]
  645. > **`ultrathink` is the only documented prompt keyword for a one-turn request for deeper reasoning.** Phrases such as `think`, `think hard`, and `think harder` are ordinary prompt text; they are not graduated Claude Code controls.
  646. Use `/effort` for an explicit session setting. `ultrathink` adds an in-context instruction for that turn without changing your saved effort level. Typed at the terminal prompt on Opus 5.5, Sonnet 5.5, Haiku 5.5, or Fable 5.1 through Anthropic's API (v2.1.311+), it can also raise that turn to `xhigh`; the word turns rainbow-colored when it can. Elsewhere, such as on Bedrock, set `/effort` instead.
  647. ```md
  648. Ultrathink. Propose a step-by-step strategy to fix flaky payment tests and add guardrails.
  649. ```
  650. <h2 id="effort-levels">Effort Levels</h2>
  651. Use `/effort` to tune how much reasoning the selected model applies before answering. Higher effort levels are best for planning-heavy work, deep reviews, and long-context tasks.
  652. ```bash
  653. /effort # Slider: Enter saves for this model, s = this session only, Tab toggles Ultracode
  654. /effort low # Faster, lighter reasoning
  655. /effort medium # Balanced; default on Opus 5.5, Sonnet 5.5, and Haiku 5.5
  656. /effort high # Deeper planning and review; default on most other models
  657. /effort xhigh # Deeper reasoning at higher token spend; default on Opus 4.7
  658. /effort max # Session-only maximum; test for diminishing returns
  659. /effort ultracode # Workflow orchestration for this session at the current level ("off" to stop)
  660. /effort auto # Clear the saved level and return to the model's default
  661. ```
  662. Available levels depend on the model. `/effort` saves a level per model (under `modelSettings`); the `effortLevel` setting accepts `low` through `xhigh` as the fallback for models without one, though a top-level `effortLevel` in user settings doesn't apply to Opus 5.5. `max` normally applies only to the current session, although `CLAUDE_CODE_EFFORT_LEVEL=max` can force it for sessions launched with that environment variable. `maxEffortLevel` caps effort on every provider. Ultracode is a toggle, not an effort level: with it on, Claude orchestrates dynamic workflows for substantive tasks at the session's current level. Set `"ultracode": true` in settings to start every session with it; `claude --effort ultracode` turns it on and also sets `xhigh`. It requires workflows and an xhigh-capable model. Prefer the lowest effort that reliably solves the task because higher effort increases latency and token use.
  663. <h2 id="advisor-tool">Advisor Tool (Experimental)</h2>
  664. The advisor pairs the main model with a second, at-least-as-capable model that Claude may consult at important planning, debugging, or completion decisions. Each consultation sends the full conversation, including tool calls and results; it counts toward subscription usage or is billed at the advisor model's API rates.
  665. ```bash
  666. /advisor # Open the picker and save the user default
  667. /advisor opus # Save Opus as the advisor
  668. /advisor off # Clear the saved advisorModel setting
  669. claude --advisor opus # Use Opus for this session without changing the saved default
  670. ```
  671. The feature runs through the first-party Anthropic API, for subscription or API-billed accounts; it is unavailable on Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, and opt-in on Claude Platform on AWS (v2.1.300+), where no advisor runs until you pick one. Claude decides when to consult it. `advisorModel` is the persistent settings key, while the intentionally hidden `--advisor` launch flag is session-only; `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` turns the tool off entirely. With Fable access you can pick Fable as the advisor (the only advisor a Fable main model accepts); where Fable bills to usage credits, accept that once with `/model fable` first. See the [advisor guide](https://code.claude.com/docs/en/advisor) for supported main/advisor pairings.
  672. <h2 id="fast-mode">Fast Mode</h2>
  673. > [!Note]
  674. > **Fast mode runs the same Opus model and capabilities up to 2.5× faster at a higher price per token, without trading model quality for speed. It is generally available on Opus 5.5 and in research preview on Opus 5 and Opus 4.8.**
  675. ```bash
  676. /fast # Space toggles, Enter confirms and saves your fastMode default
  677. /fast on # Turn it on directly (session-only in cloud sessions)
  678. # Option+O on macOS or Alt+O on Windows/Linux also toggles it
  679. ```
  680. Fast mode supports **Opus 5.5** (the default fast-mode model), **Opus 5**, and **Opus 4.8**, at \$8/\$40 per MTok input/output on Opus 5.5 and \$10/\$50 on the other two. It is unavailable for Sonnet, Haiku, and Opus 4.7, and on Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude Platform on AWS. VS Code has a **Toggle fast mode** command, and claude.ai/code has a Fast mode switch in the model menu. Subscription users need usage credits; Team and Enterprise also require Owner enablement. Use it for latency-sensitive interactive work, and standard mode for cost-sensitive or long autonomous tasks. Lower `/effort` is the separate control that may trade reasoning depth for speed.
  681. <h2 id="auto-mode">Auto Mode</h2>
  682. Auto mode lets Claude evaluate and approve lower-risk actions automatically while still blocking or asking on higher-risk operations. It is useful for trusted development loops where repeated permission prompts slow down work.
  683. ```bash
  684. # Start in auto mode, or cycle to it with Shift+Tab
  685. claude --permission-mode auto
  686. # Inspect the built-in and effective classifier configuration
  687. claude auto-mode defaults
  688. claude auto-mode config
  689. claude auto-mode critique # AI feedback on your custom rules
  690. # Remove a cached/custom classifier config and return to defaults
  691. claude auto-mode reset # Add --yes to skip confirmation
  692. ```
  693. ```json
  694. {
  695. "autoMode": {
  696. "environment": [
  697. "$defaults",
  698. "Source control: github.example.com/acme-corp and all repos under it"
  699. ],
  700. "hard_deny": [
  701. "$defaults",
  702. "Never send repository contents to third-party code-review APIs"
  703. ]
  704. }
  705. }
  706. ```
  707. Key points:
  708. - Auto mode is available on every supported provider (on Bedrock, Agent Platform, and Foundry only with Sonnet 5+, Opus 4.7+, Haiku 5.5, and Fable models); `CLAUDE_CODE_ENABLE_AUTO_MODE` is a no-op compatibility variable. With no mode configured, interactive terminal and VS Code sessions start in auto mode where it's available (otherwise Manual), while `claude -p` and Agent SDK runs start in `default` (Manual). Choose another starting mode with `--permission-mode` or `permissions.defaultMode`; `disableAutoMode: "disable"` in managed settings removes auto mode.
  709. - The classifier trusts the working directory and current repository remotes by default. Add organization infrastructure under `autoMode.environment` only when needed; `/auto-mode-setup` drafts entries from your project and recent sessions, and `/permissions` has an **Auto mode** tab for viewing and editing rules.
  710. - Put `autoMode` in user settings, managed settings, or `--settings`. Repository `.claude/settings.json` and `.claude/settings.local.json` cannot inject classifier policy.
  711. - Include `"$defaults"` in `allow`, `soft_deny`, `hard_deny`, or `environment` to extend the built-in rules. An array without it replaces that section's built-in list, so an empty `hard_deny` drops the built-in data-exfiltration rule.
  712. - Where supported, classifier checks run server-side at no extra charge (`/status` shows an **Auto mode server** row). Behind a gateway or proxy that blocks them, Claude Code makes its own classifier requests, which count toward usage; `CLAUDE_CODE_AUTO_MODE_SERVER=0` forces that.
  713. - Explicit `permissions.deny` and content-scoped `permissions.ask` rules are evaluated before the classifier. Use those for non-negotiable blocks or human checkpoints.
  714. <h2 id="plan-mode">Plan Mode</h2>
  715. > [!Note]
  716. > **Plan Mode tells Claude to research and propose changes without editing your source, and is designed for exploration, planning, and review. It permits read-only shell exploration; when auto mode is available and `useAutoModeDuringPlan` is on (the default), the classifier reviews other commands instead of prompting.**
  717. Plan Mode is a workflow mode, not a hard isolation boundary. In interactive terminal sessions where bypass permissions is available (such as with `--dangerously-skip-permissions`), its blocks aren't enforced: Claude is still told not to edit, but edits and commands it attempts run without prompting (explicit ask rules and critical-path `rm`/`rmdir` removals still prompt). Use sandboxing plus explicit deny/ask rules or managed policy when command execution must be technically constrained.
  718. When the plan is ready, choose **Yes, and use auto mode** (**Yes, auto-accept edits** without auto mode), **Yes, manually approve edits**, or **No, keep planning**; `Ctrl+G` opens it in your editor first.
  719. **When to use Plan Mode:**
  720. - **Multi-step implementation**: When your feature requires making edits to many files
  721. - **Code exploration**: When you want to research the codebase thoroughly before changing anything
  722. - **Interactive development**: When you want to iterate on the direction with Claude
  723. **How to enable Plan Mode:**
  724. ```bash
  725. # Start a new session in Plan Mode
  726. claude --permission-mode plan
  727. # Or toggle during session with Shift+Tab
  728. # (cycles through Manual, Accept Edits, Plan, and any other enabled modes)
  729. # Enter plan mode from the prompt
  730. /plan
  731. # Run headless queries in Plan Mode
  732. claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"
  733. ```
  734. **Configure Plan Mode as default:**
  735. In `.claude/settings.json`:
  736. ```json
  737. {
  738. "permissions": {
  739. "defaultMode": "plan"
  740. }
  741. }
  742. ```
  743. ---
  744. <h2 id="background-tasks">Background Tasks</h2>
  745. > [!Note]
  746. > **Claude Code supports background commands and full background sessions, allowing you to continue working while long-running processes or agents execute.**
  747. **How to use background tasks:**
  748. | Method | Description |
  749. | :----- | :---------- |
  750. | Prompt Claude | Ask Claude to run a shell command or subagent in the background |
  751. | `Ctrl+B` | Move a running Bash tool invocation or agent to the background (tmux users press twice) |
  752. | `/background` (`/bg`) | Detach this entire conversation and free the terminal |
  753. | `←` on an empty prompt | Background this session and open agent view (`leftArrowOpensAgents` in `/config` turns this off) |
  754. | `/fork` | Copy this conversation into a worktree-isolated background session while you stay here |
  755. | `claude --bg` | Launch a new background Claude session; it cannot be combined with `-p` |
  756. | `! <command>` in `claude agents` | Start an attachable background shell session from agent view |
  757. **Key features:**
  758. - Output is buffered and can be read from the persisted background output file path
  759. - The Monitor tool lets Claude stream a background script's output line by line instead of polling with `sleep`
  760. - In unattended sessions (`-p`, Agent SDK, CI, cloud), background shell commands stop at their `timeout` (default 30 minutes, or 10 in a `-p` run given a text prompt; max 2 hours); interactive sessions have no limit
  761. - Background tasks have unique IDs for tracking and output retrieval
  762. - `/tasks` shows background shells, subagents, and long-running tool calls owned by the current session
  763. - Background sessions appear in `/resume` and the `claude agents` dashboard, marked with `bg`; use `claude attach/logs/stop/rm/respawn <id>` to manage them
  764. - Use `claude agents --json` for scripts, status bars, session pickers, and tmux integrations
  765. - Background sessions preserve completed work with commits/pushes, and open a draft PR only when the task calls for one
  766. **Common backgrounded commands:**
  767. - Build tools (webpack, vite, make)
  768. - Package managers (npm, yarn, pnpm)
  769. - Test runners (jest, pytest)
  770. - Development servers
  771. - Long-running processes (docker, terraform)
  772. **Bash mode with `!` prefix:**
  773. ```bash
  774. # Run bash commands directly without Claude interpretation
  775. ! npm test
  776. ! git status
  777. ! ls -la
  778. # Run a command as an attachable background session
  779. claude --bg --exec "npm test"
  780. # Name a background session
  781. claude --bg --name nightly-check "run the full verification suite"
  782. # Detach or copy the current conversation
  783. /background "finish the verification and report back"
  784. /fork "investigate the flaky integration test" # Runs in its own worktree
  785. ```
  786. **Disable background tasks:**
  787. ```bash
  788. # Remove run_in_background and Ctrl+B for shells and subagents
  789. export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1
  790. # Also turn off background sessions: claude agents, --bg, /background
  791. export CLAUDE_CODE_DISABLE_AGENT_VIEW=1 # or "disableAgentView": true in settings
  792. ```
  793. ---
  794. <h2 id="workflows--scheduling">Workflows & Scheduling</h2>
  795. Dynamic workflows coordinate many background agents for larger work than a single foreground turn can comfortably handle. Ask for one in your own words ("use a workflow to…") or include `ultracode` in your prompt, then use `/workflows` to inspect runs and status. `/deep-research <question>` is built in, and pressing `s` on a run in `/workflows` saves its script (to `.claude/workflows/` or `~/.claude/workflows/`) as a reusable `/<name>` command. On Pro, turn workflows on in `/config` first.
  796. ```bash
  797. /workflows
  798. /goal "the migration is implemented, tested, and documented"
  799. /loop 15m "check the deployment dashboard and summarize any incidents"
  800. ```
  801. | Feature | Purpose |
  802. | :----------- | :-------------------------------------------------------------------------------------- |
  803. | `/workflows` | View workflow runs that orchestrate many agents in the background |
  804. | `/goal` | Give Claude a completion condition and let it continue across turns until it is reached |
  805. | `/loop` | Run a prompt or slash command on an interval, or omit it to let Claude self-pace |
  806. | `/schedule` | Create and manage cloud scheduled tasks that run without your machine |
  807. Use workflows for broad, decomposable efforts. Use `/goal` for a single outcome that may require several turns. Use `/loop` for monitoring within an open session; loops expire after 7 days, `Esc` stops a self-paced loop while it waits, and you ask Claude to cancel a fixed-interval one. Use `/schedule` or Desktop scheduled tasks for schedules that must run without an open session.
  808. The default `workflowSizeGuideline` is **medium** (fewer than 10 agents), or **small** (fewer than 5) on Pro; `large` aims for fewer than 50, and `unrestricted` lets Claude decide. It is advice, not a cap; the runtime separately limits a run to 16 concurrent agents by default (`CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS`, 1–256) and 1,000 in total. Change it through `/config` only when the work genuinely benefits from a smaller or larger fan-out.
  809. ---
  810. <h2 id="remote-sessions">Cloud Sessions</h2>
  811. > [!Note]
  812. > **For eligible subscribers: use `--cloud` to start a cloud session on claude.ai and `--teleport` to copy a cloud session into a local checkout. `--remote` remains only as a deprecated alias for `--cloud`.**
  813. **Start a cloud session:**
  814. ```bash
  815. # Create a new cloud session on claude.ai with task description
  816. claude --cloud "Fix the login bug"
  817. ```
  818. The cloud VM clones your GitHub remote at the current branch, not your local checkout, so push local commits first. With no git remote, or when the Claude GitHub App isn't installed on the GitHub repository, Claude Code uploads a bundle of your local repository instead (untracked files are left out; `CCR_FORCE_BUNDLE=1` forces a bundle, for example for a GitLab or Bitbucket repository). Queue a follow-up into a running cloud session with `claude -p "next step" --cloud <session-id>`. `--cloud` and `--teleport` need a claude.ai sign-in (`claude auth login`) and an organization that allows cloud sessions; they aren't available through Bedrock, Google Cloud's Agent Platform, or other third-party providers.
  819. **Resume a cloud session locally:**
  820. ```bash
  821. # Resume a cloud session in your local terminal (omit the ID for a session picker)
  822. claude --teleport <session-id>
  823. # Or, inside a running session, use the slash command (alias /tp)
  824. /teleport
  825. ```
  826. Teleport needs a clean working tree (it offers to stash), a checkout of the same repository (not a fork), the session's branch pushed to the remote, and the same claude.ai account. The terminal gets its own copy of the session: local work doesn't sync back, and a compacted cloud session arrives as its summary.
  827. **Cloud environments and PR auto-fix:** each cloud session runs in a [cloud environment](https://code.claude.com/docs/en/cloud-environments) that sets its network access (default **Trusted**: package registries and other allowlisted domains only), environment variables, and a setup script that runs before Claude starts. If an install or WebFetch fails in a cloud session, check the network level first; `/remote-env` picks the default environment for `--cloud`. On a PR's branch, `/autofix-pr` starts a cloud session that watches the PR and pushes fixes for CI failures and review comments (needs `gh` and the Claude GitHub App on the repository).
  828. Team and Enterprise organizations can also run cloud sessions on infrastructure they control (self-hosted environments, public beta, off by default). An Owner turns on **Allow self-hosted environments** on the claude.ai **Cloud environments** admin page and creates an environment, then starts a runner on a Linux or macOS host with `claude self-hosted-runner setup` (guided) or `claude self-hosted-runner --environment-secret-file <file> --base-dir <dir>`. Developers pick the environment in claude.ai/code or dispatch with `claude -p "your task" --environment ccpool_...`; see the [self-hosted environments guide](https://code.claude.com/docs/en/self-hosted-environments).
  829. ---
  830. <h2 id="claude-in-chrome">Claude in Chrome</h2>
  831. With the [Claude in Chrome extension](https://code.claude.com/docs/en/chrome), Claude Code can drive browser-based testing and UI verification from the CLI.
  832. **Setup:**
  833. ```bash
  834. claude --chrome # Launch with Chrome integration
  835. /chrome # Status, reconnect, site permissions, browser choice, "Enabled by default"
  836. ```
  837. **Capabilities:**
  838. - Navigate to URLs, click elements, fill forms
  839. - Take screenshots and analyze page content
  840. - Execute JavaScript in the browser context
  841. - Interact with web applications for testing
  842. - Read console errors and DOM state for live debugging
  843. - Upload local files to page upload fields (up to 10 MB per upload; files denied to `Read` are refused)
  844. - Record interactions as GIFs and save screenshots to disk
  845. > [!NOTE]
  846. > Requires Chrome, Edge, or another Chromium browser (Brave, Arc, Vivaldi, Opera), the Claude in Chrome extension v1.0.36+, and a claude.ai subscription sign-in (API keys and `claude setup-token` tokens keep it off). It is unavailable through WSL and third-party model providers, and an organization admin can turn it off. Project settings files can't turn it on; use `--chrome` or **Enabled by default** in `/chrome`, a setting shared with the VS Code extension. Review the extension's site permissions before granting access; in auto mode, classifier-approved browser calls skip the extension's per-site check, so add permission deny rules for sites Claude must never act on.
  847. ---
  848. <h2 id="desktop-and-ides">Desktop and IDEs</h2>
  849. The Claude Desktop Code tab supports macOS, Windows (including sessions inside a WSL 2 distribution), and a Linux beta for Ubuntu/Debian. It provides parallel local or cloud sessions, worktrees, diffs, an editor, terminal, and browser; SSH execution is also available. Desktop and the CLI share CLAUDE.md files, settings, hooks, skills, and MCP servers from `~/.claude.json` and `.mcp.json`, but each keeps its own session list. Desktop's local Code tab sessions also load MCP servers from `claude_desktop_config.json`, which the CLI ignores; on macOS and WSL, `claude mcp add-from-claude-desktop` copies them into `~/.claude.json`. Agent teams are not supported in Desktop.
  850. Run `/desktop` to move the current terminal session into the app, or `claude --desktop` (v2.1.285+) to open Desktop from your shell on the current directory, or on a session with `--continue` or `--resume <session-id>`. Both need macOS or x64 Windows and a Claude subscription sign-in.
  851. **Computer use** (research preview, Pro and Max plans) lets Claude open native apps, click, type, and take screenshots when no MCP server, shell command, or Claude in Chrome can reach a tool. Turn it on in Desktop Settings (macOS and Windows) or, in the macOS CLI, enable the built-in `computer-use` server in `/mcp` and grant Accessibility and Screen Recording. Claude asks before controlling each app; it needs an interactive session and isn't available through third-party providers.
  852. The VS Code extension requires VS Code 1.94+ and bundles a CLI for its panel; install the standalone CLI separately for terminal use. Cursor and compatible Open VSX forks are supported. Its Focus view hides tool calls, tool results, and thinking behind expandable rows (`Ctrl+Alt+F`, or `Ctrl+Option+F` on Mac). Its settings include **Enable Remote Control for all sessions**, and `claudeCode.attachSelection` and `claudeCode.attachOpenFile` control whether your editor selection and open file are added to messages. The JetBrains plugin (IntelliJ IDEA, PyCharm, WebStorm, GoLand, Android Studio, and others) doesn't bundle the CLI: install `claude` separately and run it in the IDE's integrated terminal, or connect from an external terminal with `/ide`. For JetBrains Remote Development, install the plugin on the remote host.
  853. **Slack:** Team and Enterprise organizations bring @Claude into Slack channels with [Claude Tag](https://claude.com/docs/claude-tag/overview) (public beta), which works as the organization's shared identity with admin-configured access to repositories, connectors, and skills, under an organization spend limit. On Pro and Max, in a workspace no organization has connected to Claude Tag, the earlier [Claude Code in Slack](https://code.claude.com/docs/en/slack) app (`/install-slack-app`) turns @Claude coding requests into cloud sessions under your own account and plan limits.
  854. See the current [Desktop](https://code.claude.com/docs/en/desktop), [VS Code](https://code.claude.com/docs/en/vs-code), [JetBrains](https://code.claude.com/docs/en/jetbrains), and [computer use](https://code.claude.com/docs/en/computer-use) documentation for platform-specific setup.
  855. ---
  856. <h2 id="sandbox-mode">Sandbox Mode</h2>
  857. Sandboxing is an OS-enforced boundary for the shell commands Claude runs (Bash, PowerShell, and Monitor) and the processes they start; Claude's file tools, MCP servers, and hooks run outside it, and it is separate from Claude Code's tool-permission rules. It is off by default: turn it on with `/sandbox` or `"sandbox": { "enabled": true }` in `~/.claude/settings.json`, then pick **auto-allow** (sandboxed commands run without prompting) or **regular permissions** on the `/sandbox` Mode tab. With default settings, sandboxed commands can write inside the working directory and temporary directories, read broadly except for denied paths, and reach the network only through a hostname-filtering proxy.
  858. ```bash
  859. /sandbox # Inspect dependencies and configure filesystem/network isolation
  860. ```
  861. Platform support:
  862. - macOS uses Seatbelt.
  863. - Linux and WSL 2 use bubblewrap plus socat (`sudo apt-get install bubblewrap socat` on Ubuntu/Debian). On Ubuntu 24.04+, if `sysctl kernel.apparmor_restrict_unprivileged_userns` returns `1`, AppArmor stops bubblewrap from creating user namespaces; add an AppArmor profile for `bwrap` (`/sandbox` and the startup warning explain how).
  864. - Native Windows and WSL 1 do not support sandboxing.
  865. Useful hardening settings include `sandbox.failIfUnavailable: true` to fail closed, `sandbox.allowUnsandboxedCommands: false` (**Strict sandbox mode** on the `/sandbox` Overrides tab) to remove the unsandboxed retry path, `sandbox.network.strictAllowlist: true` for an exact network allowlist, and credential rules with `mode: "deny"` or `mode: "mask"`. Commands you type at the `!` prompt run outside the sandbox even in strict mode, except in background sessions and Linux sessions with `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` set. Put tools that can't run sandboxed, such as `docker`, in `sandbox.excludedCommands` (for example `"docker compose *"`); they run with your full access, so keep patterns narrow. On Linux, `sandbox.allowNestedUserNamespaces: true` in `~/.claude/settings.json` (v2.1.305+) lets Chromium's or Electron's own sandbox, a nested bubblewrap, or `unshare` run inside the sandbox, but it turns off a security boundary; it isn't enough for rootless Podman or Buildah, which need `sandbox.excludedCommands` instead.
  866. Masking credential files works on Linux and WSL 2; on macOS a masked file is blocked like `deny`. Every `mask` entry needs `sandbox.network.tlsTerminate`, or the placeholder reaches the server unchanged and authentication fails (`claude doctor` warns `TLS termination is unavailable`). Masks can also extract structured values, mask selected JWT claims, and re-sign AWS SigV4 requests. `mask` entries, `network.tlsTerminate`, `credentials.allowPlaintextInject`, `awsPairs`, and `sigv4` are honored only from user, managed, or `--settings` configuration, never from a repository's `.claude/settings.json` or `.claude/settings.local.json`. Sandboxing reduces the impact of shell commands; it is not a substitute for reviewing permissions and secrets exposure.
  867. ---
  868. <h2 id="lsp-tool">LSP Tool (Language Server Protocol)</h2>
  869. Claude Code integrates with language servers to provide IDE-level code intelligence:
  870. - **Diagnostics after edits** — Type errors and warnings go back to Claude automatically after each file edit (`Found N new diagnostic issues`; Ctrl+O expands them)
  871. - **Go to Definition** — Jump to where a symbol is defined
  872. - **Find References** — Find all usages of a symbol across the codebase
  873. - **Hover Information** — Get type information and documentation
  874. - **Symbols and call hierarchy** — List file or workspace symbols, find implementations, and trace call hierarchies
  875. LSP support is provided by plugins. Install the language-server binary separately, then install its LSP plugin from the official marketplace with `/plugin`; for TypeScript, run `npm install -g typescript-language-server typescript`, then `/plugin install typescript-lsp@claude-plugins-official`. A server merely being present on `PATH` is not enough, though Claude Code may then offer the matching plugin. This enables Claude to navigate codebases more precisely than text search alone. Plugin language servers don't start in cloud sessions, so the LSP tool is inactive there.
  876. > Large tool results are saved to a file, and Claude gets a preview plus the path. This applies to successful Bash output over about 30,000 characters (adjustable up to 128,000 with the `bashOutputMaxChars` setting) and to MCP results over the limits described under [MCP Integration](#mcp-integration).
  877. ---
  878. <h2 id="sub-agents">Sub Agents</h2>
  879. > Sub‑Agents are purpose‑built helpers with their **own prompts, tools, and isolated context windows**. Treat this like a "mixture‑of‑experts" you **compose** per repo.
  880. <h3 id="built-in-subagents">Built-in Subagents</h3>
  881. Claude Code includes built-in subagents that Claude automatically uses when appropriate:
  882. | Subagent | Model | Tools | Purpose |
  883. | :------- | :---- | :---- | :------ |
  884. | **Explore** | Inherits the parent model (Opus under a Fable parent, except on Bedrock, Agent Platform, Foundry, and similar providers) | Read-only | File discovery, code search, and codebase exploration |
  885. | **Plan** | Inherits the parent model | Read-only | Planning complex changes without making edits |
  886. | **General-purpose** | Inherits the parent model | Inherited | General task delegation |
  887. > Claude delegates to **Explore** when it needs to search or understand a codebase without making changes, keeping exploration results out of your main conversation context.
  888. Explore and Plan start without your `CLAUDE.md` files or git status and can't be resumed. Set `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1` to remove both, or deny one with `Agent(Explore)` in `permissions.deny`.
  889. **When to use subagents:**
  890. > - You need high signal responses (plans, reviews, diffs) without side quests.
  891. > - You want version‑controlled prompts and tool policies alongside the codebase.
  892. > - You work in PR‑driven teams and want scoped edits by role.
  893. > - The task produces verbose output you don't need in your main context.
  894. <h3 id="each-sub-agent-has-its-own-context">Each Sub‑Agent Has Its Own Context</h3>
  895. **Design rules for your lineup**
  896. > - Define **one clear responsibility** per agent.
  897. > - Keep the **minimum** tool set needed for that role.
  898. > - Prefer **read‑only** agents for analysis/review tasks.
  899. > - Give edit powers to as few agents as possible.
  900. <h3 id="configure-agents">Configure Agents</h3>
  901. > Keep agents **in the project** so they're versioned with the repo and evolve via PRs.
  902. <h3 id="agents-quick-start">Quick start</h3>
  903. > Ask Claude to create an agent, mention one with `@agent-name`, or edit its Markdown definition directly. `/agents` now prints this guidance; it no longer opens the old wizard.
  904. ```bash
  905. claude update
  906. # Project agent: .claude/agents/<name>.md
  907. # Personal agent: ~/.claude/agents/<name>.md
  908. claude --agent code-reviewer "review the current branch"
  909. ```
  910. `claude agents` is a separate agent-view dashboard for running, blocked, completed, and background **sessions**. It does not list or configure subagent definitions.
  911. <h3 id="agent-scopes">Subagent Scopes</h3>
  912. | Location | Scope | Priority |
  913. | :------- | :---- | :------- |
  914. | Managed policy agents | Organization | 1 (highest) |
  915. | `--agents` CLI flag | Current session only | 2 |
  916. | `.claude/agents/` | Current project | 3 |
  917. | `~/.claude/agents/` | All your projects | 4 |
  918. | Plugin's `agents/` directory | Where plugin is enabled | 5 (lowest) |
  919. Plugin subagents ignore `hooks`, `mcpServers`, and `permissionMode`; copy the file into `.claude/agents/` or `~/.claude/agents/` to use them.
  920. Dispatched sessions honor the `agent` field in `settings.json`. Pass `--agent <name>` to override the configured default for a specific run.
  921. <h3 id="define-agents-via-cli">Define Agents via CLI</h3>
  922. ```bash
  923. # Define custom subagents dynamically via JSON
  924. claude --agents '{
  925. "code-reviewer": {
  926. "description": "Expert code reviewer. Use proactively after code changes.",
  927. "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
  928. "tools": ["Read", "Grep", "Glob", "Bash"],
  929. "model": "sonnet"
  930. },
  931. "debugger": {
  932. "description": "Debugging specialist for errors and test failures.",
  933. "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  934. },
  935. "background-impl": {
  936. "description": "Implements features in an isolated worktree in the background.",
  937. "prompt": "Implement the requested feature. Commit when done.",
  938. "isolation": "worktree",
  939. "background": true
  940. }
  941. }'
  942. ```
  943. With `-p`, `--agents` also takes a JSON file path: `claude -p --agents ./agents.json "Review my changes"`. In PowerShell, wrap inline JSON in a here-string (`@'` … `'@`) instead of single quotes.
  944. <h3 id="create-your-core-agents">Create your core agents</h3>
  945. > - **planner** (read‑only): turns features/issues into small, testable tasks; outputs a task list or plan.md.
  946. > - **codegen** (edit‑capable): implements tasks; limited to `src/` + `tests/`.
  947. > - **tester** (read‑only or patch‑only): writes _one_ failing test or a minimal repro.
  948. > - **reviewer** (read‑only): leaves structured review comments; never edits.
  949. > - **docs** (edit‑capable): updates `README.md`/`docs/` only.
  950. **\*Policy** tip: Prefer **patch output** for edit‑capable agents so changes land through your normal Git workflow.\*
  951. Grant each agent only the tools its role needs (`tools` is an allowlist, `disallowedTools` a denylist): `Read, Grep, Glob` for advisory agents, plus `Edit` and `Write` for editing ones.
  952. <h3 id="example-prompts">Example prompts</h3>
  953. > Keep prompts short, testable, and repo‑specific. Check them into `.claude/agents/`:
  954. <img width="700" height="217" alt="image" src="https://github.com/user-attachments/assets/b4f92591-ff5c-4775-aec2-051f145b9616" />
  955. _Caption: A plain request delegating to a **test‑coverage‑analyzer** agent; the `/agents` output at the top is from the since-removed wizard._
  956. **.claude/agents/tester.md (sample)**
  957. ```markdown
  958. ---
  959. name: tester
  960. description: Writes one focused failing test for a scenario I describe. Use when a bug or feature needs a reproducing test.
  961. tools: Read, Grep, Glob, Bash
  962. ---
  963. Role: Write a single, focused failing test for the specific scenario I describe.
  964. Scope: Only create/modify tests under tests/. Do not change src/.
  965. Output: A brief rationale + a unified diff or patch.
  966. If the scenario is unclear, stop and return exactly one clarifying question.
  967. ```
  968. <h3 id="expected-output">Expected output</h3>
  969. > Your tester agent should produce a small diff or patch plus a short rationale:
  970. <img width="700" height="273" alt="image" src="https://github.com/user-attachments/assets/839151ce-02c9-4283-a53b-9dd105802ada" />
  971. _Caption: Example response from the **test‑coverage‑analyzer** agent._
  972. <h3 id="subagent-frontmatter">Subagent Frontmatter Fields</h3>
  973. Subagent files use YAML frontmatter for configuration:
  974. ```markdown
  975. ---
  976. name: code-reviewer
  977. description: Reviews code for quality and best practices
  978. tools: Read, Glob, Grep
  979. disallowedTools: Write, Edit
  980. model: sonnet
  981. permissionMode: default
  982. skills:
  983. - api-conventions
  984. ---
  985. You are a code reviewer. Analyze the code and provide feedback.
  986. ```
  987. | Field | Required | Description |
  988. | :---------------- | :------- | :------------------------------------------------------------------ |
  989. | `name` | Yes | Unique identifier such as `code-reviewer` (max 256 characters, no `:`, no leading `-`); needn't match the filename |
  990. | `description` | Yes | When Claude should delegate to this subagent |
  991. | `tools` | No | Tools the subagent can use (inherits all if omitted) |
  992. | `disallowedTools` | No | Tools to deny, removed from inherited or specified list |
  993. | `model` | No | `sonnet`, `opus`, `haiku`, `fable`, a full model ID, or `inherit`; if omitted, see the model order below |
  994. | `effort` | No | Model-dependent effort override for this subagent |
  995. | `maxTurns` | No | Maximum agentic turns; hitting it returns partial output Claude can resume |
  996. | `autoCompactWindow` | No | Auto-compact earlier: plain integer `100000`–`1000000` (`200k` reads as 200); can lower, never raise, `CLAUDE_CODE_AUTO_COMPACT_WINDOW` |
  997. | `permissionMode` | No | `default`/`manual`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, or `plan` |
  998. | `skills` | No | Skills to preload into the subagent's context (max 32; the Skill tool can load others) |
  999. | `hooks` | No | Lifecycle hooks scoped to this subagent |
  1000. | `mcpServers` | No | MCP servers available to this subagent |
  1001. | `memory` | No | Persistent memory scope: `user`, `project`, or `local` |
  1002. | `omitClaudeMd` | No | `true` skips user, project, and local `CLAUDE.md` files (managed policy still loads) |
  1003. | `isolation` | No | Set to `worktree` to run the agent in an isolated git worktree, branched per [`worktree.baseRef`](#worktree-isolation) |
  1004. | `background` | No | `true` keeps it in the background even when Claude asks to wait for it |
  1005. | `color` | No | Display color in the task list and transcript: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan` |
  1006. | `initialPrompt` | No | First user turn when this definition runs as the main session via `--agent` or the `agent` setting |
  1007. | `experimental` | No | Experimental options; `cacheTtl: 5m` or `1h` sets the prompt-cache TTL (agent files only) |
  1008. Field names are case-sensitive. Unknown fields are silently ignored and a file missing `name` or `description` is skipped; `claude --debug` logs unknown fields and most skip reasons.
  1009. **Model order:** a model Claude passes for one spawn, then the definition's `model`, then `CLAUDE_CODE_SUBAGENT_MODEL`, then the main model. That variable is only a default and doesn't move Explore or Plan; add `CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1` to apply it to every subagent, teammate, and workflow agent. Asking for an effort ("use a subagent at high effort") overrides `effort` for that spawn; `/tasks` shows each subagent's model and effort.
  1010. Organization model allowlists still apply to frontmatter. A restricted family alias steps down to the newest permitted model in that family where supported; when a workflow agent, forked skill/command, or resumed background agent must run on the parent model instead, Claude Code warns rather than silently implying the requested model was honored.
  1011. **Background by default:** subagents Claude spawns from the main conversation start in the background, with every MCP tool but only core built-in tools. Claude can still wait for one under `claude -p` and the Agent SDK, but in the terminal, desktop app, and VS Code only with fork mode off (`CLAUDE_CODE_FORK_SUBAGENT=0`, e.g. in the `settings.json` `env` block, then restart). `Ctrl+B` (**Run in background** in VS Code) backgrounds a waiting subagent. Ask Claude to resume a finished subagent to continue with its history.
  1012. **Forks:** a fork (`subagent_type: "fork"`) inherits the whole conversation, model, tools, prompt cache, and permission mode, so it can't leave plan mode. Fork mode is on by default except under `claude mcp serve`; start a fork yourself with `/subtask <task>`, or stop Claude forking with `Agent(fork)` in `permissions.deny` or `CLAUDE_CODE_FORK_SUBAGENT=0`.
  1013. Background and isolated agents can switch between Claude-managed worktrees with `EnterWorktree` when the session needs to move between related isolated checkouts.
  1014. Subagents can nest up to three layers below the main conversation by default, with at most 20 running concurrently. Claude Code v2.1.224 removed the former 200-spawn session cap. Tune the remaining limits with `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` and `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`; setting the depth to `1` disables nesting. These defaults have changed across releases, so check the [live subagent reference](https://code.claude.com/docs/en/sub-agents) before building automation around them.
  1015. <h3 id="why-this-shift-matters">Why This Shift Matters</h3>
  1016. **Operational benefits**
  1017. > - **Less context switching:** you stay in one mental mode; agents do the rest.
  1018. > - **Cleaner PRs:** narrow prompts + limited tools → smaller, reviewable diffs.
  1019. > - **Fewer regressions:** tester/reviewer agents catch gaps before merge.
  1020. > - **Repeatability:** prompts + policies live in the repo and travel with branches.
  1021. **Security & governance**
  1022. > - Limit write access by path (e.g., `src/`, `tests/`, `docs/`) with a frontmatter `PreToolUse` hook that exits `2` on out-of-scope files (a `disallowedTools` entry like `Edit(src/**)` removes the whole tool).
  1023. > - Favor read‑only analysis for high‑risk areas.
  1024. > - Log/commit assistant outputs as patches for auditability.
  1025. <h3 id="a-mindset-shift">A Mindset Shift</h3>
  1026. **Do**
  1027. > - Treat agents as teammates with job descriptions.
  1028. > - Start read‑only; grant write access _last_.
  1029. > - Keep prompts in version control and iterate via PR.
  1030. **Don't**
  1031. > - Ask one agent to plan, code, and test in a single turn.
  1032. > - Give blanket write permissions.
  1033. > - Accept multi‑file diffs when you asked for one test.
  1034. ---
  1035. <h2 id="agent-teams">Agent Teams (Research Preview)</h2>
  1036. > [!Note]
  1037. > **Agent Teams is an experimental feature enabling multiple Claude instances to work in parallel on a shared codebase autonomously.**
  1038. **Enable Agent Teams:**
  1039. ```bash
  1040. export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
  1041. ```
  1042. **Key Concepts:**
  1043. - A lead session coordinates separate teammate sessions through a shared task list and direct messages.
  1044. - Teammates can specialize in independent work such as debugging, documentation, and testing.
  1045. - Agent teams coordinate through Claude Code messaging, not git synchronization.
  1046. - Teammates do not receive automatic worktree isolation. Partition files carefully or explicitly create worktrees to avoid conflicting edits.
  1047. - Teams cost substantially more tokens than subagents; start with three to five teammates and use them only for genuinely parallel work.
  1048. **Using Agent Teams:**
  1049. - Enabling teams makes any subagent Claude spawns with a `name` launch as a teammate, without asking (except forks and calls passing `isolation`); set the variable to `0` to revert. `claude -p` and the Agent SDK never spawn teammates.
  1050. - Ask in plain language (`Spawn three teammates to review PR #142: security, performance, and test coverage.`) or reuse a subagent definition (`Spawn a teammate using the security-reviewer agent type.`). Teammate models follow the [subagent model order](#subagent-frontmatter), ending with the lead's model.
  1051. - Teammates run in-process by default: select one in the agent panel and press Enter to message it, `x` to stop it, or Ctrl+T to toggle the task list. For split panes, set `"teammateMode": "auto"` in `~/.claude/settings.json` or run `claude --teammate-mode auto`; panes need tmux or iTerm2 (`it2` CLI) and don't work in VS Code's terminal, Windows Terminal, or Ghostty.
  1052. - Teammates start in the lead's permission mode (except `dontAsk`) and route permission prompts to the lead; gate their work with `TeammateIdle`, `TaskCreated`, and `TaskCompleted` [hooks](#hooks-system).
  1053. - Limits: one team per session, no nested teams, a fixed lead, and `/resume` or `/rewind` don't restore in-process teammates.
  1054. **Case Study: C Compiler Built by Agent Teams**
  1055. Anthropic's research team demonstrated agent teams by tasking 16 parallel Claude instances to build a C compiler from scratch. Key results:
  1056. | Metric | Value |
  1057. | :------------------ | :------------------------------------- |
  1058. | **Claude Sessions** | ~2,000 |
  1059. | **API Cost** | ~$20,000 |
  1060. | **Lines of Code** | 100,000 |
  1061. | **Capability** | Compiled Linux 6.9 on x86, ARM, RISC-V |
  1062. | **Test Pass Rate** | 99% on GCC torture test suite |
  1063. **Lessons for Agent Teams:**
  1064. 1. **Write high-quality tests** - The task verifier must be nearly perfect
  1065. 2. **Design for parallelism** - Agents should be able to work independently without blocking each other
  1066. 3. **Specialize agents** - Dedicate agents to specific roles (code quality, documentation, performance)
  1067. 4. **Maintain context files** - Keep READMEs and progress files updated for agent orientation
  1068. > Read the full case study: [Building a C Compiler with Parallel Claudes](https://www.anthropic.com/research/building-c-compiler)
  1069. ---
  1070. <h2 id="skills">Skills (Custom Slash Commands)</h2>
  1071. > [!Note]
  1072. > **Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`.**
  1073. <h3 id="skill-locations">Skill Locations</h3>
  1074. | Location | Scope | Description |
  1075. | :--------------------------------------- | :------- | :-------------------------------------------- |
  1076. | `<managed-settings-dir>/.claude/skills/<skill-name>/SKILL.md` | Enterprise | All users where your organization deploys it |
  1077. | `~/.claude/skills/<skill-name>/SKILL.md` | Personal | All your projects |
  1078. | `.claude/skills/<skill-name>/SKILL.md` | Project | This project only (commit to version control) |
  1079. | `<subdir>/.claude/skills/<skill-name>/SKILL.md` | Nested | Sessions in or below `<subdir>`, or once Claude works on files there |
  1080. | `<add-dir>/.claude/skills/<skill-name>/SKILL.md` | Added dir | That session; `/<folder>:<name>` on a name clash |
  1081. | `<plugin>/skills/<skill-name>/SKILL.md` | Plugin | Where plugin is enabled |
  1082. | claude.ai account (`~/.claude/skills/synced/`) | Synced | Terminal sessions signed in with that account; opt out with `"syncClaudeAiSkills": false` |
  1083. > Enterprise-managed skills override personal skills, and personal skills override project skills with the same name. Plugin skills remain namespaced. Files in `.claude/commands/` remain compatible, but new commands should use the skill layout. Local skill folders named `synced`, and local skills or commands named `anthropic-skills`, don't load; those names are reserved for claude.ai sync.
  1084. > A directory under `~/.claude/skills/` or `.claude/skills/` is a plain skill when it contains `SKILL.md`. It becomes a skills-directory plugin only when it contains `.claude-plugin/plugin.json`. Skill edits there (and in `--add-dir` folders) apply live. Run `/reload-skills` after creating a top-level skills directory mid-session (and after each later change there, since it isn't watched yet), and `/reload-plugins` for a skills-directory plugin's hooks, `.mcp.json`, agents, or output styles.
  1085. > In `/skills`, press `Space` to cycle a skill's visibility (saved as `skillOverrides` in `.claude/settings.local.json`); `/skill-doctor` shows unused skills and their context cost. Your own skill named `verify` (or `simplify`) runs right before each commit, except docs- or tests-only changes, so put pre-commit checks there.
  1086. <h3 id="create-skill">Create a Skill</h3>
  1087. ```bash
  1088. # Create skill directory
  1089. mkdir -p ~/.claude/skills/explain-code
  1090. # Optional: scaffold a personal skills-directory plugin (a separate layout)
  1091. claude plugin init explain-tools --with skills
  1092. ```
  1093. `claude plugin init` writes under `~/.claude/skills/<name>/` and adds a plugin manifest; it does not scaffold in the current project.
  1094. Create `~/.claude/skills/explain-code/SKILL.md`:
  1095. ```markdown
  1096. ---
  1097. name: explain-code
  1098. description: Explains code with visual diagrams and analogies. Use when explaining how code works.
  1099. ---
  1100. When explaining code, always include:
  1101. 1. **Start with an analogy**: Compare the code to something from everyday life
  1102. 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships
  1103. 3. **Walk through the code**: Explain step-by-step what happens
  1104. 4. **Highlight a gotcha**: What's a common mistake or misconception?
  1105. ```
  1106. **Use the skill:**
  1107. ```bash
  1108. # Let Claude invoke automatically
  1109. How does this code work?
  1110. # Or invoke directly
  1111. /explain-code src/auth/login.ts
  1112. ```
  1113. <h3 id="skill-frontmatter">Skill Frontmatter Fields</h3>
  1114. | Field | Required | Description |
  1115. | :------------------------- | :---------- | :---------------------------------------------------------- |
  1116. | `name` | No | Command name shown in the `/` menu (uses directory name if omitted) |
  1117. | `description` | Recommended | What the skill does and when to use it |
  1118. | `when_to_use` | No | Extra trigger phrases or examples, appended to `description` (1,536-character combined cap) |
  1119. | `argument-hint` | No | Hint shown during autocomplete (e.g., `[filename]`) |
  1120. | `arguments` | No | Named positional arguments for `$name` substitution (e.g., `[issue, branch]`) |
  1121. | `disable-model-invocation` | No | Set `true` to prevent Claude from auto-invoking |
  1122. | `user-invocable` | No | Set `false` to hide from / menu |
  1123. | `allowed-tools` | No | Tools allowed without asking for the turn that invokes the skill. Not gated by workspace trust, so review it in cloned repos |
  1124. | `disallowed-tools` | No | Tools removed from the model while the skill is active |
  1125. | `model` | No | Model to use when this skill is active |
  1126. | `effort` | No | Effort override while the skill is active |
  1127. | `context` | No | Set to `fork` to run in a forked subagent context |
  1128. | `agent` | No | Which subagent to use when `context: fork` is set |
  1129. | `background` | No | With `context: fork`, defaults to `true`; set `false` to wait for the result |
  1130. | `hooks` | No | Hooks registered on invocation that stay active for the rest of the session (`once: true` removes a hook after its first successful run) |
  1131. | `paths` | No | Glob patterns limiting automatic activation to matching files |
  1132. | `shell` | No | `bash` (default) or `powershell` for dynamic shell context |
  1133. <h3 id="skill-arguments">Pass Arguments to Skills</h3>
  1134. Use `$ARGUMENTS` placeholder to receive arguments:
  1135. ```markdown
  1136. ---
  1137. name: fix-issue
  1138. description: Fix a GitHub issue
  1139. disable-model-invocation: true
  1140. ---
  1141. Fix GitHub issue $ARGUMENTS following our coding standards.
  1142. 1. Read the issue description
  1143. 2. Implement the fix
  1144. 3. Write tests
  1145. 4. Create a commit
  1146. ```
  1147. **Usage:** `/fix-issue 123`
  1148. Use `$0`, `$1`, ... (or `$ARGUMENTS[N]`) for positional arguments and `$name` for names declared in `arguments`. `${CLAUDE_SKILL_DIR}` (the skill's folder, for bundled scripts), `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_SESSION_ID}`, and `${CLAUDE_EFFORT}` are also substituted.
  1149. <h3 id="skill-dynamic-context">Inject Dynamic Context</h3>
  1150. Use `` !`command` `` syntax to run shell commands before the skill content is sent to Claude:
  1151. ```markdown
  1152. ---
  1153. name: pr-summary
  1154. description: Summarize changes in a pull request
  1155. context: fork
  1156. agent: Explore
  1157. allowed-tools: Bash(gh *)
  1158. ---
  1159. ## Pull request context
  1160. - PR diff: !`gh pr diff`
  1161. - PR comments: !`gh pr view --comments`
  1162. - Changed files: !`gh pr diff --name-only`
  1163. ## Your task
  1164. Summarize this pull request...
  1165. ```
  1166. > Injected commands never prompt: one that isn't already allowed (by `allowed-tools`, an allow rule, or the read-only set) aborts the skill with `Shell command permission check failed`, hence `allowed-tools` above. Auto mode instead has Claude run it as a reviewed tool call, except in a forked skill that sets `agent`. For multi-line commands, open a fenced block with `` ```! ``.
  1167. <h3 id="skill-subagent">Run Skills in a Subagent</h3>
  1168. Add `context: fork` to run a skill in isolation:
  1169. ```markdown
  1170. ---
  1171. name: deep-research
  1172. description: Research a topic thoroughly
  1173. context: fork
  1174. agent: Explore
  1175. ---
  1176. Research $ARGUMENTS thoroughly:
  1177. 1. Find relevant files using Glob and Grep
  1178. 2. Read and analyze the code
  1179. 3. Summarize findings with specific file references
  1180. ```
  1181. > The `agent` field can be `Explore`, `Plan`, `general-purpose`, or any custom subagent from `.claude/agents/`.
  1182. > Forked skills run in the background by default as of v2.1.218. Add `background: false` when the invoking turn must wait or the skill needs a foreground-only tool.
  1183. ---
  1184. <h2 id="plugin-system">Plugin System</h2>
  1185. > [!Note]
  1186. > **Plugins package skills, agents, hooks, MCP and LSP servers, output styles, workflows, executables, and mods that change Claude Code's own behavior and interface. Experimental plugin components also include monitors and themes. The official marketplace is registered automatically unless policy disables it.**
  1187. **Key commands:**
  1188. ```bash
  1189. claude plugin init my-plugin
  1190. /plugin # Open the plugin manager
  1191. /plugin marketplace add <owner>/<repo> # Or a git URL, local path, or marketplace.json URL
  1192. /plugin install code-review@claude-plugins-official # Opens its details; pick a scope to install
  1193. /plugin install <plugin> --marketplace <source> # Adds the marketplace first if needed
  1194. /plugin list
  1195. /plugin enable <plugin>@<marketplace>
  1196. /plugin disable <plugin>@<marketplace>
  1197. /plugin configure <plugin>@<marketplace> # Set the plugin's options
  1198. /reload-plugins # Apply changes made outside the /plugin panel
  1199. # CLI equivalents for scripting and development
  1200. claude plugin marketplace add <source>
  1201. claude plugin install <plugin>@<marketplace> --scope project
  1202. claude plugin update <plugin>@<marketplace>
  1203. claude plugin configure <plugin>@<marketplace> --values-stdin < values.json
  1204. claude plugin validate ./my-plugin --strict # --json for a machine-readable report
  1205. claude plugin eval ./my-plugin # Run the plugin's eval suite
  1206. ```
  1207. **Plugin structure:**
  1208. ```
  1209. my-plugin/
  1210. ├── .claude-plugin/
  1211. │ └── plugin.json # Optional manifest; name is required when present
  1212. ├── agents/ # Custom agents (*.md frontmatter files)
  1213. ├── skills/ # Custom skills (SKILL.md files)
  1214. ├── hooks/
  1215. │ └── hooks.json # Hooks under a top-level "hooks" key; a "modules" entry makes it a mod
  1216. ├── commands/ # Legacy flat command format
  1217. ├── output-styles/ # Output styles, listed as <plugin>:<name>
  1218. ├── workflows/ # Workflow .js files
  1219. ├── bin/ # Executables on the Bash tool's PATH while enabled
  1220. ├── settings.json # Only agent and subagentStatusLine take effect
  1221. ├── .mcp.json # MCP server definitions
  1222. ├── .lsp.json # LSP server definitions
  1223. ├── monitors/ # Experimental background monitors
  1224. └── themes/ # Experimental themes
  1225. ```
  1226. **Plugin scopes:**
  1227. | Scope | Recorded in | Notes |
  1228. | :---- | :---------- | :---- |
  1229. | `--plugin-dir ./path` or `--plugin-url <zip-url>` | Session only | Development load as `<name>@inline`; not persisted |
  1230. | `user` | `~/.claude/settings.json` | Personal; default install scope |
  1231. | `project` | `.claude/settings.json` | Shared with the repository; collaborators still approve/install |
  1232. | `local` | `.claude/settings.local.json` | Private to this project |
  1233. | `managed` | Managed settings | Organization-controlled and read-only |
  1234. Plugins you or your organization turn on at claude.ai sync to terminal sessions signed in with that account as `<name>@synced`. Turn one off in `/plugin` (unless your organization requires it) or stop syncing with `"syncClaudeAiPlugins": false`.
  1235. Managed marketplace policy accepts `"owner/*"` entries in both `strictKnownMarketplaces` and `blockedMarketplaces` to allow or block every marketplace repository under a GitHub owner.
  1236. As of v2.1.224, marketplace entries can use an `archive` source to install a zip over HTTPS without git or npm. Add the optional 64-character `sha256` digest to pin the exact archive and make Claude Code reject a mismatched download. npm sources must be registry packages or `https` tarball links (git repositories and folders are refused) and are fetched with `npm pack --ignore-scripts`, so install scripts don't run.
  1237. **Plugin manifest (`.claude-plugin/plugin.json`):**
  1238. ```json
  1239. {
  1240. "name": "my-plugin",
  1241. "version": "1.0.0",
  1242. "description": "A Claude Code plugin",
  1243. "defaultEnabled": false,
  1244. "agents": ["./custom-agents/reviewer.md"],
  1245. "skills": ["./extra-skills/"],
  1246. "hooks": "./config/extra-hooks.json",
  1247. "dependencies": ["required-plugin", { "name": "secrets-vault", "version": "~2.1.0" }]
  1248. }
  1249. ```
  1250. The manifest is optional when all components use default locations; include it for metadata, dependencies, custom component paths, or default enablement. Add component keys only for non-default paths: `agents` lists `.md` files (not directories) and replaces the `agents/` scan, while `skills`, `hooks`, `mcpServers`, and `lspServers` add to their defaults. Project-declared plugins and skills-directory plugins are gated by workspace trust and user consent rather than silently installing executable components.
  1251. > Auto-update is on by default only for most official Anthropic marketplaces (such as `claude-plugins-official`) and marketplaces added from claude.ai; turn it on for community, third-party, and local marketplaces in `/plugin` → **Marketplaces**. Set `FORCE_AUTOUPDATE_PLUGINS=1` to force updates even when the main updater is disabled, or override with `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` for slow repos. Clones leave Git LFS files as pointers (`skipLfs` is no longer needed); run `git lfs pull` in the checkout if a plugin needs the real files.
  1252. Dependency behavior:
  1253. - `claude plugin enable` enables transitive dependencies automatically.
  1254. - `claude plugin disable` refuses when another enabled plugin depends on the target and reports the disable chain.
  1255. - `defaultEnabled: false` lets a plugin ship installed but disabled until the user explicitly enables it.
  1256. **Claude Mods:**
  1257. A mod is a plugin whose `hooks/hooks.json` lists a JavaScript or TypeScript module under `modules`. Its handlers run inside Claude Code, so a mod can draw panes and bands, add commands and tools, guard or rewrite tool calls (`tool.call`) and prompts (`prompt.submit`), and step in when agents spawn (`agent.spawn`). See the [mods docs](https://code.claude.com/docs/en/plugins/mods/overview).
  1258. - Ask Claude to build one: the built-in `plugin-authoring` skill writes it and, when you ask how to share it, gives the one command others run to install it. Test your own with `claude plugin test ./my-mod`.
  1259. - Before installing someone else's mod, run `claude plugin validate ./some-mod` to list the events it hooks and what it calls.
  1260. - The built-in **You should know** mod is a side agent that flags things you or Claude might miss. Turn it on with `/plugin enable cc-plugin-you-should-know@builtin` (first-party sessions with telemetry on).
  1261. > [!WARNING]
  1262. > Mods aren't sandboxed. They run with your permissions, can read your files and secrets, can see and rewrite prompts and tool calls, and can approve tool calls. Install them only from authors and marketplaces you trust. `claude --safe-mode` turns installed mods off for one session; `"disableAllHooks": true` in `~/.claude/settings.json` turns them off everywhere, along with your settings hooks.
  1263. ---
  1264. <h2 id="worktree-isolation">Worktree Isolation</h2>
  1265. > [!Note]
  1266. > **The `--worktree` (`-w`) flag starts Claude in an isolated git worktree, allowing it to make changes in a separate branch without affecting your working directory.**
  1267. **Usage:**
  1268. ```bash
  1269. # Start Claude in an isolated worktree
  1270. claude -w feature-auth
  1271. # Claude will:
  1272. # 1. Create .claude/worktrees/feature-auth/ on a new worktree-feature-auth branch from the configured base ref
  1273. # 2. Run in that isolated worktree
  1274. # 3. Keep edits and Bash commands isolated from the original checkout
  1275. # 4. On exit, offer to keep or remove it (clean worktrees of unnamed sessions are removed automatically)
  1276. # Branch from a PR: quote "#1234", or pass a GitHub PR or GitLab MR URL
  1277. claude -w "#1234"
  1278. ```
  1279. Add `.claude/worktrees/` to `.gitignore`. A worktree is a fresh checkout, so list gitignored files it needs, such as `.env`, in a `.worktreeinclude` file (`.gitignore` syntax) at the project root to copy them in.
  1280. Choose the branch source in settings:
  1281. ```json
  1282. {
  1283. "worktree": {
  1284. "baseRef": "fresh"
  1285. }
  1286. }
  1287. ```
  1288. `fresh` (the default) uses `origin/<default-branch>`; `head` uses the current local `HEAD`. Claude automatically removes a subagent worktree only when it made no changes. Background sessions commit **and** push completed work to preserve it, and create a draft PR only when the task explicitly calls for one; do not assume every worktree is automatically published or deleted.
  1289. For repositories where worktrees are impractical, `worktree.bgIsolation: "none"` lets background sessions edit the working copy directly without `EnterWorktree`. In large repositories, `worktree.symlinkDirectories` (for example `["node_modules", ".cache"]`) symlinks directories from the main checkout instead of duplicating them, and `worktree.sparsePaths` checks out only the listed directories (include `.claude` to keep project settings and rules).
  1290. **Agent-level worktree isolation:**
  1291. ```markdown
  1292. ---
  1293. name: background-coder
  1294. description: Implements features in isolation
  1295. isolation: worktree
  1296. background: true
  1297. ---
  1298. Implement the requested feature in this isolated worktree.
  1299. ```
  1300. > Subagents already run in the background by default; `background: true` keeps this one there even when Claude would wait for it. With `isolation: worktree`, multiple agents can work on separate features simultaneously.
  1301. ---
  1302. <h2 id="native-installer">Native Installer</h2>
  1303. > [!Note]
  1304. > **The native installer is the recommended installation path. It starts faster, updates itself, and does not depend on Node.js being on your PATH.**
  1305. ```bash
  1306. # Install the stable native build from an existing Claude Code installation
  1307. claude install stable
  1308. # Other supported targets
  1309. claude install latest
  1310. claude install <version>
  1311. # Check for and install an update
  1312. claude update
  1313. ```
  1314. Running `claude install` from an npm-based installation replaces it with the native build; the old `migrate-installer` command has been removed. Homebrew, WinGet, and the `apt`, `dnf`, and `apk` repositories update through their package managers. npm remains supported for compatibility, but Claude Code v2.1.198 and later require Node.js 22 or newer. If an npm 12 install leaves `claude` printing `Error: claude native binary not installed`, see [Installation / Node.js Issues](#installation--nodejs-issues).
  1315. See the [official setup guide](https://code.claude.com/docs/en/setup) for the current platform-specific installers.
  1316. ---
  1317. <h2 id="claude-auth">Authentication CLI</h2>
  1318. > [!Note]
  1319. > **Manage authentication directly from the CLI without entering the REPL.**
  1320. ```bash
  1321. # Log in to your Anthropic account
  1322. claude auth login
  1323. # Check current authentication status (JSON by default, --text for readable output; exits 1 when logged out)
  1324. claude auth status
  1325. # Log out
  1326. claude auth logout
  1327. # Print a one-year subscription OAuth token for CI and scripts (not saved)
  1328. claude setup-token
  1329. ```
  1330. Supply the `setup-token` output as `CLAUDE_CODE_OAUTH_TOKEN`; [Initial Setup](#initial-setup) covers its plan requirements and limits.
  1331. ---
  1332. <h2 id="claude-agents-cli">Agent Management CLI</h2>
  1333. > [!Note]
  1334. > **`claude agents` manages live interactive and background sessions. It does not list the Markdown subagent definitions in `.claude/agents/`.**
  1335. ```bash
  1336. # Open the interactive background-agent view
  1337. claude agents
  1338. # Script active sessions; include completed sessions with --all
  1339. claude agents --json
  1340. claude agents --json --all
  1341. # Start a prompt as a background session (in an untrusted folder it asks for trust, or exits if it can't ask)
  1342. claude --bg "review this branch and report the findings"
  1343. # Manage a background session by ID (attach and logs also accept part of its name)
  1344. claude attach <id|name>
  1345. claude logs <id|name>
  1346. claude stop <id>
  1347. claude respawn <id>
  1348. claude rm <id>
  1349. # Use a custom subagent definition for a foreground session
  1350. claude --agent code-reviewer "review the current branch"
  1351. ```
  1352. `stop` keeps the conversation so it can be attached again. `rm` removes the session from agent view and deletes its worktree when that is safe; if the worktree has unpushed commits or can't be removed, `rm` refuses and prints the flag to pass on a second `rm`. The transcript stays on disk and resumable with `claude --resume`; use `claude purge [path]` (`--dry-run` to preview) only when you intend to delete a project's local transcripts and state; it doesn't touch anything stored by Anthropic. Options such as `--agent`, `--model`, `--effort`, and `--permission-mode` on `claude agents` set defaults for sessions dispatched from that view; inside it, `/model`, `/effort`, and `/fast` do the same.
  1353. Claude can use `ListAgents` and `SendMessage` to find and message your other sessions on the same machine (macOS, Linux including WSL 2, and Windows, with any provider). While connected to Remote Control, it can also start conversations with your Remote Control sessions on other machines and message your cloud sessions, which receive messages but can't reply; set `isolatePeerMachines: true` to approve each message before it leaves the machine. Without an explicit `crossSessionInbound` policy, same-class permission modes deliver automatically while messages between bypassed and non-bypassed sessions are held for approval; `dialogExpiry` controls when held dialogs expire.
  1354. ---
  1355. <h2 id="remote-control">Remote Control</h2>
  1356. > [!Note]
  1357. > **Remote Control lets claude.ai/code or the Claude mobile app control Claude Code processes that continue running on your machine. It is not a headless SDK or CI transport.**
  1358. ```bash
  1359. # Start a persistent local Remote Control server in this directory
  1360. claude remote-control
  1361. # Give the server a recognizable name
  1362. claude remote-control --name my-workstation
  1363. # Isolate on-demand sessions in git worktrees
  1364. claude remote-control --spawn worktree
  1365. # Bring back a session after stopping the server (works for about four hours)
  1366. claude remote-control --continue # the session the server started with
  1367. claude remote-control --session-id <id> # one session by ID
  1368. # Enable Remote Control on a normal interactive session
  1369. claude --remote-control
  1370. # Connect or disconnect the current interactive session
  1371. /remote-control
  1372. ```
  1373. The server pre-creates a session and can accept multiple concurrent sessions. The default `same-dir` spawn mode shares the current checkout; use `--spawn worktree` when concurrent sessions need isolated files, or `--spawn session` for the classic single-session lifecycle. Pressing `w` while the server runs switches between `same-dir` and `worktree` and saves the choice as that folder's default. The local process must stay running.
  1374. Remote Control requires a claude.ai sign-in on a Pro, Max, Team, or Enterprise plan; on Team and Enterprise, an Owner must first enable it in admin settings. It is unavailable with API-key auth, Bedrock, Google Cloud's Agent Platform, Foundry, an `ANTHROPIC_BASE_URL` other than `api.anthropic.com`, a Claude apps gateway sign-in, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or `DISABLE_GROWTHBOOK` set. In an untrusted folder, `claude remote-control` asks for trust before starting and exits with `Workspace not trusted` when it can't ask, so trust the folder first for unattended starts. `remoteControlAtStartup` can be enabled only in user or managed settings; project settings may disable it but cannot turn it on. See the [Remote Control guide](https://code.claude.com/docs/en/remote-control).
  1375. ---
  1376. <h2 id="managed-settings">Managed Settings</h2>
  1377. > [!Note]
  1378. > **Enterprise administrators can enforce organization-wide settings through server-managed policy, MDM/registry policy, or a system-level `managed-settings.json`.**
  1379. **macOS (plist):**
  1380. Settings can be deployed via MDM profiles to `/Library/Managed Preferences/com.anthropic.claudecode.plist`.
  1381. **Windows (Registry):**
  1382. Settings can be deployed via Group Policy as JSON in a `REG_SZ` (or `REG_EXPAND_SZ`) value named `Settings` under `HKLM\SOFTWARE\Policies\ClaudeCode`. The same value under user-writable `HKCU\SOFTWARE\Policies\ClaudeCode` is only a fallback, ignored whenever an admin policy (HKLM or a managed settings file) is present, even an invalid one.
  1383. **Filesystem policy:**
  1384. - macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`
  1385. - Linux/WSL: `/etc/claude-code/managed-settings.json`
  1386. - Windows: `C:\Program Files\ClaudeCode\managed-settings.json`
  1387. To split a file-based policy between teams, add `*.json` drop-ins to a `managed-settings.d/` directory beside it. Claude Code merges the main file first, then the drop-ins alphabetically (name them like `10-telemetry.json`): later single values win, lists combine, and nested blocks merge key by key. The legacy `C:\ProgramData\ClaudeCode\` path is not read.
  1388. Managed settings take precedence over command-line, local, project, and user settings and cannot be overridden by individual users. Machine-local policy environment variables merge per key with server-delivered settings rather than being discarded wholesale.
  1389. When several managed sources reach a machine, Claude Code by default (`managedSourcesBehavior: "first-wins"`) uses only the highest-ranked one that sets a policy key (remote settings from claude.ai or a Claude apps gateway, then MDM plist or HKLM, then `managed-settings.json` and drop-ins), apart from a few keys such as `env` that it reads from every source. Set `"managedSourcesBehavior": "merge"` in the top source to combine them; `/status` shows the source in use and any `Skipped sources`. A managed file, drop-in, plist, or HKLM value that isn't a valid JSON object stops Claude Code from starting, so validate policy JSON before you deploy it.
  1390. **Commonly enforced policy keys:**
  1391. - `allowedProviders` limits which API providers a machine may use, for example `["anthropic", "bedrock"]`.
  1392. - `deniedModels` blocks specific models even when `availableModels` allows them; `availableModelsMatch: "exact"` makes each `availableModels` ID allow only the version it names, so new releases stay blocked until listed (both managed-only).
  1393. - `modelPricing` makes cost figures in `/usage`, the status line, and telemetry use your contracted rates instead of list price.
  1394. - `managedMcpServers` gives every user a set of HTTP/SSE MCP servers alongside their own. `allowedMcpServers` now governs only servers users add, so a `managed-mcp.json` server it used to filter out loads after an upgrade; list it in `deniedMcpServers` to keep it off.
  1395. ---
  1396. <h2 id="model-updates">Model Updates</h2>
  1397. ### Model Guidance
  1398. > [!Note]
  1399. > **Prefer aliases for interactive work and pin a full provider model ID only when reproducibility matters. Alias mappings vary by account, organization policy, provider, region, and Claude Code version.**
  1400. | Alias | Current intent |
  1401. | :---- | :------------- |
  1402. | `default` | Account- and policy-appropriate default (currently Opus 5.5 everywhere except Microsoft Foundry, which uses Sonnet 4.5) |
  1403. | `best` | The model `fable` resolves to when Fable is available to you, otherwise the same model as `opus` |
  1404. | `fable` | Fable 5.1 (`claude-fable-5-1`); Fable 5 in Claude apps gateway sessions |
  1405. | `opus` | Newest allowed Opus (currently Opus 5.5 on the Anthropic API) |
  1406. | `sonnet` | Newest allowed Sonnet (currently Sonnet 5.5 on the Anthropic API) |
  1407. | `haiku` | Newest allowed Haiku (currently Haiku 5.5 on the Anthropic API) |
  1408. | `sonnet[1m]`, `opus[1m]` | 1M-context variants for models without a native 1M window; no effect on Sonnet 5+ or Opus 4.7+, which already have one |
  1409. | `opusplan` | Opus for planning, then Sonnet for execution |
  1410. **Use in Claude Code:**
  1411. ```bash
  1412. # Select for this launch
  1413. claude --model sonnet
  1414. claude --model opus
  1415. # Inside a session; normally also saves the user default
  1416. /model sonnet
  1417. # Set a default from the prompt
  1418. /config model=sonnet
  1419. # Pin only when you need exact reproducibility
  1420. claude --model <full-model-id>
  1421. # Try up to three fallbacks in order (works interactively too; persist a chain with the fallbackModel setting)
  1422. claude -p --model opus --fallback-model "sonnet,haiku" "review this diff"
  1423. ```
  1424. Model selection tips:
  1425. - `/model` is the primary interactive selector; use its session-only option when you do not want to change the saved user default.
  1426. - `ANTHROPIC_MODEL` and the `model` setting provide non-interactive defaults. `ANTHROPIC_DEFAULT_MODEL` only sets the model new sessions start on, so `--model`, `ANTHROPIC_MODEL`, a `model` setting, or a saved `/model` pick overrides it. Provider deployments can map family aliases with `ANTHROPIC_DEFAULT_FABLE_MODEL`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL`; `ANTHROPIC_SMALL_FAST_MODEL` is deprecated.
  1427. - Set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` only when a compatible gateway exposes `/v1/models`; discovery can expose provider-prefixed IDs, and `CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS` extends its 3-second timeout. In `modelOverrides`, keys must be canonical Anthropic model IDs and provider/upstream IDs belong on the value side—non-Anthropic keys are ignored.
  1428. - Fast mode is a separate latency/cost toggle and currently supports Opus 5.5 (the default), Opus 5, and Opus 4.8 (the last two in research preview); auto mode is a separate permission mode and no longer needs an opt-in environment variable.
  1429. - `availableModels` restricts which models users can select; `modelPicker` (user or managed settings) adds labeled entries, such as provider-specific IDs, to the `/model` picker or replaces its lineup. See [Managed Settings](#managed-settings) for managed-only model controls.
  1430. Check the [official model configuration reference](https://code.claude.com/docs/en/model-config) before pinning a provider-specific ID.
  1431. ---
  1432. <h2 id="theming--customization">Theming & Customization</h2>
  1433. Claude Code supports built-in themes, custom named themes, and session accent colors.
  1434. ```bash
  1435. /theme # Pick a theme or create a custom one
  1436. /color # Pick a random session accent color
  1437. /color purple # red, blue, green, yellow, purple, orange, pink, or cyan
  1438. /color default # Reset to the theme's color
  1439. ```
  1440. Custom themes can be edited as JSON under `~/.claude/themes/`, and plugins can ship themes for teams. The `Auto (match terminal)` theme follows terminal light/dark mode where supported.
  1441. **Output styles** set Claude's tone, response format, and working style for a session. `/output-style` lists them and `/output-style concise` switches (also under `/config`); the choice is saved to `.claude/settings.local.json`. Built-ins are Proactive, Concise, Explanatory, and Learning; custom styles are Markdown files in `~/.claude/output-styles/` or `.claude/output-styles/`, and plugins can ship them. `maxProseWidth` caps prose width in wide terminals while tables and code blocks keep the full width.
  1442. **Status line:** `/statusline show model, git branch and context % as a bar` has Claude Code write a script under `~/.claude/` and add it to your settings; with no argument it builds one from your shell prompt. To configure it yourself:
  1443. ```json
  1444. {
  1445. "statusLine": { "type": "command", "command": "~/.claude/statusline.sh", "padding": 2 }
  1446. }
  1447. ```
  1448. The command receives session JSON on stdin, such as `model.display_name`, `context_window.used_percentage`, `cost.total_cost_usd`, `rate_limits`, and `prompt_cache`, and prints the line to show. A custom status line hides most footer hints, including `esc to interrupt`, and stays blank until you trust the folder. See [Customize your status line](https://code.claude.com/docs/en/statusline).
  1449. ---
  1450. <h2 id="code-review">Code Review</h2>
  1451. Claude Code has separate review paths for correctness, cleanup, and broader branch-level review.
  1452. | Command | Behavior |
  1453. | :------ | :--------------- |
  1454. | `/code-review [level] [--fix] [--comment] [--max-findings <n>\|all\|default] [target]` | Background correctness review of the current diff, or of a PR number, branch, or path; remembers the last level and `--max-findings` choice |
  1455. | `/review ...` | Alias of `/code-review` |
  1456. | `/code-review --fix` | Applies review findings to the working tree, including reuse/simplification/efficiency suggestions |
  1457. | `/code-review --comment` | Posts findings as inline comments on the GitHub PR, or as a single note on a GitLab merge request through `glab` |
  1458. | `/simplify` | Cleanup-only review for reuse, simplification, efficiency, and altitude |
  1459. | `/code-review ultra [target]` or `/ultrareview [target]` | Cloud review in which a fleet of agents finds and independently verifies bugs; needs a claude.ai login; 3 one-time free runs on Pro and Max, then usage credits (typically \$5 to \$25 per review) |
  1460. | `claude ultrareview [target]` | Non-interactive CI/script entrypoint; waits for findings (`--timeout`, default 45 minutes) and supports `--json` and `--post` (one comment on a github.com PR). Requires workspace trust: in CI, append `--trust-workspace` after any PR number or base branch |
  1461. Use `/code-review` for local correctness review, `/simplify` for cleanup, and `/ultrareview` when you want a broader cloud review of a branch or PR.
  1462. For automatic GitHub PR reviews, Team and Enterprise organizations can use the managed [Code Review](https://code.claude.com/docs/en/code-review) service: an Owner installs the Claude GitHub App and sets when reviews run and the review level (Quick, Standard, or Deep, optionally per repository). Findings arrive as inline comments with a check run; put review-only guidance in `REVIEW.md`. Anyone with write access can comment `@claude review` (one review), `@claude review always` (also review later pushes), or `@claude review stop`.
  1463. ---
  1464. <h2 id="insights">Claude Code Insights</h2>
  1465. > [!Note]
  1466. > **The `/insights` command generates an interactive HTML report analyzing your recent Claude Code sessions on this machine.**
  1467. **Run Insights:**
  1468. ```bash
  1469. # In Claude Code terminal
  1470. /insights
  1471. # Open the generated report
  1472. start ~/.claude/usage-data/report.html # Windows
  1473. open ~/.claude/usage-data/report.html # Mac
  1474. xdg-open ~/.claude/usage-data/report.html # Linux
  1475. ```
  1476. Each run analyzes up to 200 sessions it hasn't seen before (skipping very short ones), keeps a timestamped copy beside `report.html`, and uses your usual provider and account, so it counts against your plan or API usage. Reports are deleted after `cleanupPeriodDays` (30 days by default). Not available in cloud sessions.
  1477. **How It Works:**
  1478. 1. **Session Collection** - Pulls session logs from `~/.claude/projects/`, filters agent sub-sessions and short sessions
  1479. 2. **Metadata Extraction** - Extracts duration, token usage, tools used, languages detected, git activity
  1480. 3. **Facet Extraction** - Uses Claude (the default Opus model, or the session model where the account can't reach it) to analyze transcripts and identify goals, satisfaction signals, friction points
  1481. 4. **Report Generation** - Creates interactive HTML report with personalized suggestions
  1482. **Report Sections:**
  1483. | Section | Description |
  1484. | :-------------------- | :---------------------------------------------------------- |
  1485. | **What's Working** | Your strengths and successful patterns |
  1486. | **What's Hindering** | Where Claude struggled or where you caused friction |
  1487. | **Friction Analysis** | Breakdown of problem areas with specific examples |
  1488. | **Stats Dashboard** | Tool usage, language breakdown, coding time distribution |
  1489. | **Quick Wins** | Copy-paste suggestions for CLAUDE.md improvements |
  1490. | **Features to Try** | Personalized recommendations (skills, hooks, headless mode), plus an estimate of permission prompts auto mode could have handled |

Lines 2,001–3,073 are not shown. The link to the file on GitHub has every line.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.