Contents

Startup Parameters

Claude Code accepts command-line flags when launched from the terminal. These control session behavior, model selection, permissions, and output format.

Session and Output

FlagWhat It DoesExample
--print / -pPrint response and exit without interactive modeclaude -p "explain this project"
--continue / -cResume the most recent conversation in the current directoryclaude -c
--resume / -rResume a session by ID or nameclaude -r "auth-refactor"
--name / -nSet a display name for the sessionclaude -n "feature-work"
--fork-sessionCreate new session ID while preserving conversation historyclaude --resume abc --fork-session
--output-formatOutput format: text, json, stream-json (print mode)claude -p --output-format json "query"
--max-turnsLimit number of agentic turns (print mode)claude -p --max-turns 5 "query"
--max-budget-usdMaximum dollar amount to spend on API calls (print mode)claude -p --max-budget-usd 5.00 "query"

Model and Effort

FlagWhat It DoesExample
--modelSet model for the session (alias or full name)claude --model opus
--effortSet effort level: low, medium, high, maxclaude --effort high
--fallback-modelEnable automatic fallback when default model is overloaded (print mode)claude -p --fallback-model sonnet "query"

Permissions and Safety

FlagWhat It DoesExample
--permission-modeStart in a specific mode: default, acceptEdits, plan, auto, bypassPermissions, dontAskclaude --permission-mode plan
--allowedToolsTools that execute without promptingclaude --allowedTools "Bash(git *)" "Read"
--disallowedToolsTools removed from Claude's context entirelyclaude --disallowedTools "Bash(rm *)"
--dangerously-skip-permissionsSkip all permission prompts (isolated environments only)claude -p --dangerously-skip-permissions "refactor"

System Prompt Customization

FlagWhat It DoesExample
--system-promptReplace the entire default system promptclaude --system-prompt "You are a Python expert"
--system-prompt-fileLoad replacement system prompt from a fileclaude --system-prompt-file ./prompt.txt
--append-system-promptAppend custom text to the default promptclaude --append-system-prompt "Always use TypeScript"
--append-system-prompt-fileAppend file contents to the default promptclaude --append-system-prompt-file ./rules.txt

Configuration and Extensions

FlagWhat It DoesExample
--settingsLoad additional settings from a JSON fileclaude --settings ./settings.json
--add-dirAdd additional working directoriesclaude --add-dir ../lib ../shared
--mcp-configLoad MCP servers from JSON fileclaude --mcp-config ./mcp.json
--agentUse a specific agent for the sessionclaude --agent security-reviewer
--worktree / -wStart in an isolated git worktreeclaude -w feature-auth
--bareMinimal mode: skip hooks, skills, plugins, MCP, memory, CLAUDE.mdclaude --bare -p "query"
--verboseEnable verbose logging with full turn-by-turn outputclaude --verbose
--version / -vPrint version number and exitclaude -v

Essential Commands

Type / in Claude Code to see all available commands. These are the built-in slash commands organized by category.

Sessions and Navigation

CommandWhat It Does
/resumeResume a past session from an interactive picker
/clearStart a new session without saving the current conversation
/renameChange the display name of the current session
/btwAsk a quick side question without adding to conversation history

Memory and Instructions

CommandWhat It Does
/initGenerate a starting CLAUDE.md file based on codebase analysis
/memoryBrowse, open, and edit CLAUDE.md and auto memory files; toggle auto memory on/off

Context and Performance

CommandWhat It Does
/compactSummarize conversation to free context space; optionally add focus: /compact focus on the API changes
/contextView what is using space in the context window
/costView token and API usage costs for the current session

Configuration and Settings

CommandWhat It Does
/configOpen configuration interface to adjust settings
/settingsView or modify settings files
/modelSwitch models and adjust effort level
/effortChange effort level: low, medium, high, max, or auto
/themeChoose color theme or toggle syntax highlighting
/vimEnable vim-style editing mode
/terminal-setupSet up terminal shortcuts (e.g., Shift+Enter for multiline)

Planning and Safety

