Quick Start
Get Claude Code installed and running in under 5 minutes. Everything else in this guide builds on this.
npm install -g @anthropic-ai/claude-code claude --version
claude # opens browser for auth export ANTHROPIC_API_KEY=sk-ant-... # OR set key directly
cd my-project && claude > /init
mkdir -p .claude/agents .claude/skills .claude/commands
/agents # lists your agents /status # shows token usage /help # all available commands
Put agents used everywhere (debugger, reviewer) in ~/.claude/agents/. Put project-specific agents in .claude/agents/. Project agents override global ones on name collision.
Mental Model
Claude Code is not a chatbot — it's an agent harness: Claude models orchestrated with tools, memory, and execution environments. It has 5 layers. Once you understand them, everything else clicks.
Project Structure
One skeleton, customize per project. Works with any stack.
project/ ├── CLAUDE.MD/AGENTS.md # Entry: project overview, run commands, hard constraints within 150-200 lines ├── src/ │ ├── api/ │ │ ├── ARCHITECTURE.md # API layer architecture decisions │ │ └── ... │ ├── db/ │ │ ├── CONSTRAINTS.md # Database operation hard constraints │ │ └── ... │ └── ... ├── PROGRESS.md # Current progress: done, in-progress, blocked └── Makefile # Standardized commands: setup, test, lint, check
settings.json — Essential Config
{
"model": "sonnet",
"env": {
"MAX_THINKING_TOKENS": "10000", // caps extended thinking cost
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50" // compact at 50%, not 95%
},
"permissions": {
"allow": ["Bash(git:*)", "Bash(npm:*)", "Read", "Write", "Edit"],
"deny": ["Bash(rm -rf:*)", "Bash(curl:*)"]
}
}
The default compacts at 98% — dangerously late, context details get lost. At 50% you get a clean safety buffer. Pair with explicit /compact calls at the end of each feature in your /ship or /checkpoint commands.
CLAUDE.md Mastery
The most important file in your setup. Claude reads it at the start of every session — it's the onboarding doc for an engineer who wakes up with amnesia each morning.
There's a ~150–200 instruction compliance budget. The system prompt takes ~50 slots. Beyond the limit, Claude silently ignores your rules. Keep it under 200 lines. For each line, ask: "Would Claude make a mistake without this?" If not — delete it.
3 Levels of CLAUDE.md
Production Template
# CLAUDE.md/AGENTS.md # Project: [Name] # KEEP UNDER 200 LINES — every line costs tokens. ## Project Overview Python 3.11 FastAPI backend, PostgreSQL 15 database. ## Quick Start - Install: `make setup` - Build: `npm run build` - Test: `npm test -- --run`,`make test` # --run prevents hanging - Dev: `npm run dev` ## Hard Constraints - All APIs must use OAuth 2.0 authentication - All database queries must use SQLAlchemy 2.0 syntax - All PRs must pass pytest + mypy --strict + ruff check - NEVER commit .env, secrets, or API keys. ## IMPORTANT Rules - NEVER delete tests to make them pass. - NEVER use `any` in TypeScript. - ALWAYS run lint before declaring done. - When in doubt, ask. Do not assume. ## Architecture - Frontend: Next.js in apps/web - Backend: Express + Postgres/Prisma in apps/api - Auth: JWT in httpOnly cookies. Never localStorage. ## Code Style - TypeScript everywhere. No plain .js files. - Named exports only. No default exports except pages. - Error handling: Resultpattern. Never throw. ## Topic Docs - API Design Patterns (`docs/api-patterns.md`) — Required reading when adding endpoints - Database Rules (`docs/database-rules.md`) — Required when modifying database operations - Testing Standards (`docs/testing-standards.md`) — Reference when writing tests ## Folder Conventions - Components: src/components/[Feature]/[Component].tsx - API routes: src/app/api/[resource]/route.ts ## What NOT to do - Do not install packages without asking. - Do not refactor unrelated code while fixing a bug.
Review it when things go wrong. Prune it regularly. Grow it from real mistakes — not speculation. Use IMPORTANT or YOU MUST for rules that keep getting ignored. Link to skill files for domain detail instead of inlining everything.
Agent Team Setup
Each agent is a .md file with YAML frontmatter + a system prompt. The description field is critical — Claude reads it to decide which agent to delegate to. Make it trigger-based and specific.
Agent File Anatomy
--- name: agent-name description: Invoke when... # Claude delegates based on this line tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet # haiku | sonnet | opus memory: project # optional: persist knowledge skills: - skill-name # optional: preload a skill --- You are a [role]. Your expertise is [domain]. ## Core Responsibilities ## Output Format ## Non-Negotiables
Choose the Right Model
References are mapped to Anthropic's model tiers for simplified capability matching.
| Model | Speed | Cost | Use For |
|---|---|---|---|
| haiku | ⚡⚡⚡ Fastest | Cheapest (~5× less than Opus) | Explore, search, read-only, boilerplate |
| sonnet | ⚡⚡ Fast | Balanced | 90% of coding tasks — the default |
| opus | Slower | Most expensive | Architecture, complex debugging, code review |
The Full Agent Team — Click to Expand
--- name: ideator description: Invoke at the very beginning of a project or feature request. Brainstorms, asks clarifying questions, refines user ideas, and evaluates feature viability. tools: Read, Glob, Grep model: opus memory: project --- You are a seasoned Product Manager and Startup Founder. Your goal is to refine raw user ideas into clear, high-impact product specifications. ## Core Responsibilities 1. Ask 3-5 sharp, clarifying questions to resolve ambiguity in requirements. 2. Brainstorm at least 2 alternative approaches (e.g., simpler MVC vs. robust solution). 3. Challenge assumptions to prevent over-engineering. 4. Define the target user value and success metrics. ## Rules - Never accept a vague requirement without asking for clarification. - Suggest "what NOT to build" to reduce scope creep. - Output a clear, structured Feature Spec: Goal, User Flow, and Scope.
--- name: system-architect description: Invoke when designing system architecture, making tech stack decisions, evaluating scalability, or when asked "how should we structure this" or "what approach should we take". tools: Read, Glob, Grep model: opus memory: project --- You are a principal architect with 15+ years building distributed systems. You evaluate trade-offs, not just solutions. ## Output (always produce all three): 1. ADR — problem / options considered / decision / trade-offs 2. Mermaid diagram — component or sequence 3. Risk register — top 3 risks with mitigations ## Rules - Never commit to one approach without listing alternatives. - Always ask: what is the scale? (users, data volume, team size) - Prefer boring, proven tech unless there's a strong reason.
--- name: planner description: Invoke at the START of any feature, bug fix, or refactor. Produces plan.md with numbered steps before any code is written. Use before asking any other agent to implement. tools: Read, Glob, Grep model: sonnet --- YOU NEVER WRITE CODE — you only produce plans. ## Process 1. Explore the codebase to understand existing patterns 2. List every file to create or modify (with paths) 3. List packages/dependencies needed 4. Break work into numbered, atomic, independently-verifiable steps 5. Flag risks, unknowns, and questions before coding begins ## Output: plan.md - [ ] Numbered checklist with file paths - Complexity estimate per step (S/M/L) - Open Questions section ## End every plan with: "Confirm or annotate this plan before I proceed." This single line prevents the most expensive mistake in agentic coding.
--- name: frontend-engineer description: Invoke for React/Vue/Svelte components, CSS, state management, accessibility, responsive design, animations, or any browser-facing code. Adapts to whatever stack is in the project. tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- You are a senior frontend engineer. Stack-agnostic. Do not introduce new frameworks without asking. ## Every component must handle: Loading state | Error state | Empty state | Mobile-first responsive ## Non-Negotiables - Semantic HTML + WCAG 2.1 AA accessibility minimum - No inline styles — use the project's styling system - No new UI libraries without asking first
--- name: backend-engineer description: Invoke for API development, database schema, server logic, authentication, background jobs, caching, or API performance issues. tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- Senior backend engineer. Stack-agnostic. Build it reliable, secure, fast. ## Non-Negotiables - All endpoints: input validation + meaningful error responses - Secrets in env vars ONLY — never hardcoded - Every DB schema change needs a migration - Parameterized queries always. No SQL string concatenation. - RBAC: always least-privilege. Rate-limit public endpoints.
--- name: tester description: Invoke after any code is written to add tests, identify edge cases, verify coverage, or diagnose failing tests. tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- Adversarial QA engineer. Find what breaks code, not just what works. ## Test: happy paths | edge cases | error paths | boundaries | concurrency ## Output: what IS tested + what is NOT tested (be honest) + PASS/FAIL counts ## NEVER delete tests to make them pass. ## Tests must be deterministic — no random, no un-mocked time.
--- name: code-reviewer description: Invoke to review any diff, file, or PR for bugs, security vulnerabilities, performance issues, or code quality. Use before any merge. tools: Read, Glob, Grep model: opus memory: project --- Principal engineer doing thorough, direct, constructive code review. ## Severity labels: 🔴 BLOCKER — must fix before merge (bug, security issue) 🟡 WARNING — fix soon (tech debt, performance) 🟢 SUGGESTION — optional improvement (style, readability) ## Conclude with: APPROVE / REQUEST CHANGES / NEEDS DISCUSSION
--- name: debugger description: Invoke when there is a bug, error, unexpected behavior, or failing test. Specializes in root cause analysis. Use before trying random fixes. tools: Read, Bash, Glob, Grep model: opus --- Master debugger. Find ROOT CAUSES, not symptoms. Rule: "Never say 'try this and see' — always explain WHY." ## Protocol: REPRODUCE → ISOLATE → HYPOTHESIZE (3 causes) → VERIFY → FIX ## Output: confirmed root cause + minimal correct fix + one-line explanation
--- name: devops-engineer description: Invoke for Docker, CI/CD pipelines, GitHub Actions, Kubernetes configs, Nginx, secrets management, or deployment scripts. tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- DevOps engineer. Reliable, repeatable pipelines. ## Non-Negotiables - Docker images pinned to exact versions (NEVER :latest) - CI order: test → lint → build → deploy - Secrets via env injection — never in config files - Health check on every service + rollback strategy ## Output: working config files + one-paragraph runbook (deploy + rollback)
--- name: documentation-writer description: Invoke to write or update README, API docs, inline code comments, changelogs, or any developer documentation. tools: Read, Write, Edit, Glob, Grep model: sonnet --- Technical writer. Makes complex things clear. ## Rules: Active voice. Short sentences. Examples must be copy-paste runnable. ## Comments explain WHY, not WHAT (code says WHAT already). ## README: Setup → Usage → Examples → Contributing ## Changelog: Keep a Changelog format (Added/Changed/Fixed/Removed)
5 Rules for Building Your Own Agent
- Write a trigger-based description. Start with "Invoke when…" Be specific. List exact domains, file types, situations.
- Pick the right model. Haiku for fast, cheap exploration. Sonnet for implementation. Opus only for deep reasoning.
- Restrict tools to what's needed. A reviewer needs Read/Glob/Grep only — not Write/Bash. Restricts accidents and speeds things up.
- Write a strong, opinionated system prompt. Give it a clear identity, non-negotiables, and a specific output format.
- Test with /agents and iterate. Run /agents to confirm it's listed. Try delegating a task. Refine description if Claude doesn't delegate when expected.
Top Skills
Skills load on-demand. Zero token cost when not triggered. Put domain knowledge in skills, not CLAUDE.md — you pay CLAUDE.md cost every single session.
Create Your Own Skill
---
name: api-conventions
description: Use when writing, reviewing, or debugging API endpoints.
Contains error format, naming, auth patterns, pagination.
---
## Error Format
{"error": {"code": "RESOURCE_NOT_FOUND", "message": "User 42 not found"}}
## Naming: camelCase keys, plural nouns (/users, /orders)
## Auth: JWT in Authorization header. Check expiry before processing.
See [patterns.md](patterns.md) for full annotated examples.
Slash Commands as Workflows
Slash commands are repeatable prompt templates you invoke with /command-name. If you type the same multi-step instruction more than twice — make it a command.
Built-in Commands
| Command | What it does |
|---|---|
| /init | Generate starter CLAUDE.md from your codebase |
| /clear | Start a fresh context window |
| /compact | Compress conversation history now |
| /status | Show current token usage |
| /agents | List and create agents |
| /hooks | Configure hooks |
| /mcp | Manage MCP servers |
| /memory | View and edit memory |
| /help | Show all available commands |
10 Custom Commands Worth Building
| Command | What it does | Why it matters |
|---|---|---|
| /plan [task] | Spawns Planner, creates plan.md, pauses for review | Enforces plan-before-code on every feature |
| /ship | lint → test → review → commit → push | Full quality gate in one keystroke |
| /review [file] | Spawns Code Reviewer on diff or file | One command review before every merge |
| /checkpoint | Writes progress log, commits, /compact | Anti-amnesia checkpoint at every milestone |
| /debug [error] | Spawns Debugger in isolated context | Keeps debug logs out of main context |
| /explore [topic] | Haiku subagent scans codebase, returns summary | Clean research without polluting context |
| /standup | Reads git log + progress file, writes update | 30-second standup generation |
| /fix-tests | Runs tests, captures failures, spawns Tester (no-delete guardrail) | Automated test-fix loop with safety |
| /doc [file] | Spawns Doc Writer on a file or directory | Docs after every feature, not never |
| /onboard | Generates team-onboarding.md from CLAUDE.md + agents + git log | New devs productive in minutes |
Example: /ship command
--- description: Full quality pipeline — lint, test, review, commit, push allowed-tools: Bash(git:*), Bash(npm:*) --- Run these steps in order. STOP and report clearly if anything fails. 1. Lint: `npm run lint` → If failures: show them and STOP. 2. Test: `npm test -- --run` → If failures: show them and STOP. 3. Ask code-reviewer subagent to review `git diff HEAD` → If any 🔴 BLOCKER items: show them and STOP. 4. If all passed: commit with conventional format. → feat/fix/chore(scope): description (≤50 chars) 5. Push and report: ✅ Shipped — [hash] — [message] $ARGUMENTS # optional commit message override
Hooks
Hooks are shell commands that fire automatically at lifecycle events. Unlike slash commands (you invoke them), hooks are deterministic — they always run, regardless of what Claude decides.
| Event | When | Use for |
|---|---|---|
| PreToolUse | Before any tool call | Block dangerous ops, validate inputs, guard secrets |
| PostToolUse | After any tool call | Auto-format files, run linter, log actions |
| SubagentStop | When subagent finishes | Desktop notification, save output, update log |
| PreCompact | Before context compaction | Save critical state before compaction loses it |
| SessionStart | Session opens | Load context, inject today's date, check git status |
| SessionEnd | Session closes | Save progress, write summary |
How to Configure Hooks
Hooks are declared inside your project's .claude/settings.json under the
"hooks" object. You can write them as a single inline shell command, or reference an external
shell script file for complex scripts:
{
"hooks": {
"SessionStart": "echo 'Session started!'", // Simple inline command
"PreToolUse": "bash .claude/hooks/block-secrets.sh", // Reference external script
"PostToolUse": "npx prettier --write $TOOL_INPUT_FILE" // Access tool variables
}
}
💡 Pro-Tip: To pass arguments or context, hooks can access special environment variables
like $TOOL_INPUT (containing tool arguments in JSON) and $TOOL_OUTPUT. If
referencing files, make sure they are checked into .claude/hooks/.
4 Essential Hooks
echo '$TOOL_INPUT' | jq -r '.path' | xargs -I{} npx prettier --write {}
FILE=$(echo '$TOOL_INPUT' | jq -r '.path') if echo "$FILE" | grep -qE '\.env$|secrets\.'; then echo "BLOCKED: $FILE is off-limits" >&2; exit 1 fi
# macOS: osascript -e 'display notification "Agent task complete" with title "Claude Code"' # Linux: notify-send "Claude Code" "Agent task complete"
echo "Today: $(date '+%A, %B %d, %Y'). Timezone: $(date +%Z)."
Hooks execute arbitrary shell commands as you. Treat them exactly like shell scripts you're running personally. Never install community hooks without reading every line first.
The Token Economy
Tokens are your budget. Every character Claude reads or writes costs money. Understanding where they go is how you 10× efficiency without losing quality.
Where Your Tokens Actually Go
10 Ways to Cut Token Usage
| Technique | Impact | How |
|---|---|---|
| Install Caveman skill | −65–75% output | Compresses responses to dense shorthand, full accuracy kept |
| Trim CLAUDE.md | −25% context | Keep under 200 lines. Cut anything Claude gets right without it. |
| Route cheap tasks to Haiku | −80% API cost | Add model: haiku to search/explore agents — 5× cheaper |
| AUTOCOMPACT = 50 | Prevents loss | CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50 in settings.json |
| Research in subagents | −40% main context | Exploration results never touch your main context window |
| Skills > inline docs | −30%/session | Domain knowledge only loads when triggered |
| Single test runs | −60% output | Add "Run single tests, not full suite" to CLAUDE.md |
| Cap thinking tokens | Variable | MAX_THINKING_TOKENS=10000 |
| agentmemory MCP | −92% memory | 240 memories → 22k tokens (CLAUDE.md) vs 1,900 tokens (agentmemory) |
| Regular /compact calls | Predictable | Call at end of each feature — don't wait for auto-compact |
Memory Setup: Pick the Right Tool
At 240 stored observations: CLAUDE.md dump = 22,000 tokens. agentmemory = 1,900 tokens. That's a 92% reduction — benchmarked on 240 real coding sessions.
Context Amnesia & How to Cure It
Every new session starts with complete amnesia about your project. No memory of yesterday's architecture decisions, the library you banned, or the half-finished feature. This is the #1 pain point in agentic workflows.
The 4-Step Cure
## Current Task [What is being actively worked on right now] ## Completed - [x] Auth service setup (2026-05-10, backend-engineer) - [x] Login UI form (2026-05-11, frontend-engineer) ## In Progress - [ ] Password reset — claimed by: backend-engineer ## Decisions Made (do NOT revisit without a reason) - JWT over sessions: horizontal scaling requirement - Banned axios: use native fetch — caused pkg version conflict ## Known Issues - Rate limiting on /auth/forgot-password not yet done ## Next Steps (priority order) 1. Email verification (unassigned) 2. OAuth integration (unassigned)
--- name: agent-memory description: Read at the start of every task. Contains project state, decisions made, and what was last worked on. --- See [../../agent-coordination.md](../../agent-coordination.md)
1. Update agent-coordination.md — what was done, next steps 2. Update claude-progress.txt — one-paragraph session summary 3. Run: git add -A && git commit -m "checkpoint: [summary]" 4. Run: /compact 5. Report: ✅ Checkpoint saved. Safe to end session.
Parallel Agent Patterns
Parallel agents are the biggest speed multiplier in Claude Code. Here are the 5 named patterns with clear guidance on when to use each — and when not to.
Spawn 3 parallel Explore subagents simultaneously: 1. Explore src/auth/ — all patterns, interfaces, dependencies 2. Explore src/api/ — all routes, middleware, error handling 3. Explore src/db/ — schema, migrations, query patterns Then merge all results into CODEBASE.md
# Two isolated sessions in parallel: git worktree add ../approach-a -b experiment/approach-a git worktree add ../approach-b -b experiment/approach-b cd ../approach-a && claude # Session A cd ../approach-b && claude # Session B — simultaneously
Parallel agents with ambiguous output formats = compounded chaos. Get your sequential Pipeline working first. Then Fan-Out the independent parts. Don't start complex.
Harness Engineering
A harness is the scaffolding that makes agents reliable across many context windows. Anthropic's research: unguided agents succeed ~33% of the time. A proper harness changes that dramatically.
The Initializer + Coder Pattern (Anthropic's Official Pattern)
4 Common Failure Modes + Fixes
| Failure | What Happens | Fix |
|---|---|---|
| 🔴 One-shotting | Agent tries to build everything at once, runs out of context midway, leaves broken state | Prompt: "Work on ONE feature at a time. Leave clean, committed state after each." |
| 🔴 False completion | Agent sees prior progress and declares the whole job done prematurely | Use feature_list.json with passes:false. Require e2e verification before marking done. |
| 🟡 Context blindness | New session re-explores everything, wasting tokens | claude-progress.txt + init.sh. Agent reads state log before starting anything. |
| 🟡 Context pollution | File reads and research flood the main context | Use Explore subagent for research — returns only summary to main context. |
Agents are less likely to accidentally modify JSON than Markdown files. Use JSON for feature lists and machine-read state. Markdown for human-readable progress notes.
Open Source Boosters
The community has built extraordinary tools on top of Claude Code. These are the highest-impact ones — with direct links.
🔥 Must-Install
📚 Reference & Learning
🛡️ Security
Your First Autonomous Feature Ship
With your harness configured, here's what happens when you type one sentence. The agent team plans, builds, tests, reviews, and ships it.
Build a user password reset flow with email verification.
The quality comes from the setup — CLAUDE.md, agents, skills, and commands working as a system. The one sentence you typed is just the trigger. The harness is what makes it reliable, repeatable, and safe.
Best Practices Cheatsheet
✅ Always Do
❌ Never Do
💰 Token Savers
⚡ Quick Commands
Build your setup incrementally from real problems. Start with a lean CLAUDE.md. Add skills when Claude repeats a mistake. Add agents when you write the same persona prompt twice. Add hooks when you want something to always happen. The playbook is a destination, not a starting point.