Skip to content

Instantly share code, notes, and snippets.

@gregsantos
Created March 5, 2026 15:48
Show Gist options
  • Select an option

  • Save gregsantos/9de5b5035c76a3a26df1fb4f708aa3f0 to your computer and use it in GitHub Desktop.

Select an option

Save gregsantos/9de5b5035c76a3a26df1fb4f708aa3f0 to your computer and use it in GitHub Desktop.
CLAUDE CODE — COMPREHENSIVE GUIDE

CLAUDE CODE — COMPREHENSIVE GUIDE

Last updated: February 2026


TABLE OF CONTENTS

  1. What is Claude Code?
  2. Installation & Setup
  3. How It Works — The Agentic Loop
  4. Core Interfaces
  5. Essential Commands & Shortcuts
  6. CLAUDE.md — Persistent Memory
  7. Skills — Custom Slash Commands
  8. MCP — Connecting External Tools
  9. Subagents — Specialized Assistants
  10. Hooks — Automation & Event Triggers
  11. Plugins — Bundled Extensions
  12. Best Practices
  13. Common Workflows
  14. Advanced Use — Automation & Scale
  15. Context Management
  16. Settings & Configuration
  17. Syncing Across Machines
  18. Quick Reference Card

1. WHAT IS CLAUDE CODE?

Claude Code is an agentic AI coding assistant that runs in your terminal (and desktop/IDE/web). Unlike inline code completers that only see the current file, Claude Code sees your whole project and can act across it.

When you ask Claude to "fix the authentication bug," it:

  • Searches for relevant files
  • Reads multiple files to understand context
  • Makes coordinated edits across them
  • Runs tests to verify the fix
  • Commits the changes if you ask

The key difference: It's a capable colleague who can do things, not just suggest them.

What Claude Code can do

Category Examples
File operations Read, edit, create, rename, reorganize files
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
Orchestration Spawn subagents, ask clarifying questions, delegate tasks

Where Claude Code runs

  • Terminal (CLI) — primary interface, supports scripting and automation
  • Desktop App — visual diff review, file attachments, session management
  • VS Code / JetBrains — IDE-native integration
  • Web — run on Anthropic's cloud infrastructure
  • GitHub Actions / GitLab CI/CD — automated PR reviews and issue triage
  • Slack — route bug reports to pull requests
  • Chrome extension (beta) — browser automation, live debugging, form filling, and data extraction via --chrome flag

2. INSTALLATION & SETUP

Install Claude Code

macOS, Linux, WSL (Recommended — auto-updates):

curl -fsSL https://claude.ai/install.sh | bash

Windows PowerShell:

irm https://claude.ai/install.ps1 | iex

Homebrew (does NOT auto-update):

brew install --cask claude-code

WinGet:

winget install Anthropic.ClaudeCode

Windows users: Requires Git for Windows installed first.

First Login

claude          # Starts interactive mode, prompts for login
/login          # Switch accounts or log in again later

Supported account types:

  • Claude.ai — Pro, Max, Teams, or Enterprise subscription
  • Console — API access with pre-paid credits
  • Cloud providers — Amazon Bedrock, Google Vertex AI

Initialize a Project

cd /path/to/your/project
claude          # Opens interactive session
/init           # Generates a starter CLAUDE.md from your project structure

/init analyzes your build systems, test frameworks, and code patterns to create a solid CLAUDE.md foundation.


3. HOW IT WORKS — THE AGENTIC LOOP

Claude Code operates as a Plan → Act → Reflect loop: it reasons about what to do, takes action with tools, observes the result, and repeats until the task is complete.

Phase What happens
Directive You describe the task — a bug fix, a feature, a question
Plan Claude understands the need, explores the codebase, and decides next steps
Act Claude uses tools — reads files, runs commands, edits code, calls APIs
Reflect Claude observes the result, adjusts its approach, and loops back
Outcome Task complete — Claude responds with a summary

The loop adapts to what you ask:

  • A question → context gathering only
  • A bug fix → cycles through all phases repeatedly
  • A refactor → extensive exploration and verification

You're always in the loop. Press Esc to interrupt, type a correction, or steer Claude in a different direction at any point.

Sessions

