1.1 Installation

bash
npm install -g @anthropic-ai/claude-code

cd your-project
claude

VS Code users: install the Claude Code extension from Anthropic. You get an integrated terminal panel and a chat sidebar — use whichever fits your flow.

1.2 Choosing Your Model

Three models, different tradeoffs:

ModelUse forSpeed
HaikuSimple tasks, quick lookups, formattingFast
SonnetMost day-to-day work — good balanceMedium
OpusComplex reasoning, architecture decisions, deep debuggingSlower

Switch mid-session with /model. Default to Sonnet. Escalate to Opus when you're stuck or working on something that needs careful reasoning. Haiku is great for fast, repetitive things like generating boilerplate or reformatting.

1.3 First Run on a New Project

bash
cd my-project

# Let Claude scan the project and create CLAUDE.md
/init

# Read and improve what it generated — /init output is a starting point, not a finished file
# See Section 8 for how to make it actually good

# Start working

1.4 Essential Commands

CommandWhat it does
/initScans your project, creates CLAUDE.md
/contextShows token usage — how full your context window is
/compact [instructions]Compresses conversation history, you control what's kept
/clearWipes conversation history entirely, fresh start
/simplifyReviews your diff and applies readability/simplification fixes directly
/modelSwitch model for the current session
/hooksSet up automated scripts (session start, file save, etc.)
/pluginBrowse, install, and manage plugins
!Prefix to run a raw bash command

A CLAUDE.md that Claude actually follows isn't just about what you write — it's about how you structure it. The same instruction written as prose vs. structured markdown produces very different results.

2.1 The Signal vs. Noise Principle

Length is the ceiling. Formatting is the signal.

Claude doesn't read your CLAUDE.md the way you do. It allocates attention based on structural cues — headers, code blocks, lists. Instructions buried in paragraphs get buried in attention.

The same instruction, two ways:

❌ Gets ignored:

text
When working on this project, always make sure to run the test suite
before committing any changes. The command to run tests is pytest and
you should run it from the project root. If tests fail, fix them before
committing. Also make sure to use ruff for formatting.

✅ Gets followed:

markdown
## Testing

- `pytest` — run from project root before every commit
- Fix failures before committing

## Formatting

- `ruff check --fix && ruff format` — run before committing

Same content. One gets acted on.

2.2 Seven Formatting Rules for CLAUDE.md

Rule 1: Include the reason for every prohibition

A rule tells Claude what not to do. A rule with a reason tells Claude why, which means it can generalise. An agent that understands why force-push is banned will also avoid git reset --hard origin/main without being told.

markdown
# ❌ Rule only
- Never use `rm -rf` on the project root

# ✅ Rule + reason
- Never use `rm -rf` on the project root — irrecoverable data loss
- Never force push — rewrites shared history, unrecoverable for collaborators
- Don't modify `package-lock.json` manually — breaks lockfile integrity and causes merge conflicts

Rule 2: Keep heading depth to three levels max

Deep nesting dilutes attention. If you need an h4, you probably need a separate file.

markdown
# ✅ Max 3 levels
# Project
## Testing
### Unit Tests

# ❌ Too deep
# Project
## Development
### Testing
#### Unit Tests
##### Mocking Strategy

Rule 3: Use descriptive file names for everything Claude might open

Claude decides which files to read based on the name before opening them. api-authentication.md gets opened when working on auth. guide.md never does.

Rule 4: One topic per header

Headers act as a table of contents. They're how Claude navigates to the right section. Without them, every instruction competes equally for attention.

Rule 5: Commands go in code blocks

A command in a sentence is a suggestion. In a code fence it's a directive.

markdown
# ❌ Suggestion
You can run the linter by running npm run lint.

# ✅ Directive
- `npm run lint` — check for style issues
- `npm test` — run test suite

Rule 6: Use standard section names

Claude has been trained on millions of README files. ## Testing, ## Commands, ## Structure, ## Conventions carry built-in recognition. Creative section names don't.

Rule 7: Make every instruction immediately actionable