CommandWhat It Does
/planEnter plan mode to propose changes without making them; prefix to any prompt
/diffView uncommitted changes in the current repository

Tools and Extensions

CommandWhat It Does
/agentsList all configured subagents and manage configuration
/mcpConfigure and manage MCP servers and their costs
/pluginDiscover, install, and manage plugins
/hooksView and manage configured hooks

Utilities

CommandWhat It Does
/exportExport conversation as plain text
/statusView current authentication status and account information
/doctorDiagnose common issues and see keybinding warnings
/feedbackReport bugs, feature requests, or other feedback
/helpShow help menu
Tip: Type ! at the start of your input to run a bash command directly (e.g., ! git status). The output is added to the conversation context. Type @ to trigger file path autocomplete.

Memory System

Claude Code has an auto-memory system that accumulates knowledge across sessions. Claude saves notes for itself based on patterns, corrections, and discoveries.

What Gets Stored

Stored

  • Build commands and how to run tests
  • Debugging insights and solutions
  • Architecture notes and design patterns
  • Code style preferences Claude discovers
  • Workflow habits and shortcuts
  • Project-specific conventions

Not Stored

  • One-off questions or advice
  • Sensitive information (credentials, API keys, personal data)
  • General context that does not serve future sessions
  • Information derivable from code or git history
  • Ephemeral task details

Where Memory is Stored

~/.claude/projects/<project>/memory/
  MEMORY.md              # Index file (loaded at session start)
  debugging.md           # Topic-specific notes
  api-conventions.md     # (Claude creates these as needed)
  ...

Memory is stored per project (derived from the git repository). All worktrees within the same repo share one memory directory. Memory is machine-local and is not synced to the cloud.

Size Limits

ResourceLimit
MEMORY.md loaded at startupFirst 200 lines or 25KB, whichever comes first
Topic filesNo per-file limit; loaded on demand when relevant
Total memory directoryNo hard limit; keep reasonable for performance

Enable, Disable, and Manage

View and edit memory

/memory

Opens an interactive browser showing all CLAUDE.md and rule files loaded in the session, a toggle for auto memory, and a link to open the memory folder. You can also edit files directly at ~/.claude/projects/<project>/memory/.

Disable auto memory

Three methods:

# In a session
/memory   (then toggle off)

# In settings file (.claude/settings.json or ~/.claude/settings.json)
{ "autoMemoryEnabled": false }

# Via environment variable
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1

Custom memory location

Set in user or local settings (not project settings):

{ "autoMemoryDirectory": "~/my-custom-memory-dir" }

Clear memory

Delete files directly from ~/.claude/projects/<project>/memory/. There is no slash command to bulk-clear memory. You can also ask Claude to forget specific things and it will remove the relevant entries.

CLAUDE.md vs. Auto Memory: CLAUDE.md is written by you and contains instructions and rules. Auto memory is written by Claude and contains learnings and patterns. Both are loaded at session start. Use CLAUDE.md for things that must always be followed; let auto memory handle things Claude discovers on its own.

Context Window Management

The context window holds your conversation history, file contents, command outputs, CLAUDE.md instructions, auto memory, loaded skills, and system instructions. When it fills up, older content is compressed.

Context Limits by Model

ModelStandardExtended
Opus 4.6200K tokens1M tokens
Sonnet 4.6200K tokens1M tokens
Haiku 4.5200K tokensNot available

1M context is included with Max and Team plans. Pro and API users can access it via extra usage.

How /compact Works

Basic compaction

/compact

Claude summarizes earlier parts of the conversation, preserving your requests and key code snippets. Detailed instructions from early in the conversation may be lost, but CLAUDE.md is always re-injected fresh from disk.

Focused compaction

/compact focus on the API changes

Tells Claude what to prioritize when summarizing. Use this to preserve specific context that matters for your current task.

When Context Fills Up

Claude Code manages context automatically in this order:

  1. First: Clears older tool outputs
  2. Next: Summarizes conversation if needed
  3. Preserved: Your requests and key code snippets
  4. May lose: Detailed instructions from early in the conversation
