Animated guide · Claude Code from zero to expert

Claude Code from the inside

What really happens between your prompt and a green test suite: the loop, the context window, memory, permission modes, skills, subagents, hooks, MCP, parallel sessions and CI. Every option, when to use it, and the workflows that experts actually run. Scroll — the diagrams start by themselves.

Your brain on agents 🧠
scroll ↓
0

How to read this guide

…and why there are jokes, sliders and a fake terminal

This is not a list of Claude Code features. The docs already have that, and it changes every week. This guide is about mechanisms: why Claude reads five files before it edits one, why a long session gets worse, why a rule in CLAUDE.md is a request and a hook is a guarantee. When you understand the mechanism, every new feature is just a new knob on a machine you already know.

The path goes from zero to expert in four stages. Chapters 1–3 build the mental model (loop, terminal, context). Chapters 4–8 are the daily-driver skills (memory, permissions, planning, prompting, rewinding). Chapters 9–12 are the extension layer (skills, subagents, hooks, MCP, plugins). Chapters 13–16 are the expert layer (parallel sessions, CI, model choice, habits). Each chapter has one interactive figure: click the buttons, break things, press ↺ Reset.

🧠 Brain power

Before you start: if you had to design an AI that edits a real repository, what would you worry about most? Wrong edits? Deleted files? Forgetting what it was doing? Running up a bill? Keep your list. By chapter 16 every item on it will have a named feature that exists precisely for it.

😌 Relax

You do not need to memorize commands. Type / in Claude Code and the full menu appears; press ? on an empty prompt for shortcuts. Memorize the ideas — the menu will remind you of the names. Facts here were checked against the official docs at code.claude.com/docs in September 2026; Claude Code ships often, so run /release-notes when something looks different.

1

The agentic loop

it's not autocomplete — it's a worker with hands

A chat model answers. An agent acts. Claude Code wraps a Claude model in a loop with tools: the model reads your request, decides which tool to call (read a file, grep, edit, run a shell command, fetch a URL), sees the result, and decides again. It repeats until it thinks the job is done — or until you interrupt.

The docs describe three phases that blend into each other: gather context, take action, verify results. The single most important sentence in this whole guide follows from that loop: Claude is only as good as its ability to check its own work. If there is a test, a build, a linter, or a screenshot it can look at, the loop closes itself. If not, you are the verification step.

▶ The loop, live task: “the login test fails — fix it”
tool calls0
model turns0
result—
Press ▶ to watch Claude gather, act and verify.
Simplified: a real run may batch several read-only tool calls in parallel and stream its reasoning. The tool names are the real ones (Grep, Read, Edit, Bash).
❓ There are no dumb questions
Q:
Why did it read files before editing? I told it which test fails.
A:
Because the model starts every session knowing nothing about your code. It has no index of your repo in its head. Everything it knows comes from what it read in this session, plus CLAUDE.md and auto memory (chapter 4). Reading first is the correct behavior — you can make it faster by pointing at files with @path.
Q:
Can I type while it works?
A:
Yes. Messages you type during a turn are queued and read by Claude at the next step. Press Esc to stop the current step immediately; the work done so far stays, and you can redirect.
📌 Bullet points
  • Claude Code = model + tools + a loop: gather context → act → verify → repeat.
  • Apart from CLAUDE.md and auto memory, it knows nothing about your repo at start; reading is not wasted time.
  • Give it a way to verify (tests, build, screenshots). No verification ⇒ plausible-looking bugs.
  • Esc interrupts, typing mid-turn queues a correction. Steer early.
2

Your first session

install, surfaces, and the five magic prefixes

Install with the native installer and start it inside a project directory:

# macOS, Linux, WSL
curl -fsSL https://claude.ai/install.sh | bash
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex

cd my-project
claude            # interactive session
claude "explain the auth flow"   # start with a prompt
claude -c         # continue the latest conversation in this directory
claude -r         # pick an older session to resume

The same engine runs in several surfaces: the terminal CLI, VS Code and JetBrains extensions, the Desktop app, the web at claude.ai/code (cloud sessions in a sandbox), the mobile app, and Slack. They share your repo's CLAUDE.md files, settings and MCP servers. With a claude.ai subscription you can move a session between them: /desktop hands a terminal session to the Desktop app, --teleport pulls a cloud session into your terminal, and /remote-control lets you steer a local session from your phone.

Inside the prompt, a few characters change what you type into something else. Learn these and you already use Claude Code better than most people:

▶ A fake terminal click a key to see what it does
? for shortcuts⏸ manual mode on
The prompt bar at the bottom shows the permission mode — watch it change.
Output is abbreviated. In a real session / shows every built-in command, bundled skill and your own skills, filtered as you type.
KeyWhat it doesUse it when
EscInterrupt the current stepClaude heads the wrong way. Do it early.
Esc EscClear the draft, or on empty input open the rewind menuUndo the last few prompts (chapter 8)
Shift+TabCycle permission modesSwitch to plan mode or accept-edits (chapter 5)
Ctrl+GOpen the prompt (or plan) in your editorLong prompts, editing a plan
Ctrl+BSend running tasks to the backgroundA long build/test you don't want to wait on
Ctrl+OTranscript viewerSee every tool call in detail
Ctrl+TToggle Claude's task checklistTrack progress of a multi-step job
Ctrl+VPaste an imageScreenshots of bugs, mockups to implement
Option/Alt+P · +T · +OSwitch model · toggle thinking · toggle fast modeChapter 15
✏️ Sharpen your pencil