Each session is a conversation saved locally. Key facts:

  • Sessions are tied to directories — each project has its own sessions
  • Sessions start with a fresh context window (previous sessions don't bleed in)
  • Sessions can be resumed, rewound, and forked
  • Checkpoints are created before every file edit — fully reversible
  • Use auto memory and CLAUDE.md to persist learnings across sessions

4. CORE INTERFACES

Terminal (CLI)

The primary interface. Full feature support, scripting, automation.

claude                    # Start interactive session
claude "do this task"     # One-time task, then exit
claude -p "query"         # Single query (headless/non-interactive)
claude -c / --continue    # Resume most recent conversation
claude -r / --resume      # Pick from recent sessions
claude --worktree          # Start in an isolated git worktree

Desktop App

Best for: visual diff review, file attachments, managing parallel sessions.

To move a CLI session into Desktop:

/desktop    # (from inside CLI) — saves session and opens in Desktop app

Desktop vs CLI:

Use Desktop when... Use CLI when...
Visual diff review Scripting or automation
File attachments Third-party providers
Session management sidebar Prefer terminal workflow
PR monitoring Headless/CI use

Models Available

Select model from the dropdown (Desktop) or /model command (CLI):

  • Sonnet 4.6 — Fast, balanced for most tasks (default). 77.2% on SWE-bench Verified.
  • Opus 4.6 — Most capable, best for complex reasoning. Extended thinking for deep, multi-step problems. 65.4% on Terminal-Bench 2.0.
  • Haiku 4.5 — Fastest, cheapest, ideal for simple/repetitive tasks

Switch models mid-session with /model. Use Option/Alt + T to toggle extended thinking on/off.


5. ESSENTIAL COMMANDS & SHORTCUTS

Built-in Slash Commands

Command What it does
/help Show available commands
/init Generate CLAUDE.md from project structure
/clear Clear conversation history (fresh context)
/compact Compress session for long context
/compact focus on X Compact while preserving specific context
/context Show what's using context space
/memory Edit memory files (CLAUDE.md, auto memory)
/mcp Manage MCP servers and authentication
/permissions Manage tool permissions and allowlists
/model Change model or effort level
/agents View and manage subagents
/hooks Configure event hooks
/resume Open session picker
/rename Name the current session
/rewind Open checkpoint rewind menu
/desktop Move CLI session to Desktop app
/login Switch accounts
/sandbox Enable OS-level isolation
/statusline Configure terminal status line
/commit-push-pr Commit, push, and open PR in one step

Keyboard Shortcuts

Shortcut Action
Esc Interrupt Claude (context preserved)
Esc + Esc or /rewind Open rewind/checkpoint menu
Shift + Tab Cycle permission modes (Normal → Auto-accept → Plan)
Ctrl + G Open current plan in text editor
Ctrl + B Background a running task
Ctrl + O Toggle verbose mode (see Claude's reasoning)
Option/Alt + T Toggle extended thinking on/off
Tab Autocomplete filenames
? Show all keyboard shortcuts
@filename Reference a file in your prompt
/ Browse skills and commands

Permission Modes

Mode Behavior
Normal (default) Approves before every file edit
Auto-accept edits Auto-accepts file edits, faster iteration
Plan mode Read-only exploration, no file changes

6. CLAUDE.md — PERSISTENT MEMORY

CLAUDE.md is the single most important configuration file. Claude reads it at the start of every session, giving it persistent context it can't infer from code alone.

Memory Hierarchy

Type Location Scope
Managed policy /Library/Application Support/ClaudeCode/CLAUDE.md (macOS) All users in org
Personal (all projects) ~/.claude/CLAUDE.md All your projects
Project (shared) ./CLAUDE.md or ./.claude/CLAUDE.md Team via git
Project (local only) ./CLAUDE.local.md (auto-gitignored) Just you, current project
Auto memory ~/.claude/projects/<project>/memory/ Auto-managed by Claude
Modular rules ./.claude/rules/*.md Per-topic, path-scoped

What to Include

✅ Include ❌ Exclude
Bash commands Claude can't guess Anything Claude can figure out from code
Code style rules that differ from defaults Standard language conventions
Testing instructions and preferred test runners Detailed API documentation (link instead)
Repository etiquette (branch naming, PR conventions) Information that changes frequently
Architectural decisions specific to your project Long explanations or tutorials
Developer environment quirks (required env vars) File-by-file descriptions of the codebase
Common gotchas or non-obvious behaviors Self-evident practices like "write clean code"

Example CLAUDE.md

# Code style

- Use ES modules (import/export), not CommonJS (require)
- Destructure imports when possible

# Workflow

- Run `npm test` to verify changes
- Prefer running single tests over full suite for performance
- Always typecheck after a series of code changes

# Architecture

- API routes live in src/routes/, models in src/models/
- Use the existing error handler pattern (see src/middleware/errors.js)

# Git

- Branch names: feature/_, bugfix/_, chore/\*
- PR titles: "[TYPE] short description"

CLAUDE.md Tips

  • Keep it short and human-readable — overly long files cause Claude to ignore rules
  • For each line ask: "Would removing this cause Claude to make mistakes?" If not, cut it.
  • Add IMPORTANT: or YOU MUST to improve adherence to critical rules
  • Check it into git so your team can contribute — it compounds in value over time. When Claude makes a mistake, add a rule so it doesn't repeat it.
  • Import other files: See @README.md for project overview
  • Run /memory to edit all memory files interactively

Modular Rules (.claude/rules/)

For larger projects, organize instructions into focused files:

.claude/rules/
├── code-style.md     # Code style guidelines
├── testing.md        # Testing conventions
└── api-design.md     # API design patterns (scoped to src/api/**/*.ts)

Scope rules to specific file paths using frontmatter:

---
paths:
  - "src/api/**/*.ts"
---

# API Rules

- All endpoints must include input validation
- Use standard error response format

Auto Memory

Claude automatically saves useful context between sessions: project patterns, debugging insights, key commands, your preferences.

/memory              # Open memory file selector and toggle

Auto memory is stored in ~/.claude/projects/<project>/memory/MEMORY.md. You can tell Claude to save specific things: "remember that we use pnpm, not npm."


7. SKILLS — CUSTOM SLASH COMMANDS

Skills are reusable prompts and workflows you invoke with /skill-name or that Claude uses automatically when relevant. They follow the Agent Skills open standard.

Where Skills Live

Location Scope
~/.claude/skills/<name>/SKILL.md All your projects (personal)
.claude/skills/<name>/SKILL.md Current project only
<plugin>/skills/<name>/SKILL.md Where plugin is installed

Create a Skill

mkdir -p ~/.claude/skills/my-skill
# Create ~/.claude/skills/my-skill/SKILL.md

Every skill needs a SKILL.md with YAML frontmatter and markdown instructions:

---
name: fix-issue
description: Fix a GitHub issue by number. Use when asked to work on a specific issue.
disable-model-invocation: true
argument-hint: "[issue-number]"
---

Fix GitHub issue: $ARGUMENTS

1. Run `gh issue view $ARGUMENTS` to understand the problem
2. Search the codebase for relevant files
3. Implement the fix following our coding standards
4. Write and run tests to verify
5. Ensure linting and typechecking passes
6. Commit with descriptive message
7. Open a PR with `gh pr create`

Invoke with: /fix-issue 1234

Skill Frontmatter Reference

Field Description
name Creates /name slash command
description Claude uses this to decide when to load automatically
argument-hint Hint shown in autocomplete (e.g., [issue-number])
disable-model-invocation true = only YOU can invoke (Claude won't auto-trigger)
user-invocable false = hidden from / menu, only Claude can use
allowed-tools Tools Claude can use without asking when skill is active
model Model to use when skill is active
context fork = run in isolated subagent context
agent Which subagent to use with context: fork

Variable Substitutions

Variable Description
$ARGUMENTS All arguments after the skill name
$ARGUMENTS[0], $0 First argument
$ARGUMENTS[1], $1 Second argument
${CLAUDE_SESSION_ID} Current session ID
!`command` Runs shell command and injects output before Claude sees it

Invocation Control

# Only you can run this — Claude won't auto-trigger
disable-model-invocation: true

# Claude can auto-use but it's not a user command
user-invocable: false

Inner-Loop Workflow Tip

Use skills/commands for workflows you repeat many times a day — committing, reviewing PRs, running tests. Pre-compute context with inline bash (!`git status`) so the command runs fast without back-and-forth. Check commands into git (.claude/commands/) so the whole team benefits.

Run a Skill in a Subagent

---
name: deep-research
description: Research a topic thoroughly using isolated context
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Analyze the code
3. Summarize findings with file references

Workshop Examples — Useful Custom Skills

# .claude/skills/generate-hook/SKILL.md

---

name: generate-hook
description: Scaffold a React custom hook

---

Create a React hook called $ARGUMENTS with proper TypeScript types,
a corresponding test file, and add it to the hooks index.
# .claude/skills/pr-review/SKILL.md

---

name: pr-review
description: Comprehensive PR review
context: fork
agent: Explore

---

Review the current PR:

- Diff: !`gh pr diff`
- Comments: !`gh pr view --comments`

Check for: security issues, edge cases, test coverage, code style, performance.
Report findings organized by severity.

8. MCP — CONNECTING EXTERNAL TOOLS

Model Context Protocol (MCP) is an open standard for connecting Claude Code to external tools, databases, and APIs. With MCP, Claude can query your database, manage GitHub issues, check Slack, read Figma designs, and much more.

Add an MCP Server

# Remote HTTP server (recommended)
claude mcp add --transport http notion https://mcp.notion.com/mcp

# Remote HTTP with auth header
claude mcp add --transport http secure-api https://api.example.com/mcp \
  --header "Authorization: Bearer your-token"

# Local stdio server (runs as a process)
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
  --dsn "postgresql://user:pass@host:5432/mydb"

# With environment variables
claude mcp add --transport stdio airtable \
  --env AIRTABLE_API_KEY=YOUR_KEY -- npx -y airtable-mcp-server

Manage MCP Servers

claude mcp list           # List all configured servers
claude mcp get github     # Details for a specific server
claude mcp remove github  # Remove a server
/mcp                      # Check server status and authenticate (inside Claude Code)

Scopes

Scope Where stored Use for
local (default) ~/.claude.json (per-project) Personal / sensitive credentials
project .mcp.json (git-checked-in) Team-shared tools
user ~/.claude.json (global) Personal tools across all projects
# Project-scoped (shared with team via .mcp.json)
claude mcp add --scope project --transport http github https://api.githubcopilot.com/mcp/

# User-scoped (available in all projects)
claude mcp add --scope user --transport http sentry https://mcp.sentry.dev/mcp

OAuth Authentication

# Add server then authenticate
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
/mcp    # Follow browser login flow

Import from Claude Desktop

claude mcp add-from-claude-desktop    # Interactive selection of servers to import

Popular MCP Servers

Server What it enables
GitHub PR reviews, issue management, code search
Sentry Error monitoring, stack traces, deployment tracking
Slack Post messages, read channels, route issues
Notion Read/write docs and databases
Figma Access design files and components
PostgreSQL / Databases Query data naturally in plain English
Playwright Browser testing automation
Linear / Jira Issue tracker integration

Use MCP Resources with @

> Analyze @github:issue://123 and suggest a fix
> Compare @postgres:schema://users with @docs:file://database/user-model

Workflow Example

# 1. Add GitHub and Sentry MCP servers
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# 2. Use them together
> "Check Sentry for the most common errors in the last 24 hours,
   then create GitHub issues for the top 3 and assign them to me"

9. SUBAGENTS — SPECIALIZED ASSISTANTS

Subagents are specialized AI assistants with their own context window, custom system prompt, and specific tool access. Claude delegates tasks to them automatically or on your request.

Key benefits:

  • Context isolation — research stays out of your main conversation
  • Enforce constraints — limit which tools a subagent can use
  • Specialization — focused prompts for specific domains
  • Cost control — route simple tasks to Haiku

Built-in Subagents

Agent Model Tools Purpose
Explore Haiku (fast) Read-only File discovery, codebase search
Plan Inherits Read-only Research during Plan Mode
General-purpose Inherits All Complex multi-step tasks
Bash Inherits Bash Terminal commands in separate context

Create a Custom Subagent

Using the /agents command (recommended):

/agents

Select → Create new agent → User-level → Generate with Claude → Configure tools & model

Manually (create .claude/agents/security-reviewer.md):

---
name: security-reviewer
description: Reviews code for security vulnerabilities. Use proactively after implementing auth or data handling code.
tools: Read, Grep, Glob, Bash
model: opus
---

You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling

Provide specific line references and suggested fixes.

Subagent Frontmatter Reference

Field Description
name Unique identifier (lowercase-with-hyphens)
description When Claude should delegate to this agent (be descriptive!)
tools Tools the agent can use (omit = inherits all)
disallowedTools Tools to deny
model sonnet, opus, haiku, or inherit
permissionMode default, acceptEdits, dontAsk, bypassPermissions, plan
maxTurns Max agentic turns before stopping
skills Skills to preload into this agent's context
mcpServers MCP servers available to this agent
memory user, project, or local — enables cross-session learning
isolation worktree = run in isolated git worktree
background true = always run as background task

Usage Patterns

Let Claude decide: Describe the task and Claude picks the right agent

Review my recent code changes for security issues

Request explicitly:

Use the security-reviewer subagent to check the auth module
Use a subagent to investigate how our authentication system handles token refresh

Parallel research:

Research the auth, database, and API modules in parallel using separate subagents

Chain agents:

Use the code-reviewer to find performance issues, then use the optimizer to fix them

Persistent Memory for Subagents

---
name: code-reviewer
memory: user
---
You are a code reviewer. Update your memory with patterns and recurring issues you discover.

Memory is stored in ~/.claude/agent-memory/<name>/ and builds institutional knowledge over time.

Worktree Isolation

---
name: experimenter
isolation: worktree
---

Each invocation gets its own git worktree — safe to make risky changes.


10. HOOKS — AUTOMATION & EVENT TRIGGERS

Hooks run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions (advisory), hooks are deterministic guarantees.

Hook Events

Event Fires when
PreToolUse Before Claude uses any tool
PostToolUse After Claude uses any tool
Stop When Claude finishes responding
Notification When Claude needs your attention
SubagentStart When a subagent begins
SubagentStop When a subagent completes

Configure Hooks

/hooks    # Interactive configuration menu

Or edit .claude/settings.json directly:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npm run lint -- $TOOL_INPUT_FILE"
          }
        ]
      }
    ],
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

