Complete Reference · Beginner to Pro · Stack-Agnostic

The Claude Code Guide
Agent Engineering Playbook

Everything you need — from install to a fully autonomous agent team that ships production code. 14 sections, 9 ready-to-use agent configs, copy-paste everything.

14Sections
9Ready Agents
10Top Skills
~92%Token Savings
5Parallel Patterns
00

Quick Start

🚀

Get Claude Code installed and running in under 5 minutes. Everything else in this guide builds on this.

1
Install (Node.js 18+ required)
bash
npm install -g @anthropic-ai/claude-code
claude --version
2
Authenticate
bash
claude                            # opens browser for auth
export ANTHROPIC_API_KEY=sk-ant-... # OR set key directly
3
Bootstrap your project
Navigate to your project and run /init — Claude analyzes your codebase and writes a starter CLAUDE.md.
bash
cd my-project && claude
> /init
4
Create the directory structure
bash
mkdir -p .claude/agents .claude/skills .claude/commands
5
Verify inside Claude Code
slash
/agents   # lists your agents
/status   # shows token usage
/help     # all available commands
💡
Global vs Project scope

Put agents used everywhere (debugger, reviewer) in ~/.claude/agents/. Put project-specific agents in .claude/agents/. Project agents override global ones on name collision.

01

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.

👤 YOU CLAUDE CODE Main Session CLAUDE.md — loaded every session Skills — on-demand expertise Tools: Read / Write / Bash / Grep Hooks — deterministic automation SUBAGENT Own context window Returns only summary MCP SERVERS GitHub, Notion, Slack… Cap at 5–6 active HOOKS Pre/Post tool events Always fires, no LLM choice RESULTS Summary only returned to main context ✓ Context isolated ✓ Tokens protected ✓ Only summary back Invokes Returns result
📋
CLAUDE.md
The "constitution" — read every session. Keep it lean. There's a ~150–200 instruction compliance budget; the system prompt uses ~50 slots already.
Skills
On-demand expertise — like downloading kung fu from The Matrix. Zero token cost until triggered. Put domain knowledge here, not in CLAUDE.md.
🤖
Subagents
Isolated workers with their own context. Do heavy work, return only a summary. Your main context stays clean.
🔌
MCP Servers
Connect to GitHub, Notion, Slack, databases. Each is a subprocess — keep to 5–6 active max to avoid performance overhead.
🪝
Hooks
Shell commands that fire automatically at lifecycle events. They always run — regardless of what Claude decides. Format on save, block secrets, notify you.
02

Project Structure

📁

One skeleton, customize per project. Works with any stack.

treeFull layout
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

json.claude/settings.json
{
  "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:*)"]
  }
}
⚠️
Always set AUTOCOMPACT to 50

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.

03

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.

🚨
The #1 Mistake: Bloated CLAUDE.md

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

🌍 GLOBAL — ~/.claude/CLAUDE.md Personal preferences, coding style, tools you always use. Applies to every project on your machine. Scope: Machine 📦 PROJECT — ./CLAUDE.md Build commands, conventions, architecture rules, forbidden patterns. Team-shared via git. Scope: Repo 📂 SUBFOLDER — ./src/api/CLAUDE.md Module-specific rules. Overrides parent for that folder only. More specific overrides less specific ↓

Production Template

markdownCLAUDE.md — copy and customize
# 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: Result pattern. 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.

💡
Treat CLAUDE.md like code

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.

04

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

markdown.claude/agents/example.md
---
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