Tip: Put persistent rules in CLAUDE.md, not just in conversation messages. CLAUDE.md is re-loaded from disk after compaction, so its content is never lost. Run /context to see what is consuming space.

Permission Modes

Permission modes control what Claude can do without asking. Cycle through them with Shift+Tab during a session.

ModeClaude Can Do Without AskingBest For
defaultRead files onlyGetting started, sensitive work
acceptEditsRead and edit filesIterating on code you are reviewing
planRead files, explore only (no edits)Exploring codebase, planning refactors
autoAll actions with background safety checksLong-running tasks, reducing prompts
dontAskOnly pre-approved tools (allow rules)Locked-down environments
bypassPermissionsEverything, no checksIsolated containers and VMs only

How to Set

During a session

Press Shift+Tab to cycle through: default, acceptEdits, plan, auto.

At startup

claude --permission-mode plan
claude --permission-mode acceptEdits

As a persistent default

# In .claude/settings.json or ~/.claude/settings.json
{
  "permissions": {
    "defaultMode": "acceptEdits"
  }
}

Fine-Grained Permission Rules

Add allow and deny rules in settings for specific tool patterns:

{
  "permissions": {
    "allow": [
      "Bash(npm test)",
      "Bash(git *)",
      "Read"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push --force *)"
    ]
  }
}

Auto Mode Details

Auto mode uses a background classifier to evaluate actions. It blocks by default:

It allows by default: local file operations, installing declared dependencies, read-only HTTP requests, and pushing to your branch.

Model Selection

Claude Code supports multiple models with aliases for convenience. Aliases always point to the latest version.

Available Models

AliasModelBest For
opusClaude Opus 4.6Complex reasoning, architecture decisions
sonnetClaude Sonnet 4.6Daily coding tasks, fast iteration
haikuClaude Haiku 4.5Simple tasks, quick answers
opus[1m]Opus with 1M contextLong sessions, large codebases
sonnet[1m]Sonnet with 1M contextLong sessions with fast execution
opusplanOpus for planning, Sonnet for executionStrong planning with efficient coding

How to Switch

MethodCommandPriority
In session/model opusHighest
At startupclaude --model opusHigh
Environment variableexport ANTHROPIC_MODEL=opusMedium
Settings file{ "model": "opus" }Lowest

Effort Levels

Controls how deeply Claude reasons about each response. Persists across sessions except max.

LevelWhen to Use
lowFast, straightforward tasks
mediumDefault; recommended for most coding
highComplex debugging, architectural decisions
maxDeepest reasoning (Opus 4.6 only)
autoReset to model default

Set with /effort high, claude --effort high, or include "ultrathink" in your prompt for a one-off high-effort turn.

MCP Servers

MCP (Model Context Protocol) servers are external integrations that extend Claude's capabilities by connecting to third-party services, databases, and tools.

What MCP Servers Do

Configuration

Interactive setup

/mcp

Shows installed MCP servers, per-server token costs, and options to add or remove servers.

Via settings file

# In .claude/settings.json or ~/.claude/settings.json
{
  "mcpServers": {
    "github": {
      "type": "stdio",
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "YOUR_TOKEN"
      }
    }
  }
}

At startup

claude --mcp-config ./mcp.json

Server Types

TypeDescriptionUse Case
stdioLocal process communicating via stdin/stdoutLocal tools, CLIs, scripts
httpCloud-hosted server over HTTPHosted services, SaaS integrations
sseServer-sent events connectionStreaming data sources

Installation Scopes

ScopeFileShared
Local (personal).claude/settings.local.jsonNo
Project (team).claude/settings.jsonYes, via git
User (all projects)~/.claude/settings.jsonNo
Context efficiency: MCP tool definitions are deferred by default. Only tool names consume context tokens at session start. Full definitions load on demand when Claude uses a specific tool. Run /mcp to check per-server token costs.

Keyboard Shortcuts

All shortcuts except Ctrl+C and Ctrl+D are customizable via /keybindings.