Common Hook Use Cases

# Run linter after every file edit
"command": "eslint --fix $TOOL_INPUT_FILE"

# Run tests after edits
"command": "npm test"

# Desktop notification when Claude is waiting
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"  # macOS
"command": "notify-send 'Claude Code' 'Needs your attention'"  # Linux

# Block writes to a protected folder
# (exit code 2 = block the action and report to Claude)
"command": "./scripts/check-protected-paths.sh"

Ask Claude to Write Your Hooks

Write a hook that runs eslint after every file edit
Write a hook that blocks writes to the migrations folder
Write a hook that sends me a desktop notification when you're waiting for input

11. PLUGINS — BUNDLED EXTENSIONS

Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit. Install them from the marketplace or from the community.

Install Plugins

+ button (next to prompt box) → Plugins → Browse and install

Or in CLI:

/plugin

What Plugins Can Include

  • Skills — domain-specific prompts and workflows
  • Subagents — specialized AI assistants
  • MCP servers — external tool integrations (auto-started when plugin is enabled)
  • Hooks — automation scripts

Code Intelligence Plugins

If you write TypeScript, Python, Go, or other typed languages, install a code intelligence plugin for your language. These give Claude:

  • Precise "go to definition" navigation
  • "Find all references" across files
  • Automatic error detection after edits