Test: could Claude act on this right now without a clarifying question? If not, it's not an instruction.

markdown
# ❌ Not actionable
Make sure code quality is maintained.

# ✅ Actionable
## Conventions
- Format with `ruff format` before committing
- Type annotations required on all public functions
- No `print()` in production code — use `logging`

2.3 Before / After: A Full Rewrite

Before:

text
This project is a Python CLI tool. We use pytest for testing and ruff
for linting. Make sure to run tests before you commit anything. The
source code is in src/myapp and tests are in tests/. Don't modify
anything in the dist/ folder because that's generated.

After:

markdown
## Project
Python CLI tool for [purpose].

## Testing
- `pytest` — run from project root before every commit
- Test behaviour, not implementation — assert outcomes, not internal calls
- Use `@pytest.mark.parametrize` when cases share the same assertion shape

## Formatting
- `ruff check --fix && ruff format`

## Structure
- Source: `src/myapp/`
- Tests: `tests/`

## Boundaries
- `dist/` — generated, do not modify

Half the words. Every instruction lands.

2.4 Path-Scoped Rules (L4 Level)

For larger projects, load only the rules relevant to the file being edited:

text
.claude/
└── rules/
    ├── api-rules.md        # applies when editing: src/api/**
    ├── frontend-rules.md   # applies when editing: src/components/**
    └── test-rules.md       # applies when editing: tests/**

Working in src/api/? Only API rules load. Working on tests? Only test rules. Saves context and keeps Claude's attention on what's actually relevant.


Context management is the highest-leverage skill in Claude Code. Get this right and you get consistent quality throughout long sessions. Get it wrong and you watch Claude slowly degrade into vague, confused responses.

3.1 Understanding the Context Window

The context window is Claude's working memory. Everything in it — conversation history, file contents Claude has read, tool outputs, MCP server schemas — takes up space measured in tokens.

170K
Clean session
130K
With 5 MCP servers
100K
With 9+ servers
60%
Act threshold

Typical budgets:

Session setupAvailable tokens
Clean session, no MCP servers~160,000–170,000 tokens
Session with 5 MCP servers~120,000–130,000 tokens
Session with 9+ MCP serversDown to ~100,000 tokens
Degradation Point
Performance starts dropping noticeably around 147,000 tokens — not 200,000. Anthropic's own engineering data backs this up, which is why auto-compaction now fires at 64–75% capacity, not 90%. By 90% you've been working in degraded mode for the past hour.

Context rot:
As token count grows, accuracy degrades. This is not a Claude quirk — it's how transformer models work. The fix isn't a bigger window. The fix is curation.

In a typical session with a few MCP servers, your real working budget is 100,000–120,000 tokens. Plan sessions accordingly.

Reclaim tokens from unused MCP servers: Each connected MCP server consumes 10,000–20,000 tokens for its schema alone. Disable servers you don't need in the current session:

text
@servername disable

Be specific in prompts: A vague prompt ("fix the bug in the API") forces Claude to read broadly, consuming tokens exploratorily. A specific prompt ("fix the null check in src/api/auth.ts:47–52") can be up to 40× more token-efficient.

3.2 The 60% Rule

Run /context any time. When it shows 60% — act. Do not wait for auto-compaction to rescue you.

bash
/context

# Also useful mid-session
"What do you currently have in context? Give me a summary."

That second prompt is worth running even when you're not planning to compact. It shows you what Claude is actually holding — often surprising.

3.3 /compact — Keep Continuity

/compact triggers a summarisation pass. Claude reads the full conversation, produces a compressed summary, and replaces the history with it. You don't restart — you continue with a lighter context.

The numbers: A typical compaction reduces context by 60–70%. 140,000 tokens becomes roughly 42,000–56,000.

The catch: Compaction is lossy. Specific file contents, exact error messages, granular details don't survive. What survives is the high-level thread — decisions, direction, constraints. You lose the specifics.

The fix: Always give /compact explicit instructions:

bash
# ❌ Generic — you lose whatever Claude decides is unimportant
/compact