General Controls

ShortcutAction
Ctrl+CCancel current input or generation
Ctrl+DExit Claude Code session
Ctrl+LClear terminal screen (keeps conversation)
Ctrl+OToggle verbose output / transcript view
Ctrl+RReverse search command history
Ctrl+TToggle task list visibility
Esc EscRewind or summarize

Mode and Model Switching

ShortcutAction
Shift+TabCycle permission modes: default, acceptEdits, plan, auto
Option+P / Alt+PSwitch model without clearing prompt
Option+T / Alt+TToggle extended thinking mode
Option+O / Alt+OToggle fast mode

Text Editing

ShortcutAction
Ctrl+KDelete to end of line
Ctrl+UDelete from cursor to line start
Ctrl+YPaste deleted text
Alt+BMove cursor back one word
Alt+FMove cursor forward one word
Ctrl+GOpen input in external text editor
Ctrl+SStash current prompt

Multiline Input

MethodHow
Quick escape\ then Enter (works in all terminals)
macOS defaultOption+Enter
Shift+EnterWorks in iTerm2, WezTerm, Ghostty, Kitty; run /terminal-setup for others
Control sequenceCtrl+J (line feed)
Paste modePaste directly for multi-line code blocks

Quick Input Prefixes

PrefixAction
/Show available commands and skills
!Run bash command directly (output added to session)
@File path autocomplete mention
macOS note: Option/Alt shortcuts require configuring Option as Meta in your terminal. In iTerm2: Settings, Profiles, Keys, set Left Option to "Esc+". Run /terminal-setup to configure Shift+Enter for multiline input.

Tracking Projects Between Sessions

Claude Code sessions are independent by default -- each new session starts fresh. Keeping context across sessions requires deliberate use of persistence mechanisms. Here is every tool available and when to use each one.

1. Resume a Previous Session

Continue exactly where you left off

The most direct way to maintain context is to resume the previous session. Claude reloads the full conversation history, including all file reads, edits, and decisions made.

# Resume the most recent session in the current directory
claude -c

# Pick from a list of past sessions
claude --resume

# Resume a specific named session
claude -r "auth-refactor"

# Resume and continue with a new prompt
claude -c "now add the unit tests"

# Inside a session
/resume

When to use: You are continuing the same task from yesterday. You want Claude to remember everything -- the files it read, the approach it chose, and the rationale for decisions.

Limitations: Old sessions eventually exceed the context window. If the session is very long, earlier messages may be auto-compacted. Named sessions make it easier to find the right one later.

2. Name Your Sessions

Make sessions findable later

Unnamed sessions pile up and become hard to distinguish. Name every session that you might return to.

# Start a named session
claude -n "payment-refactor"

# Rename the current session
/rename checkout-migration

# Resume by name later
claude -r "payment-refactor"

When to use: Any multi-session task. Name by feature, ticket, or branch -- whatever helps you find it in a list of 20 sessions.

3. CLAUDE.md for Persistent Instructions

Rules that survive every session

CLAUDE.md is re-loaded from disk at the start of every session and re-injected after compaction. It is the most durable form of project context.

# .claude/CLAUDE.md -- always loaded, never lost
## Current Sprint
- Auth migration to Supabase (deadline: April 15)
- Do not modify legacy auth until migration is complete

## In-Progress Work
- Payment refactor: branch payment-v2, PR #142
- Checkout flow: waiting on design review before proceeding

## Decisions Made
- Using Riverpod over Bloc (decided March 15, see ADR-003)
- Storing monetary values as integers in cents

When to use: Project-level context that every session should know. Sprint priorities, in-progress branches, architectural decisions, and constraints that apply to all work.

How to maintain: Update the "Current Sprint" and "In-Progress Work" sections weekly. Remove completed items. Claude reads this every time -- stale entries waste context and cause confusion.

4. Auto Memory for Learned Context

What Claude remembers on its own

Auto memory persists things Claude discovers during sessions -- build commands, debugging patterns, your preferences, and project conventions. It is stored in ~/.claude/projects/<project>/memory/ and the index (MEMORY.md) is loaded at every session start.