Browse the official plugin marketplace for your language at the + menu in Desktop.


12. BEST PRACTICES

The Fundamental Constraint

Most best practices exist because Claude's context window fills up fast, and performance degrades as it fills. Manage context aggressively.

Give Claude a Way to Verify Its Work

This is the single highest-leverage thing you can do. Include tests, screenshots, or expected outputs.

Strategy Vague Specific
Provide verification criteria "implement email validation" "write validateEmail. Test cases: user@example.com = true, invalid = false. Run tests after implementing"
Verify UI changes visually "make dashboard look better" "[paste screenshot] implement this design. Take screenshot of result, compare to original, list and fix differences"
Address root causes "the build is failing" "build fails with [paste error]. Fix it and verify build succeeds. Address root cause, don't suppress"

The Four-Phase Workflow

For complex tasks:

  1. Explore → Enter Plan Mode (Shift+Tab twice). Read files, understand context.
  2. Plan → Ask Claude to create a detailed implementation plan. Press Ctrl+G to edit it.
  3. Implement → Switch back to Normal Mode. Let Claude code, verifying against the plan.
  4. Commit → Ask Claude to commit with a descriptive message and open a PR.

Provide Specific Context

Strategy Vague Specific
Scope the task "add tests for foo.py" "write a test for foo.py covering the case where the user is logged out. avoid mocks."
Reference existing patterns "add a calendar widget" "look at HotDogWidget.php as a pattern example. follow that pattern for a new calendar widget"
Describe the symptom "fix the login bug" "login fails after session timeout. check src/auth/ especially token refresh. write a failing test first, then fix"

