CLAUDE CODE MASTER CLASS
From first session to power user · 12 modules · about 60 minutes end-to-end.
Who this is for
You have used a coding assistant before, but Claude Code feels deeper than a chat box and you suspect there's a system underneath. There is. This Master Class walks the 12 surfaces of that system, from the claude binary all the way to headless CI/CD, with one diagram per concept and one copy-paste recipe per module.
How to use this page
- Top to bottom is the canonical path. Each module builds on the last.
- If you only have 10 minutes — read §1 Mental Model, §3 CLAUDE.md, §8 Hooks. Those three are the conceptual core.
- Each module ends with a Deep dive → link to the dense reference cheatsheet for the full table-of-flags / full diagram / full schema.
- Built against Claude Code
v2.1.143. CLI flags and hook event names track that version.
Mental Model
foundationsTL;DR — Claude Code is not "Claude in a terminal." It's an agent harness: a loop that reads your repo, runs tools, watches results, and iterates. The model is one node; the harness is the system.
▸ Three things Claude offers (pick the right one)
- claude.ai (chat) — conversation, no tools, no repo. Best for thinking out loud.
- Claude Code — terminal-native agent that reads your codebase, edits files, runs commands, fixes errors. Best for shipping code.
- Anthropic API — programmable Claude in your own application. Best when YOU are the harness.
▸ The agent loop, in five steps
▸ What makes Claude Code different
- It owns a workspace. It can `Read`, `Edit`, `Write`, `Bash` against your files — not just talk about them.
- It has a contract. Permissions, hooks, and CLAUDE.md are the rails. You configure intent; Claude works inside it.
- It composes. Skills, agents, MCP servers, hooks — each is a primitive. The Master Class teaches each one.
▸ Try it now
cd ~/your-project
claude
> what does this codebase do? Deep dive → cheatsheet PART I (CLI surface) Your First Session
foundationsTL;DR — Four entry shapes cover 95% of real use: claude (interactive), claude -p (one-shot), claude -c (continue), claude -r (resume by id). The rest are flags on top.
▸ The four shapes
claude— interactive REPL. The 90% case. You type, it responds, you iterate.claude -p "task"— one-shot. Print result and exit. For pipes, scripts, CI.claude -c— resume the last conversation in this dir. Picks up where you left off.claude -r [id|search]— pick a specific past session. Interactive picker if no arg.
▸ Three flags worth knowing day one
--model haiku|sonnet|opus— pick the brain. Default is sonnet. (§9 covers when to pick what.)--add-dir <path>— let Claude see files outside cwd. Multi-repo workflow.--max-budget-usd 0.50— hard ceiling. Session stops when the cost cap is hit.
▸ The session graph
▸ Try it now
# scriptable one-shot, structured output, budgeted
claude -p --output-format json --max-budget-usd 0.50 \
"summarize the last 3 commits" Deep dive → cheatsheet PART I (execution modes · model · I/O · subcommands) CLAUDE.md, the instruction manual
foundationsTL;DR — CLAUDE.md is the first thing Claude reads. Put your project conventions here and you stop repeating yourself every session. Files merge along an ancestor walk; nested files can be path-scoped.
▸ The hierarchy (all merge into the prompt)
▸ The four things worth putting in it
- Stack. Language, framework, test runner. Saves Claude from guessing.
- Build & test. Exact commands.
bun test,pnpm run lint, etc. - Conventions. Style, patterns, naming. The stuff a reviewer would correct.
- Gotchas. Non-obvious behaviors. The stuff that bit you once.
▸ Path-scoped frontmatter
---
paths: ["src/**", "tests/**"]
---
# Only loaded when files under src/ or tests/ are touched.
# Use to keep CLAUDE.md focused. ▸ Imports (compose, don't duplicate)
@./conventions.md # relative
@~/.claude/snippet.md # user-home
@/abs/path.md # absolute Deep dive → cheatsheet PART II (CLAUDE.md card · imports · reload triggers) Permissions & Safety
foundationsTL;DR — Claude asks before doing destructive things, but you decide the policy. Four modes go from "ask everything" to "trust the agent", plus an allow/deny list with glob patterns.
▸ The four modes (least to most trusting)
- default — prompt on every tool call. Safest, slowest.
- acceptEdits — auto-accept file edits, still prompt for Bash. Good for refactors.
- plan — read-only mode; Claude proposes a plan, you approve before any write.
- bypassPermissions — agent runs free. Use in throwaway sandboxes or CI with hard budget caps.
▸ Allow / deny with glob patterns
// .claude/settings.json
{ "permissions": {
"defaultMode": "default",
"allow": ["Bash(git *)", "Read", "Edit"],
"deny": ["Bash(rm -rf *)", "Bash(curl *)"]
} } ▸ The rule of safety
- Most patterns are
ToolName(arg-pattern). The arg pattern is a shell-glob. - Deny wins over allow for the same tool. Build your safety net with deny.
- Never paste
--dangerously-skip-permissionson a real repo. The flag exists for sandboxes only — it disables every permission check including the deny list. - Pair high-trust modes with
--max-budget-usdso a runaway agent burns money instead of files.
The MCP Universe
capabilitiesTL;DR — MCP (Model Context Protocol) is how Claude talks to the world beyond your filesystem. One .mcp.json declares servers; each server exposes tools named mcp__<srv>__<tool>.
▸ Five mature servers worth knowing
- playwright — browser automation. Click, type, screenshot, evaluate JS. Default for authenticated workflows.
- chrome-devtools — network observability, performance, runtime. Debug-only.
- dbhub — multi-DB SQL (Postgres, MySQL, SQLite). Read-only by default.
- nextjs-devtools — build logs, routes, server actions, cache diagnostics.
- github — structured issues / PRs / repos / workflows (richer than
ghCLI).
▸ Adding a server
// .mcp.json at repo root
{ "mcpServers": {
"playwright": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-playwright"]
}
} } ▸ Trust gate
By default Claude prompts before enabling MCP servers declared in a project. Set enableAllProjectMcpServers: true in settings to skip the prompt — only do that for repos you trust.
▸ Mental model
Skills — bottling your prompts
capabilitiesTL;DR — a skill is a folder with a SKILL.md inside. Its body IS the prompt. Invoke as /<name>. You stop pasting the same instructions every session.
▸ Anatomy
▸ Frontmatter that matters
---
description: One-line discovery hint (Claude reads this to know when to suggest you)
argument-hint: <new <slug> | list>
allowed-tools: [Read, Grep, Bash]
paths: ["docs/specs/**"] # path-scoped: only loadable in matching dirs
context: fork # isolated turn (doesn't pollute main convo)
---
# /name — body below this line is the prompt ▸ Two killer features
$ARGUMENTS— whatever the user typed after the slash command. Lets one skill handle many phrasings.!`shell-cmd`— runs at skill-load time; stdout is injected as context. Great for live state ("today's date", "current branch", "open PR list").
▸ Bundled skills (already on your machine)
/simplify · /batch · /debug · /loop · /claude-api — all ship with Claude Code. /help lists them in your install.
Agents — delegation done right
capabilitiesTL;DR — an agent runs in an isolated context and returns a single message. Delegate when (a) the work needs many tool calls, (b) the result fits in a summary, or (c) you want to keep noise out of your main conversation.
▸ The five built-in agents
- general-purpose — multi-step research and execution. The default.
- Explore — read-only fast search. "Where is X defined? Which files use Y?"
- Plan — architect mode. Produces an implementation plan, doesn't write code.
- claude-code-guide — Q&A about Claude Code itself (this Master Class is a real-world example).
- statusline-setup — configures your status line. Niche but ships.
▸ A good delegation has five parts
TASK: one sentence — what to do
CONTEXT: files/paths the agent should read first
CONSTRAINTS: what NOT to do · budgets · style guardrails
DELIVERABLE: concrete artifact (file path, PR, summary shape)
DONE_WHEN: verifiable condition (tests pass, file exists) Either DELIVERABLE or DONE_WHEN is required (or both). The agent inherits no context from the parent — give it everything it needs upfront.
▸ Dispatch from a tool call
Agent({
subagent_type: "Explore",
prompt: "TASK: locate all callers of getUser() across src/.\n..." ,
model: "sonnet", // optional · overrides default
isolation: "worktree", // optional · runs in a temp git worktree
}) ▸ Model-fit cheatsheet
Mechanical implementation → sonnet. Quick schema/protocol lookup → haiku. Architecture review or exploratory debugging → opus. Multi-source comparative research → opus if ≥2 signals fire; otherwise sonnet.
Hooks — gate every action
capabilitiesTL;DR — hooks are shell scripts that run on lifecycle events. 29 events total. Each gets JSON on stdin and decides via exit code: 0 = allow, 2 on PreToolUse = BLOCK (stderr shown to agent), anything else = log-only.
▸ The seven event families
- Session lifecycle — SessionStart · SessionEnd · Setup · Stop · StopFailure
- Prompts & instructions — UserPromptSubmit · UserPromptExpansion · InstructionsLoaded
- Tool gates — PreToolUse · PostToolUse · PostToolUseFailure · PostToolBatch
- Permission — PermissionRequest · PermissionDenied
- Sub-agents & tasks — SubagentStart · SubagentStop · TaskCreated · TaskCompleted
- Compaction — PreCompact · PostCompact
- System — Notification · TeammateIdle · ConfigChange · CwdChanged · FileChanged · WorktreeCreate · WorktreeRemove · Elicitation · ElicitationResult
▸ Minimum viable hook
// .claude/settings.json
{ "hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "bash .claude/hooks/check-bash.sh"
}]
}]
} } #!/usr/bin/env bash
# .claude/hooks/check-bash.sh — read JSON from stdin, decide via exit
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command')
if [[ "$cmd" =~ rm\ -rf ]]; then
echo "blocked: rm -rf is denied in this project" >&2
exit 2
fi
exit 0 ▸ The one gotcha worth flagging
PostToolUse(Bash) fires only on tool success. To catch failures, pair it with PostToolUseFailure(Bash). The failure payload uses .error and has no tool_response.
▸ Three handler types
type: command— shell script. The default.type: prompt— single-turn Claude eval over$ARGUMENTS.type: agent— spawn a sub-agent with tools for deep verification.
Cost & Model Fit
powerTL;DR — the same task at Opus rates can cost 60× more than at Haiku. The diagonal is optimal; off-diagonal is overpay or underpay. Picking right once can cut a project's bill by 70%.
▸ The three models · per million tokens
▸ Effort knob (Opus only)
--effort low|medium|high trades latency for depth. low for tight loops, high for one-shot architecture review.
▸ The cache is your second-best lever
- Anthropic caches prompts for 5 minutes (free tier) or 1 hour (with explicit
cache_control). - System prompts + CLAUDE.md + long file reads are all cache candidates. Repeating them within the TTL is ~90% cheaper.
- Long sleeps (≥5 min) bust the cache. Plan your loop intervals accordingly.
▸ The hard ceiling
claude -p --max-budget-usd 1.00 --max-turns 12 \
"run tests, fix failures, repeat until green" Budget caps and turn caps are the safety net — when a loop fails to converge, it stops burning money instead of getting clever.
Deep dive → Atlas Cost × Model fit matrixWorkflow Patterns
powerTL;DR — most real Claude Code work fits one of five shapes. Picking the right shape matters more than picking the right model.
▸ The five patterns
- Sequential — one Claude, one task, top-to-bottom. The default. Use for anything where step N depends on step N−1.
- Operator — you stay in the loop, Claude proposes diffs, you accept/reject. Use for code review and surgical edits.
- Split-merge — one parent fans out N delegated agents (one per file, one per module), parent merges the returns. Use for codemod-style refactors.
- Agent teams — Plan → Implement → Review chain, each a different sub-agent with its own context. Use for non-trivial features.
- Headless —
claude -pin CI/CD with structured output. No human in the loop. Use for PR review bots, test-fix loops, dependency audits.
▸ Picking the shape
▸ The hidden trade-off
Parallel patterns (split-merge, agent teams) are fast but cost more in total tokens because each delegated agent loads its own context. Sequential is slower but cheaper. Pick parallel only when wall-clock latency genuinely matters.
Deep dive → cheatsheet WORKFLOW PATTERNS cardCompaction & Memory
powerTL;DR — Claude Code summarizes long sessions automatically. The summary is lossy. The PreCompact → SessionStart(compact) hook bridge is how you preserve the raw signal that matters.
▸ Three memory layers
- CLAUDE.md — always in context. The "this is how this project works" layer.
- Auto-memory — Claude writes facts about your project into
~/.claude/projects/<slug>/memory/as it learns. Indexed byMEMORY.md, loaded at session start. - Transcript — the conversation itself. When it grows past the budget, compaction kicks in.
▸ The compaction flow
▸ Why the hook bridge matters
- The summarizer is the only thing that crosses the boundary by default — and summarization drops verbatim quotes, file paths, exact wording.
- Only
PreCompactcan write before truncation; onlySessionStartcan inject after. No other hook bridges the gap. - Save raw turns to disk in PreCompact, read them back in SessionStart-with-source-compact. That's the canonical pattern.
▸ Try it now
# manual compaction
/compact
# review what was preserved
/memory Deep dive → Atlas Compaction interrupt flow CI/CD & Headless
powerTL;DR — claude -p is the gateway to non-interactive use. Pair it with --output-format json, --max-budget-usd, and --max-turns to get a deterministic, budgeted, parseable agent in your pipeline.
▸ The five flags that make headless work
-p, --print— print result and exit. No REPL.--output-format json|text|stream-json— JSON is the right default for machines.--max-turns N— hard cap on agent iterations. Stops runaways.--max-budget-usd X— hard cap on cost. Stops cost overruns.--permission-mode bypassPermissions— required in CI where no human can approve. Pair with the two caps above.
▸ A real GitHub Actions step
- name: PR review bot
run: |
claude -p \
--permission-mode bypassPermissions \
--output-format json \
--max-turns 6 \
--max-budget-usd 0.50 \
"review PR #${{ github.event.number }} for security issues,
return findings as JSON: {findings: [{file, line, severity, why}]}"
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ▸ Three patterns that ship
- PR review bot — runs on
pull_request, posts findings as a review comment. - Test-fix loop — runs on
workflow_dispatch, attempts to fix failing tests, opens a PR with the fix. - Dependency audit — runs nightly, reads
package.json+ advisories, files issues for vulnerable deps.
▸ The discipline
- Always set a turn cap AND a budget cap. Both. CI loops are where money disappears.
- Use the cheapest model that gets the job done. Most CI work is
sonnetat most. - Treat the JSON output as a contract — fail the CI step if the JSON is malformed instead of letting it cascade.