💡
Ideator & Product Thinker
Clarifies intent · brainstorms solutions · refines user ideas
Opus
ReadGlobGrepmemory: project
markdown.claude/agents/ideator.md
---
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.
🏛️
System Architect
Tech decisions · system design · ADRs · scalability
Opus
ReadGlobGrepmemory: project
markdown.claude/agents/system-architect.md
---
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.
🗺️
Planner
Breaks any task into a step-by-step plan before code is written
Sonnet
ReadGlobGrep
markdown.claude/agents/planner.md
---
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.
🎨
Frontend Engineer
UI · state · a11y · responsive — adapts to any stack
Sonnet
ReadWriteEditBashGlobGrep
markdown.claude/agents/frontend-engineer.md
---
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
⚙️
Backend Engineer
APIs · database · auth · server logic — any stack
Sonnet
ReadWriteEditBashGlobGrep
markdown.claude/agents/backend-engineer.md
---
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.
🧪
Tester
Unit · integration · edge cases — thinks adversarially
Sonnet
ReadWriteEditBashGlobGrep
markdown.claude/agents/tester.md
---
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.
🔍
Code Reviewer
Bugs · security · performance · before every merge
Opus
ReadGlobGrepmemory: project
markdown
---
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
🐛
Debugger
Root cause analysis — never symptom-chasing
Opus
ReadBashGlobGrep
markdown
---
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
🚢
DevOps Engineer
Docker · CI/CD · infra-as-code · deployment
Sonnet
ReadWriteEditBashGlobGrep
markdown
---
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)
📚
Documentation Writer
READMEs · API docs · changelogs · comments
Sonnet
ReadWriteEditGlobGrep
markdown
---
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

  1. Write a trigger-based description. Start with "Invoke when…" Be specific. List exact domains, file types, situations.
  2. Pick the right model. Haiku for fast, cheap exploration. Sonnet for implementation. Opus only for deep reasoning.
  3. Restrict tools to what's needed. A reviewer needs Read/Glob/Grep only — not Write/Bash. Restricts accidents and speeds things up.
  4. Write a strong, opinionated system prompt. Give it a clear identity, non-negotiables, and a specific output format.
  5. 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.
05

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.

🪨Caveman⭐ 27.9k
Makes agent reply in compressed shorthand. "Bug auth. Fix guard." Full accuracy, 65–75% fewer output tokens. MCP wrapper included.
↓ 65–75% output tokens
🛡️Security Scanner🔴 Critical
Detects secrets in code, SQL injection patterns, insecure auth, exposed endpoints. Integrates with AgentShield for red-team analysis. Run before every PR.
Prevents prod incidents
📦Conventional Commits🔧 DevOps
Enforces feat/fix/chore format. Messages ≤50 chars, explains WHY not WHAT. Makes changelogs auto-generatable.
Clean git history
🗜️Strategic Compact💰 Cost
Suggests /compact at logical breakpoints instead of waiting for risky 95% auto-compact. Prevents catastrophic context loss.
Prevents context loss
🧪TDD Workflow📐 Quality
Enforces Red → Green → Refactor. Claude writes the failing test first, then the code to pass it. Major quality improvement for logic-heavy work.
Fewer production bugs
🧠Agent Memory Protocol🔑 Core
Structured handoff format. Loads agent-coordination.md dynamically so each new agent picks up exactly where the last one left off.
Solves context amnesia
🗺️Codebase Mapper🔍 Explore
Spawns parallel Explore subagents to scan the whole repo and produce CODEBASE.md. Future sessions orient instantly without re-reading everything.
Saves hours re-exploring
📋PR Review Checklist✅ Process
Structured review with severity labels. One-line comments: "L42: 🔴 bug: user null — add guard." Loads when reviewing code.
Consistent review quality
🚀Deploy Guard🔒 Safety
Deployment checklist: tests → build → tag → push. Set disable-model-invocation: true so only YOU can trigger it — Claude cannot accidentally deploy.
Safe deployment gate
🏛️API Conventions (Custom)📐 Custom
Your project's API patterns: naming, error format, auth, pagination. Loaded only when writing or reviewing API code. Highest-ROI custom skill to build first.
Consistent API design

Create Your Own Skill

markdown.claude/skills/api-conventions/SKILL.md
---
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.
06

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

markdown.claude/commands/ship.md
---
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
07

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:

