1.1 Installation
npm install -g @anthropic-ai/claude-code
cd your-project
claudeVS 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:
| Model▲ | Use for▲ | Speed▲ |
|---|---|---|
| Haiku | Simple tasks, quick lookups, formatting | Fast |
| Sonnet | Most day-to-day work — good balance | Medium |
| Opus | Complex reasoning, architecture decisions, deep debugging | Slower |
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
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 working1.4 Essential Commands
| Command▲ | What it does▲ |
|---|---|
/init | Scans your project, creates CLAUDE.md |
/context | Shows token usage — how full your context window is |
/compact [instructions] | Compresses conversation history, you control what's kept |
/clear | Wipes conversation history entirely, fresh start |
/simplify | Reviews your diff and applies readability/simplification fixes directly |
/model | Switch model for the current session |
/hooks | Set up automated scripts (session start, file save, etc.) |
/plugin | Browse, 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:
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:
## Testing
- `pytest` — run from project root before every commit
- Fix failures before committing
## Formatting
- `ruff check --fix && ruff format` — run before committingSame 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.
# ❌ 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 conflictsRule 2: Keep heading depth to three levels max
Deep nesting dilutes attention. If you need an h4, you probably need a separate file.
# ✅ Max 3 levels
# Project
## Testing
### Unit Tests
# ❌ Too deep
# Project
## Development
### Testing
#### Unit Tests
##### Mocking StrategyRule 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.
# ❌ Suggestion
You can run the linter by running npm run lint.
# ✅ Directive
- `npm run lint` — check for style issues
- `npm test` — run test suiteRule 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.
# ❌ 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:
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:
## 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 modifyHalf 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:
.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.
Typical budgets:
| Session setup▲ | Available 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 servers | Down to ~100,000 tokens |
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:
@servername disableBe 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.
/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:
# ❌ 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 handlingThe 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.mdrulesFiles 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:
| Situation▲ | Use▲ |
|---|---|
| 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/compactwhen 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:
# 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-reviewEach 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:
# 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.
# .claudeignore
node_modules/
vendor/
.venv/
dist/
build/
coverage/
.next/
__pycache__/
*.log
*.map
*.generated.ts
*.generated.js
*.pb.goCritical 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:
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:
#!/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:
chmod +x ~/.claude/hooks/preserve-context.sh2. Register the hook globally in ~/.claude/settings.json:
{
"hooks": {
"PreCompact": [
{
"hooks": [
{
"type": "command",
"command": "/Users/YOUR_USERNAME/.claude/hooks/preserve-context.sh"
}
]
}
]
}
}Use an absolute path in the
commandfield — tilde (~) expansion is not guaranteed in hook commands.
3. Add to .gitignore in each project:
.claude/session-handoff.mdThe 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:
## 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.
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.
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:
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:
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)
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.
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.mdtracks state across sessions, replacing context continuity
4.3 Brownfield Workflow
For existing codebases:
# 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 phase▲ | Manual (sections 10.1–10.3)▲ | Superpowers equivalent▲ |
|---|---|---|
| Spec | Write in a chat tool, save as spec.md | Brainstorming skill — Socratic Q&A, saves a design doc, dispatches a spec reviewer |
| Plan | Feed spec to a reasoning model, save as prompt-plan.md | Writing-plans skill — decomposes into bite-sized tasks with exact file paths, code, and verification commands |
| Execute | Run Claude Code in a fresh session per phase | Subagent-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:
| Situation▲ | Use▲ |
|---|---|
| No superpowers plugin installed | GSD (manual workflow) |
| Quick task, low complexity | GSD — the overhead of full automation isn't worth it |
| Multi-file feature, needs review gates | Superpowers — automated review catches issues between tasks |
| Team without Claude Code experience | GSD — teaches the underlying principles first |
| Team standardising on Claude Code | Superpowers — 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:
.claude/skills/
└── code-review/
└── SKILL.md ← instructions for how to perform a code reviewSkills 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:
| ▲ | Skill▲ | MCP Server▲ |
|---|---|---|
| What it is | A SKILL.md with instructions | A running server with tools |
| What it does | Teaches Claude how to work | Gives Claude things to act on |
| Example | "How to run a security review" | "Call our /users endpoint" |
| Requires a running process | ❌ No | ✅ Yes |
| Good for | Team workflows, standards | External integrations |
5.3 Using Both Together
The most useful setups combine both:
Skill: "run-api-test"
├── SKILL.md: "Here's how we test API endpoints at our company"
└── Uses MCP: actually calls the API during the testThe 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 workflow | Skill |
| Call our API | MCP Server |
| Apply a team coding pattern | Skill |
| Read from the database | MCP Server |
| Run a security checklist | Skill |
| Create a Jira ticket | MCP Server |
| Generate tests in our style | Skill |
| Check for open PRs in GitHub | MCP 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
# ❌ 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
"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
"Generate a new API endpoint following this pattern: [GOOD EXAMPLE]
Do NOT follow this pattern: [BAD EXAMPLE]"State what's out of scope explicitly
"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
/contextshows 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:
# 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 --scanConfigure with /hooks.
6.5 The Repomix Pattern
When working on a specific part of an existing codebase, bundle only what's relevant:
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-pattern▲ | Why it hurts▲ | Better approach▲ |
|---|---|---|
| One giant session for everything | Context degrades, quality drops | Parallel sessions, /clear between tasks |
| "Fix everything in the auth module" | Unpredictable scope, burns context | Specific files and line ranges |
| Accepting all changes without reading | Bugs and policy violations slip through | Read every diff before accepting |
| Never updating CLAUDE.md | Claude works from stale instructions | Update after every structural change |
| Pasting secrets into prompts | Security violation | Use env vars; describe the type only |
| Letting Claude pick dependencies | Unknown CVEs, bloat, licence issues | Run /audit-dependencies |
Ignoring /context until auto-compaction | Already degraded for an hour | 60% rule |