You want Claude to look at the output of git log --oneline -20 and summarize what changed this week. What is the fastest way that doesn't make Claude ask for permission to run git?

Answer

Type ! git log --oneline -20. The ! prefix runs the command yourself, adds its output to the conversation, and Claude responds to it. No permission prompt, because you ran it.

📌 Bullet points
  • / commands & skills, @ file mention, ! shell, Esc stop, Esc Esc rewind, Shift+Tab mode.
  • claude -c continues, claude -r resumes; name sessions with /rename or -n.
  • One engine, many surfaces — sessions can move between terminal, desktop, web and phone.
3

The context window

the one resource you must manage

Everything Claude “knows” in a session lives in its context window: the system prompt, tool definitions, your CLAUDE.md, skill descriptions, every message, every file it read, every command output. The window has a fixed size. When it fills, Claude Code compacts: it replaces older history with a summary. Details get lost in summaries.

And there is a quieter problem before the window is full: noise. The more irrelevant stuff sits in context — a debugging tangent, three unrelated questions, a 2,000-line log — the worse Claude follows your instructions. Expert users treat context like RAM on a small machine.

▶ Fill the window then clean it up
Main session
Subagent
Used
0 / 200K tokens · noise: 0%
system + toolsCLAUDE.md + skillstask worknoisesummary
A fresh session already uses some context for the system prompt, tools and CLAUDE.md.
Numbers are illustrative. The real window depends on the model (200K is common; some models offer 1M). /context shows your real usage as a colored grid; /autocompact sets when automatic compaction starts.
🔥 Fireside chat

Tonight's guests: /compact and /clear.

/compact
I'm the gentle one. I summarize the conversation and keep going. You can steer me: /compact focus on the API changes.
/clear
And I'm the honest one. A summary still carries the dead ends and the wrong guesses. New task? Start clean.
/compact
But then Claude forgets what we decided!
/clear
Decisions belong in files — a plan, a CLAUDE.md line, a commit message. Not in chat history. Then clearing costs nothing.
🤓 Deep dive

Not all context is equal. MCP tools load only their names at start; full schemas are fetched when used (tool search). Skills load only their descriptions; the body loads when triggered. Subagents run in their own window and return only a summary. Hooks cost nothing unless they print output. That's why the extension chapters keep asking “where does this land in context?” — it's the design principle behind all of them. For partial compaction, open the rewind menu (Esc Esc), pick a message and choose Summarize from here or Summarize up to here.

📌 Bullet points
  • Context is finite and noise hurts before it's full. /context to look, /clear between unrelated tasks.
  • /compact [focus] keeps going with a summary; /btw asks without adding to history.
  • Big searches → subagents: their reading stays in their window.
  • Persist decisions in files, not in chat.
4

Memory: CLAUDE.md, rules, auto memory

how Claude remembers your project between sessions