Give Claude Rich Context

  • @filename — reference files directly in your prompt
  • Paste images — copy/paste or drag and drop screenshots and diagrams
  • Pipe datacat error.log | claude -p "explain the root cause"
  • Give URLs — documentation and API references
  • Let Claude fetch — "use gh cli to get the issue details"

Prompting for Depth

Use explicit thinking modes:

think
think hard
think harder
ultrathink

Or use XML structure for complex prompts:

<instructions>Refactor the payment module</instructions>
<context>We use Stripe, the code is in src/payments/</context>
<constraints>Maintain backward compatibility with existing API</constraints>

Manage Sessions Well

  • /clear between unrelated tasks — fresh context nearly always outperforms a long cluttered one
  • If you've corrected Claude twice on the same issue/clear and rewrite the prompt incorporating what you learned
  • Name sessions with /rename oauth-migration — treat sessions like branches
  • Resume sessions with claude --resume oauth-migration
  • Rewind checkpoints with Esc+Esc or /rewind — every action is reversible

CLAUDE.md Maintenance

  • Prune regularly — if Claude already does something without the rule, delete it
  • Too long = ignored — critical rules get lost in noise
  • Convert stale rules to hooks — deterministic is better than advisory
  • Test changes by observing whether Claude's behavior actually shifts