# View and manage memory
/memory

# Ask Claude to remember something specific
"Remember that the payments service requires VPN access to test locally"

# Ask Claude to forget something
"Forget what you saved about the old auth system"

When to use: Let it run in the background. Claude will save things that help future sessions -- corrections you give it, patterns it discovers, and solutions to problems it encounters. Review periodically with /memory and prune stale entries.

What it does not do: Auto memory does not save task progress, TODO lists, or debugging logs. It saves patterns and learnings, not ephemeral state.

5. Git as the Source of Truth

Commits and branches carry context forward

The most reliable way to carry work between sessions is through git. Commits, branch names, and PR descriptions persist indefinitely and Claude can read them.

# Start a new session and catch up via git
claude
> "Check git log and the open PRs to understand what I was working on yesterday"

# Or be specific
claude -c "I was working on the checkout migration on branch checkout-v2.
Check the recent commits and continue where I left off."

When to use: Always. Commit frequently with descriptive messages. Create PRs with detailed descriptions. When you return to a session, Claude can reconstruct context from the git history even without resuming the old session.

Best practices:

  • Commit at natural stopping points, even if the work is incomplete (use a WIP commit on a feature branch)
  • Write commit messages that explain why, not just what
  • Use PR descriptions to document the overall approach and remaining work
  • Branch names should match the task: feature/checkout-migration, fix/payment-rounding

6. Worktrees for Parallel Workstreams

Isolated branches with their own sessions

Git worktrees let you work on multiple features simultaneously, each with its own directory and Claude session.

# Start Claude in an isolated worktree
claude -w checkout-migration

# Each worktree gets its own session history
# Resume a worktree session later
claude -w checkout-migration -c

When to use: You are juggling multiple features or reviewing a PR while working on something else. Each worktree has its own working directory, branch, and Claude session, so context does not bleed between tasks.

7. TODO Comments and Task Files

Leave breadcrumbs in the code

For fine-grained task tracking within a feature, leave TODO comments in the code itself. Claude can find and act on them in the next session.

// TODO(floyd): Add retry logic for failed payments -- see Stripe docs
// TODO: Validate coupon codes against the promotions table
// TODO: Write integration tests for the checkout flow

When to use: When you stop mid-feature and need to remember specific next steps. In the next session, ask Claude to find and work through the TODOs:

"Find all TODO comments in the checkout feature and work through them"

8. Handoff Prompts

Write a briefing for the next session

Before ending a session, ask Claude to write a handoff summary that you can paste into the next session.

# At the end of a session
"Write a handoff summary of what we did, what is left to do, and any
decisions we made. I will paste this into our next session."

Claude will produce a structured summary of the work done, open questions, and next steps. Save it in a file, a note, or just copy it. Paste it as the first message of the next session:

# Start of next session
"Here is context from our last session: [paste handoff summary].
Continue with the next item."

When to use: When resuming the old session is not practical (too long, too old, or different machine). The handoff summary is more focused than a full session resume because it captures only what matters for the next step.

Recommended Workflow

Combine these mechanisms based on the duration and complexity of your work:

ScenarioApproach
Quick task (1 session)No special tracking needed. Commit when done.
Multi-day featureName the session. Commit at stopping points. Resume with claude -c or claude -r "name".
Long-running projectTrack priorities and in-progress work in CLAUDE.md. Use git branches and PRs. Let auto memory accumulate patterns.
Team projectCLAUDE.md in version control for shared context. PR descriptions for handoffs. Named branches per feature.
Switching between tasksUse worktrees (claude -w). Each task gets its own isolated branch and session.
Different machineGit carries everything. Start a new session and point Claude at the branch, PR, or recent commits.
Key principle: The more durable the context, the less you need to repeat yourself. CLAUDE.md survives every session. Auto memory survives across sessions. Git survives across machines. Session resume preserves everything but expires. Conversation messages are the most ephemeral -- anything important should graduate to one of the persistent layers.