
Claude Code Deep Dive: The Complete Guide to Anthropic's Agentic Coding Tool
Claude Code is Anthropic’s agentic coding tool. It reads your codebase, edits files, runs shell commands, and talks to the services you already use. Most people meet it as a terminal program, but the same engine also runs inside VS Code, JetBrains IDEs, a desktop app, the web, Slack, and CI pipelines.
This guide is both a reference and a field manual. Every fact comes from the official documentation, which I checked on October 3, 2026, against the 2.1 release line. Claude Code ships updates almost every week, so treat version numbers, prices, and model names as a snapshot. Confirm anything critical with /release-notes or the docs before you depend on it.
If you want a wider comparison with Cursor, Codex, and other tools, start with my guide to AI-powered IDEs. This article goes much deeper on one tool. I suggest reading sections 1 to 8 in order, then jumping to whatever you need.
Table of Contents
- What Claude Code Actually Is
- Where You Can Run It
- Installation, Requirements, and Updates
- Your First Session
- Models, Effort, and Speed
- Memory, Rules, and Project Instructions
- Permissions and Safety
- Managing Context
- Settings and Configuration
- Extending Claude Code
- Working in Parallel
- Automation and CI
- Review, Security, and Privacy
- Costs and Usage
- Commands and Shortcuts Cheat Sheet
- Best Practices and Failure Patterns
- Troubleshooting
- Frequently Asked Questions
- Conclusion
- References
If you are short on time, jump to the quick reference card and come back to the details later.
Quick Reference Card
Snapshot note: model names, prices, and defaults below reflect the official documentation on October 3, 2026.
Start, resume, and parallelize
claude # start in the current directory
claude -p "prompt" # one-shot, non-interactive
claude -c # continue the latest conversation here
claude -r "name" # resume a named session
claude --worktree name # isolated git worktree session
claude agents # watch background sessions
Twelve commands worth memorizing
| Command | Use it to |
|---|---|
/init |
Generate a starter CLAUDE.md |
/memory |
Edit CLAUDE.md files and auto memory |
/model |
Switch models |
/effort |
Set reasoning effort |
/plan |
Enter plan mode |
/context |
See what fills the context window |
/compact |
Summarize the conversation to free space |
/clear |
Start fresh between unrelated tasks |
/rewind |
Undo code, conversation, or both |
/permissions |
Manage allow, ask, and deny rules |
/doctor |
Run a setup checkup |
/usage |
See cost and plan limits |
Permission modes (press Shift+Tab to cycle): Manual (default), acceptEdits, plan, auto, dontAsk, and bypassPermissions.
Model aliases: opus, sonnet, haiku, fable, best, opusplan, sonnet[1m], and opus[1m].
Three keys: Shift+Tab changes the permission mode, Esc stops Claude, and pressing Esc twice on an empty prompt opens the rewind menu.
1. What Claude Code Actually Is
Claude Code is an agentic assistant that lives in your terminal. It excels at coding, but it can help with anything you can do from a command line: writing docs, running builds, searching files, and researching topics.
The agentic loop
When you give Claude a task, it works through three phases: gather context, take action, and verify results. The phases blend together, and Claude chains dozens of actions while adjusting to what each step reveals. A question about your code might need only the first phase. A bug fix cycles through all three phases several times.
You are part of the loop. Press Esc to stop Claude immediately and redirect it. You can also type a correction and press Enter while Claude works, and it reads your message as soon as its current tool calls finish.
Two components power the loop. Models do the reasoning, and tools do the acting. Claude Code is the layer around the model that supplies the tools and manages the context the model sees, which is why people call it an agentic harness.
Built-in tools
Without tools, Claude can only answer with text. With tools, it can read your code, edit files, run commands, search the web, and talk to external services. Every tool result feeds back into the loop and shapes the next decision. The built-in tools fall into five categories.
| Category | What Claude can do |
|---|---|
| File operations | Read files, edit code, create new files, rename and reorganize |
| Search | Find files by pattern, search content with regex, explore codebases |
| Execution | Run shell commands, start servers, run tests, use git |
| Web | Search the web, fetch documentation, look up error messages |
| Code intelligence | See type errors after edits, jump to definitions, find references (needs a code intelligence plugin) |
The exact tool names matter because you use them in permission rules, subagent tool lists, and hook matchers. These are the ones you will meet most often.
| Tool | What it does | Asks permission in Manual mode |
|---|---|---|
Read |
Reads file contents | No |
Edit |
Makes targeted edits to files | Yes |
Write |
Creates or overwrites files | Yes |
Bash |
Runs shell commands (a built-in read-only set runs without prompts) | Yes |
PowerShell |
Runs PowerShell commands natively | Yes |
Glob, Grep |
Find files by pattern and search file contents; absent by default on macOS, Linux, and WSL | No |
WebFetch, WebSearch |
Fetch a URL or search the web | Yes |
Agent |
Spawns a subagent with its own context window | No |
Skill |
Runs a skill inside the main conversation | Yes |
LSP |
Language-server navigation and diagnostics | No |
Monitor |
Runs a command in the background and feeds each output line back to Claude | Yes |
NotebookEdit |
Edits Jupyter notebook cells | Yes |
AskUserQuestion |
Asks you multiple-choice questions | No |
EnterPlanMode |
Switches to plan mode | No |
Workflow |
Runs a dynamic workflow that orchestrates many subagents | Yes |
Artifact |
Publishes an HTML or Markdown file as a private page on claude.ai | Yes |
ToolSearch |
Loads deferred tools on demand | No |
Two details are worth knowing. On macOS, Linux, and WSL, Glob and Grep are left out of the default tool set, but search still works. Claude searches with find and grep through the Bash tool, and in Claude’s shell those commands run embedded versions of bfs and ugrep. Those searches reach your hooks and permission rules as Bash calls. Naming Glob or Grep in --tools or --allowedTools at launch brings the tools back, and on Windows they are part of the default set. The Grep tool itself is built on ripgrep. The old TodoWrite checklist is also disabled by default in favor of the TaskCreate, TaskGet, TaskList, and TaskUpdate tools, which ship by default only on certain models.
What Claude can access
When you run claude in a directory, Claude Code gains access to the following:
- Your project: Files in the directory and its subdirectories, plus files elsewhere when you give permission.
- Your terminal: Any command you could run yourself, including build tools, git, package managers, and scripts.
- Your git state: The current branch, uncommitted changes, and recent commit history.
- Your CLAUDE.md files: Project instructions that load at the start of every session.
- Auto memory: Notes Claude saves for itself. The first 200 lines or 25KB of
MEMORY.md, whichever comes first, load at session start. - Your extensions: MCP servers, skills, subagents, plugins, and Claude in Chrome.
Because Claude sees the whole project, it can work across it. Ask it to fix an authentication bug, and it searches for the relevant files, reads several of them, makes coordinated edits, runs the tests, and commits the result if you ask.
Sessions
Each conversation is a session tied to your current directory. Claude Code saves it locally as plaintext JSONL under ~/.claude/projects/, which is what makes rewinding, resuming, and forking possible. Sessions are independent, so a new session starts with a fresh context window. Persistent knowledge lives in CLAUDE.md files and auto memory instead.
2. Where You Can Run It
Every surface connects to the same underlying engine. Your CLAUDE.md files, settings, and MCP servers therefore work across all of them. What changes is where the code executes and how you interact with it.
| Surface | What it gives you | Notes |
|---|---|---|
| Terminal CLI | The full-featured experience | Install with a one-line command |
| VS Code extension | Inline diffs, @-mentions with line ranges, plan review, conversation history, multiple tabs | Needs VS Code 1.94.0 or later; also installs in Cursor |
| JetBrains plugin | Interactive diffs, selection sharing, IDE diagnostics | Works with IntelliJ IDEA, PyCharm, Android Studio, WebStorm, PhpStorm, and GoLand; needs the CLI installed separately |
| Desktop app | Visual diff review, parallel sessions with worktrees, scheduled tasks, app previews, PR monitoring | macOS, Windows x64 and ARM64, and a Linux beta for Ubuntu and Debian; needs a paid plan |
| Web and mobile | Cloud sessions at claude.ai/code and in the Claude app for iOS and Android | No local setup; runs on Anthropic-managed VMs |
| Slack | Mention @Claude with a coding task to start a cloud session and get a pull request back |
Works in channels only, with GitHub repositories; see the note below about Claude Tag |
| Remote Control | Drive a local session from your phone or any browser | Code and files stay on your machine |
| Chrome | Test pages, fill forms, read console logs | Start with claude --chrome or /chrome; needs a claude.ai login |
| CI/CD | Review PRs, triage issues, run tasks on events | GitHub Actions and GitLab CI/CD |
| Agent SDK | Build your own agents on the same tools and loop | Python and TypeScript packages |
Claude Code runs in three execution environments. Local is the default, with full access to your files and tools. Cloud runs on Anthropic-managed VMs or on self-hosted environments your organization operates. Remote Control keeps execution and files on your machine while you use the web interface.
Claude Code in Slack is changing for organizations. Anthropic is retiring the earlier Slack integration for Team and Enterprise workspaces in favor of Claude Tag, which runs @Claude as your organization’s shared identity with admin-configured access. Your existing Slack app and @Claude handle stay, and your Anthropic account team can give you the cutover date. Pro and Max plans keep the earlier version, which you set up with /install-slack-app. It works only in channels, not direct messages, and only with GitHub repositories.
Sessions are not tied to one surface. You can move work around with these commands:
claude --cloud "task"starts a new cloud session from your terminal.claude --teleportor/teleportpulls a cloud session into your terminal. It requires a claude.ai subscription./desktopcontinues the current terminal session in the Desktop app on macOS and x64 Windows./remote-control(alias/rc) orclaude --remote-controlmakes the session available from claude.ai or the Claude app./resumeinside the Desktop app picks up any session you started from the CLI.
3. Installation, Requirements, and Updates
System requirements
- Operating systems: macOS 13.0 or later, Windows 10 1809 or later (or Windows Server 2019), Ubuntu 20.04 or later, Debian 10 or later, and Alpine Linux 3.19 or later.
- Hardware: 4 GB of RAM or more, with an x64 or ARM64 processor.
- Network: an internet connection is required, and you must be in an Anthropic-supported country.
- Shell: Bash, Zsh, PowerShell, or CMD.
- Account: a Pro, Max, Team, or Enterprise plan, or a Claude Console account. The free claude.ai plan does not include Claude Code. Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS also work as providers.
Install commands
The native installer is the recommended route. It updates itself in the background.
# macOS, Linux, WSL
curl -fsSL https://claude.ai/install.sh | bash
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex
:: Windows CMD
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
If PowerShell shows The token '&&' is not a valid statement separator, you pasted the CMD command into PowerShell. If CMD says 'irm' is not recognized, you pasted the PowerShell command into CMD.
Other install methods exist, and they behave differently on updates:
| Method | Command | Auto-updates |
|---|---|---|
| Homebrew | brew install --cask claude-code (stable) or claude-code@latest |
No |
| WinGet | winget install Anthropic.ClaudeCode |
No |
| apt, dnf, apk | Signed repositories with stable and latest channels |
No |
| npm | npm install -g @anthropic-ai/claude-code |
Only if npm can write its global directory |
The npm package needs Node.js 22 or later, but the installed claude binary is native and does not call Node at runtime. Never install it with sudo npm install -g, because that causes permission problems. Homebrew, WinGet, and Linux packages update only when you run the upgrade command, unless you set CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE to 1 for Homebrew or WinGet.
After installing, open a new terminal and check the result:
claude --version
claude doctor
claude doctor prints read-only diagnostics about your install and settings without starting a session.
Windows setup
| Option | Requires | Sandboxing | Use it when |
|---|---|---|---|
| Native Windows | Nothing; Git for Windows is optional | Not supported | You work on Windows-native projects and tools |
| WSL 2 | WSL 2 enabled | Supported | You want Linux toolchains or sandboxed commands |
| WSL 1 | WSL 1 enabled | Not supported | WSL 2 is unavailable |
On native Windows, Claude Code uses Git Bash for the Bash tool when Git for Windows is installed. Without it, Claude Code uses the PowerShell tool. If it cannot find Git Bash, set CLAUDE_CODE_GIT_BASH_PATH in the env block of your settings file.
Alpine and other musl-based distributions need extra packages. Install bash, curl, libgcc, libstdc++, and ripgrep, then set USE_BUILTIN_RIPGREP to 0.
Signing in
Run claude and follow the browser prompts on first use. If ANTHROPIC_API_KEY is set, Claude Code asks you once to approve the key instead. Useful auth commands include claude auth login (with --console for API billing or --sso), claude auth logout, and claude auth status. The claude setup-token command generates a long-lived OAuth token for CI and scripts, and it requires a Claude subscription.
Several features need a claude.ai login or the Anthropic API, and they are unavailable through third-party providers such as Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. If you reach Claude only through one of those providers, you need a separate claude.ai account for these:
- Fast mode and the advisor tool
- Ultrareview, which runs as
/code-review ultra - Artifacts,
/design, and/slides - Claude in Chrome and computer use
- Routines created through
/schedule - Remote Control and
/teleport /import, which brings configuration from other coding agents
Updates and release channels
Native installs check for updates on startup and periodically while running. New versions take effect the next time you start Claude Code. Run claude update to apply one immediately.
The autoUpdatesChannel setting picks a channel. "latest" is the default and delivers features as soon as they ship. "stable" serves a version that is typically about a week old and skips releases with major regressions. The minimumVersion setting sets a floor so a switch to stable never downgrades you. To stop background checks, set DISABLE_AUTOUPDATER to "1" in the env block. To block every update path, including claude update, set DISABLE_UPDATES instead.
Each release publishes a manifest.json with SHA256 checksums, signed with an Anthropic GPG key. The expected fingerprint is below. Binaries also carry platform signatures on macOS and Windows.
31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE
To uninstall a native install on macOS, Linux, or WSL, delete ~/.local/bin/claude and ~/.local/share/claude. On Windows, remove the matching claude.exe and claude folders under .local in your user profile. Your settings and history live in ~/.claude and ~/.claude.json, so remove those too only if you want a clean slate.
Official docs: Advanced setup and Troubleshoot installation and login.
4. Your First Session
Open a terminal in a project and start Claude Code.
cd your-project
claude
Run /init first in any new project. Claude analyzes your codebase and writes a starter CLAUDE.md with build commands, test instructions, and conventions it discovers. If the file already exists, /init suggests improvements instead of overwriting it.
Then start with a plain-language request. Describing the goal works better than dictating steps.
The checkout flow is broken for users with expired cards.
The relevant code is in src/payments/. Can you investigate and fix it?
You can also pass a prompt on the command line. These commands show the main entry points.
claude "explain this project" # interactive session with an opening prompt
claude -p "explain this function" # one-shot answer, then exit
cat logs.txt | claude -p "explain" # pipe data in
claude -c # continue the latest conversation in this directory
claude -r "auth-refactor" "Finish this PR" # resume a named session
claude update # update to the latest version
Claude Code is conversational, so iterate. If the first attempt misses, say what is wrong and Claude adjusts. Run /help for the command list, /powerup for interactive lessons with animated demos, and /doctor whenever setup feels off.
5. Models, Effort, and Speed
Snapshot note: model names, defaults, and prices in this section reflect the documentation on October 3, 2026. Confirm them with /release-notes or the linked docs before you rely on them.
Model aliases
| Alias | What it selects |
|---|---|
default |
Clears your override and returns to the default for your account type |
best |
fable where available, otherwise opus |
fable |
Fable 5.1, the most capable model, built for long and complex tasks |
sonnet |
The latest Sonnet, which is Sonnet 5.5 on the Anthropic API |
opus |
The latest Opus, which is Opus 5.5 on most providers |
haiku |
The fast and efficient Haiku model |
sonnet[1m], opus[1m] |
Sonnet or Opus with the 1M-token context window |
opusplan |
Opus in plan mode, then an automatic switch to Sonnet for execution |
The default model depends on your plan and provider, and it changes as new models ship. Run /model to see what your account uses. Fable models are never a plan default. You select them explicitly with /model fable or claude --model fable, and on some plans they bill to usage credits after a one-time consent.
Aliases resolve differently on each provider, which matters for enterprise rollouts. This table shows what opus and sonnet mean today.
| Provider | opus |
sonnet |
|---|---|---|
| Anthropic API | Opus 5.5 | Sonnet 5.5 |
| Claude Platform on AWS | Opus 5.5 | Sonnet 4.6 |
| Amazon Bedrock, Google Cloud’s Agent Platform | Opus 5.5 | Sonnet 4.5 |
| Microsoft Foundry | Opus 4.6 | Sonnet 4.5 |
Unless you set ANTHROPIC_DEFAULT_FABLE_MODEL, the fable alias resolves to Fable 5.1. Claude apps gateway sessions are the exception, because fable and best resolve to Fable 5 there. Pin exact versions with the ANTHROPIC_DEFAULT_*_MODEL variables so a new release never changes behavior under you.
Pick your model and effort level before you start real work. Switching either one mid-session can invalidate the prompt cache on most models, which makes the next turn slower and more expensive, as section 8 explains.
Choosing a model
Claude Code resolves the model in this order, from highest to lowest priority:
/model <alias or name>during a sessionclaude --model <alias or name>at startup- The
ANTHROPIC_MODELenvironment variable - The
modelfield in a settings file - The
ANTHROPIC_DEFAULT_MODELenvironment variable for new sessions
Run /model with no argument to open a picker. Press s on a row to switch for the current session only. Inside the picker, the left and right arrows adjust effort for models that support it.
Enterprise admins can restrict choices with availableModels and enforceAvailableModels. Teams on third-party providers pin versions with ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL, and ANTHROPIC_DEFAULT_FABLE_MODEL. CLAUDE_CODE_SUBAGENT_MODEL sets the default model for subagents.
For resilience, claude --fallback-model sonnet,haiku or the fallbackModel setting defines up to three models to try in order when the primary is overloaded or unavailable. Separately, when a safety classifier flags a request in certain categories, Claude Code can re-run it on a fallback model automatically.
Effort levels and thinking
Effort controls how much reasoning the model applies. The levels are low, medium, high, xhigh, and max, and the levels available depend on the model. max applies to one session only. Defaults vary by model, so check /effort rather than assuming.
/effortopens a slider, and/effort highsets a level directly./effort autoclears your saved level for the model.claude --effort highsets it at launch, andCLAUDE_CODE_EFFORT_LEVELdoes the same through the environment.- The
effortLeveland per-modelmodelSettingsentries persist a preference. ultracodeis not a true level. It requestsxhigheffort and turns on automatic workflow orchestration, which section 11 covers.
Extended thinking is on by default. Press Option+T on macOS or Alt+T on Windows and Linux to toggle it for a session, or set alwaysThinkingEnabled in your settings. Opus 5.5, Sonnet 5.5, and the Fable models always think, so you cannot turn thinking off there. On models with a fixed thinking budget, MAX_THINKING_TOKENS caps it, and MAX_THINKING_TOKENS=0 disables thinking.
The 1M-token context window
Fable 5.1, Fable 5, Sonnet 5.5, Sonnet 5, and Opus 4.7 or later (on the Anthropic API) have a native 1M-token window. Older models such as Opus 4.6 and Sonnet 4.6 reach it through the [1m] suffix, which may need usage credits or a higher plan. Set CLAUDE_CODE_DISABLE_1M_CONTEXT=1 to force a 200K window.
Claude Code compacts automatically as the window fills. On models with a native 1M window, the default threshold is roughly 967K tokens. You can change it with /autocompact 500k, claude --autocompact 500k, the autoCompactWindow setting, or CLAUDE_CODE_AUTO_COMPACT_WINDOW. Accepted values run from 100K to 1M tokens.
Fast mode
Fast mode makes Opus up to 2.5 times faster at a higher cost per token. It is the same model with a different API configuration, not a different model. It works on Opus 5.5, Opus 5, and Opus 4.8, and it is a research preview.
- Pricing per million input and output tokens is $8 and $40 on Opus 5.5, and $10 and $50 on Opus 5 and Opus 4.8.
- Toggle it with
/fastor thefastModesetting. A↯icon appears next to the prompt while it is on. - On subscription plans it bills to usage credits only. Console organizations need access provisioned, and Team and Enterprise owners must enable it first.
- It is not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS.
- Turn it on at the start of a session. Enabling it deep into a conversation means paying the full uncached input price for the existing context once.
Fast mode and a lower effort level both increase speed, but they work differently. Fast mode keeps quality and raises cost. A lower effort level reduces thinking time and may reduce quality on hard tasks. You can combine them for straightforward work.
The advisor tool
The advisor lets your main model consult a second, usually stronger model at key moments, such as before committing to an approach or before declaring a task done. It runs server-side, so it needs the Anthropic API. Set it with /advisor opus, the advisorModel setting, or claude --advisor opus, and turn it off with /advisor off. Claude decides when to call it, and each call bills the advisor model’s tokens on top of your main model. The advisor must rank at or above your main model, so a Sonnet main model pairs well with an Opus advisor.
Official docs: Model configuration, Fast mode, and Advisor tool.
6. Memory, Rules, and Project Instructions
Every session starts with an empty context window. Two mechanisms carry knowledge forward. CLAUDE.md files hold instructions you write, and auto memory holds notes Claude writes about you and your project. Both load at the start of every conversation as context, not as enforced configuration. If a rule must hold every time, use a hook instead.
Where CLAUDE.md files live
| Scope | Location | Shared with |
|---|---|---|
| Managed policy | macOS /Library/Application Support/ClaudeCode/CLAUDE.md, Linux and WSL /etc/claude-code/CLAUDE.md, Windows C:\Program Files\ClaudeCode\CLAUDE.md |
Everyone in the organization |
| User | ~/.claude/CLAUDE.md |
Just you, in every project |
| Project | ./CLAUDE.md or ./.claude/CLAUDE.md |
Your team, through version control |
| Local | ./CLAUDE.local.md (add it to .gitignore) |
Just you, in this project |
Claude Code loads CLAUDE.md and CLAUDE.local.md from your working directory and every directory above it. All files are concatenated rather than overriding each other, ordered from the filesystem root down to your working directory. Inside each directory, the local file comes last. Files in subdirectories load on demand when Claude reads files there. Block-level HTML comments are stripped before the content reaches Claude, so you can leave notes for maintainers without spending tokens.
Imports
A CLAUDE.md file can import other files with @path/to/file syntax. Relative paths resolve from the file that contains the import. Imports can nest up to four hops deep. Code spans and fenced code blocks are skipped, so writing `@README` in backticks keeps the text literal. The first time a project imports a file outside the working directory, Claude Code shows an approval dialog.
See @README for the project overview and @package.json for npm commands.
# Additional Instructions
- Git workflow: @docs/git-instructions.md
Rules and AGENTS.md
For larger projects, split instructions into topic files under .claude/rules/. A rule with paths frontmatter loads only when Claude works with matching files, which saves context.
---
paths:
- "src/api/**/*.ts"
---
# API Development Rules
- All endpoints validate input with the shared schema helpers.
User-level rules live in ~/.claude/rules/. If your repository has an AGENTS.md for other coding agents, Claude reads it only when no CLAUDE.md or CLAUDE.local.md exists in your working directory or above it. The Project instructions setting in /config changes that behavior. Its values are claude-md-or-agents-md (the default), claude-md-and-agents-md, claude-md, and managed-only. The simplest way to share one file with other tools is a short CLAUDE.md that imports @AGENTS.md.
Writing instructions that work
- Be concrete: “Use 2-space indentation” beats “format code properly.”
- Stay short: Aim for under 200 lines per file. Claude Code warns about long files, and it skips any file over 4 MiB.
- Prune regularly: For each line, ask whether removing it would cause mistakes. If not, cut it.
- Avoid contradictions: Two conflicting rules mean Claude may pick one arbitrarily.
- Emphasize sparingly: Adding “IMPORTANT” to one stubborn line helps. Adding it to many lines helps none.
- Move procedures out: Task-specific workflows belong in skills, which load only when needed.
Run /doctor for a checkup that proposes trims, and /doctor prompt-audit to look for outdated or conflicting instructions across your CLAUDE.md files, skills, and rules. After /compact, Claude re-reads the project-root CLAUDE.md from disk. You can also add a “Compact Instructions” section to guide what survives summarization.
Auto memory
Auto memory is on by default in local sessions. As Claude works, it saves four kinds of notes, recorded in a type frontmatter field: user (your role and preferences), feedback (corrections and approaches you confirmed), project (ongoing work and decisions), and reference (where to find outside information). Claude skips anything it can derive from the code or that your CLAUDE.md already says.
Notes live in ~/.claude/projects/<project>/memory/, with a MEMORY.md index and one file per topic. All worktrees of the same repository share one directory. Memory is machine-local, and the retention sweep never deletes it. Only the first 200 lines or 25KB of MEMORY.md load at startup. Topic files load on demand.
Use /memory to browse files, open them in your editor, or toggle auto memory. You can also disable it with autoMemoryEnabled: false or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, and relocate it with autoMemoryDirectory. Tell Claude “remember that the API tests need a local Redis instance” and it saves a note. Say “add this to CLAUDE.md” if you want an instruction instead.
Official docs: How Claude remembers your project.
7. Permissions and Safety
Snapshot note: the default permission mode and the auto mode rules changed several times during 2026. Check the permission modes page for the current behavior.
Permission modes
A permission mode sets what Claude can do without asking. Press Shift+Tab to cycle modes during a session, or start with claude --permission-mode <mode>.
| Mode | Runs without asking | Best for |
|---|---|---|
default (labeled Manual) |
Reads only | Sensitive work and unfamiliar code |
acceptEdits |
Reads, file edits, and common filesystem commands | Iterating on code you review afterward |
plan |
Reads; edits stay blocked until you approve a plan | Exploring before changing anything |
auto |
Everything, with background safety checks | Long tasks and fewer interruptions |
dontAsk |
Pre-approved tools only; anything else is denied | Locked-down CI and scripts |
bypassPermissions |
Everything | Isolated containers and VMs only |
With Claude Code 2.1.283 or later, auto is the built-in starting mode for interactive terminal and VS Code sessions. Earlier versions start in auto only on Pro, Max, and Team plans. A new session takes its mode from the first match among the --permission-mode flag, permissions.defaultMode in settings, and the built-in default. A defaultMode of "auto" or "bypassPermissions" does not take effect from project settings files, so put it in ~/.claude/settings.json. Manual is the label in the CLI, the IDE extensions, and the desktop app, while default is the config value that hooks and SDK integrations use. The CLI accepts manual as an alias wherever you type the value, which needs version 2.1.200 or later.
Not every mode sits in the default Shift+Tab cycle. dontAsk never appears and needs the --permission-mode dontAsk flag. bypassPermissions appears only after you launch with --dangerously-skip-permissions, --allow-dangerously-skip-permissions, or an equivalent setting. auto appears when it is available to your account.
Plan mode
Plan mode researches and proposes without editing your source. Enter it with Shift+Tab, with /plan, or with claude --permission-mode plan. When the plan is ready, you choose between approving with auto mode, approving with manual edit approval, or continuing to plan. Press Ctrl+G to edit the plan in your editor first. Plan mode adds overhead, so skip it when you could describe the diff in one sentence.
Accept edits mode
acceptEdits auto-approves file edits and the filesystem commands mkdir, touch, rm, rmdir, mv, cp, and sed inside your working directory. Paths outside it, protected paths, and critical-path removals still prompt.
Auto mode
In auto mode, a separate classifier model reviews actions before they run and blocks the risky ones. It trusts your working directory and the git remotes configured when the session started. Everything else counts as external until you describe your trusted infrastructure with autoMode.environment or the /auto-mode-setup command.
Auto mode works on all plans with a supported model: Opus 4.6 or later, Sonnet 4.6 or later, or a Fable model on the Anthropic API, and newer minimum versions on Bedrock, Google Cloud, and Foundry. Administrators can turn it off with permissions.disableAutoMode set to "disable". It reduces prompts but does not guarantee safety.
The classifier blocks these actions by default, among others:
- Downloading and executing code, such as
curl | bash - Sending sensitive data to external endpoints
- Production deploys and migrations
- Force pushes,
git reset --hard, and other commands that discard uncommitted work - Granting IAM or repository permissions
- Merging a pull request no human approved, or disabling CI checks
terraform destroyand similar teardown commands- Printing a live credential into the transcript or a file
It allows local file operations in your working directory, installing declared dependencies, read-only HTTP requests, and pushing to any branch of the repository you are working in. Run claude auto-mode defaults to print the full rule lists as JSON. Boundaries you state in conversation, like “don’t push until I review”, also count as block signals. They are not stored as rules, so compaction can drop them. For a hard guarantee, add a deny rule.
Some actions still prompt even in auto mode. Tools matched by an explicit ask rule keep asking, so a rule like Bash(git push *) preserves a human checkpoint before every push. AskUserQuestion always needs your answer. Removals that target a critical path, such as rm -rf ~, are never auto-approved in any mode, bypass included.
dontAsk and bypassPermissions
dontAsk denies everything that would otherwise prompt, which suits locked-down CI. bypassPermissions skips prompts entirely and belongs only in a container or VM, ideally as a non-root user. Deny rules still apply in every mode, including bypass, and so does a PreToolUse hook that denies a call.
Permission rules
Rules use the form Tool(specifier) and live in the permissions block of a settings file. They are evaluated in order: deny first, then ask, then allow. The first match wins, and specificity does not change the order.
{
"permissions": {
"allow": ["Bash(npm run *)", "Bash(git commit *)"],
"deny": ["Read(./.env)", "Read(./secrets/**)"]
}
}
Bash(npm run *) matches npm run build but not npm install. The space before the asterisk matters, because Bash(git diff*) would also match git diff-index. Path rules follow gitignore-style patterns. A leading / anchors a pattern to the settings source, and **/ matches at any depth. Scoped deny rules match a command as written, so they are not a substitute for a sandbox. Run /permissions to browse and edit rules, and /fewer-permission-prompts to build an allowlist from your own transcripts.
Safety defaults also include a workspace trust dialog the first time you open a folder, a built-in set of read-only commands that never prompt, and fail-closed matching for commands Claude Code cannot fully analyze. Sessions started with -p show no trust dialog, so use --bare or review project hooks and MCP files before running headless in an untrusted repository.
The Bash sandbox
The sandbox is an operating-system boundary around shell commands. It restricts which files and network domains Bash, PowerShell, and Monitor commands can reach, so Claude can run sandboxed commands without asking. It works on macOS, Linux, and WSL2. Native Windows runs commands unsandboxed.
Toggle it with /sandbox, or set sandbox.enabled to true. The sandbox covers shell commands only. Claude’s file tools, MCP servers, and hooks run outside it. Pair it with permission rules for file access, and consider dev containers or VMs when you handle untrusted code.
Official docs: Permission modes, Permissions, and Sandboxing.
8. Managing Context
Most best practices come from one constraint. Claude’s context window fills fast, and performance degrades as it fills. The window holds your conversation, every file Claude reads, every command output, CLAUDE.md, auto memory, loaded skills, and system instructions. Treat it as your most important resource.
Seeing and shrinking context
/contextshows what fills the window as a colored grid, with suggestions. Passallto expand the per-item breakdown./clear [name]starts a new conversation with empty context. Aliases are/resetand/new. Use it between unrelated tasks./compact [instructions]summarizes the conversation, for example/compact focus on the API changes./btw [question]asks a side question whose answer never enters the history./renamenames a session, and/resumereturns to it later.
Claude Code compacts automatically near the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets survive. Detailed early instructions may not. After compaction, the project-root CLAUDE.md is re-read from disk. Nested CLAUDE.md files and path-scoped rules reload when Claude touches matching files. Invoked skills are re-attached, up to 5,000 tokens each within a shared 25,000-token budget.
If one file or output is so large that context refills after each summary, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping. A custom status line can display context usage continuously.
Checkpoints and rewind
Before Claude edits a file, it snapshots the contents. Each prompt that starts a turn creates a checkpoint, and Claude Code keeps snapshots for the 100 most recent ones. Press Esc twice on an empty prompt, or run /rewind, to open the menu. The aliases are /checkpoint and /undo.
The menu offers these actions at any earlier prompt:
- Restore code and conversation reverts both.
- Restore conversation rewinds the chat and keeps your current code.
- Restore code reverts file changes and keeps the conversation.
- Summarize from here compresses everything after that point.
- Summarize up to here compresses everything before that point.
Checkpoints have several limits you should know about. They do not track files changed by Bash commands such as rm or mv. They usually do not restore subagent edits. They ignore edits made outside the session. They skip symlinked and hard-linked files. They cannot undo remote effects like database changes or deployments. Snapshots are deleted by the retention sweep after about 30 days. Checkpoints are session-level recovery, not a replacement for git.
To try a different approach without losing the current path, use /branch [name] or claude --continue --fork-session. /branch copies the conversation up to this point and switches you into the copy. The original stays available through /resume.
Resuming and naming sessions
| Command | What it does |
|---|---|
claude --continue |
Reopens the most recent conversation in this directory |
claude --resume |
Opens the session picker |
claude --resume <name> |
Resumes a named session directly |
claude --from-pr <number> |
Filters the picker to sessions linked to a pull request |
claude -n my-feature |
Names a session at startup |
In the picker, Ctrl+W widens the list to all worktrees, Ctrl+A to all projects, and Ctrl+B filters to the current branch. A resumed session restores its history, model, agent, active goal, and unexpired scheduled tasks. It does not restore flags such as --mcp-config, --settings, --plugin-dir, or --add-dir, so pass those again. On Pro and Max, resuming a session that has been idle for about an hour and holds over 100,000 tokens offers to resume from a summary.
Prompt caching
Claude Code resends your full context on every request. Prompt caching lets the API reuse the unchanged prefix at a cheaper rate, but any change early in the prefix recomputes everything after it. Knowing what breaks the cache saves money and time.
The cache lifetime is one hour for the main conversation on a Claude subscription within your plan’s included usage. It is five minutes on an API key, a cloud provider, or once you draw on usage credits. The promptCacheTtl setting (5m or 1h) overrides the main conversation, and subagentPromptCacheTtl covers subagents, workflows, and compaction.
| These actions invalidate the cache | These actions keep it |
|---|---|
| Switching models (each model has its own cache) | Editing files in your repository |
| Changing effort level on most models | Editing CLAUDE.md mid-session (it also will not apply until /clear, /compact, or restart) |
| Turning on fast mode for the first time in a conversation | Changing the permission mode |
| Changing the tool list when MCP tool search is not deferring tools | Changing the output style |
| Compacting the conversation | Invoking skills and commands |
| Accumulating many images | Running /recap or rewinding |
| Upgrading Claude Code | Spawning a subagent |
Pick your model and effort at the start of a session and save /compact for natural breaks. Run /usage to see a Prompt cache (main) line with your hit rate, misses, and whether the cache is warm. DISABLE_PROMPT_CACHING=1 turns caching off for debugging.
Official docs: Context window, Checkpointing, Prompt caching, and Manage sessions.
9. Settings and Configuration
Where settings live and which wins
A key set at a higher level overrides the same key lower down. The order from highest to lowest is:
- Managed settings from
managed-settings.json, MDM, or the claude.ai console, set by your organization - Command line through
claude --settings <file or JSON> - Project local in
.claude/settings.local.json, for you in this project - Shared project in
.claude/settings.json, committed for the whole team - User in
~/.claude/settings.json, for you in every project
Run /config to open the settings interface, or set values directly with /config key=value, for example /config theme=dark or /config model=sonnet. The key=value form also works with -p. /status shows version, model, account, and connectivity. claude --setting-sources user,project restricts which sources load, and /update-config lets you describe a change in words and have Claude edit the right file.
A small starting ~/.claude/settings.json might look like this.
{
"model": "opus",
"autoUpdatesChannel": "stable",
"permissions": {
"allow": ["Bash(npm run *)", "Bash(git status *)"],
"deny": ["Read(./.env)"]
},
"env": {
"DISABLE_TELEMETRY": "1"
}
}
The env block sets environment variables for every session. Hooks and many other keys live in the same files. The full key list is in the official settings reference.
A map of the .claude folders
| Path | Purpose |
|---|---|
CLAUDE.md, CLAUDE.local.md |
Project instructions, shared and personal |
.claude/settings.json, settings.local.json |
Shared and personal project settings |
.claude/rules/ |
Topic or path-scoped instructions |
.claude/skills/<name>/SKILL.md |
Skills, with optional supporting files |
.claude/agents/ |
Custom subagents |
.claude/commands/ |
Legacy custom commands, which still work |
.claude/output-styles/ |
Custom output styles |
.claude/workflows/ |
Saved dynamic workflows |
.claude/worktrees/ |
Worktrees that --worktree creates |
.mcp.json |
Project-scoped MCP servers, in the project root |
~/.claude.json |
User state, plus local-scope and user-scope MCP servers |
~/.claude/projects/ |
Session transcripts and per-project auto memory |
~/.claude/plugins/ |
Installed plugins |
~/.claude/themes/ |
Custom themes |
~/.claude/debug/<session-id>.txt |
Debug logs |
~/.claude/usage-data/report.html |
The latest /insights report |
Claude Code deletes session transcripts after cleanupPeriodDays, which defaults to 30. Memory files are exempt. claude purge [path] deletes all local state for a project, and it supports --dry-run. Setting CLAUDE_CONFIG_DIR moves everything off ~/.claude.
Official docs: Settings and Settings reference.
Large repositories and monorepos
In a large codebase, defaults tuned for small projects can fill the context window with instructions and file reads unrelated to the task. The goal is to scope Claude to the part of the tree a task touches. These settings layer, so apply whichever ones fit.
| I want to | Use |
|---|---|
| Load only the conventions for the code I touch | Per-directory CLAUDE.md files |
| Skip CLAUDE.md files for packages I never work in | claudeMdExcludes |
| Stop Claude from opening generated or vendored code | Read deny rules in permissions.deny |
| Find definitions without scanning files | A code intelligence plugin |
| Check out only some directories in a worktree | worktree.sparsePaths |
| Edit a sibling package or repository from one session | --add-dir or additionalDirectories |
| Give one area its own procedures | Per-directory skills |
| Share conventions that outgrew layering | A plugin in an internal marketplace |
Where you launch claude matters. From the repository root, Claude can reach every file, and subdirectory CLAUDE.md files load on demand when it reads there. From a subdirectory, Claude reaches only that subtree until you grant more, and it loads that directory’s CLAUDE.md plus every ancestor’s. Project settings in .claude/settings.json are not inherited from parent directories the way CLAUDE.md files are.
Content searches respect .gitignore by default, so folders like node_modules/, dist/, and build/ stay out of results. For checked-in generated code or a vendored SDK, add Read deny rules. Sparse worktrees keep parallel sessions light, and symlinkDirectories avoids copying node_modules into each one.
{
"permissions": {
"deny": ["Read(./**/dist/**/*)", "Read(./**/vendor/**/*)"]
},
"worktree": {
"sparsePaths": [".claude", "packages/api", "packages/shared"],
"symlinkDirectories": ["node_modules"]
}
}
Deny rules cover Claude’s file tools and the Bash file commands Claude Code recognizes, such as cat and head. A Bash grep -r over a directory that holds denied files still includes them in its output. Root-level files are always checked out in a sparse worktree, but root-level directories are not, so list .claude if you want its settings available inside the worktree.
To exclude another team’s CLAUDE.md files, set claudeMdExcludes with glob patterns such as **/packages/web/**, ideally in .claude/settings.local.json. Managed policy CLAUDE.md files cannot be excluded. Install a code intelligence plugin with /plugin install typescript-lsp@claude-plugins-official. Each developer also needs the language server binary on their machine.
additionalDirectories and --add-dir give file access to sibling packages. The setting never loads their CLAUDE.md or skills. The flag loads skills, and it loads CLAUDE.md only when CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 is set.
Per-directory skills under .claude/skills/ load on demand, so API tooling does not consume context during frontend work. A paths field in a skill’s frontmatter limits it to matching files. With many skills, some lose their descriptions, so keep descriptions short and lead with words a request would contain. For a change that spans packages, plan first in plan mode, because Claude Code re-injects the plan file after each compaction.
Official docs: Set up Claude Code in a monorepo or large codebase.
10. Extending Claude Code
The built-in tools cover most coding tasks. The extension layer customizes what Claude knows, connects it to outside services, and automates workflows.
| Feature | What it does | Use it when |
|---|---|---|
| CLAUDE.md | Persistent context, loaded every session | Conventions and “always do X” rules |
| Skill | Instructions and workflows that load on demand | Reusable playbooks and reference docs |
| Subagent | Isolated worker with its own context | Side tasks that read many files |
| Dynamic workflow | A script that runs many subagents | Work that outgrows a handful of subagents |
| MCP | Connections to external services | Databases, trackers, browsers, chat |
| Hook | A script, request, or prompt on a lifecycle event | Anything that must happen every time |
| Plugin | A package of the above | Sharing a setup across repositories |
| Output style | Role, tone, and format for every response | Shorter answers or a different persona |
| Artifact | A private interactive page on claude.ai | Output best seen visually |
Each feature costs context differently. CLAUDE.md and output styles load fully every request. Skill descriptions load every request, and the full text loads when used. MCP tools load as names only until needed. Subagents use their own window. Hooks cost nothing unless they return output.
When the same feature exists at several levels, CLAUDE.md files are additive. Skills and subagents override by name, with managed above user above project for skills. MCP servers override by name, with local above project above user. Hooks merge, and all of them fire.
Skills
A skill is a folder with a SKILL.md file. The frontmatter describes it, and the body holds instructions. Claude sees only the name and description until a skill is used, so large reference material costs nothing until needed. Type /skill-name to run one, or let Claude load it when the description matches your task.
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.
1. Use `gh issue view` to get the issue details
2. Search the codebase for relevant files
3. Implement the fix and write tests
4. Run linting and type checking, then commit and open a PR
Run it with /fix-issue 1234. Skills live in several places, and a higher location wins on a name clash.
| Location | Path | Scope |
|---|---|---|
| Enterprise | .claude/skills/ in the managed settings directory |
All users the organization targets |
| Personal | ~/.claude/skills/<name>/SKILL.md |
All your projects |
| Project | .claude/skills/<name>/SKILL.md |
One repository |
| Nested | <subdir>/.claude/skills/<name>/SKILL.md |
Sessions in or below that folder |
| Plugin | <plugin>/skills/<name>/SKILL.md |
Where the plugin is enabled, as /plugin-name:skill-name |
Useful frontmatter fields include these:
descriptionandwhen_to_usetell Claude when to invoke the skill. Both together truncate at 1,536 characters.disable-model-invocation: truemakes it manual-only, which suits workflows with side effects like deploys.user-invocable: falsehides it from the menu so only Claude can use it as background knowledge.allowed-toolspre-approves tools for the turn that runs the skill, for exampleBash(git add *) Bash(git commit *).context: forkwith anagentruns the skill in an isolated subagent. The agent can beExplore,Plan,general-purpose, or a custom one.model,effort,paths,arguments,argument-hint,shell, andhooksrefine behavior further.
Skill bodies support substitutions such as $ARGUMENTS, $0, $1, ${CLAUDE_SESSION_ID}, ${CLAUDE_SKILL_DIR}, and ${CLAUDE_PROJECT_DIR}. A line like !`git diff HEAD` runs a shell command before Claude sees the skill, so Claude receives live data. You can chain up to six skills at the start of one message.
Claude Code ships bundled skills, including /batch, /code-review, /simplify, /debug, /doctor, /loop, /claude-api, /verify, /run, /fewer-permission-prompts, and /update-config. Use /skills to list them, /skill-doctor to see what each skill costs in context, /reload-skills after editing files on disk, and claude plugin validate .claude/skills to catch parse errors. Old .claude/commands/ files still work, but new work should use skills.
Subagents
Subagents are specialized assistants with their own context window, system prompt, tool access, and permissions. They keep exploration, logs, and file contents out of your main conversation, and they hand back a summary. Claude Code includes built-in subagents: Explore (read-only search), Plan (research for plan mode), and general-purpose (multi-step work). Explore and Plan skip CLAUDE.md and the git status snapshot to stay fast and cheap.
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for injection flaws,
authentication and authorization gaps, leaked secrets, and insecure data handling.
Provide specific line references and suggested fixes.
Save agents in .claude/agents/ for a project or ~/.claude/agents/ for yourself. Priority runs from managed settings, then the --agents flag, then project, then user, then plugins. Key frontmatter fields include tools, disallowedTools, model (sonnet, opus, haiku, fable, a full ID, or inherit), permissionMode, maxTurns, skills, memory (user, project, or local), background, isolation: worktree, mcpServers, and hooks.
You can invoke a subagent in three ways: name it in your prompt, @-mention it to guarantee the choice, or run the whole session as that agent with claude --agent <name> or the agent setting. In interactive sessions, subagents run in the background by default, so you keep working. /tasks lists running and finished background work. /subtask <task> forks the current conversation into a background subagent that inherits everything so far. By default, subagents can nest three layers deep and 20 can run at once. Both limits are configurable.
Use a subagent when work is noisy or isolated, such as running tests, reading many files, or reviewing a diff in a fresh context. Block them with a deny rule like Agent(Explore), or block all with Agent.
Hooks
Hooks are user-defined actions that Claude Code runs at fixed points in its lifecycle. They give you deterministic control. Instructions in CLAUDE.md are advisory, while a hook always fires.
Most setups need only a handful of events: PreToolUse, PostToolUse, Notification, Stop, and SessionStart. The table below lists every event for reference.
| Event | When it fires |
|---|---|
SessionStart |
A session begins or resumes |
Setup |
--init-only, or --init and --maintenance in -p mode |
UserPromptSubmit |
You submit a prompt, before Claude processes it |
UserPromptExpansion |
A typed command expands into a prompt; can block it |
PreToolUse |
Before a tool call; can block it |
PermissionRequest |
A tool call needs a permission decision |
PermissionDenied |
Auto mode denies a tool call |
PostToolUse |
After a tool call succeeds |
PostToolUseFailure |
After a tool call fails |
PostToolBatch |
After a batch of parallel tool calls resolves |
Notification |
Claude Code sends a notification |
MessageDisplay |
Assistant text is displayed |
SubagentStart, SubagentStop |
A subagent starts or finishes |
TaskCreated, TaskCompleted |
A task is created or completed |
Stop |
Claude finishes responding (not on interrupts) |
StopFailure |
The turn ends on an API error |
TeammateIdle |
An agent-team teammate is about to go idle |
InstructionsLoaded |
A CLAUDE.md or rules file loads into context |
ConfigChange |
A configuration file changes mid-session |
CwdChanged, DirectoryAdded |
The working directory changes, or /add-dir runs |
FileChanged |
A watched file changes on disk |
WorktreeCreate, WorktreeRemove |
A worktree is created or removed |
PreCompact, PostCompact |
Around context compaction |
PreModelSwitch, PostModelSwitch |
Around a model switch; the first can block |
Elicitation, ElicitationResult |
An MCP server asks you for input, and your answer |
SessionEnd |
A session terminates |
Most hooks use "type": "command", which runs a shell command. Four other types exist: http posts event data to a URL, mcp_tool calls a tool on an MCP server, prompt asks a model for a single-turn yes-or-no decision, and agent runs a multi-turn verification subagent (experimental).
Hooks talk to Claude Code through stdin, stdout, stderr, and exit codes. Claude Code passes event data as JSON on stdin, including fields such as session_id, cwd, hook_event_name, tool_name, and tool_input. Exit code 0 means no objection, and for PreToolUse it does not approve the call. Exit code 2 blocks the action, and stderr becomes feedback. Any other code is a non-blocking error unless valid JSON on stdout says otherwise. For richer control, exit 0 and print JSON with a permissionDecision of allow, deny, or ask. Choose one approach per hook.
This script blocks destructive SQL.
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q "drop table"; then
echo "Blocked: dropping tables is not allowed" >&2
exit 2
fi
exit 0
Register it, and add a formatter that runs after every edit, in .claude/settings.json.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-drop-table.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}
A few rules govern how hooks combine. When several hooks match, they all run in parallel, and for PreToolUse the most restrictive answer wins in the order deny, defer, ask, allow. A PreToolUse hook that denies a call blocks it even in bypassPermissions mode, so hooks can enforce policy that users cannot bypass. A hook returning allow never overrides deny rules. Matchers filter by tool name, so "Edit|Write" and "Edit, Write" are equivalent. An if field narrows tool events by arguments.
Timeouts default to 10 minutes for command, http, and mcp_tool hooks, 30 seconds for prompt hooks, and 60 seconds for agent hooks. SessionEnd hooks share a 1.5-second budget. Hooks can live in user settings, project settings, local settings, managed settings, plugin hooks/hooks.json, and skill or subagent frontmatter. Run /hooks to browse what is configured. Set disableAllHooks to true to turn them off. Treat hooks like code you run as yourself, because they are.
MCP servers
The Model Context Protocol is an open standard for connecting AI tools to external systems. With MCP, Claude can read design docs, update tickets, query databases, and use your internal tooling.
# Remote HTTP server (recommended for remote services)
claude mcp add --transport http notion https://mcp.notion.com/mcp
# HTTP server with a header
claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \
--header "Authorization: Bearer YOUR_GITHUB_PAT"
# Local stdio server (note the -- separator)
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
--dsn "postgresql://readonly:pass@host:5432/analytics"
# From a JSON definition
claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp"}'
HTTP is the recommended transport for remote servers, SSE is deprecated, and stdio runs a local process. WebSocket servers are configured through .mcp.json or claude mcp add-json. A project-scoped server saved in .mcp.json looks like this.
{
"mcpServers": {
"shared-server": {
"type": "http",
"url": "https://example.com/mcp"
}
}
}
| Scope | Loads in | Stored in |
|---|---|---|
| Local (default) | The current project only, private | ~/.claude.json |
| Project | The current project, shared with the team | .mcp.json in the project root |
| User | All your projects, private | ~/.claude.json |
Precedence runs local, then project, then user, then plugin servers, then claude.ai connectors. Manage servers with claude mcp list, claude mcp get <name>, claude mcp remove <name>, and the in-session /mcp panel. OAuth works from /mcp or from the shell with claude mcp login <name> (add --no-browser over SSH). Project-scoped servers need your approval in interactive sessions. In .mcp.json, ${VAR} and ${VAR:-default} expand environment variables.
Tool search is on by default, so only tool names enter context until Claude needs a specific tool. Run /context all to see what each tool costs. MCP output over 10,000 tokens triggers a warning, and the default cap is 25,000 tokens. Raise it with MAX_MCP_OUTPUT_TOKENS. MCP_TIMEOUT and MCP_TOOL_TIMEOUT tune startup and call timeouts. claude mcp serve runs Claude Code itself as an MCP server for other clients.
Prefer a CLI tool when one exists. gh, aws, gcloud, and sentry-cli add no per-tool listing, so they are more context-efficient than an MCP server. Security-wise, use servers you trust, since Anthropic does not audit them for you. Administrators can restrict servers with managed MCP settings.
Plugins
A plugin is a directory of skills, agents, hooks, MCP servers, and other components that installs as one unit. Plugins come from marketplaces. Claude Code adds Anthropic’s official marketplace the first time you start an interactive session. Run /plugin to browse it, or install directly from the shell.
claude plugin install code-review@claude-plugins-official
Choose an install scope: user (every project), project (everyone who uses the repo), or local (you, in this repo). Plugin skills are namespaced, such as /my-plugin:review. Code intelligence plugins add the LSP tool for typed languages, which gives precise navigation and automatic type errors after edits. Load a plugin from a folder or archive for one session with --plugin-dir, or from a URL with --plugin-url. Run /reload-plugins after changes, and use claude plugin eval to test a plugin against a suite of cases. A plugin runs code with your privileges, so review it before installing.
Output styles and the status line
An output style sets Claude’s role, tone, and response format for a session. Claude Code starts in the Default style. Four built-in styles add behavior on top of it:
- Proactive starts work immediately and makes reasonable assumptions on routine decisions.
- Concise leads with the result and drops preamble and recaps.
- Explanatory adds
Insightblocks that explain the choices behind the code. - Learning adds insights and leaves small
TODO(human)pieces for you to write.
Switch with /output-style concise or through /config. The outputStyle setting is case-sensitive. Custom styles are Markdown files in ~/.claude/output-styles or .claude/output-styles, with name, description, and keep-coding-instructions frontmatter. Use styles for how Claude responds, CLAUDE.md for what it knows, and hooks for what must happen.
Run /statusline to describe the status line you want, or run it with no arguments to base one on your shell prompt. Status line scripts receive JSON that includes context usage, cost, prompt_cache statistics, session_name, and transcript_path.
Browser and computer control
Claude can reach beyond the terminal, and it tries the most precise tool first. An MCP server for the service comes first, a shell command comes next, and Claude in Chrome handles browser work. Computer use is the broadest and slowest option, so Claude reaches for it only when nothing else can.
Claude in Chrome
- Start it with
claude --chrome, or run/chrometo check status, reconnect, pick a browser, or turn on “Enabled by default”. That default loads browser tool instructions into every session, which raises context use. - It needs the Claude in Chrome extension version 1.0.36 or later, Chrome or Edge (other Chromium browsers are detected too), and a direct Anthropic plan signed in with
/login. API keys andclaude setup-tokencredentials keep it off, and WSL is not supported. - Claude opens tabs in your visible browser and shares your login state. It pauses at login pages and CAPTCHAs so you can handle them. It can read console errors and the DOM, test forms and flows, fill forms, extract data, upload files up to 10 MB per upload, and record GIFs. Site permissions come from the extension.
Computer use
- Computer use lets Claude open apps, click, type, and see your screen. In the CLI it is a research preview on macOS only, for Pro and Max plans but not Team or Enterprise. It needs an interactive session, so it does not work with
-p. - Enable the built-in
computer-useserver from/mcp, then grant macOS Accessibility and Screen Recording permissions. - You approve each app per session. Apps with broad reach, such as terminals, Finder, and System Settings, show extra warnings. Control also varies by category: browsers and trading platforms are view-only, terminals and IDEs are click-only, and everything else gets full control.
- Other visible apps are hidden while Claude works, your terminal is excluded from screenshots, and only one session can hold the computer at a time. Press
Escanywhere to stop it. - The Desktop app offers the same engine on macOS and Windows.
Artifacts and other helpers
Artifacts publish session output as a private, interactive page on claude.ai that you can share. They need a Pro, Max, Team, or Enterprise plan and a claude.ai login, and /artifacts lists the ones you own. /design drafts UI mockups as editable artboards, and /slides builds a slide deck, both as artifacts. /import brings configuration from Codex, Gemini CLI, and Cursor, and /team-onboarding turns your usage history into a guide for teammates.
Official docs: Extend Claude Code, Skills, Subagents, Hooks, MCP, Chrome, and Computer use.
11. Working in Parallel
Claude Code gives you several ways to run more than one agent at once. They differ in who coordinates the work and how isolated the edits are.
| Approach | What it is | Best for |
|---|---|---|
| Subagents | Workers Claude spawns inside one session | Focused side tasks that return a summary |
Forks (/subtask) |
A subagent that inherits the full conversation | Side work without re-explaining context |
Worktrees (--worktree) |
Separate git checkouts per session | Isolating file edits between sessions |
Agent view (claude agents) |
Background sessions you watch from one screen | Several independent tasks |
| Agent teams | A lead plus teammates sharing a task list (experimental) | Work that needs discussion and collaboration |
| Dynamic workflows | A script that runs dozens of subagents | Audits and migrations at scale |
/batch |
Splits one change into 5 to 30 units, each in its own worktree | Codebase-wide changes |
| Cross-session messaging | Your sessions message each other (macOS and Linux) | Passing findings between sessions you run |
| Cloud sessions | Parallel tasks on Anthropic-managed VMs | Long tasks while your laptop is closed |
Worktrees
A git worktree is a separate working directory with its own files and branch. Running each session in its own worktree means edits never collide.
claude --worktree feature-auth # creates .claude/worktrees/feature-auth on branch worktree-feature-auth
claude -w "#1234" # branches from pull request 1234
claude -w feature-auth --tmux # also opens a tmux session
Add .claude/worktrees/ to .gitignore. A .worktreeinclude file, in .gitignore syntax, copies ignored files such as .env into each new worktree. The worktree.baseRef setting chooses whether new worktrees branch from the remote default ("fresh") or your local HEAD ("head"). On exit, Claude removes a clean unnamed worktree and prompts you when work remains. A subagent can run in its own worktree with isolation: worktree. For SVN, Perforce, or Mercurial, WorktreeCreate and WorktreeRemove hooks replace the git logic.
Agent view and background sessions
Run claude agents to open one screen for every session. Each row shows a state: working, needs input, idle, completed, failed, or stopped. Dispatch work from the input at the bottom or from your shell with claude --bg "investigate the flaky test". Inside a session, /background (alias /bg) detaches it, and /fork copies the conversation into a new background session.
Press Space on a row to peek and reply without leaving the view, and Enter or the right arrow to attach. Shell commands include claude attach <id>, claude logs <id>, claude stop <id>, claude rm <id>, and claude respawn <id>. A supervisor process keeps sessions alive after you close the view, and it stops idle sessions after about an hour unless you pin them with Ctrl+T. Dispatched sessions get worktrees automatically. Remember that ten parallel sessions use your quota roughly ten times faster. To disable agent view, set CLAUDE_CODE_DISABLE_AGENT_VIEW=1.
Agent teams
Agent teams are experimental and off by default. Enable them with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1. One session acts as lead, and teammates work in their own context windows, message each other, and claim tasks from a shared list. Teammates display in-process by default, or in split panes with --teammate-mode tmux or iterm2.
Teams use significantly more tokens, roughly seven times more when teammates run in plan mode. Start with three to five teammates, give each a distinct set of files, and begin with research or review tasks. Known limits include no session resumption for in-process teammates, one team per session, and no nested teams. TeammateIdle, TaskCreated, and TaskCompleted hooks can enforce quality gates.
Dynamic workflows and ultracode
A dynamic workflow is a JavaScript script that orchestrates many subagents. Claude writes it for your task, and a runtime executes it in the background while your session stays free. The script holds the loop, branching, and intermediate results, so your context sees only the final answer. That also makes the orchestration repeatable.
ultracode: audit every API endpoint under src/routes/ for missing auth checks
Including the keyword ultracode, or saying “use a workflow,” asks Claude to write one. Setting /effort ultracode makes Claude plan a workflow for every substantive task in the session, which uses many more tokens. /workflows opens a progress view where you can pause with p, stop with x, restart an agent with r, and save the script with s as a reusable command in .claude/workflows/ or ~/.claude/workflows/. The bundled /deep-research workflow fans out web searches, cross-checks sources, and returns a cited report.
The runtime caps a run at 16 concurrent agents by default (adjustable from 1 to 256), 4,096 items per parallel() or pipeline() call, and 1,000 agents total. A run that schedules more than 25 agents or projects over 1.5 million tokens shows a Large workflow warning. Pro plans default to a small size guideline. Turn workflows off with disableWorkflows or CLAUDE_CODE_DISABLE_WORKFLOWS=1.
Cross-session messaging
On macOS and Linux, your sessions can message each other, so Claude passes a finding from one session to another instead of you re-explaining it. /list-agents (alias /peers) shows who can be reached. A message arriving at an idle session starts a new turn, which costs context. Set crossSessionInbound to hold to queue messages instead.
Official docs: Worktrees, Agent view, Agent teams, and Dynamic workflows.
12. Automation and CI
Headless mode
Add -p to run non-interactively. Claude Code exits 0 on success and non-zero on failure. Piped input is capped at 10MB.
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
git diff main --name-only | claude -p "review these changed files for security issues"
claude -p "Summarize this project" --output-format json | jq -r '.result'
--output-format accepts text, json, and stream-json. The JSON result includes the session ID, usage, and total_cost_usd. With --json-schema, the validated result appears in structured_output. Streaming needs --output-format stream-json --verbose, and --include-partial-messages adds token-level events. Continue work with --continue, or resume by ID with --resume <session-id>.
The most important scripting flags are below.
| Flag | Purpose |
|---|---|
--bare |
Skip hooks, skills, plugins, MCP, auto memory, and CLAUDE.md discovery for faster, reproducible runs |
--allowedTools, --disallowedTools |
Pre-approve or deny tools; Bash(git diff *) uses prefix matching |
--permission-mode |
Set a baseline such as auto, dontAsk, or acceptEdits |
--permission-prompts none |
Deny anything that would prompt, for unattended runs |
--max-turns, --max-budget-usd |
Cap turns and spend |
--no-session-persistence |
Do not save the session to disk |
--append-system-prompt, --system-prompt |
Add to or replace the system prompt |
--model, --effort, --fallback-model |
Choose model behavior per run |
--add-dir, --settings, --mcp-config, --agents, --plugin-dir |
Supply extra context and configuration |
--tools |
Restrict which built-in tools exist |
Use --bare in CI. Without it, a -p session runs the hooks and MCP servers in a project’s .claude files even in a folder you never trusted. Bare mode uses ANTHROPIC_API_KEY or an apiKeyHelper instead of your subscription login. The docs say it will become the default for -p in a future release.
Prefer --append-system-prompt when Claude should remain a coding assistant with extra rules. Use --system-prompt only when the identity or permission model truly differs, because replacing the prompt drops the default tool guidance and safety instructions. Stopping a -p run with SIGTERM exits with code 143 and records no result for the unfinished turn.
A simple fan-out loop shows the pattern.
for file in $(cat files.txt); do
claude -p "Migrate $file from Python 2 to Python 3. Return OK or FAIL." \
--allowedTools "Edit,Bash(git commit *)"
done
GitHub Actions
Claude Code GitHub Actions runs Claude inside your repository workflows. Mention @claude in a pull request or issue comment, or give the action a prompt to run on any event. The quickest setup is /install-github-app, which installs the GitHub App, stores a secret, and opens a pull request with the workflow. It works only with github.com repositories and needs the gh CLI. Store either ANTHROPIC_API_KEY or a CLAUDE_CODE_OAUTH_TOKEN from claude setup-token as a repository secret.
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
jobs:
claude:
if: contains(github.event.comment.body, '@claude')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
actions: read
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
Without a prompt input, the action runs in interactive mode and waits for the trigger phrase. With one, it runs in automation mode. Pass CLI flags through claude_args, such as --max-turns 5 or --model claude-sonnet-5. The triggering user needs write access, and bot actors are rejected unless you list them in allowed_bots. Control cost with specific requests, a short CLAUDE.md, --max-turns, workflow timeouts, and concurrency limits. For Bedrock, Google Cloud, or Foundry, set use_bedrock, use_vertex, or use_foundry and authenticate through OIDC. For my broader comparison of CI platforms, see the CI/CD decision guide. GitLab pipelines have a matching GitLab CI/CD integration.
Loops, goals, and schedules
| Tool | Runs when | Where | Keeps running with your laptop closed |
|---|---|---|---|
/loop [interval] [prompt] |
A time interval elapses, or Claude self-paces | Inside an open CLI session | No |
/goal <condition> |
Each turn finishes, until a condition holds | Inside the current session | No |
| Desktop scheduled tasks | On a schedule | Your machine, with local file access | No |
| Routines | On a schedule, an API call, or a GitHub event | Anthropic’s cloud | Yes |
/goal is a session-scoped wrapper around a prompt-based Stop hook. After each turn, a small fast model checks your condition and returns not yet met, met, or impossible. Write conditions Claude’s own output can prove, such as “npm test exits 0 and git status is clean.” A condition can be up to 4,000 characters, and a clause like “or stop after 20 turns” bounds the run. /goal clear removes it. It also works with -p and in the desktop app.
Routines are in research preview on Pro, Max, Team, and Enterprise plans. Create them at claude.ai/code/routines, in the desktop app, or with /schedule. Schedule triggers have a one-hour minimum interval. API triggers use a per-routine bearer token and an experimental-cc-routine-2026-04-01 beta header. GitHub triggers react to pull request and release events. A routine runs autonomously with the repositories, environment, and connectors you give it, so scope them tightly.
The Agent SDK
For full control, the Agent SDK gives you Claude Code’s tools, agent loop, and context management as Python and TypeScript packages. It supports custom tools, MCP, subagents, hooks, permissions, structured output, and session storage. The claude -p flags and the GitHub Action are built on the same foundation.
Official docs: Run Claude Code programmatically, GitHub Actions, Routines, and Goal.
13. Review, Security, and Privacy
Reviewing code with Claude
/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [pr#|branch|path]reviews your diff, a pull request, a branch, or a path for correctness bugs./reviewis an alias.--fixapplies findings, and--commentposts them on a GitHub PR or GitLab merge request./simplifyruns four parallel review agents for reuse, simplification, efficiency, and abstraction level, then applies fixes. It does not hunt for bugs./security-reviewanalyzes the diff between your branch and the default branch for vulnerabilities such as injection, authentication issues, and data exposure. It needs anoriginremote./autofix-prstarts a cloud session that watches your PR and pushes fixes when CI fails or reviewers comment./verifyand/runbuild and launch your app to confirm a change works, instead of trusting tests alone.
Ultrareview is the deepest option. /code-review ultra, with /ultrareview as an alias, launches a fleet of reviewer agents in a cloud sandbox, and each reported finding is independently reproduced and verified. A review typically takes five to ten minutes. Pro and Max plans include three free runs, a one-time allotment per account that does not refresh. After that it bills usage credits, usually $5 to $25 per review. It needs a claude.ai login, is not available on third-party providers or with zero data retention, and does not start unless you invoke it. For scripts, claude ultrareview [target] blocks until findings print, and --post can comment them on a GitHub pull request.
Anthropic also offers security-focused plugins. The security-guidance plugin reviews Claude’s own changes for vulnerabilities as it works, and the Claude Security plugin runs a multi-agent scan of a codebase. For secrets specifically, my guides on secrets management and Gitleaks pair well with a PreToolUse hook.
How Claude Code protects you
- Permission-based architecture: Manual mode starts read-only and asks before edits and commands. Auto mode uses a classifier, and you control both.
- Sandboxed Bash: Filesystem and network isolation reduce prompts while keeping a boundary.
- Network command approval: Commands like
curlandwgetare not auto-approved by default. - Web page summaries: For most fetches,
WebFetchruns a separate model call and Claude receives the answer, not the raw page. - Trust verification: Interactive sessions show a workspace trust dialog, and
.mcp.jsonservers have their own approval prompt. - Command injection detection: Claude Code asks before running a Bash command it cannot fully analyze.
- Credential storage: Keys live in the macOS Keychain when available, in a
0600file on Linux, and in a profile-protected file on Windows.
No system is immune to prompt injection. Review commands before approving them, avoid piping untrusted content straight into Claude, and use a VM or dev container for risky work. On Windows, avoid enabling WebDAV for Claude Code, because it can trigger network requests that bypass the permission system. Report vulnerabilities through Anthropic’s HackerOne program, not publicly.
Data usage and retention
Commercial users on Team, Enterprise, the API, and third-party platforms are not trained on by default. Anthropic does not train generative models on code or prompts under commercial terms unless the customer opts in, for example through the Development Partner Program. Free, Pro, and Max users choose whether their data helps improve models, and that choice includes Claude Code use from those accounts.
| Account type | Retention |
|---|---|
| Consumer, data use allowed | 5 years |
| Consumer, data use not allowed | 30 days |
| Commercial (Team, Enterprise, API) | 30 days by default |
| Enterprise with zero data retention | No server-side persistence, enabled per organization |
Locally, transcripts stay in plaintext under ~/.claude/projects/ for 30 days by default. Transcripts you send with /feedback, /bug, or /share are retained for 5 years. Telemetry is controlled by environment variables:
DISABLE_TELEMETRY=1stops usage metrics, which never include your code, prompts, or file paths.DISABLE_ERROR_REPORTING=1stops error reports.DISABLE_FEEDBACK_COMMAND=1disables/feedback, andCLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1disables rating surveys.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFICturns off all non-essential traffic at once.
On Bedrock, Google Cloud, and Foundry, telemetry and feedback default to off. One check runs regardless: before fetching a URL, WebFetch sends only the hostname to api.anthropic.com for a safety blocklist check. Set skipWebFetchPreflight in settings to disable it, and combine that with WebFetch rules if you need to limit domains.
Official docs: Security, Data usage, and Ultrareview.
14. Costs and Usage
Snapshot note: prices, plan limits, and free-run counts in this section reflect the documentation on October 3, 2026 and can change.
Claude Code bills by token consumption, or draws from your subscription’s usage allowance. Across enterprise deployments, the average cost is around $13 per developer per active day, or $150 to $250 per developer per month. Costs stay below $30 per active day for 90 percent of users. Your numbers depend on model choice, codebase size, and habits such as running several instances.
Heavy parallel use multiplies cost quickly. Ten parallel background sessions draw on your quota roughly ten times faster, agent teams use about seven times more tokens when teammates run in plan mode, and ultracode plans a workflow for every substantive task. Watch /usage closely when you scale out.
Tracking usage
/usageshows session cost, plan usage limits, and activity stats./costand/statsare aliases. The dollar figure is a local estimate at list price./usage-creditsmanages usage credits, which let you keep working past plan limits./insightswrites an HTML report on how you work, covering friction points and suggestions.- Pro, Max, Team, and Enterprise plans show a breakdown by skills, subagents, plugins, and MCP servers, plus flags for long context and cache misses.
- On Team and Enterprise plans, seat allowances reset on a rolling five-hour window and a weekly window.
- OpenTelemetry export streams per-user token and cost metrics into your own observability stack.
For API organizations, the Console dashboard and Analytics API report per-user spend, and workspace spend limits cap it. These per-user rate limit starting points apply to teams that set limits.
| Team size | Tokens per minute, per user | Requests per minute, per user |
|---|---|---|
| 1 to 5 | 200k to 300k | 5 to 7 |
| 5 to 20 | 100k to 150k | 2.5 to 3.5 |
| 20 to 50 | 50k to 75k | 1.25 to 1.75 |
| 50 to 100 | 25k to 35k | 0.62 to 0.87 |
| 100 to 500 | 15k to 20k | 0.37 to 0.47 |
| 500 or more | 10k to 15k | 0.25 to 0.35 |
Spending less
- Clear between tasks: Stale context wastes tokens on every later message. Use
/renamefirst so you can/resumethe old one. - Match the model to the job: Sonnet handles most coding tasks. Save Opus for hard architectural reasoning, and set
model: haikuon simple subagents. - Lower effort or thinking for simple tasks. Thinking tokens bill as output tokens.
- Trim MCP overhead: Disable unused servers with
/mcp, and prefer CLI tools. - Offload work to hooks and skills: A hook that greps a log for
ERRORcan shrink tens of thousands of tokens to hundreds. - Move procedures out of CLAUDE.md and into skills.
- Delegate noisy work to subagents so verbose output stays out of your main context.
- Write specific prompts: “Improve this codebase” triggers broad scanning, while a named file and function do not.
- Use plan mode and early course correction: Press
Escthe moment Claude drifts. - Install code intelligence plugins for typed languages, which replace many file reads with symbol lookups.
Background usage is small. Conversation summarization and some commands typically cost under $0.04 per session. Long sessions climb for specific reasons: full history on every request, cache misses after long breaks, scheduled tasks firing while idle, cross-session messages, goal check-ins, subagents, and teammates. Agent teams use roughly seven times more tokens than a standard session.
Official docs: Manage costs effectively.
15. Commands and Shortcuts Cheat Sheet
Slash commands by workflow
| Moment | Commands |
|---|---|
| Starting a repo | /init, /memory, /mcp, /permissions, /doctor |
| During a task | /plan, /model, /effort, /fast, /advisor, /context, /compact, /btw, /goal |
| Running in parallel | /tasks, /subtask, /background, /fork, /batch, /workflows, /loop, /list-agents |
| Before shipping | /diff, /code-review, /simplify, /security-review, /verify, /autofix-pr |
| Between sessions | /clear, /resume, /branch, /rename, /teleport, /remote-control, /desktop, /export |
| When something is wrong | /rewind, /doctor, /debug, /status, /feedback, /bug |
| Customizing | /config, /output-style, /statusline, /theme, /keybindings, /hooks, /skills, /plugin, /sandbox |
| Cost and account | /usage, /usage-credits, /insights, /login, /logout, /privacy-settings |
| Integrations | /ide, /chrome, /install-github-app, /install-slack-app, /schedule, /mobile, /voice |
| Misc | /help, /powerup, /release-notes, /recap, /copy, /radio, /tui, /terminal-setup |
A command is recognized only at the start of your message. If you send one while Claude is responding, it queues and runs after the turn, except for quick ones like /status, /tasks, and /usage. MCP servers can expose prompts as extra commands.
Keyboard shortcuts
| Shortcut | Action |
|---|---|
Shift+Tab |
Cycle permission modes |
Esc |
Stop Claude mid-action; context is preserved |
Esc twice |
Open the rewind menu when the prompt is empty |
Ctrl+C |
Interrupt, or clear input; a second press exits |
Ctrl+D |
Exit; press twice to confirm |
Ctrl+G or Ctrl+X Ctrl+E |
Edit your prompt or a plan in your default editor |
Ctrl+O |
Show details such as an advisor’s or evaluator’s reasoning |
Ctrl+X Ctrl+K |
Stop all background subagents; press twice within 3 seconds |
Option+T or Alt+T |
Toggle extended thinking |
Option+W or Alt+W |
Dismiss the ultracode keyword highlight for one prompt |
@ |
Mention a file, or another session or agent |
! at the start |
Run a shell command directly, such as ! npm test |
On macOS, Option-key shortcuts need Option configured as Meta in your terminal. /terminal-setup installs a Shift+Enter binding for newlines in VS Code, Cursor, Alacritty, Zed, and similar terminals.
16. Best Practices and Failure Patterns
The official guidance rests on one idea. Context is the scarce resource, so keep it clean and give Claude ways to check its own work.
- Give Claude a way to verify its work: Tests, a build, a linter, or a screenshot comparison turn “looks done” into pass or fail. For unattended work, use a
/goalcondition or a Stop hook. - Explore, plan, then code: Use plan mode for multi-file changes or unfamiliar code. Skip it when you could describe the diff in one sentence.
- Be specific: Name the file, the scenario, and the existing pattern to follow. Point to sources, such as a file’s git history.
- Provide rich content: Reference files with
@, paste screenshots, give URLs, and pipe data withcat error.log | claude -p "explain". - Write a short CLAUDE.md: Include what Claude cannot guess, such as commands and quirks. Exclude what it can read from the code.
- Pre-approve safe commands and enable the sandbox so approvals do not become muscle memory.
- Use hooks for guarantees and instructions for guidance.
- Delegate investigation to subagents so exploration stays out of your main context.
- Correct early: After two failed corrections on the same issue, run
/clearand write a better opening prompt. - Let Claude interview you for larger features. Ask it to use
AskUserQuestion, write aSPEC.md, and then start a fresh session to implement it. - Use a writer and reviewer pair: A reviewer in a fresh context is not biased toward code it just wrote.
- Add an adversarial review step before you count unattended work as done, and tell the reviewer to flag only correctness or requirement gaps.
These failure patterns are common:
- The kitchen sink session: You mix unrelated tasks. Fix it with
/clearbetween tasks. - Correcting over and over: Failed approaches pollute the context. Restart with a sharper prompt.
- The over-specified CLAUDE.md: Rules get lost in noise. Prune hard, or convert rules into hooks.
- The trust-then-verify gap: A plausible implementation misses edge cases, so always demand evidence.
- The infinite exploration: An unscoped “investigate” reads hundreds of files. Scope it or delegate it.
17. Troubleshooting
claudeis not found after install: Open a new terminal. If it persists, the install directory is not on your PATH. Runclaude doctorfor details.- Something feels broken: Run
/doctorfor a checkup that can fix issues, orclaude doctoroutside a session.claude --safe-modestarts with every customization disabled, which tells you whether a plugin, hook, or CLAUDE.md is the cause. - Need logs: Run
/debugmid-session, start withclaude --debug, or use--debug-file <path>. Logs land in~/.claude/debug/<session-id>.txt. - Claude ignores CLAUDE.md: Run
/contextand check the Memory files list. Make instructions specific, remove contradictions, and use anInstructionsLoadedhook to log what loads. If the rule must always run, make it a hook. - AGENTS.md is not loading: A
CLAUDE.mdin your working directory or above wins by default. Import@AGENTS.mdfrom it, or change the Project instructions setting. - A hook does not fire: Run
/hooks, check the matcher and event name, and confirmdisableAllHooksis not set. Remember thatStophooks do not fire on user interrupts. - Auto mode is unavailable: Check your model, your provider, and whether any settings file sets
disableAutoMode. AdefaultModeof"auto"in project settings has no effect, so move it to~/.claude/settings.json. - Auto-compaction keeps failing: A single huge file or output is refilling context. Remove it, read it in parts, or delegate it to a subagent.
- Too many prompts: Add allow rules, enable the sandbox, or run
/fewer-permission-prompts. - Background sessions misbehave:
claude daemon statusprints the supervisor’s state, andclaude daemon stop --anyrecovers from an unresponsive one. - High memory use:
/heapdumpwrites a snapshot and a diagnostics file. Share only the diagnostics file, because the snapshot contains your conversation and credentials. - Start clean:
claude purge ~/work/repo --dry-runpreviews deleting a project’s local state.
18. Frequently Asked Questions
Is Claude Code free?
No, it needs a Pro, Max, Team, or Enterprise plan, a Claude Console account, or a supported cloud provider. The free claude.ai plan does not include it. The Desktop app also needs a paid plan.
Does Claude Code train on my code?
Under commercial terms (Team, Enterprise, API, and third-party platforms), Anthropic does not train generative models on your code or prompts unless your organization opts in. For Free, Pro, and Max accounts, a privacy setting lets you decide.
Which model does it use?
It depends on your plan and provider, and you can change it with /model. Aliases like opus, sonnet, haiku, and fable always point at the latest version for your provider. Pin exact versions with the ANTHROPIC_DEFAULT_*_MODEL variables.
Can it work offline?
No, Claude Code needs an internet connection to reach the model.
Can I use it with Amazon Bedrock, Google Cloud, or Microsoft Foundry?
Yes, the terminal CLI, VS Code, and JetBrains support third-party providers. Some features, such as fast mode, the advisor, and ultrareview, are not available there.
Does it replace my IDE?
No, it complements one. The VS Code extension and JetBrains plugin add inline diffs and selection sharing, while the terminal gives scriptability. See my IDE roundup and the IDE guide for the wider picture.
How do I stop it asking for permission constantly?
Use auto mode, pre-approve trusted commands in permissions.allow, and turn on /sandbox. Reserve bypassPermissions for isolated containers.
What is the difference between subagents and agent teams?
Subagents report results back to the session that spawned them. Teammates in an agent team are fully independent sessions that message each other and share a task list, at much higher token cost, and teams are experimental.
CLAUDE.md or a skill?
Put always-true rules in CLAUDE.md. Put reference material and workflows you need only sometimes in skills, which load on demand.
Does it work on Windows?
Yes, natively or through WSL. Native Windows runs without the sandbox, so use WSL 2 if you want sandboxed commands.
Can I run it in CI?
Yes, use claude -p with --bare, --allowedTools, and a permission mode, or use the official GitHub Action. Cap spend with --max-turns and --max-budget-usd.
19. Conclusion
Claude Code is best understood as a harness. A strong model reasons, a set of tools acts, and everything around them decides how much you can trust the loop. CLAUDE.md and auto memory give it durable context. Permission modes, rules, the sandbox, and hooks bound what it can do. Skills, subagents, MCP, and plugins extend it. Worktrees, agent view, and workflows multiply it.
The most reliable habit is also the simplest. Keep context clean, give Claude a check it can run, and review evidence instead of trusting claims. Start small with /init, a short CLAUDE.md, and plan mode. Add hooks, skills, and parallel agents only when a specific frustration calls for them.
Because the tool changes weekly, bookmark the official docs and the weekly “What’s new” digest. When this guide and the docs disagree, trust the docs.
20. References
Core documentation
- Claude Code overview
- How Claude Code works
- Advanced setup
- Best practices
- Extend Claude Code
- What’s new
Configuration and safety
- How Claude remembers your project
- Settings files and precedence
- Choose a permission mode
- Configure permissions
- Sandboxing
- Security
- Data usage
- Model configuration
- Fast mode
- Advisor tool
- Prompt caching
- Checkpointing
- Manage costs
Extending and automating
- Skills
- Subagents
- Hooks guide
- MCP
- Plugins overview
- Output styles
- Worktrees
- Agent view
- Agent teams
- Dynamic workflows
- Run Claude Code programmatically
- GitHub Actions
- Routines
- Keep Claude working toward a goal
- Ultrareview
Surfaces and reference
- Commands
- CLI reference
- Tools reference
- Manage sessions
- VS Code
- JetBrains IDEs
- Desktop application
- Remote Control
- Agent SDK overview