Common Failure Patterns to Avoid

Anti-pattern Fix
Kitchen sink session — mixing unrelated tasks /clear between tasks
Correction loop — fixing the same issue repeatedly After 2 failures: /clear and write a better initial prompt
Bloated CLAUDE.md — too many rules, Claude ignores them Ruthlessly prune. Convert rules to hooks where possible
Trust without verify — shipping code without testing Always provide verification (tests, screenshots, scripts)
Infinite exploration — "investigate" without scope Scope investigations narrowly OR use subagents

13. COMMON WORKFLOWS

Understand a New Codebase

give me an overview of this codebase
explain the main architecture patterns used here
what are the key data models?
how is authentication handled?
trace the login process from front-end to database

Fix a Bug

I'm seeing this error when I run npm test: [paste error]
suggest a few ways to fix the null pointer in user.ts
update user.ts to add the null check you suggested
run the tests and confirm the fix works

Write Tests

find functions in AuthService.ts not covered by tests
add tests for the notification service covering edge conditions
run the new tests and fix any failures

Create a Pull Request

/commit-push-pr

Or step by step:

summarize the changes I've made to the authentication module
create a pr with a clear title and description
enhance the PR description with security improvement context

Refactor Code

find deprecated API usage in our codebase
suggest how to refactor utils.js to use modern JavaScript features
refactor utils.js to ES2024 features while maintaining the same behavior
run tests for the refactored code

Work with Images

  1. Drag and drop image into Claude Code window, or paste with Ctrl+V
  2. Describe what you want:
generate CSS to match this design mockup
what HTML structure would recreate this component?
here's a screenshot of the error — what's causing it?

Use Plan Mode for Safe Analysis

claude --permission-mode plan    # Start in plan mode
# or press Shift+Tab twice during a session

> read src/auth/ and understand how we handle sessions
> create a detailed plan for adding OAuth support
> what about backward compatibility?

Press Ctrl+G to open the plan in your editor and modify it directly.

Resume Previous Work

claude --continue          # Resume most recent conversation in current directory
claude --resume            # Open session picker
claude --resume auth-refactor    # Resume by name

Get Desktop Notifications

/hooks → Notification → + Match all → [enter notification command]

macOS: osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'


14. ADVANCED USE — AUTOMATION & SCALE

Headless Mode (Scripting & CI)

# One-off query
claude -p "What does this project do?"

# Structured output for scripts
claude -p "List all API endpoints" --output-format json

# Streaming real-time output
claude -p "Analyze this log file" --output-format stream-json

# Pipe data
cat error.log | claude -p "explain the root cause" > output.txt

Output formats: text (default), json, stream-json

Integrate into CI/CD

// package.json
{
  "scripts": {
    "lint:claude": "claude -p 'look at changes vs. main and report typos. format: filename:line on line 1, description on line 2'"
  }
}
# In GitHub Actions
claude -p "Review this PR for security issues" --output-format json

Fan-Out — Process Many Files in Parallel

# Generate task list
claude -p "list all Python files needing migration" > files.txt

# Loop through tasks in parallel
for file in $(cat files.txt); do
  claude -p "Migrate $file from Django 3 to Django 5. Return OK or FAIL." \
    --allowedTools "Edit,Bash(git commit *)" &
done
wait

Writer/Reviewer Pattern (Parallel Sessions)

Session A (Writer) Session B (Reviewer)
Implement a rate limiter for our API endpoints
Review the rate limiter in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with existing patterns.
Here's the review feedback: [paste Session B output]. Address these issues.

Parallel Sessions with Git Worktrees

# Start Claude in isolated worktree (auto-names it)
claude --worktree feature-auth