json.claude/settings.json
{
  "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

hookAuto-format on save (PostToolUse)
echo '$TOOL_INPUT' | jq -r '.path' | xargs -I{} npx prettier --write {}
hookBlock secret files (PreToolUse)
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
hookDesktop notification when agent finishes (SubagentStop)
# macOS:
osascript -e 'display notification "Agent task complete" with title "Claude Code"'
# Linux: notify-send "Claude Code" "Agent task complete"
hookInject current date — fixes "Claude thinks it's 2024" (SessionStart)
echo "Today: $(date '+%A, %B %d, %Y'). Timezone: $(date +%Z)."
⚠️
Security — always review hooks before installing

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.

08

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

TOKEN CONSUMPTION PER SESSION — by source System Prompt ~38% Includes CLAUDE.md. Always loaded. CLAUDE.md content ~24% Bloated = silent rule-ignoring. Conversation history ~17% Grows each turn. /compact helps. File reads (tool results) ~12% Read only what you need. Skills (when loaded) ~6% 0% if not triggered. Use skills. Extended thinking ~3% Cap with MAX_THINKING_TOKENS=10000. 0% 25% 50% 75%

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

📋
CLAUDE.md (Built-in)
Permanent rules only. Under 200 lines. Always loaded — you pay this cost every session. Link to skills for detail.
Always loaded200-line limitFree
🧠
memory: project field
Add to any agent frontmatter. Agent writes observations to MEMORY.md — first 200 lines loaded per session. Built-in, zero setup.
Per-agentBuilt-in200-line limit
📝
claude-progress.txt
Session handoff log. Each agent reads it first to get oriented. Core of Anthropic's Initializer+Coder harness pattern.
Multi-sessionManualFree
agentmemory MCP
92% fewer tokens than CLAUDE.md at scale. Persistent, searchable. Hybrid search. 200× more tool calls before limits. 5k+ stars.
MCP server−92% tokensTeams
🔄
claude-mem (74.8k ⭐)
Captures sessions, compresses with AI, auto-injects relevant context into the next session. Postgres backend for team-wide shared memory.
Session bridgeAuto-compressTeams
🫛
Beads
Git-backed task tracker for agents. Saves work-in-progress to .beads/ that survives session ends. Best for long multi-session features.
Git-backedCross-sessionTask tracking
📊
agentmemory benchmark

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.

09

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.

WITHOUT memory system — sessions restart from zero Session 1 Context built up ✗ LOST Session 2 Starts at zero ✗ LOST Session 3 Starts at zero Effective window: 15–20 min WITH memory system — sessions chain together Session 1 Writes progress log ✓ saved Session 2 Reads → full context ✓ saved Session 3 Continues exactly here Effective window: 2+ hours

The 4-Step Cure

1
Create agent-coordination.md
A shared file every agent reads at the start and updates when done. Dynamic — changes as work progresses. Not static like CLAUDE.md.
markdownagent-coordination.md
## 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)
2
Load it as a Skill — not in CLAUDE.md
If you put it in CLAUDE.md, you pay the token cost every session. As a skill, it loads on demand — zero cost in sessions that don't need it.
markdown.claude/skills/agent-memory/SKILL.md
---
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)
3
Run /checkpoint at every milestone
Writes the progress log, commits to git, compacts context. The next session starts informed instead of blind.
markdown.claude/commands/checkpoint.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.
4
Install agentmemory or claude-mem for serious scale
For teams or projects with 100+ sessions: claude-mem auto-captures, compresses, and re-injects session context. agentmemory gives persistent searchable memory (92% fewer tokens). Both work as MCP servers — install once, works everywhere.
10

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.

1. Fan-Out — Independent parallel work
✅ USE WHEN: One task splits into independent, non-overlapping workstreams
One orchestrator spawns N subagents simultaneously. Each works on its own slice. Results merge when all finish. Best for: parallel codebase exploration, writing docs for multiple modules, running isolated tests.
ORCHESTRATOR Agent A: src/auth/ Agent B: src/api/ Agent C: src/db/ All 3 run simultaneously → results merged → CODEBASE.md
prompt
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
❌ Don't use Fan-Out when agents need each other's results to proceed, or when they write to the same files
2. Pipeline — Sequential quality gates
✅ USE WHEN: Tasks have strict dependencies — A must finish before B starts
Each agent's output becomes the next agent's input. Best for: Plan → Build → Test → Review → Document workflows. Each stage validates the previous one before proceeding.
Planner Backend Eng Tester Reviewer Doc Writer DONE ✓
❌ Don't use Pipeline when tasks are independent — Fan-Out is faster
3. Council — Multiple expert perspectives
✅ USE WHEN: A decision is high-stakes and needs independent expert opinions
Multiple specialists independently review the same thing, then an orchestrator synthesizes. Best for: architecture decisions before committing, security audits, major refactors. Think of it as getting second, third, and fourth opinions before doing something irreversible.
❌ Don't use for routine tasks — overhead only pays off for genuinely high-stakes decisions
4. Worktree Isolation — A/B implementation testing
✅ USE WHEN: You want to try multiple implementations simultaneously with no conflicts
Git worktrees let N Claude sessions run in isolated repo checkouts. No edit conflicts. Each tries a different approach. You compare and pick the winner.
bash
# 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
❌ Don't use for small changes — setup overhead only pays off for significant alternatives
5. Background Agent — Long tasks while you keep working
✅ USE WHEN: A task takes 10+ minutes and you don't need to watch it
Press Ctrl+B to background the current agent. Keep working in the main session. A hook notifies you when it's done. Best for: generating test suites, full codebase documentation, large refactors.
❌ Don't background tasks that need your approval at intermediate steps
💡
Start with Pipeline, add Fan-Out once it's working