# ✅ Targeted — you decide what survives
/compact preserve: all modified file names, the decision to use Drizzle over Prisma,
the test failure pattern in the auth module, and the API route naming convention

# ✅ Scoped to what you're working on
/compact Focus on the authentication changes only

# ✅ Keeping a decision log
/compact preserve the list of modified files and the decisions we made on error handling

The instructions you pass get injected into the summary prompt. Claude keeps what you told it to keep.

When to compact:

  • At 60% context fill

  • After finishing a logical chunk of work (a feature, a module, a bug fix)

  • Before switching concern within the same session

  • Never mid-implementation — you'll lose the reasoning thread

3.4 /clear — Fresh Start

/clear wipes the entire conversation. No summary, no history. Gone.

What survives:

  • Your CLAUDE.md rules

  • Files on disk

  • Slash commands and hooks

  • Any handoff files you created

What dies: Everything accumulated in the session.

The common mistake is treating /clear as a last resort. Flip that. Use it proactively between distinct tasks, like closing browser tabs before starting something new.

A clean 160K token budget beats a polluted 80K budget every time.

When to use which:

SituationUse
Switching to a completely different task/clear
Session feels noisy from failed attempts/clear
Need continuity — same task, different phase/compact with instructions
Key decisions were made earlier in session/compact preserving those decisions
Task boundary, no strong continuity needed/clear

Default to /clear. Reach for /compact when continuity actually matters.

3.5 Parallel Sessions

Instead of one long session that degrades, run parallel sessions for distinct concerns.

Use --worktree to run sessions on isolated branches without conflicts:

bash
# Isolated worktree session — own branch, no conflicts with your main checkout
claude --worktree feature-auth

# Or use separate terminals for distinct concerns
# Terminal 1: frontend work
cd frontend/ && claude

# Terminal 2: backend work (at the same time)
cd backend/ && claude

# Terminal 3: security review (at the same time)
cd . && claude /security-review

Each session gets its own clean context window. Subagents spawned via the Task tool also run in their own independent windows — useful for long-running work that would otherwise pollute your main session.

A practical feature breakdown:

  • Session 1: Plan and spec — save the output to a file, close the session

  • Session 2: Implement — fresh context, just load the spec file

  • Session 3: Review and test — fresh context, load the implementation

3.6 Session Handoff Files

The context window ends when the session ends. But files persist. A handoff file bridges sessions on multi-day tasks without losing continuity.

Before ending a session — when asked to exit, when the final task is done, or when context is getting full — write a session-handoff.md in the current project directory using this format:

markdown
# Session Handoff — [date]

## Accomplished
- [what was done this session]

## Decisions
- [decision] — [why]

## Files modified
- [path] — [what changed]

## Next session: start here
[one paragraph on exactly where to pick up and what the first action should be]

## Open questions
- [anything unresolved or blocked]

Keep it under 150 lines. Write the file directly — do not print it to the terminal. This file survives /clear and --resume, so it is the primary continuity mechanism across sessions.

With the global continuity instruction from section 9.10, Claude automatically reads the handoff file at the start of every session — no manual prompt needed.

3.7 The .claudeignore File

Same idea as .gitignore — tell Claude what to skip. Less noise in the context window means more room for what actually matters.

gitignore
# .claudeignore

node_modules/
vendor/
.venv/
dist/
build/
coverage/
.next/
__pycache__/
*.log
*.map
*.generated.ts
*.generated.js
*.pb.go

Critical in monorepos, projects with large vendor directories, or anything with generated code.

3.8 The Context Budget Template

Start significant tasks with an explicit brief:

text
Project: [Name]
Stack: [Core tech]
Current focus: [Specific task — narrow]
Key files: [2-3 files we'll touch]
Constraints: [Critical rules]
Out of scope: [What NOT to touch this session]

About 100 tokens. Replaces 5,000 tokens of Claude exploring and guessing.

3.9 Automating Session Handoff with a PreCompact Hook

Section 9.6 described manual handoff files. You can automate this with a global PreCompact hook that saves session state before every compaction — manual or auto-triggered.

1. Create the hook script at ~/.claude/hooks/preserve-context.sh:

bash
#!/bin/bash

INPUT=$(cat)

claude -p "From this conversation, extract and save to .claude/session-handoff.md:
1. All files modified
2. All decisions made with their reasoning
3. Current task state and next step
4. Any open questions or blockers
Format it as markdown. Be specific." <<< "$INPUT"

echo "Context preserved to .claude/session-handoff.md"

Make it executable:

bash
chmod +x ~/.claude/hooks/preserve-context.sh

2. Register the hook globally in ~/.claude/settings.json:

json
{
  "hooks": {
    "PreCompact": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "/Users/YOUR_USERNAME/.claude/hooks/preserve-context.sh"
          }
        ]
      }
    ]
  }
}

Use an absolute path in the command field — tilde (~) expansion is not guaranteed in hook commands.

3. Add to .gitignore in each project:

text
.claude/session-handoff.md

The handoff file is volatile session state, not project knowledge — it should not be committed.

3.10 Global Session Continuity Instructions

Instead of adding session continuity instructions to every project's CLAUDE.md, add them once to ~/.claude/CLAUDE.md — which is read automatically in every session across all projects:

markdown
## Session startup

At the start of every session, check for a session-handoff.md in the current
project directory. If it exists and was modified in the last 7 days, read it
before doing anything else and confirm what you found.

## Session handoff

Before ending any session — when asked to exit, when the final task is done,
or when context is getting full — write a session-handoff.md in the current
project directory.

Format:

# Session Handoff — [date]

## Accomplished
- [what was done this session]

## Decisions
- [decision] — [why]

## Files modified
- [path] — [what changed]

## Next session: start here
[one paragraph on exactly where to pick up and what the first action should be]

## Open questions
- [anything unresolved or blocked]

Keep it under 150 lines. Write the file directly — do not print it to the terminal.
This file survives /clear and --resume, so it is the primary continuity mechanism
across sessions.

This gives you two things: automatic pickup at session start (with a 7-day staleness check) and automatic handoff at session end. Combined with the PreCompact hook from section 9.9, you get fully automatic session continuity across all projects.


The most effective way to use Claude Code on anything non-trivial: separate planning from implementation. Don't jump straight to code.

Key insight
Spend 15 minutes on a spec and you'll save hours of back-and-forth during implementation. The spec is the highest-leverage artifact you produce.

4.1 The Three-Phase Workflow

Phase 1: Spec (10–15 min, use a conversational AI)

Use a chat tool to sharpen the idea and produce a spec. Save Claude Code's context for coding.

text
Ask me one question at a time so we can develop a thorough spec for this idea.
Build each question on my previous answers. End goal: a spec I can hand to a developer.
One question at a time.

Here's the idea: [YOUR IDEA]

At the end of the conversation:

text
Compile our findings into a developer-ready specification.
Include requirements, architecture choices, data handling, error handling, and a testing plan.

Save as spec.md in the repo.

Phase 2: Plan (use a reasoning model — GPT 5.4, Opus 4.6)

Feed the spec to a reasoning model to break it into implementation steps:

text
Draft a step-by-step blueprint for building this. Break it into small iterative chunks.
Each chunk should be safe to implement with tests, but big enough to move forward.

Output a series of sequential prompts for a code-generation LLM.
Each prompt builds on the previous. No orphaned code.

<SPEC>
[paste spec.md]
</SPEC>

Save as prompt-plan.md. Also generate a todo.md checklist.

Phase 3: Execute (Claude Code, fresh session)

bash
cd project/
claude

"Read prompt-plan.md and todo.md. We'll work through these step by step.
Start with step 1. Check off todo.md items as we complete them."

Start a new session for each major phase. Keep context clean throughout.

No Yes Phase 1Spec Phase 2Plan Phase 3Execute Done? Open PR