# Another session in a separate worktree
claude --worktree bugfix-123

# Auto-generate a random name
claude --worktree

Worktrees are created at <repo>/.claude/worktrees/<name>/. Add to .gitignore:

.claude/worktrees/

Agent Teams

For sustained parallelism with shared tasks and messaging, use agent teams:

# See agent-teams documentation at code.claude.com/docs/en/agent-teams

Skip Permission Prompts (Use with Caution!)

# For contained workflows like lint fixes or boilerplate generation
claude --dangerously-skip-permissions

# Or use /sandbox for OS-level isolation with similar autonomy but better security
/sandbox

⚠️ Only use --dangerously-skip-permissions in a sandboxed environment without internet access.

Long-Running Autonomous Tasks

For tasks that run unattended (large refactors, migrations, multi-file generation), combine autonomy with verification:

  1. Verify when done — prompt Claude to use a background agent to check its own work when finished, or use an agent Stop hook to run verification deterministically
  2. Remove permission blockers — use --permission-mode=dontAsk (less nuclear than --dangerously-skip-permissions) or run in a /sandbox so Claude isn't blocked waiting for approval
  3. Isolate the work — use --worktree so long-running changes happen on an isolated branch
# Long-running autonomous task in a sandboxed worktree
claude --worktree --permission-mode=dontAsk

Let Claude Interview You for Specs

I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs.
Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.

Then start a fresh session to implement the spec with clean context.


15. CONTEXT MANAGEMENT

Context is your most precious resource. Performance degrades as context fills.

How Context Is Used

Claude's context window holds:

  • Your entire conversation history
  • Every file Claude reads
  • Every command output
  • CLAUDE.md contents
  • Loaded skills and subagents descriptions
  • MCP server tool definitions

Monitor Context

/context    # See what's using context space
/mcp        # Check per-server context costs (MCP servers add tool definitions)

Install a custom status line to track context usage continuously:

/statusline

When Context Fills

Claude compacts automatically:

  • Clears older tool outputs first
  • Summarizes conversation if needed
  • Preserves your requests and key code snippets
  • May lose detailed instructions from early in the conversation

This is why CLAUDE.md exists. Don't rely on conversation history for persistent rules.

Control Compaction

/compact                           # Manual compact
/compact focus on the API changes  # Compact while preserving specific context

In CLAUDE.md:

# Compact Instructions

When compacting, always preserve: the full list of modified files, test commands, and API design decisions.

Context-Saving Strategies

Strategy How it helps
/clear between tasks Resets context entirely
Subagents Get their own fresh context window; return only a summary
Skills with disable-model-invocation: true Don't add description to context until invoked
Scoped investigations "only look at src/auth/" vs "investigate everything"
MCP Tool Search Dynamically loads tools on demand vs all upfront

16. SETTINGS & CONFIGURATION

Settings Files