Each session starts blank — except for files Claude Code loads automatically. The main one is CLAUDE.md: plain markdown with build commands, conventions and “never do X” rules. Run /init once and Claude writes a first version by reading your repo. There are several levels, and they add up (they don't override each other):

LevelLocationFor
Managed policy/Library/Application Support/ClaudeCode/CLAUDE.md (macOS), /etc/claude-code/CLAUDE.md (Linux)Company-wide rules set by IT
User~/.claude/CLAUDE.mdYour personal preferences, all projects
Project./CLAUDE.md or ./.claude/CLAUDE.mdTeam conventions — commit it
Local./CLAUDE.local.mdYour private notes for this repo — gitignore it
Nestedpackages/web/CLAUDE.mdLoaded lazily when Claude reads files in that folder
Rules.claude/rules/*.md with paths: globsLoad only when matching files are touched
Auto memorywritten by Claude per repo (MEMORY.md index)Corrections and preferences Claude learned; first 200 lines / 25KB load each session
▶ What gets loaded, and when a monorepo session
Instruction adherence (illustrative)
Nothing is loaded before the session starts.
The adherence meter is a teaching device, not a measurement. The docs' guidance behind it is real: keep each CLAUDE.md under ~200 lines; longer files consume more context and reduce adherence.

What goes in a good project CLAUDE.md? Only what Claude can't guess and will need in most sessions:

# Build & test
- `pnpm dev` starts the app, `pnpm test -- path/to/file` runs one test file
- Always run `pnpm typecheck` after changing types

# Conventions
- Use pnpm, never npm. ES modules only.
- API handlers live in src/api/, one file per resource. See @docs/api-style.md

# Gotchas
- The `legacy/` folder is frozen. Never edit it.
- When compacting, preserve the list of modified files and test commands.
⚠️ Watch it!

CLAUDE.md is advice, not enforcement. “Never edit .env” in CLAUDE.md usually works; a deny permission rule (chapter 5) or a PreToolUse hook (chapter 11) always works. If a rule must hold every time, don't write it as prose.

❓ There are no dumb questions
Q:
My repo already has an AGENTS.md for other tools. Duplicate it?
A:
No. Claude Code can read AGENTS.md on its own or alongside CLAUDE.md, or you can import it from CLAUDE.md with @AGENTS.md. Imports work with relative and absolute paths, up to four hops deep.
Q:
How do I see or edit what's loaded?
A:
/memory lists the loaded files, opens them in your editor, and toggles auto memory. /context shows how many tokens they cost.
📌 Bullet points
  • Levels add up: managed + user + project + local + nested + rules + auto memory.
  • Keep each CLAUDE.md short (<200 lines). Move procedures to skills, folder-specific rules to .claude/rules/.
  • A mistake Claude makes twice → one line in CLAUDE.md. A rule that must never break → hook or deny rule.
5

Permissions & modes

how much rope to give the agent

Every tool call passes a gate. Two things decide the outcome: your permission rules (explicit allow / ask / deny lists) and the session's permission mode (the default behavior for anything no rule matches).

ModeRuns without askingBest for
default (manual)Reads onlySensitive work, learning what Claude does
acceptEditsReads, file edits, and common filesystem commands (mkdir, touch, rm, rmdir, mv, cp, sed) inside the working directoriesIterating on code you review in git
planReads (research only, no edits)Exploring and designing before changing
autoEverything, with a background safety classifierLong tasks, less prompt fatigue
dontAskReads and pre-approved tools; anything that would prompt is deniedLocked-down CI and scripts
bypassPermissionsEverything, no checksIsolated containers / VMs only

Shift+Tab cycles default → acceptEdits → plan, and optional modes you have enabled slot in after plan. dontAsk is never in the cycle; start it with --permission-mode dontAsk. Rules live in settings.json under permissions and are checked in a fixed order: deny, then ask, then allow. First match wins; specificity does not matter.

▶ The permission gate pick a tool call, pick a mode
Pick a tool call to send it through the gate.
Simplified: the real auto classifier sees your messages and Claude's actions (not tool output), and writes to protected paths (like .git) have their own rules. Rule syntax is real — try it in /permissions.
// .claude/settings.json  (shared with the team — commit it)
{
  "permissions": {
    "allow": ["Bash(npm run *)", "Bash(git commit *)"],
    "ask":   ["Bash(git push *)"],
    "deny":  ["Read(./.env)", "Read(./secrets/**)", "Bash(curl *)"]
  }
}

Settings come in layers too. For a single key the higher layer wins — but list keys such as permissions.allow and deny are merged across layers: managed policy > command-line flags (--settings) > .claude/settings.local.json (you, this project) > .claude/settings.json (team) > ~/.claude/settings.json (you, everywhere). Not sure where a key belongs? Ask: /update-config allow npm test — or run /fewer-permission-prompts, which scans your history and proposes an allowlist of safe read-only commands.

⚠️ Watch it!

An allow rule can't carve an exception out of a deny rule. With deny: Bash(aws *), allow: Bash(aws s3 ls) never fires. And put the * after the subcommand: Bash(git log *) allows only git log …; Bash(git *) allows git push --force too. --dangerously-skip-permissions belongs in a throwaway container, never on your laptop.

🤓 Deep dive

For fewer prompts and real safety on your machine, try the Bash sandbox: /sandbox runs shell commands with OS-level filesystem and network isolation (macOS, Linux, WSL2), and its auto-allow mode lets sandboxed commands run without asking. The sandbox limits what a command can do; permissions limit what Claude may try. Defense in depth uses both.

📌 Bullet points
  • Rules: deny → ask → allow, first match wins. Mode decides everything no rule matched.
  • Learn in default, iterate in acceptEdits, design in plan, go long in auto, script in dontAsk.
  • Team rules in .claude/settings.json, personal ones in settings.local.json.
6

Explore → Plan → Code → Verify

the workflow that saves the most time

The most common beginner move is “implement feature X” as the first prompt. Claude will — and it will solve the problem it guessed, not the one you have. The recommended workflow separates research from execution:

  1. Explore (plan mode): “read src/auth and explain how sessions are refreshed.” No edits.
  2. Plan: “plan how to add Google login. Which files change? What's the migration?” Press Ctrl+G to edit the plan yourself in your editor. Approving the plan exits plan mode.
  3. Code: Claude implements against the plan, checking it off.
  4. Verify & commit: tests, typecheck, a look at /diff, then “commit with a clear message and open a PR”.
▶ Race: straight to code vs plan first same task, two approaches
🏃 Straight to code
0 min
🧭 Explore + plan
0 min
exploreplancodeverifyrework
Pick a task size and race.
Minutes are illustrative, but the shape is the lesson: planning has a fixed cost that pays off only when the change spans several files or you're unsure of the approach.
🧠 Brain power

When would you skip plan mode entirely? (Hint: the docs' own rule of thumb — if you can describe the diff in one sentence, skip the plan.)

❓ There are no dumb questions
Q:
What if I don't know enough to write a good spec?
A:
Let Claude interview you: “I want to add rate limiting. Interview me with questions until you can write a spec to SPEC.md.” Then /clear and start a fresh session that implements SPEC.md. The spec is the handoff — clean context, full intent.
Q:
Can I plan with a stronger model and code with a cheaper one?
A:
Yes: the opusplan model setting uses Opus in plan mode and Sonnet for execution.
📌 Bullet points
  • Explore and plan in plan mode (Shift+Tab or /plan), edit the plan with Ctrl+G.
  • Planning pays for multi-file or uncertain work; skip it for one-sentence diffs.
  • For big features: interview → SPEC.md → /clear → implement.
7

Prompting that works

remove guesses, add a finish line

Claude can infer a lot, but not what's in your head. Every fact you leave out becomes a guess, and every guess is a chance to solve the wrong problem. A good prompt is not long — it's specific: where to look, what's wrong, what “done” means, and what not to touch.

▶ Prompt builder tick ingredients, watch the guesses disappear
Claude must guess:
    Start from the vague prompt most people write.
    Every ingredient maps to a best practice from the official docs: reference files, describe the symptom, point to existing patterns, give a verification command, state constraints.
    🧰 Prompt patterns that work
    1. Onboarding question: “How does logging work here? Trace one request from @src/server.ts to the DB.”
    2. Bug with evidence: paste the stack trace or screenshot (Ctrl+V), say how to reproduce, ask for a failing test first.
    3. Follow the pattern: “Add a /invoices endpoint like @src/api/orders.ts.”
    4. TDD: “Write tests for X, confirm they fail, commit them. Then implement until they pass without changing the tests.”
    5. UI iteration: give a mockup image, ask Claude to screenshot its result and compare, iterate 2–3 times.
    6. Pipe data in: cat error.log | claude -p "find the root cause".
    🤓 Deep dive

    You can ask for more thinking in plain words (“think hard about edge cases”) or raise the session's effort level with /effort (chapter 15). Rich context beats clever phrasing: a URL to the docs, an image, @-mentioned files, piped logs. If Claude should fetch docs, allow the domain with a rule like WebFetch(domain:docs.stripe.com).

    📌 Bullet points
    • Where (@file) + symptom + pattern to follow + verification + constraints.
    • Give Claude a finish line it can check itself: a test, a command, a screenshot.
    • Two failed corrections in a row → /clear and write a better first prompt.
    8

    Sessions, checkpoints & rewind

    an undo button for an agent

    Claude Code saves a checkpoint before each prompt: the conversation state plus snapshots of the files Claude edited. Press Esc Esc on an empty prompt (or run /rewind), pick a message, and choose: restore code, restore conversation, or both — or summarize from that point. That makes experiments cheap: let Claude try a bold approach, and rewind if you don't like it.

    ▶ Rewind a session 4 prompts, 3 files
    Play the session first.
    Real behavior: checkpoints track edits made by Claude's file tools. Changes made by Bash commands (rm, mv, cp), by you outside the session, or by other sessions are not restored. Checkpoints are not a replacement for git.
    CommandWhat it does
    claude -c / --continueContinue the most recent conversation in this directory
    claude -r / /resumePick any older session (by name or ID)
    /rename, claude -n nameName a session so you can resume it by name
    /branchBranch the conversation at this point to try something different
    --fork-sessionResume into a new session ID, leaving the original intact
    /rewind, Esc EscRestore code and/or conversation to a checkpoint, or summarize from there
    /diffReview the working tree changes so far
    /export, /copySave the conversation / copy the last answer
    ⚠️ Watch it!

    Checkpoints are local undo, git is history. Commit at every green state (“commit this with a descriptive message” is a perfectly good prompt). Then even a rm -rf through Bash is one git checkout away.

    📌 Bullet points
    • Every prompt = a checkpoint. Esc Esc → restore code, conversation, or both.
    • Bash-made file changes are not tracked. Commit often.
    • Name sessions, resume with -c / -r, branch with /branch.
    9

    Skills: reusable know-how

    write the playbook once, load it only when needed

    A skill is a folder with a SKILL.md: YAML frontmatter plus markdown instructions, optionally with scripts and reference files next to it. You invoke it as a command (/deploy staging), or Claude loads it by itself when your task matches its description. Custom slash commands were merged into skills: an old .claude/commands/deploy.md still works and creates /deploy too.

    The trick is progressive disclosure. At session start only each skill's name and description sit in context. The full body loads when the skill is used; files it links load only if Claude opens them. So you can have fifty skills and pay for fifty short descriptions.

    .claude/skills/release-notes/SKILL.md
    ---
    name: release-notes
    description: Draft release notes from merged PRs since the last tag. Use when asked for a changelog or release notes.
    disable-model-invocation: true      # only I can trigger it (/release-notes)
    allowed-tools: Bash(git log *) Bash(gh pr list *)
    context: fork                       # run in a forked subagent, return a summary
    ---
    1. Find the last tag with `git describe --tags --abbrev=0`.
    2. List merged PRs since then …
    3. Group by feat / fix / chore. Output markdown. See [template.md](template.md).
    ▶ Progressive disclosure four skills, one context window
    Main context
    Forked subagent
    At start only descriptions load — except for the dashed skill, which Claude can't even see.
    Token sizes are illustrative. /skills lists your skills; /skill-doctor shows what each one costs in context and how often it triggers.
    FrontmatterEffect
    descriptionHow Claude decides to use it. Say what and when. Vague = wrong triggers.
    disable-model-invocation: trueOnly you can run it. Use for side effects (deploy, publish). Zero context cost until used.
    user-invocable: falseOnly Claude uses it (background knowledge); hidden from the / menu.
    allowed-toolsTools pre-approved while the skill runs
    context: fork + agentRun in a forked subagent; only the result returns
    model, effortOverride model / effort while the skill is active
    pathsAuto-load only when working with matching files
    arguments, argument-hintNamed args ($name) and autocomplete hint
    hooksHooks registered when the skill is invoked

    Where skills live: ~/.claude/skills/ (you, all projects), .claude/skills/ (the repo — commit it), managed (your company), and plugins (namespaced like /my-plugin:review). Claude Code also bundles skills you get for free: /code-review, /simplify, /debug, /batch, /loop, /run, /verify, /doctor, /fewer-permission-prompts and more.

    🔥 Fireside chat

    Tonight's guests: CLAUDE.md and a Skill.

    CLAUDE.md
    I'm loaded in every session. Every single one. People love me.
    Skill
    And they pay for you every single request. I show up only when I'm useful.
    CLAUDE.md
    So what should live in me?
    Skill
    Facts needed almost always: build commands, conventions. Procedures and reference docs — the deploy checklist, the API style guide — give them to me.
    📌 Bullet points
    • Skill = SKILL.md + optional files. Invoked with /name or auto-loaded by description.
    • Only descriptions cost context until use. Write sharp descriptions.
    • Third time you paste the same instructions → make it a skill.
    • Side effects → disable-model-invocation: true. Heavy work → context: fork.
    10

    Subagents: delegate, don't pollute

    a fresh brain for every side quest

    A subagent is a separate Claude instance with its own context window, its own system prompt, and optionally its own tools, model and permissions. The main session hands it a task; it reads, searches, runs things, and returns only a summary. The 40 files it read never enter your main context.

    Claude uses built-in subagents on its own: Explore (read-only codebase search), Plan (research during plan mode) and general-purpose (explore + modify, multi-step). You can also ask: “use subagents to investigate how payments, auth and emails each handle retries.” Several can run in parallel.

    ▶ Inline vs delegated “how do payments, auth and email handle retries?”
    Main session
    Same question, two strategies. Watch where the reading lands.
    Token counts are illustrative. Subagents spend their own tokens — delegation mainly protects your main context (a cheaper subagent model, e.g. Haiku, can also cut cost). Parallel subagents finish sooner than sequential reading.
    .claude/agents/security-reviewer.md
    ---
    name: security-reviewer
    description: Reviews diffs for injection, authz and secret-handling bugs. Use after changes to auth or API code.
    tools: Read, Grep, Glob, Bash
    model: opus
    permissionMode: plan        # read-only
    memory: project             # keeps its own notes across sessions
    ---
    You are a senior application security engineer. For each finding give file:line,
    the exploit scenario, and the minimal fix. No style comments.

    Other useful fields: skills (preload full skills), mcpServers, hooks, maxTurns, effort, isolation: worktree (work on its own copy of the repo), background: true. Put agents in .claude/agents/ (team) or ~/.claude/agents/ (you). The easiest way to write one: ask Claude to create it.

    ❓ There are no dumb questions
    Q:
    Skill with context: fork vs subagent — what's the difference?
    A:
    A skill is content (instructions); a subagent is a worker (a context with a role, tools and model). context: fork runs a skill's content inside a worker; a subagent's skills: field preloads content into a worker. They compose.
    Q:
    Can a subagent see my conversation?
    A:
    A normal subagent sees only what the lead passes in the prompt (plus CLAUDE.md and git status, except Explore and Plan which skip them). A fork (/fork, /subtask) copies the whole conversation so far.
    ✏️ Sharpen your pencil

    You just finished a feature. Design an “adversarial review” step that doesn't share your session's blind spots.

    Answer

    Spawn a fresh reviewer subagent (or a second session) that sees only the diff and the spec, not your conversation — it can't inherit the assumptions you made while building. Or run /code-review, which does exactly this; /code-review ultra runs a deep multi-agent review in the cloud.

    📌 Bullet points
    • Subagent = isolated context + role + tools + model. Returns a summary.
    • Use for research that reads a lot, parallel independent questions, and unbiased review.
    • Define in .claude/agents/*.md; restrict tools and permissionMode for safety.
    11

    Hooks: guarantees, not requests

    code that runs at every lifecycle event

    Everything so far is advice the model interprets. A hook is different: Claude Code itself runs your shell command (or HTTP call, MCP tool, prompt, or subagent) when a lifecycle event fires. It always runs. It can block actions, inject context, or just log. Configure hooks in settings.json; /hooks lets you browse them (read-only).

    {
      "hooks": {
        "PreToolUse": [{ "matcher": "Bash",
          "hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous.sh" }] }],
        "PostToolUse": [{ "matcher": "Edit|Write",
          "hooks": [{ "type": "command", "command": "npx prettier --write \"$(jq -r .tool_input.file_path)\"" }] }]
      }
    }

    The hook gets a JSON payload on stdin (tool name, input, session info). Exit code 0 = go on; exit code 2 = block, and stderr goes back as the reason (for PreToolUse, Claude reads it and adjusts). For finer control, print JSON with a decision.

    ▶ One turn, every event toggle hooks, then run the turn
    The turn: Claude edits a file, then tries rm -rf ./build ~/ (oops — a stray ~/).
    Simplified to the main events. The full list also has PermissionRequest, PostToolUseFailure, SubagentStart/Stop, PreCompact/PostCompact, Notification, FileChanged, CwdChanged, WorktreeCreate and more.
    EventClassic use
    SessionStartInject context: current sprint, open issues, env setup
    UserPromptSubmitAdd context or reject prompts (e.g. leaked secrets)
    PreToolUseBlock dangerous commands, protect files, enforce rules
    PermissionRequestAuto-approve or deny a permission prompt by policy
    PostToolUseFormat, lint, typecheck after edits — exit 2 (stderr) or JSON additionalContext feeds problems back to Claude
    StopRun tests before Claude may finish; notify you
    NotificationDesktop / phone ping when Claude waits for input
    PreCompactSave a transcript backup before compaction
    SessionEndCleanup, logging, metrics
    ⚠️ Watch it!

    Hooks run with your user's permissions, automatically, on every matching event. Review any hook you copy (and any plugin that ships hooks) like you'd review a script you pipe into bash. Quote variables, use absolute paths via $CLAUDE_PROJECT_DIR, and keep them fast — a slow PostToolUse hook slows every edit.

    📌 Bullet points
    • Hook = deterministic code on a lifecycle event. CLAUDE.md = a request; hook = a guarantee.
    • Exit 2 blocks (PreToolUse) and stderr becomes Claude's feedback; JSON output can add context. Plain stdout of most events goes only to the debug log.
    • Best starter hooks: format after edit, block dangerous Bash, notify when waiting.
    12

    MCP & plugins

    new hands for the agent, packaged for the team

    MCP (Model Context Protocol) connects Claude to external systems as tools: GitHub, Sentry, Linear, Notion, your database, a browser. If you keep copying data from a browser tab into the chat, that system wants to be an MCP server.

    # remote HTTP server (OAuth in /mcp)
    claude mcp add --transport http notion https://mcp.notion.com/mcp
    # local stdio server: everything after -- is the server command
    claude mcp add --transport stdio db -- npx -y @bytebase/dbhub --dsn "postgresql://readonly:…@localhost:5432/app"
    # share with the team via .mcp.json
    claude mcp add --scope project --transport http sentry https://mcp.sentry.dev/mcp
    ▶ Connect servers then ask a question that needs them
    Config written to
    —
    In context
    No servers yet. Claude can only use its built-in tools.
    Tool search is on by default: only tool names load at start; a full schema loads when Claude needs that tool. /mcp shows status and handles OAuth; /context all shows how many tokens each loaded MCP tool uses.

    MCP scopes override by name: local > project > user. Local and user servers are stored in ~/.claude.json; project servers in .mcp.json at the repo root, which teammates approve on first use. Never commit secrets there — use ${ENV_VAR} expansion.

    Plugins are the packaging layer: one installable unit bundling skills, subagents, hooks, MCP servers (and LSP code-intelligence servers). Add a marketplace once, then install from it:

    /plugin marketplace add your-org/claude-plugins
    /plugin install commit-commands@claude-plugins-official
    /plugin            # browse, enable, disable, choose scope
    🤓 Deep dive

    MCP gives access; a skill gives know-how. The strongest combo is both: an MCP server for your database plus a skill that documents your schema, naming and “never query prod without LIMIT” rules. For typed languages, a code intelligence plugin (LSP) lets Claude jump to definitions and see type errors after each edit instead of grepping — fewer file reads, less context.

    ⚠️ Watch it!

    An MCP server that fetches untrusted content (web pages, issues, emails) can carry prompt injection. Use servers you trust, keep permission prompts on for tools with side effects, and prefer read-only credentials.

    📌 Bullet points
    • MCP = external tools. claude mcp add, scopes local > project > user, /mcp to manage.
    • Only tool names cost context until a tool is used.
    • Plugins bundle skills + agents + hooks + MCP; share them through a marketplace when a 2nd repo needs the same setup.
    13

    Parallel work & long-running jobs

    from one agent to a small team

    Once one session works well, the next bottleneck is you waiting. Claude Code has several ways to run more than one thing at once. The question that separates them: who holds the plan?

    ▶ Pick the right tool click a scenario
    Each scenario lights up the approach that fits best.
    Availability varies: agent teams are experimental (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1), routines and agent view are in research preview, dynamic workflows need a paid plan or API / cloud-provider access (on Pro, switch them on in /config).
    ApproachHowWho decides what runs next
    Subagents“use subagents to…”, /subtaskClaude, turn by turn
    Worktreesclaude -w feature-auth — own checkout under .claude/worktrees/You, one session each
    Background sessions/background, claude agents (agent view), Ctrl+B for tasksYou dispatch, check back later
    Agent teamsLead + teammates with a shared task list and messagingThe lead agent
    Dynamic workflowsAsk for “a workflow”A script Claude writes
    /batchBundled skill: splits a big change across subagents in their own worktreesClaude, following the skill
    /goal“until all tests pass” — keeps taking turns until a checker says doneA completion condition
    /loop/loop 5m check the deploy — repeats while the session is openA timer
    Routines/schedule — cloud runs on cron, API or GitHub events, laptop closedA trigger
    🧰 Workflow: three features before lunch
    1. claude -w search, claude -w billing-fix, claude -w docs in three terminal tabs — each gets its own branch and files.
    2. Plan each in plan mode, approve, switch to auto or acceptEdits.
    3. Set a Notification hook so you get pinged when one needs you; work the queue.
    4. Each session opens its own PR; review with /code-review in a fresh session.
    ⚠️ Watch it!

    Parallel agents multiply review work, not only output. Two sessions editing the same files in one checkout will fight — isolate with worktrees. And more agents cost more tokens: agent teams in particular use a separate context per teammate.

    📌 Bullet points
    • Side quest → subagent. Separate features → worktrees. Debate → agent team. Huge cross-checked fan-out → workflow; big mechanical change → /batch.
    • Keep going until done → /goal. Poll → /loop. Laptop closed → routine via /schedule.
    14

    Headless mode & CI

    Claude Code as a Unix tool

    claude -p "prompt" runs one task non-interactively and prints the result. Everything you learned still applies — CLAUDE.md, skills, hooks, MCP — so it slots into scripts, pre-commit checks, and CI.

    # one-off, pipe in, JSON out
    git diff main | claude -p "review for bugs; reply as a list" --output-format json
    
    # structured output validated against a schema (the root must be an object)
    claude -p "list TODOs" --output-format json \
      --json-schema '{"type":"object","properties":{"todos":{"type":"array","items":{"type":"string"}}},"required":["todos"]}' \
      | jq '.structured_output'
    
    # locked down for CI: listed tools + reads / read-only commands; anything that would prompt is denied
    claude -p "run the tests and fix failures" \
      --permission-mode dontAsk --allowedTools "Read" "Edit" "Bash(npm test *)" \
      --max-turns 20 --max-budget-usd 5
    
    # fan out over files
    git ls-files -z 'src/*.js' | while IFS= read -r -d '' f; do   # git's * also matches across /
      claude -p "migrate $f from CommonJS to ESM, keep behavior" --allowedTools "Read" "Edit" 
    ▶ A PR review job GitHub Actions + claude -p
    The job runs in dontAsk mode: reads plus pre-approved tools only.
    Based on anthropics/claude-code-action@v1. Run /install-github-app once: it installs the app, adds the secret and pushes a branch with the workflow files, opening a ready-to-create PR in your browser; after you create and merge it, @claude in an issue or PR comment triggers Claude too. A workflow with a prompt runs in automation mode and writes results to the run log unless the prompt tells Claude to post and it has a tool that can comment.
    🤓 Deep dive

    --output-format stream-json emits events as they happen (for dashboards and bots). --bare skips auto-discovery of hooks, skills, plugins, MCP and CLAUDE.md for reproducible scripts. --append-system-prompt adds instructions. -c -p continues a conversation in a script. For full control (tool approval callbacks, native objects) use the Agent SDK in Python or TypeScript — it is the same engine.

    📌 Bullet points
    • -p + --output-format json|stream-json + --json-schema for machines.
    • CI: --permission-mode dontAsk + an exact --allowedTools list + --max-turns/--max-budget-usd.
    • GitHub: /install-github-app; scheduled or event-driven cloud runs: routines.
    15

    Models, effort & cost

    spend thinking where it matters

    Two dials decide how hard Claude thinks. The model (/model, --model, Option/Alt+P) picks the brain; the effort level (/effort, --effort) picks how much it reasons per step: low, medium, high, xhigh, max. Aliases track the recommended version for your provider: haiku, sonnet, opus, fable, best; plus opusplan (Opus to plan, Sonnet to execute) and [1m] variants for a 1M-token window.

    ▶ Match the dial to the task heuristics, not benchmarks
    Suggested
    Reasoning depth
    Speed
    Token spend
    Bars are qualitative. Real defaults: effort is high on most models (Opus 5.5 defaults to medium). Fast mode runs the same Opus model with faster output at a higher price, not a smaller model.
    ❓ There are no dumb questions
    Q:
    How do I see what I'm spending?
    A:
    /usage (alias /cost) shows session cost and plan limits; /context shows what fills the window; a custom status line (/statusline) can show model, context % and cost all the time.
    Q:
    Which cost levers matter?
    A:
    Context matters as much as the model: token costs scale with context size, so clearing between tasks, lean CLAUDE.md, subagents for heavy reading and fewer idle MCP servers all cut spend. Then pick the smallest model and effort that do the job, and raise them for the hard parts.
    📌 Bullet points
    • Model = which brain; effort = how long it thinks. Raise both for design and hard debugging only.
    • opusplan: strong planning, cheaper execution. Subagents can use model: haiku for search.
    • Watch /usage and /context; context hygiene is one of the biggest savings.
    16

    Expert habits & anti-patterns

    the difference is mostly discipline

    Experts don't know secret commands. They build a setup over time, each piece triggered by a real annoyance, and they keep sessions clean. The official docs list the order most teams add things:

    When this happens……add this
    Claude gets a convention or command wrong twiceA line in CLAUDE.md
    You keep asking for shorter / more explained answersAn output style (/output-style)
    You type the same starting prompt againA user-invocable skill
    You paste the same playbook for the third timeA skill
    You copy data from a browser tab Claude can't seeAn MCP server
    A side task floods the chat with outputA subagent
    Something must happen every timeA hook
    A second repo needs the same setupA plugin
    ▶ Where are you on the ladder? tick what you already do
    Anti-pattern clinic — click a symptom
    Five failure patterns straight from the official best practices.
    Your ticks are saved only in this browser (localStorage), never sent anywhere.
    🧰 Daily expert loop
    1. Start clean: one task per session, named (claude -n billing-bug).
    2. Explore in plan mode with @ files; for big work, interview → SPEC.md.
    3. Give a finish line (test / command / screenshot); switch to acceptEdits or auto.
    4. Steer early with Esc; rewind bad paths instead of arguing with them.
    5. Verify: tests, /diff, /code-review in a fresh context. Commit at green.
    6. Harvest: turn the repeated correction into a CLAUDE.md line, skill or hook. /clear.
    📌 Bullet points
    • Grow your setup from real triggers; prune CLAUDE.md ruthlessly.
    • Kitchen-sink sessions, endless corrections, bloated CLAUDE.md, no verification, unscoped exploration — the five killers.
    • Always close the loop: something Claude can run to prove it's done.
    17

    Exam + cheat sheet

    check what stuck

    14 questions. Each tests a mechanism from the chapters, not just a command name.

    Score: 0 / 0

    Cheat sheet

    Command / fileWhat it doesUse when
    claude -c / -r / -nContinue / resume / name a sessionPicking work back up
    /init, CLAUDE.mdProject memory loaded every sessionBuild commands, conventions (<200 lines)
    .claude/rules/*.mdRules scoped with paths: globsFolder- or language-specific guidance
    /memoryEdit loaded memory, toggle auto memoryChecking what Claude “knows”
    Shift+Tab, /planCycle modes / enter plan modeExplore before editing
    --permission-modedefault · acceptEdits · plan · auto · dontAsk · bypassPermissionsChoosing autonomy
    /permissionsallow / ask / deny rules (deny → ask → allow)Fewer prompts, hard limits
    /sandboxOS-level isolation for BashSafer autonomy on your machine
    /context, /usageContext grid / cost and limitsSessions getting slow or pricey
    /clear, /compact [focus]Reset / summarize contextBetween tasks / long tasks
    /btwSide question, not added to historyQuick lookups mid-task
    Esc · Esc Esc · /rewindInterrupt · rewind code/conversationWrong direction, failed experiment
    @file, !cmd, Ctrl+VMention file · run shell · paste imageGiving precise context
    .claude/skills/x/SKILL.mdReusable skill, /xRepeated playbooks
    .claude/agents/x.mdCustom subagentIsolated research, reviews, roles
    settings.json → hooksCode on lifecycle events; exit 2 blocksMust-always rules, formatting, alerts
    claude mcp add, /mcp, .mcp.jsonExternal tools (local > project > user)GitHub, DBs, browsers, trackers
    /pluginInstall bundles from marketplacesSharing a setup across repos
    claude -w nameSession in its own git worktreeParallel features
    /goal · /loop · /scheduleUntil done · on interval · cloud routineLong or recurring work
    claude -p … --output-format jsonHeadless runScripts, CI, pipes
    /model · /effort · /fastBrain · thinking depth · faster outputHard vs routine tasks
    /code-review [ultra]Review diff / deep cloud multi-agent reviewBefore merging
    /doctor, /release-notesDiagnose setup / what changedSomething looks off
    🎓 Congratulations

    You went from “what is an agent” through context, memory, permissions, planning, prompting and rewind, to skills, subagents, hooks, MCP, parallel sessions, CI and model choice. Look at the worry list you wrote in chapter 0: wrong edits (plan mode, verification, rewind), deleted files (permissions, sandbox, hooks, git), forgetting (CLAUDE.md, auto memory, specs), bills (context hygiene, effort, budgets). Next step: pick one annoyance from this week and add exactly one piece of setup that removes it. Repeat weekly.