Claude Certification · Topic 6 · Exam domains D1, D2, D5

Claude Code — the complete architect's guide

Claude Code is an agentic coding harness: a model running in a loop, with tools, permissions, memory and extension points around it. The exam tests whether you know which extension point solves a given problem and why.

D1 Agentic architecture 27% D2 Claude Code config & workflows 20% D5 Context & reliability 15% ≈ 60–90 min read

1. What Claude Code is (mental model)

Claude Code wraps a Claude model in a harness. The model decides what to do. The harness carries it out: it runs tools, enforces permissions, loads memory, fires hooks, and manages context.

🧠 Model

Reasons, plans, and emits tool_use blocks. It never touches your machine directly.

🔁 Loop

Calls the model, runs the requested tools, feeds results back, and repeats until stop_reason is end_turn.

🧰 Tools

Read, Edit, Write, Bash, Grep, Glob, WebFetch, Agent… plus any MCP tools.

📜 Context

System prompt, CLAUDE.md memory, skill descriptions, conversation, and tool results — all within one context window.

🛡 Guardrails

Permission rules and modes, hooks, managed settings, sandboxing.

🧩 Extensions

Skills, slash commands, subagents, hooks, MCP servers, plugins.

Where it runs

The same configuration files (CLAUDE.md, .claude/settings.json, .claude/skills, .claude/agents, .mcp.json) apply on every surface.

🎯 Exam lens Most D2 questions read as "a team wants X — what's the best mechanism?" Match the problem to the tool: always-on knowledge → CLAUDE.md, on-demand procedure → skill, isolated context / parallel work → subagent, must-happen-every-time → hook, external system → MCP, allow/deny actions → permissions.

2. The agentic loop & stop_reason

Every agent, Claude Code included, comes down to the same loop on the Messages API. The model replies with content blocks plus a stop_reason field that says why it stopped generating. Your code decides whether to loop by reading stop_reason, not by reading the text.

User task messages[] Call the model messages.create() stop_reason = ? Done return final text Run the tools harness runs tool_use end_turn tool_use append assistant msg + tool_result → loop
The loop continues while stop_reason == "tool_use" and ends on end_turn.

Every stop_reason value

stop_reasonMeaningWhat your loop should do
end_turnThe model finished its turn naturally.Stop. Return the final answer.
tool_useThe model wants one or more tools run.Run every tool_use block. Send all results back in one user message as tool_result blocks with matching tool_use_id. Call the model again.
max_tokensThe output hit your max_tokens cap. The response is truncated.Don't treat it as complete. Raise max_tokens or ask the model to continue. A cut-off tool_use block is invalid.
stop_sequenceThe output matched one of your custom stop_sequences.Read response.stop_sequence and handle it in your application.
pause_turnThe API paused a long-running turn (usually with server tools such as web search).Send the response back unchanged as the assistant turn so the model can continue.
refusalThe model declined for safety reasons.Don't retry blindly. Surface it, or route to a human.
model_context_window_exceededThe conversation hit the model's context window limit.Compact, summarise, or trim the history, then continue.

Minimal correct loop (Python)

import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": task}]

while True:
    resp = client.messages.create(
        model="claude-sonnet-5-5", max_tokens=4096,
        tools=TOOLS, messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})  # keep full history

    if resp.stop_reason == "tool_use":
        results = []
        for block in resp.content:
            if block.type == "tool_use":
                try:
                    out = run_tool(block.name, block.input)
                    results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
                except ToolError as e:                           # structured error, not a crash
                    results.append({"type": "tool_result", "tool_use_id": block.id,
                                    "content": str(e), "is_error": True})
        messages.append({"role": "user", "content": results})       # ALL results in ONE message
        continue

    if resp.stop_reason == "max_tokens":
        raise TruncatedResponse()                                   # or continue with a higher cap
    break                                                          # end_turn / stop_sequence / refusal
⚠️ Classic loop anti-patterns (distractor fodder)
  • Parsing text to decide when to stop (e.g. looking for "DONE" or "I have completed"). Use stop_reason.
  • A fixed iteration cap as the main stop condition. max_turns is a safety net, not the control logic.
  • Stopping when the response contains text. A tool_use response can contain text and tool calls.
  • Dropping the assistant message before appending tool_result. Every result must follow the assistant turn that contains its tool_use.
  • Running only the first tool_use when the model asked for several in parallel.

Claude Code's own loop

Inside Claude Code the loop works in three phases: gather context → take action → verify results, repeated until done. The harness adds behaviour between iterations: permission checks before each tool call, PreToolUse/PostToolUse hooks around it, a Stop hook when the model tries to end, and auto-compaction as the window fills.

Related: tool_choice

ValueBehaviourUse when
{"type":"auto"}The model decides whether to call a tool (default with tools).Normal agent loops.
{"type":"any"}The model must call some tool, and picks which.You need structured output, but the right schema varies by input.
{"type":"tool","name":"x"}Forces that specific tool.Guaranteed structured extraction with one schema, or a mandatory first step.
{"type":"none"}No tool calls allowed.A final text-only answer.
💡 RememberA JSON schema (through tool input or --json-schema) guarantees shape, not correctness. You still need semantic validation, such as "do line items add up to the total?", with a retry that tells the model the specific error.

3. Built-in tools