4.2 Why This Works

  • A precise spec cuts back-and-forth during implementation

  • The planning phase breaks the problem into Claude-sized chunks

  • Fresh sessions per phase mean Claude always has a clean context

  • todo.md tracks state across sessions, replacing context continuity

4.3 Brownfield Workflow

For existing codebases:

bash
# Bundle only the relevant code
npx repomix --include "src/auth/**"

# Start with an explicit brief
"Here is the relevant code. The task is: [SPECIFIC TASK].
Key files: [LIST]. Out of scope: [LIST].
Tell me your plan before writing any code."

# Review the plan, then approve
"Looks right. Go ahead."

"Tell me your plan first" is one of the highest-value prompting habits you can build. It forces reasoning before action and catches misunderstandings before they become code.

4.4 Automated Alternative: The Superpowers Plugin

The GSD workflow above is manual and tool-agnostic — it works with any AI assistant, any editor, any setup. If your team uses the superpowers plugin for Claude Code, the same spec→plan→execute philosophy is available as an automated, enforced workflow.

What superpowers automates:

GSD phaseManual (sections 10.1–10.3)Superpowers equivalent
SpecWrite in a chat tool, save as spec.mdBrainstorming skill — Socratic Q&A, saves a design doc, dispatches a spec reviewer
PlanFeed spec to a reasoning model, save as prompt-plan.mdWriting-plans skill — decomposes into bite-sized tasks with exact file paths, code, and verification commands
ExecuteRun Claude Code in a fresh session per phaseSubagent-driven development — dispatches a fresh agent per task with isolated context

What superpowers adds on top of GSD:

  • Automatic triggering. Skills detect when they apply and activate without manual invocation. You say "build X" and brainstorming fires before any code is written.

  • Mandatory TDD. No production code is written before a failing test exists. This is enforced per task, not suggested.

  • Two-stage review per task. Every completed task is reviewed for spec compliance (did you build what was asked?) and then code quality (is it well-built?) before the next task starts.

  • Evidence-based verification. You cannot claim "done" without showing passing test output. No "should work" — only "ran it, saw green."

  • Git worktree isolation. Feature work runs in an isolated worktree so your main branch stays clean throughout.

When to use which:

SituationUse
No superpowers plugin installedGSD (manual workflow)
Quick task, low complexityGSD — the overhead of full automation isn't worth it
Multi-file feature, needs review gatesSuperpowers — automated review catches issues between tasks
Team without Claude Code experienceGSD — teaches the underlying principles first
Team standardising on Claude CodeSuperpowers — enforces consistent quality across developers

The GSD workflow teaches you why separating planning from implementation matters. Superpowers is what it looks like when that principle is codified into an automated pipeline.


These solve different problems. Mixing them up leads to wrong architectural choices.

5.1 Skills: Reusable Workflows

A skill is a SKILL.md file that tells Claude how to perform a specific task. It's a procedural document — steps, patterns, rules Claude follows when the skill is invoked.

Skills are for:

  • Repeatable multi-step workflows (code review, test generation, refactoring)

  • Team-specific patterns ("our API always follows this structure")

  • Letting non-experts run expert workflows

Skills live in:

text
.claude/skills/
└── code-review/
    └── SKILL.md     ← instructions for how to perform a code review

Skills don't:

  • Call external APIs

  • Read from databases

  • Maintain state between invocations

5.2 MCP Servers: External Integrations

An MCP server exposes tools Claude can call to interact with external systems. Where a skill teaches Claude how to think, an MCP server gives Claude things to act on.

MCP servers are for:

  • Reading from or writing to external systems (GitHub, Jira, Slack, databases)

  • Wrapping our API so Claude can call it during development

  • Giving Claude real-time data it can't get from training

The key mental model difference:

SkillMCP Server
What it isA SKILL.md with instructionsA running server with tools
What it doesTeaches Claude how to workGives Claude things to act on
Example"How to run a security review""Call our /users endpoint"
Requires a running process❌ No✅ Yes
Good forTeam workflows, standardsExternal integrations

5.3 Using Both Together

The most useful setups combine both:

text
Skill: "run-api-test"
├── SKILL.md: "Here's how we test API endpoints at our company"
└── Uses MCP: actually calls the API during the test

The skill carries the process knowledge. The MCP server provides the external capability.

5.4 When to Build Which

You need Claude to...Build a...
Follow a repeatable coding workflowSkill
Call our APIMCP Server
Apply a team coding patternSkill
Read from the databaseMCP Server
Run a security checklistSkill
Create a Jira ticketMCP Server
Generate tests in our styleSkill
Check for open PRs in GitHubMCP Server

The habits that make Claude Code effective fall into two categories:

  • Compounding habits — things you set up once that make every future session smarter. Your CLAUDE.md, feedback loops (tests/linters after changes), path-scoped rules. Each correction you encode compounds: Claude never makes that class of error again.

  • Session habits — in-the-moment discipline that keeps a single session on track. Planning before coding, being specific, managing context, keeping scope small.

Invest in both. Compounding habits raise the floor. Session habits keep you from hitting the ceiling.

6.1 Prompting Principles

Be narrow, not broad

text
# ❌ Wastes context, produces sprawl
"Refactor the authentication module"

# ✅ Specific and contained
"Refactor the login function in src/auth/service.ts.
Focus only on the token refresh logic (lines 45-78).
Do not change the function signature."

Always ask for the plan first

text
"Before writing any code, tell me how you'd approach [TASK].
What files will you touch? What's your strategy?"

Catches misunderstandings before they become 200 lines of wrong code.

Use positive and negative examples

text
"Generate a new API endpoint following this pattern: [GOOD EXAMPLE]
Do NOT follow this pattern: [BAD EXAMPLE]"

State what's out of scope explicitly

text
"In this session we are ONLY working on the login flow.
Do not touch the registration flow, password reset,
or any other files in src/auth/ not listed here."

6.2 The /simplify Habit

After any feature or fix, run /simplify before requesting review. 30 seconds, consistently catches:

  • Duplicated logic from multiple iterations

  • Meaningless variable names from rapid prototyping

  • Overcomplicated solutions to simple problems

Especially valuable in vibe-coded sessions where complexity crept in incrementally.

6.3 Recognising When to Reset

These are signals to /clear or start a fresh session:

  • Claude asks about something you established 30 minutes ago

  • Claude writes code that contradicts an earlier decision

  • Responses get vague where they used to be specific

  • Claude starts hallucinating function names or file paths

  • /context shows above 70%

Don't try to fix a degraded session by adding more context. The token is already spent. Start fresh.

6.4 Hooks for Automation

Hooks fire scripts automatically at session events. Useful patterns:

bash
# Inject today's date (Claude's training has a cutoff)
# Hook: session start
python scripts/get_dates.py

# Run tests after Claude writes files
# Hook: after file write
npm test --silent

# Scan for secrets before commits
# Hook: before commit
git-secrets --scan

Configure with /hooks.

6.5 The Repomix Pattern

When working on a specific part of an existing codebase, bundle only what's relevant:

bash
npm install -g repomix

# Bundle only the auth module
npx repomix --include "src/auth/**,src/types/auth.ts" --output auth-context.txt

"I've bundled the relevant auth code in auth-context.txt.
Read it, then help me [SPECIFIC TASK]."

Much more token-efficient than letting Claude explore the codebase freely.

6.6 Common Anti-Patterns

Anti-patternWhy it hurtsBetter approach
One giant session for everythingContext degrades, quality dropsParallel sessions, /clear between tasks
"Fix everything in the auth module"Unpredictable scope, burns contextSpecific files and line ranges
Accepting all changes without readingBugs and policy violations slip throughRead every diff before accepting
Never updating CLAUDE.mdClaude works from stale instructionsUpdate after every structural change
Pasting secrets into promptsSecurity violationUse env vars; describe the type only
Letting Claude pick dependenciesUnknown CVEs, bloat, licence issuesRun /audit-dependencies
Ignoring /context until auto-compactionAlready degraded for an hour60% rule