File Purpose
~/.claude/settings.json Personal settings across all projects
.claude/settings.json Project settings (commit to git)
.claude/settings.local.json Local project overrides (auto-gitignored)
~/.claude.json OAuth tokens, machine state (don't sync!)

Key Settings

{
  "permissions": {
    "defaultMode": "plan", // or "normal", "acceptEdits"
    "allow": ["Bash(npm run lint)", "Bash(git commit *)"],
    "deny": ["Bash(rm -rf *)"]
  },
  "autoMemoryEnabled": true,
  "alwaysThinkingEnabled": true,
  "env": {
    "MAX_THINKING_TOKENS": "10000",
    "CLAUDE_CODE_EFFORT_LEVEL": "high", // low, medium, high (Opus 4.6)
    "ENABLE_TOOL_SEARCH": "auto" // for MCP tool search
  }
}

Allowlist Safe Commands

Reduce permission fatigue by pre-approving safe operations:

/permissions    # Interactive permission management

Or add directly to settings.json:

{
  "permissions": {
    "allow": [
      "Bash(npm run lint)",
      "Bash(npm test)",
      "Bash(git add *)",
      "Bash(git commit *)",
      "Bash(git push)"
    ]
  }
}

Prefer /permissions over --dangerously-skip-permissions. Pre-approve the specific commands you know are safe in your environment, and check them into .claude/settings.json so the whole team shares the same allowlist. This eliminates permission fatigue without disabling the safety model entirely.

Environment Variables

Variable Purpose
MAX_THINKING_TOKENS Limit thinking token budget
CLAUDE_CODE_EFFORT_LEVEL Thinking depth for Opus 4.6 (low/medium/high)
ENABLE_TOOL_SEARCH MCP tool search behavior (auto/true/false)
MCP_TIMEOUT MCP server startup timeout in ms
MAX_MCP_OUTPUT_TOKENS Max tokens for MCP tool output (default: 25000)
CLAUDE_CODE_DISABLE_AUTO_MEMORY 1 = disable auto memory
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS 1 = disable background tasks
SLASH_COMMAND_TOOL_CHAR_BUDGET Override skills context budget

17. SYNCING ACROSS MACHINES

What to Sync

Store in a dotfiles repo or iCloud:

~/.claude/
├── settings.json     # Permissions, hooks, env vars
├── CLAUDE.md         # Personal instructions
├── agents/           # Custom subagents
├── rules/            # Personal rules
└── skills/           # Personal skills

What NOT to Sync

  • ~/.claude.json — contains OAuth tokens, machine-specific state. Each machine authenticates independently.

Dotfiles Repo (Recommended)

# Main machine
mkdir -p ~/.dotfiles/claude
cp ~/.claude/settings.json ~/.dotfiles/claude/
cp ~/.claude/CLAUDE.md ~/.dotfiles/claude/
git add && git commit && git push

# Other machines
git clone https://github.com/you/dotfiles ~/.dotfiles
ln -s ~/.dotfiles/claude/settings.json ~/.claude/settings.json
ln -s ~/.dotfiles/claude/CLAUDE.md ~/.claude/CLAUDE.md

iCloud Symlinks

mkdir -p ~/Library/Mobile\ Documents/com~apple~CloudDocs/claude-config
mv ~/.claude/settings.json ~/Library/Mobile\ Documents/.../claude-config/
ln -s ~/Library/Mobile\ Documents/.../claude-config/settings.json ~/.claude/settings.json

Project Config — Syncs Automatically via Git

.claude/
├── settings.json          # Team settings
├── CLAUDE.md              # Project instructions (committed)
├── CLAUDE.local.md        # Personal overrides (gitignored)
├── agents/                # Team subagents
├── skills/                # Team skills
└── rules/                 # Modular rules
.mcp.json                  # MCP server config (committed)

18. QUICK REFERENCE CARD

Start Here

curl -fsSL https://claude.ai/install.sh | bash    # Install
claude                                              # Start session
/init                                               # Generate CLAUDE.md
/help                                               # Show commands

Daily Workflow

claude                         # Start
@filename                      # Reference a file
Shift+Tab                      # Cycle permission modes
Esc                            # Interrupt Claude
Esc+Esc or /rewind             # Undo / checkpoint
/clear                         # Fresh context
/compact                       # Compress context
claude --continue              # Resume last session

Context Ladder (from least → most control)

Conversation instruction
→ CLAUDE.md rule
→ Skill (reusable prompt)
→ Hook (guaranteed execution)
→ Subagent (isolated context)
→ MCP server (external tool)
→ Plugin (bundled package)

Key Files

CLAUDE.md           → What Claude knows by default
.claude/agents/     → Custom subagents
.claude/skills/     → Custom slash commands
.claude/rules/      → Modular instruction files
.mcp.json           → Shared MCP server config
~/.claude/          → Personal config (all projects)

When to Use What

Need Use
Persistent project instructions CLAUDE.md
Personal instructions across projects ~/.claude/CLAUDE.md
Reusable prompt or workflow Skill (.claude/skills/)
Guaranteed action on every event Hook
Task in isolated context Subagent
External tool / database / service MCP server
Bundled tools for distribution Plugin
CI/CD / scripting claude -p (headless)
Multiple tasks in parallel Git worktrees + parallel sessions

Prompt Quality Checklist

  • Reference specific files (@src/auth/login.ts)
  • Describe symptoms, not just requests ("login fails after session timeout")
  • Include verification method ("run tests after implementing")
  • Point to example patterns ("follow the pattern in HotDogWidget.php")
  • State constraints ("maintain backward compatibility")
  • Use Plan Mode for multi-file changes

The Golden Rules

  1. Give Claude a way to verify its work — tests, screenshots, expected outputs
  2. Explore first, then plan, then code — separate research from implementation
  3. Manage context aggressively/clear between unrelated tasks
  4. Be specific — vague prompts work but specific prompts succeed on the first attempt
  5. Keep CLAUDE.md short — bloated = ignored; ruthlessly prune
  6. Commit CLAUDE.md — it compounds in value over time for your whole team
  7. Interrupt early — correct off-track work immediately, don't let it compound
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment