Cheat sheet
Quick-reference entries for last-minute cramming, filterable by blueprint domain. The cross-domain judgment rules are on the Overview.
stop_reason control flow
Continue while stop_reason == "tool_use": execute every tool_use block, append all tool_result blocks in one user message, iterate. "end_turn" terminates. "max_tokens" is truncation, not completion. A failed tool returns tool_result with is_error: true — never a dropped block. Parse input as JSON, never by string matching.
Never terminate on: natural-language signals · iteration caps as the primary mechanism · the presence of assistant text.
- TypeScript
- Python
while (true) {
const response = await client.messages.create({ ...req, messages });
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break; // end_turn -> done
messages.push({ role: "user", content: await runTools(response.content) });
}
while True:
response = client.messages.create(**req, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break # end_turn -> done
messages.append({"role": "user", "content": run_tools(response.content)})
Hub-and-spoke coordinator
The coordinator owns decomposition, delegation, aggregation, error handling and routing. Subagents have isolated context — they inherit nothing and share no memory, so context must be passed explicitly in each subagent prompt, with content separated from metadata (URL, doc name, page, date). Coordinator prompts state goals and quality criteria, not procedure. A coverage gap while every subagent reports success means the fault is in coordinator decomposition. Iterative refinement: synthesize → evaluate gaps → re-delegate targeted → re-synthesize.
Task tool and parallelism
The coordinator must have "Task" in allowedTools / allowed_tools or delegation is impossible. Parallel execution is multiple Task calls in a single response. Define subagents with a description (when to use), a prompt (role) and a scoped tool list.
- TypeScript
- Python
options: {
allowedTools: ["Task", "Read", "Grep"],
agents: {
"web-search": { description: "…", prompt: "…", tools: ["WebSearch", "WebFetch"] },
},
}
options = ClaudeAgentOptions(
allowed_tools=["Task", "Read", "Grep"],
agents={
"web-search": AgentDefinition(
description="…", prompt="…", tools=["WebSearch", "WebFetch"]
),
},
)
PostToolUse and interception
PostToolUse transforms results before the model sees them — normalize Unix seconds / millis / ISO 8601 into one format, collapse numeric status codes to an enum, trim fields. Tool-call interception blocks and redirects: a refund above $500 is denied with a reason that names escalate_to_human as the next call. Hooks are the deterministic layer; prompts are the probabilistic one.
Human handoff payload
The human has no transcript access. A handoff carries customer ID, root cause, amount, recommended action, and what was already attempted. A multi-concern customer message is decomposed, investigated in parallel against shared context, and answered in one unified reply.
{
"customer_id": "cus_8842",
"root_cause": "Carrier damage confirmed by photo; item out of stock for replacement.",
"refund_amount": 649.0,
"policy_reference": "returns.damaged.v3 — silent on out-of-stock replacements",
"recommended_action": "Approve full refund plus expedited shipping credit.",
"attempted": ["get_customer", "lookup_order", "process_refund (blocked: >$500)"]
}
Prompt chaining vs dynamic
Prompt chaining for predictable multi-aspect work (per-file pass, then a cross-file pass). Dynamic decomposition for open-ended work: map the structure, find the high-impact areas, then build an adaptive prioritised plan.
Resume, fork, compact
--resume <name> when prior context is mostly valid — and tell it which files changed. Start a new session with a structured summary when tool results are stale. fork_session / forkSession branches divergent work from one baseline. /compact shrinks a long session in place.
Domain 1 one-liners
stop_reason, never text parsing.- All
tool_resultblocks in one user message. "Task"in allowed tools or no delegation.- Subagents inherit nothing.
- Parallel = many
Taskcalls, one response. - Coverage gap → coordinator decomposition.
- Compliance → hook. Judgment → prompt.
Descriptions are the selection mechanism
A description that differentiates carries: purpose · input formats · example queries · edge cases · boundaries versus similar tools · outputs. When selection is unreliable, expand descriptions first — not few-shot examples, not a routing layer. Then audit the system prompt for keyword-sensitive wording ("always analyze the content") that overrides good descriptions.
Fixing functional overlap
Two fixes for near-identical tools: rename and re-describe (analyze_content → extract_web_results), or split a generic tool into purpose-specific ones (analyze_document → extract_data_points, summarize_content, verify_claim_against_source).
Structured error responses
Every error carries an isError flag, an errorCategory (transient / validation / permission / business), isRetryable, and a human-readable message; business errors add retriable: false and customer-facing text. An access failure is not a valid empty result, and a generic "Operation failed" blocks recovery. Subagents recover locally from transient failures and propagate only the unresolvable, with partial results and what was attempted.
{
"isError": true,
"errorCategory": "business",
"isRetryable": false,
"retriable": false,
"message": "Refunds above $500 require human approval.",
"customerFacing": "I can't approve this amount myself — I'll bring in a colleague."
}
Tool count and role scoping
18 tools degrades selection badly versus 4–5. Scope tools per role, then add limited cross-role tools for high-frequency needs (verify_fact on the synthesis agent for the 85% case, coordinator for the 15%). Replace generic tools with constrained ones (fetch_url → load_document).
tool_choice semantics
"auto" may return text · "any" must call some tool · {type: "tool", name: "…"} forces that tool for one turn.
- TypeScript
- Python
tool_choice: { type: "any" } // some tool, model picks
tool_choice: { type: "tool", name: "extract_invoice" } // that tool, this turn
tool_choice={"type": "any"} # some tool, model picks
tool_choice={"type": "tool", "name": "extract_invoice"} # that tool, this turn
MCP scoping and secrets
.mcp.json is project scope, version-controlled and shared; ~/.claude.json is user scope for personal or experimental servers. Both are active at once and all tools are discovered at connection time. ${GITHUB_TOKEN} expansion keeps secrets out of git. Resources are content catalogs (issue summaries, doc hierarchies, DB schemas) that cut exploratory calls; tools are actions. Thin MCP descriptions push the agent back to built-in Grep. Adopt community servers for standard integrations; build custom only for team-specific workflows.
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
}
}
}
Built-in tool selection
Grep = contents · Glob = paths (**/*.test.tsx) · Read/Write = whole file · Edit = unique-anchor edit · Bash = shell. Edit fails on non-unique text, so fall back to Read + Write. Explore incrementally: Grep entry points, then Read to follow imports. To trace through wrappers, list every exported name and Grep each.
Domain 2 one-liners
- Descriptions are the selection mechanism.
errorCategory+isRetryable, or the agent guesses.- Access failure ≠ empty result.
- Fewer tools per agent, scoped by role.
"any"guarantees a call; forced guarantees the tool..mcp.jsonproject ·~/.claude.jsonuser.- Resources are catalogs; tools are actions.
Configuration paths and scope
| Path | Scope |
|---|---|
~/.claude/CLAUDE.md | user — not shared |
CLAUDE.md / .claude/CLAUDE.md | project — shared |
subdirectory CLAUDE.md | directory-bound |
.claude/rules/*.md + paths: globs | conditional, path-matched, automatic |
.claude/commands/ | project slash commands (shared) |
~/.claude/commands/ | personal slash commands |
.claude/skills/<name>/SKILL.md | on-demand skills |
~/.claude/skills/ | personal skill variants — use a different name |
Memory mechanics
@import keeps CLAUDE.md modular · /memory verifies which memory files are loaded · there is no .claude/config.json commands array. Globs beat a subdirectory CLAUDE.md when the files are spread across directories (tests beside source).
Skill frontmatter and scope
context: fork runs the skill in an isolated subagent (verbose or exploratory output) · allowed-tools pre-approves tools for the invoking turn (no permission prompt) and restricts nothing · disallowed-tools removes tools from the pool and is what prevents destructive actions · argument-hint prompts for missing arguments. Skills are on-demand task workflows; CLAUDE.md is always-loaded universal standards.
Plan mode vs direct execution
Plan mode: large-scale changes, multiple valid approaches, architectural decisions, multi-file work (monolith → microservices, a 45-file migration). Direct: a single-file fix with a clear stack trace, one validation conditional. Combine them — plan to investigate, direct to implement. The Explore subagent isolates verbose discovery and returns a summary.
Iterative refinement patterns
Two or three concrete input/output examples beat prose. Write tests first, then share the failures. Use the interview pattern to surface unanticipated considerations. Interacting problems go in one detailed message; independent problems go sequentially.
Headless mode in CI
claude -p "…" (or --print) — not CLAUDE_HEADLESS, not --batch, not stdin redirection. --output-format json plus --json-schema gives parseable findings for inline PR comments. Put testing standards, fixtures and review criteria in CLAUDE.md. On re-runs, pass prior findings and report only new or unaddressed ones. For test generation, supply the existing test files. An independent instance beats self-review — the generator retains its own reasoning context.
claude -p "Review the staged diff against CLAUDE.md" \
--output-format json --json-schema ./review.schema.json
Domain 3 one-liners
~/.claude/CLAUDE.mdis never shared.- Globs beat directory
CLAUDE.mdfor spread-out files. -pfor CI.--batchdoes not exist.- Independent reviewer instance beats self-review.
Explicit categorical criteria
"Flag only when the claimed behaviour contradicts the actual behaviour" beats "be conservative" or "high-confidence only" — vague hedges do not improve precision. One high-false-positive category poisons trust in the accurate ones, so temporarily disable it while the prompt is fixed. Severity levels need concrete code examples per level.
When few-shot is the answer
Most effective for a consistent format when instructions alone fail, and for 2–4 targeted examples on ambiguous cases. Show why one action beat a plausible alternative. Examples enable generalization, not just matching, and reduce extraction hallucination across varied structures (inline citations vs bibliographies, empty or null required fields).
Schemas kill syntax errors, not semantic ones
tool_use with a JSON schema guarantees schema-compliant output and eliminates syntax errors — not semantic errors (line items that do not sum, values in the wrong field). Nullable or optional fields make the model return null instead of fabricating. enum with "unclear" handles ambiguity; "other" plus a detail string keeps it extensible. Format normalization rules belong in the prompt — the schema constrains shape only.
- TypeScript
- Python
po_number: { type: ["string", "null"] }, // null, never invented
document_type: { type: "string", enum: ["invoice", "credit_note", "unclear"] },
conflict_detected: { type: "boolean" }, // self-checking field
"po_number": {"type": ["string", "null"]}, # null, never invented
"document_type": {"type": "string", "enum": ["invoice", "credit_note", "unclear"]},
"conflict_detected": {"type": "boolean"}, # self-checking field
Retry with error feedback
A retry carries the original document, the failed extraction, and specific validation errors. Retry cannot recover information absent from the source — only format and structural errors. Design for self-correction: calculated_total against stated_total, a conflict_detected boolean, a detected_pattern field so dismissal patterns can be analysed.
Message Batches API
50% cheaper · up to 24 h · no latency SLA · no multi-turn tool calling in one request · custom_id correlation with results in any order. Batch is for overnight, weekly or nightly work; synchronous calls are for blocking pre-merge checks. A 30 h SLA with a 24 h window means submitting every ~4 h. Resubmit only failures by custom_id, and chunk oversized documents. Refine prompts on a sample before a large batch.
- TypeScript
- Python
for await (const r of await client.messages.batches.results(batch.id)) {
r.result.type === "succeeded" ? store(r.custom_id, r.result.message)
: failed.push(r.custom_id);
}
for r in client.messages.batches.results(batch.id):
if r.result.type == "succeeded":
store(r.custom_id, r.result.message)
else:
failed.append(r.custom_id)
Review architectures
An independent instance without the generator's reasoning context finds what self-review cannot. Use per-file passes plus a cross-file integration pass. Confidence self-reports are for routing review attention only, never as a correctness gate.
Domain 4 one-liners
- Schemas kill syntax errors, not semantic ones.
- Nullable fields beat fabricated values.
- Batch is for overnight, never for blocking.
- Retry cannot invent missing source data.
Summarization destroys specifics
Numbers, percentages, dates and customer-stated expectations are the first things lost. Keep a case facts block outside the summarized history, included in every prompt; give multi-issue conversations a separate structured issue layer. The API is stateless — the full history is resent every call.
Lost in the middle
Attention is reliable at the beginning and end of a long context. Put a key findings summary first and use explicit section headers. A bigger context window does not fix attention dilution — decompose into focused passes instead.
Trim tool output before it accumulates
Reduce a 40-plus-field payload to the five fields the task needs, before it enters history. Upstream agents return structured facts, citations and relevance — not verbose reasoning.
- TypeScript
- Python
const trim = (o: RawOrder) => ({
order_id: o.id, status: o.fulfilment_status, total: o.total_amount,
return_eligible_until: o.return_window_ends_at,
});
def trim(o: dict) -> dict:
return {
"order_id": o["id"], "status": o["fulfilment_status"],
"total": o["total_amount"],
"return_eligible_until": o["return_window_ends_at"],
}
Escalation triggers
Escalate when: the customer asks for a human (immediately, no investigation first) · there is a policy gap or exception (silent or ambiguous policy — competitor price matching) · there is no meaningful progress. Not triggers: sentiment · self-reported confidence · "complex case". Frustrated but solvable → acknowledge and offer resolution, escalate only if they reiterate. Multiple matches → ask for another identifier, never guess heuristically.
Error propagation payload
Failure type · attempted query · partial results · alternatives. Anti-patterns: generic status, empty-as-success, terminating the whole workflow. Annotate synthesis with coverage gaps — what is well-supported versus unavailable.
{
"status": "error",
"failure_type": "timeout",
"attempted_query": "AI adoption in film production 2024-2026",
"partial_results": [{ "claim": "…", "source": "https://…" }],
"alternatives": ["Narrow to 2025-2026 and retry", "Use the industry-press set"]
}
Long exploration hygiene
Degradation shows up as "typical patterns" replacing specific class names. Counters: scratchpad files · subagent delegation for verbose discovery · phase summaries injected into the next phase's prompt · /compact · manifest state exports for crash recovery.
Calibration and sampling
A 97% aggregate can hide one bad document type or field — segment accuracy before automating. Stratified random sampling of high-confidence extractions gives an error rate and surfaces novel patterns. Field-level confidence must be calibrated on a labeled validation set. Route low-confidence and ambiguous or contradictory sources to humans to prioritise limited reviewer capacity.
Claim → source mappings
Structured claim-to-source mappings (URL, doc name, excerpt) are preserved and merged through synthesis. Conflicting credible sources → annotate both with attribution, let the coordinator reconcile, and separate well-established from contested in the report. Require publication or collection dates so temporal differences are not read as contradictions. Render financial data as tables, news as prose, technical findings as lists.
Domain 5 one-liners
- Case facts live outside the summary.
- Trim tool output before it accumulates.
- Human request escalates immediately; sentiment never does.
- Segment accuracy before trusting an aggregate.
- Dates on every claim, or contradictions are imaginary.