← claude-core
Resources
EN PT ES
▮ CLAUDE-CORE · ACADEMY CLAUDE CODE v2.1.143 12 MODULES · BEGINNER → POWER ▮

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

§1

Mental Model

foundations

TL;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)

  1. claude.ai (chat) — conversation, no tools, no repo. Best for thinking out loud.
  2. Claude Code — terminal-native agent that reads your codebase, edits files, runs commands, fixes errors. Best for shipping code.
  3. Anthropic API — programmable Claude in your own application. Best when YOU are the harness.

▸ The agent loop, in five steps

promptmodeltool calltool resultmodel → (loop until done) repeat until: text-only response · max-turns hit · budget hit · user interrupt

▸ 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)
Next → §2 · Your First Session
§2

Your First Session

foundations

TL;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

  1. claude — interactive REPL. The 90% case. You type, it responds, you iterate.
  2. claude -p "task" — one-shot. Print result and exit. For pipes, scripts, CI.
  3. claude -c — resume the last conversation in this dir. Picks up where you left off.
  4. 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

startup ─SessionStart→ interactive ⇄ /compact ⇄ compacted │ └─/clear→ fresh ctx ─SessionEnd→ ended

▸ 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)
Next → §3 · CLAUDE.md, the manual
§3

CLAUDE.md, the instruction manual

foundations

TL;DRCLAUDE.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)

~/.claude/CLAUDE.md # user-global · per-machine preferences <ancestors>/CLAUDE.md # every dir from cwd up to repo root ./CLAUDE.md # project · the canonical one · git-tracked ./CLAUDE.local.md # personal overrides · gitignored <subdir>/CLAUDE.md # nested · on-demand when files in subdir are touched

▸ The four things worth putting in it

  1. Stack. Language, framework, test runner. Saves Claude from guessing.
  2. Build & test. Exact commands. bun test, pnpm run lint, etc.
  3. Conventions. Style, patterns, naming. The stuff a reviewer would correct.
  4. 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)
Next → §4 · Permissions & Safety
§4

Permissions & Safety

foundations

TL;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)

  1. default — prompt on every tool call. Safest, slowest.
  2. acceptEdits — auto-accept file edits, still prompt for Bash. Good for refactors.
  3. plan — read-only mode; Claude proposes a plan, you approve before any write.
  4. 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-permissions on 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-usd so a runaway agent burns money instead of files.
Deep dive → cheatsheet PERMISSIONS card (defaultMode · allow patterns · escape hatches)
Next → §5 · The MCP Universe
§5

The MCP Universe

capabilities

TL;DRMCP (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 gh CLI).

▸ 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

playwrightgithub ───── CLAUDE ───── chrome-devtoolsdbhub nextjs-devtools each server = one external surface · each tool = one verb on that surface
Deep dive → Atlas MCP ecosystem radial
Next → §6 · Skills — bottling prompts
§6

Skills — bottling your prompts

capabilities

TL;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

.claude/skills/<name>/ ├── SKILL.md # frontmatter + body is the prompt ├── templates/ # optional assets └── examples/ # reference material

▸ 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

  1. $ARGUMENTS — whatever the user typed after the slash command. Lets one skill handle many phrasings.
  2. !`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.

Deep dive → cheatsheet SKILLS card (full frontmatter · invocation patterns)
Next → §7 · Agents — delegation
§7

Agents — delegation done right

capabilities

TL;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.

Deep dive → Atlas Skill · Agent · Hook composition diagram
Next → §8 · Hooks — gate every action
§8

Hooks — gate every action

capabilities

TL;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

  1. Session lifecycle — SessionStart · SessionEnd · Setup · Stop · StopFailure
  2. Prompts & instructions — UserPromptSubmit · UserPromptExpansion · InstructionsLoaded
  3. Tool gates — PreToolUse · PostToolUse · PostToolUseFailure · PostToolBatch
  4. Permission — PermissionRequest · PermissionDenied
  5. Sub-agents & tasks — SubagentStart · SubagentStop · TaskCreated · TaskCompleted
  6. Compaction — PreCompact · PostCompact
  7. 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.
Deep dive → Atlas Hook taxonomy radial · 29 events at a glance
Next → §9 · Cost & Model Fit
§9

Cost & Model Fit

power

TL;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

haiku sonnet opus $0.25/$1.25 $3/$15 $15/$75 input/output input/output input/output formatting docs ✓ optimal ~ okay ✗ 60× waste simple refactor ───────────────────────────────────────────────────────────────── coding tasks ~ underspec ✓ optimal ~ 5× overpay test fixes ───────────────────────────────────────────────────────────────── architecture ✗ misses ~ tries hard ✓ optimal hard debugging

▸ 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 matrix
Next → §10 · Workflow Patterns
§10

Workflow Patterns

power

TL;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

  1. Sequential — one Claude, one task, top-to-bottom. The default. Use for anything where step N depends on step N−1.
  2. Operator — you stay in the loop, Claude proposes diffs, you accept/reject. Use for code review and surgical edits.
  3. Split-merge — one parent fans out N delegated agents (one per file, one per module), parent merges the returns. Use for codemod-style refactors.
  4. Agent teams — Plan → Implement → Review chain, each a different sub-agent with its own context. Use for non-trivial features.
  5. Headlessclaude -p in CI/CD with structured output. No human in the loop. Use for PR review bots, test-fix loops, dependency audits.

▸ Picking the shape

need a human checkpoint between steps? ─yes→ operator │ no ▼ work is naturally parallel? ─yes→ split-merge │ no ▼ work decomposes into different reasoning ─yes→ agent teams modes (plan / code / review)? │ no ▼ runs in CI without human? ─yes→ headless │ no ▼ default → sequential

▸ 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 card
Next → §11 · Compaction & Memory
§11

Compaction & Memory

power

TL;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

  1. CLAUDE.md — always in context. The "this is how this project works" layer.
  2. Auto-memory — Claude writes facts about your project into ~/.claude/projects/<slug>/memory/ as it learns. Indexed by MEMORY.md, loaded at session start.
  3. Transcript — the conversation itself. When it grows past the budget, compaction kicks in.

▸ The compaction flow

turn N → PreCompact hook → summarizer runs → PostCompact │ ▼ SessionStart(source:compact) re-injects additionalContext for turn N+1

▸ 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 PreCompact can write before truncation; only SessionStart can 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
Next → §12 · CI/CD & Headless
§12

CI/CD & Headless

power

TL;DRclaude -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

  1. PR review bot — runs on pull_request, posts findings as a review comment.
  2. Test-fix loop — runs on workflow_dispatch, attempts to fix failing tests, opens a PR with the fix.
  3. 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 sonnet at most.
  • Treat the JSON output as a contract — fail the CI step if the JSON is malformed instead of letting it cascade.
Deep dive → cheatsheet I/O & FORMAT card · recipes section