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.
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
- Terminal CLI (
claude): the interactive REPL, or headless withclaude -p. - IDE extensions: VS Code (and forks), JetBrains. They share the CLI's config.
- Desktop app and web (claude.ai/code): cloud sessions in a sandbox.
- CI/CD: GitHub Actions (
anthropics/claude-code-action), GitLab, or any pipeline throughclaude -p. - Claude Agent SDK (Python / TypeScript): the same harness, used as a library to build your own agents.
The same configuration files (CLAUDE.md, .claude/settings.json, .claude/skills, .claude/agents, .mcp.json) apply on every surface.
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.
stop_reason == "tool_use" and ends on end_turn.Every stop_reason value
| stop_reason | Meaning | What your loop should do |
|---|---|---|
end_turn | The model finished its turn naturally. | Stop. Return the final answer. |
tool_use | The 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_tokens | The 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_sequence | The output matched one of your custom stop_sequences. | Read response.stop_sequence and handle it in your application. |
pause_turn | The 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. |
refusal | The model declined for safety reasons. | Don't retry blindly. Surface it, or route to a human. |
model_context_window_exceeded | The 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
- 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_turnsis a safety net, not the control logic. - Stopping when the response contains text. A
tool_useresponse can contain text and tool calls. - Dropping the assistant message before appending
tool_result. Every result must follow the assistant turn that contains itstool_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
| Value | Behaviour | Use 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. |
--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
| Tool | Purpose | Exam-relevant notes |
|---|---|---|
Read | Read files (text, images, PDFs, notebooks) | Read-only, so no permission prompt. Large files are read in ranges. |
Write | Create or overwrite a whole file | An existing file must be Read first. |
Edit | Exact string replacement | old_string must be unique. If the match isn't unique, add surrounding context or fall back to Read + Write. |
Glob | Find files by name pattern (**/*.test.ts) | Use it to find files by path or name. |
Grep | Search file contents (ripgrep) | Use it to find callers, definitions, or error strings. |
Bash | Run shell commands | Gated by permission rules like Bash(npm test:*). Can run in the background. |
WebFetch / WebSearch | Fetch a URL or search the web | Domain rules: WebFetch(domain:docs.example.com). |
Agent (formerly Task) | Spawn a subagent | The subagent gets a fresh, isolated context. Several Agent calls in one turn run in parallel. |
TodoWrite | Maintain a task checklist | Keeps multi-step work on track. |
NotebookEdit | Edit Jupyter cells | |
Skill | Invoke a skill | The model can call it on its own, based on the skill's description. |
mcp__<server>__<tool> | Tools from MCP servers | Named like mcp__github__create_issue. Permission rules can target them. |
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
| Level | Location | Shared via git? | Use for |
|---|---|---|---|
| Enterprise / managed | OS-level managed policy path (set by IT) | Org-wide | Company standards that apply to everyone |
| User | ~/.claude/CLAUDE.md | ❌ personal | Your preferences in every project |
| Project | ./CLAUDE.md or ./.claude/CLAUDE.md | ✅ committed | Team conventions, commands, architecture |
| Project-local | ./CLAUDE.local.md | ❌ gitignored | Your 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
@pathimports pull other files in. They resolve recursively up to 4 hops deep, and aren't evaluated inside code spans or blocks..claude/rules/*.mdholds modular rule files. Addpaths:frontmatter to scope a rule so it loads only when Claude touches matching files:
---
paths:
- "src/api/**/*.ts"
- "**/*.test.ts"
---
- All API handlers must validate input with zod.
- Tests use vitest; never import from jest.
Commands for memory
/init: analyse the repo and generate a starter CLAUDE.md./memory: open and edit the loaded memory files, and see which ones are active.
- "A new teammate doesn't get the instructions" → they were in
~/.claude/CLAUDE.mdorCLAUDE.local.md(personal), not the committed projectCLAUDE.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/withpaths:.
5. Settings, permissions & permission modes
Settings files and precedence (highest wins)
- Managed settings (
managed-settings.json, deployed by IT or MDM). Can't be overridden. - Command-line arguments (
--permission-mode,--allowedTools,--model…), for this session only - Local project
.claude/settings.local.json: personal, gitignored - Shared project
.claude/settings.json: committed for the team - 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
| Rule | Matches |
|---|---|
Bash | Any 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)
| Mode | Behaviour | Typical use |
|---|---|---|
default | Prompts the first time each tool or command is used | Normal interactive work |
acceptEdits | Auto-approves file edits. Still asks for risky bash. | Trusted refactors you're watching |
plan | Read-only: Claude explores and proposes a plan without editing | Complex or unfamiliar changes; review the approach first |
auto | A classifier approves routine actions and blocks risky ones | Long autonomous runs with a safety net (newer; availability varies) |
dontAsk | Denies anything not pre-approved, without prompting | Locked-down, non-interactive runs |
bypassPermissions | Skips all prompts (--dangerously-skip-permissions) | Only in isolated containers or VMs |
.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
| Command | What it does |
|---|---|
/init | Generate a CLAUDE.md for the project |
/memory | View and edit loaded memory files |
/clear | Wipe 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) |
/context | Visualise context-window usage by category |
/cost, /usage | Token and cost usage, plan limits |
/model | Switch model (e.g. Opus for planning, Sonnet for execution) |
/permissions | View and edit allow/ask/deny rules |
/hooks | Manage hook configuration |
/agents | Create and manage subagents |
/mcp | MCP server status, OAuth authentication |
/plugin | Browse and install plugins and marketplaces |
/resume | Pick a previous session to resume |
/rewind | Roll back to a checkpoint (code and/or conversation) |
/review, /security-review | Review code changes, or audit them for vulnerabilities |
/add-dir | Add another working directory |
/config, /status, /doctor | Settings UI, session status, installation health check |
/install-github-app | Set up the GitHub Action and app for @claude in PRs and issues |
/export | Export the conversation |
/help | List all commands, including your custom skills |
Keyboard & input shortcuts
| Input | Effect |
|---|---|
| Shift+Tab | Cycle permission modes (default → acceptEdits → plan …) |
| Esc | Interrupt Claude mid-action (context is kept) |
| Esc Esc | Open rewind: jump back to an earlier message or checkpoint |
@path/to/file | Mention a file or folder to pull it into context |
!command | Bash mode: run a shell command directly, with output added to context |
/ | Slash-command and skill menu |
| Ctrl+C / Ctrl+D | Cancel input / exit |
| \+Enter or Shift+Enter | Newline in the prompt (after /terminal-setup) |
| Ctrl+B | Send 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
.claude/skills/<name>/SKILL.md: project, committed, shared with the team~/.claude/skills/<name>/SKILL.md: personal, available in all projects- Plugins can ship skills too (namespaced
plugin:skill)
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.
| Frontmatter | Effect |
|---|---|
name, description | The description is what the model uses to decide when to auto-invoke. Make it specific. |
allowed-tools | Tools pre-approved while the skill runs (restricts or expands what it can do without prompting) |
argument-hint | Autocomplete hint. The arguments arrive in $ARGUMENTS. |
context: fork | Runs in a separate subagent context, so verbose output doesn't pollute the main conversation |
disable-model-invocation | The model can't trigger it on its own; the user must type /name |
model | Override the model for this skill |
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
- Explore: fast, read-only codebase search
- Plan: researches the codebase to build a plan in plan mode
- general-purpose: multi-step tasks with the full tool set
Key facts
auth/session.ts, line 88", it must write that into the delegation prompt.- Parallelism: several
Agentcalls in a single assistant response run concurrently, e.g. one subagent per independent module. - Context protection: the subagent reads 40 files, and only a summary returns. This is the main reason to use them.
- Hub-and-spoke: a coordinator decomposes the work, delegates, aggregates, and validates. Subagents don't talk to each other; all communication goes through the coordinator.
- No nesting: in Claude Code, subagents can't spawn their own subagents.
- Structured hand-off: ask subagents for structured output (with sources or file:line) so the coordinator can merge results without losing provenance.
- Independent review: a fresh subagent (or separate session) reviews better than the same session reviewing its own work, because it doesn't share the author's assumptions.
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
| Event | Fires | Can block? | Typical use |
|---|---|---|---|
SessionStart | Session start or resume | – | Inject context (git branch, open tickets) |
UserPromptSubmit | Before a prompt is processed | ✅ | Validate prompts, add context, block secrets |
PreToolUse | Before a tool runs (after Claude builds its params) | ✅ | Block dangerous commands, enforce policy, change input |
PermissionRequest | When a permission dialog would show | ✅ | Auto-allow or deny programmatically |
PostToolUse | After a tool succeeds | feedback | Auto-format, lint, run tests, normalise data |
Notification | Claude needs input or is idle | – | Desktop or Slack notification |
Stop | The main agent tries to finish | ✅ | "Tests must pass before stopping" |
SubagentStop | A subagent finishes | ✅ | Validate subagent output |
PreCompact | Before compaction | – | Back up the transcript, preserve key facts |
SessionEnd | Session 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 code | Meaning |
|---|---|
0 | Success. Execution continues. stdout can return JSON for fine-grained control (and for SessionStart/UserPromptSubmit, it's added as context). |
2 | Blocking error. The action is blocked and stderr is fed back to Claude so it can adjust. |
| other | Non-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_active field in its input. Otherwise it can block forever.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
| Scope | Stored in | Visible to |
|---|---|---|
local (default) | ~/.claude.json under the project path | Only you, only this project |
project | .mcp.json at the repo root (committed) | The whole team (each member approves it on first use) |
user | ~/.claude.json | Only 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
- Tools: callable actions, named
mcp__server__tool. - Resources: readable data you can
@-mention (e.g.@github:issue://123). They give the agent a catalogue without many exploratory tool calls. - Prompts: show up as slash commands (
/mcp__server__prompt).
- 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
| Flag | Purpose |
|---|---|
-p, --print | Non-interactive (headless) mode |
--output-format text|json|stream-json | json 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-json | Stream input messages through stdin |
--allowedTools / --disallowedTools | Pre-approve or forbid tools: "Read,Grep,Bash(npm test:*)" |
--permission-mode | default, acceptEdits, plan, bypassPermissions… |
--max-turns N | Cap agent iterations (a safety net) |
--model | Choose the model (alias or full ID) |
--append-system-prompt / --system-prompt | Add to, or replace, the system prompt |
--mcp-config file.json | Load MCP servers for this run |
--agents '{json}' | Define subagents for this session |
-c, --continue | Continue the most recent session in this directory |
-r, --resume [id] | Resume a specific session (or pick from a list) |
--fork-session | With --resume/--continue: branch into a new session ID instead of appending |
--add-dir | Grant access to extra directories |
--verbose | Full turn-by-turn logging |
--dangerously-skip-permissions | Same 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.
- 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
| Technique | When |
|---|---|
/clear | Switching to an unrelated task. Stale context hurts quality. |
/compact [focus] | A long task you want to continue. You decide what the summary keeps. |
| Auto-compaction | Triggers automatically near the limit. Project CLAUDE.md is re-loaded afterwards, but conversation-only details may be lost. |
| Subagents | Offload verbose exploration. Only the summary comes back. |
| Scratchpad / notes files | Persist key findings (decisions, exact IDs, amounts) to a file that survives compaction and new sessions. |
| Trim tool outputs | Have tools or hooks return only the relevant fields, not 40-field records. |
| "Case facts" block | Keep critical facts (customer ID, amounts, dates) in a structured block, not buried in prose, so summaries don't drop exact values. |
Sessions
claude --continue: pick up the latest conversation.claude --resume: choose one.--fork-session: try two approaches from the same starting point without clobbering the original.- When resuming after files have changed, tell Claude what changed. Stale tool results in history can mislead it. Sometimes a new session with a summary is better than resuming.
Checkpoints & rewind
Claude Code checkpoints file edits automatically. EscEsc or /rewind restores code, conversation, or both to an earlier point.
rm, DB migrations, git push) or external changes. Git is still your real safety net.Recommended workflow: Explore → Plan → Implement → Commit
- Explore in plan mode. Read files without editing.
- Plan: have Claude write a plan (extended thinking helps). Review and edit it.
- Implement step by step, verifying with tests. TDD works well: write the tests first, then iterate until they pass.
- 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" …)
query(): one-shot async iterator.ClaudeSDKClient: multi-turn conversation with interrupts.- Custom tools: define in-process with
@tool+create_sdk_mcp_server, then reference them asmcp__name__tool. - Hooks: Python or TS callbacks for
PreToolUse,PostToolUse, etc. Same semantics as the CLI. - Sessions:
resume=session_id,fork_session=True. can_use_toolcallback: custom permission logic at runtime.
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
| Need | Use | Why not the alternative |
|---|---|---|
| Facts and conventions Claude should always know | CLAUDE.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.md | Keeps the root CLAUDE.md lean |
| A repeatable multi-step procedure | Skill / slash command | CLAUDE.md would bloat every turn |
| Verbose or parallel work, isolated context, a specialist role | Subagent (or skill with context: fork) | The main context stays clean |
| Must happen 100% of the time | Hook | Prompts are probabilistic |
| Allow or forbid specific actions or files | Permission rules (managed for the org) | Enforced by the harness, not the model |
| Talk to Jira, GitHub, a DB, an internal API | MCP server | Standard, reusable, permissionable |
| Distribute all of the above to many teams | Plugin (+ marketplace) | One versioned bundle |
| Automation in pipelines | claude -p / GitHub Action / Agent SDK | No 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 distractor | Better answer |
|---|---|
| Detect completion by parsing "Task complete" in text | Loop on stop_reason == "tool_use", stop on end_turn |
| A hard iteration cap is the stop condition | stop_reason drives the loop. max_turns is only a safety net. |
| Subagent "already knows" what the coordinator found | Pass 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 / ~/.claude | Commit .claude/settings.json, CLAUDE.md, .mcp.json |
| Add a classifier or routing layer for wrong tool picks | Fix the tool descriptions first, and reduce tool count per agent |
| Same session reviews its own code | A separate instance or subagent with fresh context |
| JSON schema means the data is correct | A schema guarantees structure. Add semantic validation and a retry with the specific error. |
| Retry until the field appears | If the data isn't in the source, retrying won't help. Make the field nullable or "not found". |
| Batch API for pre-merge checks | Batch is for non-blocking, latency-tolerant work |
| Escalate on negative sentiment or low self-reported confidence | Escalate on explicit request, policy gaps, or inability to make progress |
| Return a generic "error" or empty list on failure | Structured error: category, retryable?, message. Distinguish "no results" from "failed". |
| Summarise everything into prose | Keep exact values (amounts, IDs, dates) in a structured facts block |
Invented flags like --headless, --batch, --ci | The real ones: -p, --output-format, --json-schema, --allowedTools, --max-turns |
| Rewind undoes everything | Checkpoints don't undo bash side effects or remote actions |
16. Self-check quiz
Score: 0 / 0 answered (of 10)
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..env files in a repo, for every developer. Best approach?session.ts:88. The subagent starts searching the whole repo from scratch. Why?.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.-p is headless mode. --output-format json plus --json-schema gives validated structured output. --headless and --batch are invented flags./release. A would bloat every session; B is personal; hooks aren't procedures.