ToolPurposeExam-relevant notes
ReadRead files (text, images, PDFs, notebooks)Read-only, so no permission prompt. Large files are read in ranges.
WriteCreate or overwrite a whole fileAn existing file must be Read first.
EditExact string replacementold_string must be unique. If the match isn't unique, add surrounding context or fall back to Read + Write.
GlobFind files by name pattern (**/*.test.ts)Use it to find files by path or name.
GrepSearch file contents (ripgrep)Use it to find callers, definitions, or error strings.
BashRun shell commandsGated by permission rules like Bash(npm test:*). Can run in the background.
WebFetch / WebSearchFetch a URL or search the webDomain rules: WebFetch(domain:docs.example.com).
Agent (formerly Task)Spawn a subagentThe subagent gets a fresh, isolated context. Several Agent calls in one turn run in parallel.
TodoWriteMaintain a task checklistKeeps multi-step work on track.
NotebookEditEdit Jupyter cells
SkillInvoke a skillThe model can call it on its own, based on the skill's description.
mcp__<server>__<tool>Tools from MCP serversNamed like mcp__github__create_issue. Permission rules can target them.
🎯 Exam lens"Find every place that calls processRefund" → Grep. "Find all test files" → Glob. Build understanding incrementally (Grep for entry points, then Read the specific files) rather than reading the whole codebase up front.

4. CLAUDE.md — project memory

CLAUDE.md files are instructions loaded into context automatically at session start. Use them for things Claude should always know: build and test commands, conventions, architecture notes, and things it must never do.

The hierarchy

LevelLocationShared via git?Use for
Enterprise / managedOS-level managed policy path (set by IT)Org-wideCompany standards that apply to everyone
User~/.claude/CLAUDE.md❌ personalYour preferences in every project
Project./CLAUDE.md or ./.claude/CLAUDE.md✅ committedTeam conventions, commands, architecture
Project-local./CLAUDE.local.md❌ gitignoredYour personal notes for this repo
Subdirectory./packages/api/CLAUDE.md✅Loaded on demand when Claude works with files in that directory

Files above the working directory (walking up to root) load at startup. Files in subdirectories load lazily when Claude reads files there. More specific instructions take precedence when they conflict.

Imports and modular rules

# CLAUDE.md
See @README.md for an overview and @package.json for npm scripts.

## Conventions
- Use pnpm, never npm.
- Run `pnpm test --filter <pkg>` before committing.
- @docs/api-conventions.md
- @~/.claude/my-personal-prefs.md      # imports can point to home dir
---
paths:
  - "src/api/**/*.ts"
  - "**/*.test.ts"
---
- All API handlers must validate input with zod.
- Tests use vitest; never import from jest.

Commands for memory

⚠️ Traps
  • "A new teammate doesn't get the instructions" → they were in ~/.claude/CLAUDE.md or CLAUDE.local.md (personal), not the committed project CLAUDE.md.
  • CLAUDE.md is advisory: it's text in the prompt. If something must happen every time (formatting, blocking a command), use a hook or a permission rule.
  • Keep it concise. A bloated CLAUDE.md wastes context on every turn. Move rarely-needed procedures into skills and directory-specific rules into .claude/rules/ with paths:.

5. Settings, permissions & permission modes

Settings files and precedence (highest wins)

  1. Managed settings (managed-settings.json, deployed by IT or MDM). Can't be overridden.
  2. Command-line arguments (--permission-mode, --allowedTools, --model…), for this session only
  3. Local project .claude/settings.local.json: personal, gitignored
  4. Shared project .claude/settings.json: committed for the team
  5. User ~/.claude/settings.json: your defaults in every project

Permission arrays (allow/deny) are merged across levels. A deny anywhere wins.

A realistic .claude/settings.json

{
  "permissions": {
    "allow": [
      "Bash(npm run test:*)",
      "Bash(npm run lint)",
      "Read(./src/**)",
      "mcp__github__get_issue"
    ],
    "ask":   ["Bash(git push:*)"],
    "deny":  [
      "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)",
      "Bash(curl:*)", "Bash(rm -rf:*)"
    ],
    "defaultMode": "default",
    "additionalDirectories": ["../shared-lib"]
  },
  "env": { "NODE_ENV": "development" },
  "hooks": { "...": "see Hooks section" },
  "enabledPlugins": {}
}

Permission rule syntax

RuleMatches
BashAny bash command
Bash(npm run test:*)Commands starting with npm run test (prefix match)
Read(./.env) / Edit(src/**)File paths (gitignore-style globs)
WebFetch(domain:example.com)Fetches to that domain
mcp__github / mcp__github__*All tools from the github MCP server
Agent(Explore)A specific subagent type

Evaluation order: deny → ask → allow. The first matching category decides. Anything unmatched falls back to the current permission mode.

Permission modes (cycle with Shift+Tab)

ModeBehaviourTypical use
defaultPrompts the first time each tool or command is usedNormal interactive work
acceptEditsAuto-approves file edits. Still asks for risky bash.Trusted refactors you're watching
planRead-only: Claude explores and proposes a plan without editingComplex or unfamiliar changes; review the approach first
autoA classifier approves routine actions and blocks risky onesLong autonomous runs with a safety net (newer; availability varies)
dontAskDenies anything not pre-approved, without promptingLocked-down, non-interactive runs
bypassPermissionsSkips all prompts (--dangerously-skip-permissions)Only in isolated containers or VMs
🎯 Exam lens"Never let Claude read .env in this repo, for everyone" → deny rule in the committed .claude/settings.json (or managed settings for the whole org). Not a line in CLAUDE.md, and not settings.local.json (personal).

6. Built-in slash commands & keyboard shortcuts

CommandWhat it does
/initGenerate a CLAUDE.md for the project
/memoryView and edit loaded memory files
/clearWipe the conversation and start fresh (use between unrelated tasks)
/compact [focus]Summarise history to free context, optionally with what to keep (/compact keep the API decisions)
/contextVisualise context-window usage by category
/cost, /usageToken and cost usage, plan limits
/modelSwitch model (e.g. Opus for planning, Sonnet for execution)
/permissionsView and edit allow/ask/deny rules
/hooksManage hook configuration
/agentsCreate and manage subagents
/mcpMCP server status, OAuth authentication
/pluginBrowse and install plugins and marketplaces
/resumePick a previous session to resume
/rewindRoll back to a checkpoint (code and/or conversation)
/review, /security-reviewReview code changes, or audit them for vulnerabilities
/add-dirAdd another working directory
/config, /status, /doctorSettings UI, session status, installation health check
/install-github-appSet up the GitHub Action and app for @claude in PRs and issues
/exportExport the conversation
/helpList all commands, including your custom skills

Keyboard & input shortcuts

InputEffect
Shift+TabCycle permission modes (default → acceptEdits → plan …)
EscInterrupt Claude mid-action (context is kept)
Esc EscOpen rewind: jump back to an earlier message or checkpoint
@path/to/fileMention a file or folder to pull it into context
!commandBash mode: run a shell command directly, with output added to context
/Slash-command and skill menu
Ctrl+C / Ctrl+DCancel input / exit
\+Enter or Shift+EnterNewline in the prompt (after /terminal-setup)
Ctrl+BSend a running command or agent to the background

7. Skills & custom slash commands

A skill is a folder with a SKILL.md: reusable instructions (and optional scripts or reference files) that load only when needed. Custom slash commands (.claude/commands/*.md) have been merged into skills. Both create a /name command, and old command files still work.

Locations

Anatomy

.claude/skills/review-pr/
├── SKILL.md            # required
├── checklist.md        # loaded only if SKILL.md references it
└── scripts/diff.sh     # can be executed by the skill

# SKILL.md
---
name: review-pr
description: Review a pull request for correctness and security. Use when the user asks to review a PR.
argument-hint: [pr-number]
allowed-tools: Read, Grep, Glob, Bash(gh pr diff:*)
context: fork               # run in an isolated subagent context
disable-model-invocation: true   # only the user can trigger it via /review-pr
---
Review PR #$ARGUMENTS.
1. Run `gh pr diff $ARGUMENTS`.
2. Check against @checklist.md.
3. Report findings as: file:line — severity — issue — fix.
FrontmatterEffect
name, descriptionThe description is what the model uses to decide when to auto-invoke. Make it specific.
allowed-toolsTools pre-approved while the skill runs (restricts or expands what it can do without prompting)
argument-hintAutocomplete hint. The arguments arrive in $ARGUMENTS.
context: forkRuns in a separate subagent context, so verbose output doesn't pollute the main conversation
disable-model-invocationThe model can't trigger it on its own; the user must type /name
modelOverride the model for this skill
💡 Progressive disclosureAt startup only each skill's name and description sit in context. The body loads when the skill is invoked, and referenced files load only if needed. That's why skills scale better than piling everything into CLAUDE.md.

8. Subagents & orchestration

A subagent is a separate Claude instance with its own context window, its own system prompt, and a restricted tool set. The main agent delegates through the Agent tool and gets back only the final result.

Defining one

# .claude/agents/security-reviewer.md   (project)  or  ~/.claude/agents/ (personal)
---
name: security-reviewer
description: Reviews diffs for injection, authz and secrets issues. Use proactively after changes to auth or payment code.
tools: Read, Grep, Glob          # least privilege — read-only
model: sonnet                    # sonnet | opus | haiku | inherit
---
You are a senior application-security reviewer.
Return findings as JSON: [{file, line, severity, issue, fix}].
Report only issues you can point to in code.

Other ways to define them: /agents (interactive), claude --agents '{...json...}' (session-only), or the agents option in the Agent SDK.

Built-in subagents

Key facts

⚠️ #1 trap: subagents do NOT inherit the parent's context A subagent sees only its own system prompt and the prompt string the parent passes. It doesn't see the conversation history. If the coordinator found that "the bug is in auth/session.ts, line 88", it must write that into the delegation prompt.
🎯 Exam lens"A coordinator's final report misses whole areas" → the root cause is usually task decomposition (the coordinator's scope was too narrow), not the subagents. Fix the coordinator's decomposition instead of adding another layer.

9. Hooks — deterministic control

Hooks are shell commands (or LLM prompts) that the harness runs at fixed lifecycle events. Unlike CLAUDE.md instructions, they always run. Use them for anything that must happen every single time.

Events

EventFiresCan block?Typical use
SessionStartSession start or resume–Inject context (git branch, open tickets)
UserPromptSubmitBefore a prompt is processed✅Validate prompts, add context, block secrets
PreToolUseBefore a tool runs (after Claude builds its params)✅Block dangerous commands, enforce policy, change input
PermissionRequestWhen a permission dialog would show✅Auto-allow or deny programmatically
PostToolUseAfter a tool succeedsfeedbackAuto-format, lint, run tests, normalise data
NotificationClaude needs input or is idle–Desktop or Slack notification
StopThe main agent tries to finish✅"Tests must pass before stopping"
SubagentStopA subagent finishes✅Validate subagent output
PreCompactBefore compaction–Back up the transcript, preserve key facts
SessionEndSession ends–Cleanup, logging

Configuration (in any settings.json)

{
  "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)\"" }] }
    ]
  }
}

matcher is a regex on the tool name (Edit|Write, mcp__github__.*). The hook receives JSON on stdin: session_id, transcript_path, cwd, hook_event_name, tool_name, tool_input (plus tool_response for PostToolUse).

Exit codes — memorise these

Exit codeMeaning
0Success. Execution continues. stdout can return JSON for fine-grained control (and for SessionStart/UserPromptSubmit, it's added as context).
2Blocking error. The action is blocked and stderr is fed back to Claude so it can adjust.
otherNon-blocking error. stderr is shown to the user and execution continues.
#!/usr/bin/env bash  — .claude/hooks/block-dangerous.sh
cmd=$(jq -r '.tool_input.command')
if echo "$cmd" | grep -qE 'rm -rf /|git push --force|DROP TABLE'; then
  echo "Blocked by policy: $cmd. Use a safer alternative." >&2
  exit 2          # block + tell Claude why
fi
exit 0

Advanced JSON output, e.g. PreToolUse: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"…"}} with allow / deny / ask.

Stop-hook loop guardWhen a Stop hook blocks (forcing Claude to keep working), check the stop_hook_active field in its input. Otherwise it can block forever.
🎯 Exam lens: prompt vs hook"Claude sometimes forgets to run the formatter" or "refunds over $500 must never be auto-approved" → a hook (deterministic), not a stronger CLAUDE.md instruction (probabilistic). For business rules with financial or compliance impact, the answer is programmatic enforcement.

10. MCP — connecting external systems

The Model Context Protocol lets Claude Code use tools, resources, and prompts from external servers (GitHub, Jira, databases, Sentry, internal APIs) without custom glue code.

Scopes

ScopeStored inVisible to
local (default)~/.claude.json under the project pathOnly you, only this project
project.mcp.json at the repo root (committed)The whole team (each member approves it on first use)
user~/.claude.jsonOnly you, in every project

Adding servers

# Remote HTTP server (recommended transport for remote)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# Local stdio server, shared with the team
claude mcp add --transport stdio --scope project db -- npx -y @bytebase/dbhub --dsn "$DB_URL"

claude mcp list | get <name> | remove <name>
claude mcp add-json <name> '{...}'
# inside a session: /mcp  → status + OAuth login

.mcp.json with environment-variable expansion

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": { "Authorization": "Bearer ${GITHUB_TOKEN}" }
    },
    "jira": {
      "command": "npx",
      "args": ["-y", "@acme/jira-mcp"],
      "env": { "JIRA_URL": "${JIRA_URL:-https://acme.atlassian.net}", "JIRA_TOKEN": "${JIRA_TOKEN}" }
    }
  }
}

${VAR} and ${VAR:-default} keep secrets out of git while the config itself is shared.

MCP primitives

🎯 Exam lens
  • Claude picks the wrong tool → improve the tool descriptions (purpose, inputs, when to use it vs. similar tools). Don't add a routing classifier.
  • Too many tools (e.g. 18) degrade selection → give each agent only the tools its role needs.
  • Tool errors should be structured (isError, error category, whether it's retryable, a human-readable message). Never return an empty success for a failure. An empty result for a valid query is not an error.
  • Team-wide server → .mcp.json (project scope). Personal experiment → local or user scope.

11. Headless mode, CLI flags & CI/CD

claude -p "<prompt>" (print mode) runs the full agent loop non-interactively and exits. It's the basis for scripts, cron jobs, and CI pipelines.

CLI flags you must know

FlagPurpose
-p, --printNon-interactive (headless) mode
--output-format text|json|stream-jsonjson gives one result object (result, session_id, total_cost_usd, num_turns, is_error…). stream-json gives newline-delimited events.
--json-schema '<schema>'Validated structured output matching a JSON Schema (with --output-format json)
--input-format stream-jsonStream input messages through stdin
--allowedTools / --disallowedToolsPre-approve or forbid tools: "Read,Grep,Bash(npm test:*)"
--permission-modedefault, acceptEdits, plan, bypassPermissions…
--max-turns NCap agent iterations (a safety net)
--modelChoose the model (alias or full ID)
--append-system-prompt / --system-promptAdd to, or replace, the system prompt
--mcp-config file.jsonLoad MCP servers for this run
--agents '{json}'Define subagents for this session
-c, --continueContinue the most recent session in this directory
-r, --resume [id]Resume a specific session (or pick from a list)
--fork-sessionWith --resume/--continue: branch into a new session ID instead of appending
--add-dirGrant access to extra directories
--verboseFull turn-by-turn logging
--dangerously-skip-permissionsSame as bypassPermissions. Only use it in sandboxes.

Examples

# Pipe input, get JSON back
git diff main | claude -p "Review this diff for bugs" --output-format json | jq -r .result

# Guaranteed structured output
claude -p "Extract all TODOs in src/ with file and line" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"todos":{"type":"array","items":{"type":"object","properties":{"file":{"type":"string"},"line":{"type":"integer"},"text":{"type":"string"}},"required":["file","line","text"]}}},"required":["todos"]}'

# Locked-down CI run
claude -p "Fix the failing lint errors" \
  --allowedTools "Read,Edit,Bash(npm run lint:*)" --max-turns 10

GitHub Actions

# .github/workflows/claude-review.yml
on: { pull_request: { types: [opened, synchronize] } }
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review this PR against CLAUDE.md standards. Comment only on real issues."
          claude_args: "--max-turns 8 --allowedTools Read,Grep,Glob"

Run /install-github-app once to set it up. After that, team members can @claude in issues and PRs.

🎯 Exam lens: CI design
  • Put review standards in the project CLAUDE.md so CI and humans share them.
  • Use a separate session or instance to review code that Claude generated. Self-review in the same context is weaker.
  • Use --output-format json (plus --json-schema) so a script can post inline comments.
  • On re-runs, pass in previous findings to avoid duplicate comments.
  • Message Batches API (≈50% cheaper, up to 24 h, matched by custom_id) suits non-blocking overnight jobs, not pre-merge checks that developers wait on.

12. Sessions, context management & checkpoints

What fills the context window

System prompt + tool definitions (including MCP tools) + CLAUDE.md files + skill descriptions + the conversation + every tool result. Big tool outputs are the usual culprit. Check with /context.

Strategies

TechniqueWhen
/clearSwitching to an unrelated task. Stale context hurts quality.
/compact [focus]A long task you want to continue. You decide what the summary keeps.
Auto-compactionTriggers automatically near the limit. Project CLAUDE.md is re-loaded afterwards, but conversation-only details may be lost.
SubagentsOffload verbose exploration. Only the summary comes back.
Scratchpad / notes filesPersist key findings (decisions, exact IDs, amounts) to a file that survives compaction and new sessions.
Trim tool outputsHave tools or hooks return only the relevant fields, not 40-field records.
"Case facts" blockKeep critical facts (customer ID, amounts, dates) in a structured block, not buried in prose, so summaries don't drop exact values.
💡 Lost in the middleModels attend most reliably to the start and end of long inputs. Put key findings and instructions at the beginning or end, and use clear section headers.

Sessions

Checkpoints & rewind

Claude Code checkpoints file edits automatically. EscEsc or /rewind restores code, conversation, or both to an earlier point.

LimitationCheckpoints track Claude's file-edit tools only. They don't undo bash side effects (rm, DB migrations, git push) or external changes. Git is still your real safety net.

Recommended workflow: Explore → Plan → Implement → Commit

  1. Explore in plan mode. Read files without editing.
  2. Plan: have Claude write a plan (extended thinking helps). Review and edit it.
  3. Implement step by step, verifying with tests. TDD works well: write the tests first, then iterate until they pass.
  4. Commit and open a PR.

Plan mode is worth it for multi-file, architectural, or ambiguous changes. For a clear one-line fix, go straight to editing.

13. Claude Agent SDK

The Agent SDK exposes Claude Code's harness (loop, tools, permissions, hooks, subagents, MCP, compaction) as a library, so you can build your own agents: support bots, research agents, data pipelines.

from claude_agent_sdk import query, ClaudeAgentOptions

options = ClaudeAgentOptions(
    system_prompt="You are a careful refactoring agent.",
    allowed_tools=["Read", "Grep", "Glob", "Edit", "Bash"],
    permission_mode="acceptEdits",
    max_turns=15,
    cwd="/repo",
    setting_sources=["project"],      # load CLAUDE.md / .claude settings from the repo
    mcp_servers={"jira": {...}},
    agents={"tester": AgentDefinition(description="Runs and fixes tests", tools=["Bash","Read","Edit"], prompt="...")},
)

async for msg in query(prompt="Rename UserSvc to UserService everywhere", options=options):
    print(msg)          # AssistantMessage, ToolUse…, finally ResultMessage(subtype="success" | "error_max_turns" …)

14. Plugins & choosing the right mechanism

A plugin bundles skills, commands, subagents, hooks, and MCP servers into one installable unit (.claude-plugin/plugin.json). Install with /plugin marketplace add owner/repo and then /plugin install name@marketplace, or pin them for a team through enabledPlugins in settings.

Decision table

NeedUseWhy not the alternative
Facts and conventions Claude should always knowCLAUDE.md (or .claude/rules)A skill loads only when invoked
Rules for one directory or file type.claude/rules/ with paths: or a subdirectory CLAUDE.mdKeeps the root CLAUDE.md lean
A repeatable multi-step procedureSkill / slash commandCLAUDE.md would bloat every turn
Verbose or parallel work, isolated context, a specialist roleSubagent (or skill with context: fork)The main context stays clean
Must happen 100% of the timeHookPrompts are probabilistic
Allow or forbid specific actions or filesPermission rules (managed for the org)Enforced by the harness, not the model
Talk to Jira, GitHub, a DB, an internal APIMCP serverStandard, reusable, permissionable
Distribute all of the above to many teamsPlugin (+ marketplace)One versioned bundle
Automation in pipelinesclaude -p / GitHub Action / Agent SDKNo interactive prompts

Also good to know: output styles (change Claude's response style or persona), a custom status line (/statusline), sandboxed bash (filesystem and network isolation), and extended thinking for hard planning.

15. Exam traps cheat sheet

Tempting distractorBetter answer
Detect completion by parsing "Task complete" in textLoop on stop_reason == "tool_use", stop on end_turn
A hard iteration cap is the stop conditionstop_reason drives the loop. max_turns is only a safety net.
Subagent "already knows" what the coordinator foundPass all needed context explicitly in the delegation prompt
Make the CLAUDE.md instruction stronger ("ALWAYS!!")A hook or permission rule for anything mandatory
Put team config in settings.local.json / ~/.claudeCommit .claude/settings.json, CLAUDE.md, .mcp.json
Add a classifier or routing layer for wrong tool picksFix the tool descriptions first, and reduce tool count per agent
Same session reviews its own codeA separate instance or subagent with fresh context
JSON schema means the data is correctA schema guarantees structure. Add semantic validation and a retry with the specific error.
Retry until the field appearsIf the data isn't in the source, retrying won't help. Make the field nullable or "not found".
Batch API for pre-merge checksBatch is for non-blocking, latency-tolerant work
Escalate on negative sentiment or low self-reported confidenceEscalate on explicit request, policy gaps, or inability to make progress
Return a generic "error" or empty list on failureStructured error: category, retryable?, message. Distinguish "no results" from "failed".
Summarise everything into proseKeep exact values (amounts, IDs, dates) in a structured facts block
Invented flags like --headless, --batch, --ciThe real ones: -p, --output-format, --json-schema, --allowedTools, --max-turns
Rewind undoes everythingCheckpoints don't undo bash side effects or remote actions

16. Self-check quiz

Score: 0 / 0 answered (of 10)

1 · [D1] Your custom agent loop sometimes stops after the model says "Let me check the database" without calling a tool, and sometimes keeps looping after the answer is complete. What's the fix?
C. stop_reason is the structured signal. Text parsing (A, D) is brittle: tool_use responses often contain text too. A fixed cap (B) either cuts work short or wastes calls.
2 · [D2] Your team wants Claude Code to never read .env files in a repo, for every developer. Best approach?
A. Permission rules are enforced by the harness, and the shared settings file reaches every teammate. B is advisory only. C is personal and gitignored. D affects git, not Claude's file access.
3 · [D1] A coordinator delegates "fix the bug" to a subagent after spending 20 turns finding that the bug is in session.ts:88. The subagent starts searching the whole repo from scratch. Why?
D. Subagents start with fresh, isolated context. The coordinator has to pass the file, line, and reasoning explicitly.
4 · [D2] Developers complain that Claude Code sometimes forgets to run Prettier after editing files. What's the most reliable fix?
B. Hooks are deterministic and run every time. Prompt instructions (A) are probabilistic, and C still depends on someone remembering.
5 · [D2] A hook script must block a Bash command and tell Claude why, so it can try another approach. How should it exit?
C. Exit code 2 is the blocking error, and stderr is fed back to Claude. Other non-zero codes are non-blocking and stderr goes only to the user.
6 · [D2] The team wants a shared Jira MCP server that every developer gets automatically, without committing the API token. What should they do?
A. Project scope (.mcp.json) shares the config, and ${VAR} expansion keeps secrets in each developer's environment. B's default scope is local, so each developer would have to set it up manually.
7 · [D2] A CI job needs Claude to output review findings in a strict JSON shape that a script turns into inline PR comments. Which invocation fits?
B. -p is headless mode. --output-format json plus --json-schema gives validated structured output. --headless and --batch are invented flags.
8 · [D5] After two hours on one task, Claude starts forgetting the exact refund amount agreed earlier. Which change helps most?
D. Progressive summarisation loses exact values. Persisting them in a structured block or file, plus a focused compaction, preserves them. B throws away context; A only delays the problem.
9 · [D2] You have a 12-step release checklist that's only needed a few times a month. Where should it live?
C. Skills load on demand (progressive disclosure), are shared through git, and can be invoked as /release. A would bloat every session; B is personal; hooks aren't procedures.
10 · [D1] Claude finishes generating code and you want a high-quality review before merge. What's the best setup?
B. An independent reviewer doesn't share the author's assumptions. A is self-review bias; D is wrong for blocking pre-merge checks.
📚 Source of truthVerify details against the official docs at code.claude.com/docs and docs.claude.com. Claude Code ships fast, and flags and features change.