Parallel agents with ambiguous output formats = compounded chaos. Get your sequential Pipeline working first. Then Fan-Out the independent parts. Don't start complex.

11

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)

INITIALIZER Session 1 only Creates feature_list.json Creates init.sh (dev server) Creates claude-progress.txt Initial git commit Sets up test harness passes to CODING AGENT Every session after START: 1. Read claude-progress.txt 2. Run init.sh → start dev server 3. Verify basic e2e functionality 4. Pick ONE failing feature END: 5. Commit + update progress 6. Leave clean, mergeable state Loops until all features pass = true feature_list.json { passes: false } { passes: false } { passes: false } { passes: true ✓ }

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.
💡
JSON over Markdown for state files

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.

12

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

13

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.

you type
Build a user password reset flow with email verification.
1
Planner activates
Explores codebase for existing auth patterns. Produces plan.md with 8 steps: email service, token generation, DB schema, API endpoints, frontend form, error handling, tests, docs. Then pauses for your review.
2
You annotate the plan
Add two notes: "Use existing email service at src/lib/email.ts" and "Tokens expire in 1 hour." Reply: "address all notes, don't implement yet." Planner updates. Now it's unambiguous.
3
Backend Engineer builds the API
Token generation, DB migration, POST /auth/forgot-password and POST /auth/reset-password — with full validation, error handling, rate limiting.
4
Frontend Engineer builds the UI (Fan-Out: parallel with step 3)
Forgot-password + reset-password forms, loading/error/success states, accessible markup, mobile-first.
5
Tester writes and runs tests
Unit tests for token validation. Integration: full flow form → email → password change. Edge cases: expired token, already-used token, invalid email.
6
Code Reviewer reviews the diff
Reports: ✅ No blockers. 🟡 1 warning: rate limiting on forgot-password missing. 🟢 2 style suggestions. APPROVE with noted follow-up.
7
/ship runs the full gate
Lint ✅ → Tests ✅ → Review ✅ → git commit: "feat(auth): add password reset with email verification" → pushed. Desktop notification: ✅ Shipped.
🚀
This is what harness engineering enables

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.

14

Best Practices Cheatsheet

📌

✅ Always Do

CLAUDE.mdKeep under 200 lines
Haiku for search5× cheaper than Sonnet
Plan firstPlanner before every feature
/checkpointAt every major milestone
Single test runsNot the full suite
Restrict toolsGive agents only what they need

❌ Never Do

Bloat CLAUDE.mdBreaks compliance budget
Vague descriptionsAgent won't know to delegate
All Opus agents5× cost for no gain on simple tasks
Skip planningVibe coding = expensive backtracking
6+ MCP serversSubprocess overhead kills perf
Unreviewed hooksThey run as you. Read them first.

💰 Token Savers

caveman skill−65% output tokens
agentmemory MCP−92% memory tokens
AUTOCOMPACT=50Compact at 50%, not 95%
Skills not CLAUDE.mdLoad only when triggered
Haiku for search5× cheaper per call
MAX_THINKING=10kCap extended thinking cost

⚡ Quick Commands

/initGenerate CLAUDE.md
/agentsView / create agents
/compactCompress context now
/clearFresh context window
Ctrl+BBackground current agent
/statusCheck token usage
🎯
The one principle that ties it all together

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.

×