CCAR-F · CHEAT SHEET
Claude Certified Architect – Foundations
Key concepts grouped by official exam weight.
Download as PDF (free, no sign-up)1. Agentic Architecture & Orchestration
27–27%Design and implement agentic loops for autonomous task execution
- In a hand-written loop on the Messages API, stop_reason drives the flow: while it is tool_use, run the tools, send back tool_result blocks and call the API again; end_turn means the response is final. Other values need their own handling: max_tokens means truncation and pause_turn requires resending the conversation. In the Claude Agent SDK the loop runs automatically and the end is read from the ResultMessage subtype.
- Between iterations, append the assistant response unchanged to the history, then a user message with one tool_result block per tool_use, matched by tool_use_id, including when the tool fails (with is_error). The tool_result blocks go together in a single message and before any text. This is how Claude incorporates the new information and decides its next step.
- Loop termination should rest on stop_reason, not on the model's text. Matching phrases such as task complete, treating any text block as the final answer, or using a fixed iteration cap as the main stopping rule causes early exits or unfinished answers, because a tool_use response can carry text. Turn or spend caps are only a safety net.
Orchestrate multi-agent systems with coordinator-subagent patterns
- An effective coordinator analyzes each query and decides which subagents it needs instead of always running the whole pipeline. Anthropic recommends scaling effort to complexity (one agent for a simple fact, several for broad comparisons), and in the Agent SDK Claude picks a subagent from its description field. Limits such as maxBudgetUsd bound spend deterministically.
- To avoid duplication and gaps, the coordinator splits the scope into non-overlapping parts (by subtopic, period, region or source type) and gives each subagent an objective, an output format, guidance on tools and sources and clear boundaries. Anthropic saw vague instructions make several subagents run the same searches. In the Agent SDK, tools and mcpServers restrict each subagent's sources.
- In a refinement loop, the coordinator evaluates the synthesis against what the user asked for, turns each gap into targeted queries for the search and analysis subagents, and re-invokes synthesis until coverage is sufficient. It works when there are clear evaluation criteria and feedback improves the result; a cap on rounds is only a safeguard.
- Routing all communication through the coordinator gives it a single point to observe every handoff, apply the same policy to errors or partial results, and decide what information each subagent receives. In the Agent SDK, a subagent returns only its final message to the parent and receives only the Agent tool prompt; SubagentStart and SubagentStop hooks let you audit each delegation.
Configure subagent invocation, context passing, and spawning
- A subagent that is not a fork starts with a fresh context: it does not see the coordinator's conversation or tool results and receives only the Agent tool prompt. The coordinator must therefore put the complete findings of earlier agents in that prompt (search results, analyses, file paths, errors and decisions), without summaries that lose detail.
- When passing context between agents, separate content from its metadata (URL, document name, page) with a structured format: XML tags such as document, source and document_content, records with their own fields, or search_result blocks with source and title, which enable automatic citations. Each agent then keeps attribution without having to infer it from the text.
- To run subagents in parallel, the coordinator emits several calls to the Agent tool (formerly named Task) in a single response, so the total time is that of the slowest subagent rather than the sum. It only suits independent, self-contained subtasks; when one stage depends on another, such as synthesis on the searches, it is spawned once their results arrive.
- The coordinator should give subagents the goal, its context and the quality criteria (which sources count, what a good answer contains) instead of a step-by-step procedure. Anthropic found that in research, where the path cannot be predicted, heuristics work better than rigid rules, and that clear success criteria help a subagent know when to stop.
Implement multi-step workflows with enforcement and handoff patterns
- When one step must always precede another, the guarantee cannot rest on the prompt: a PreToolUse hook on the downstream tool can return permissionDecision "deny" while the prerequisite is missing, and Claude reads the permissionDecisionReason to change course. A PostToolUse hook can read the earlier tool's tool_response and record the verified value per session_id.
- A request with several problems is split into independent items that are investigated in parallel and resolved in one reply. Claude can emit several tool_use blocks in one turn; all tool_result blocks go back together in a single user message. A subagent starts without the parent's history: the Agent tool prompt is all it receives, so it must carry the already verified facts.
- If the person receiving the escalation cannot see the conversation, the handoff must stand on its own: an escalation tool whose input_schema requires customer_id, root cause, amount and recommended action. With strict: true the input always matches the schema (required fields and types), and detailed parameter descriptions steer the content; a PreToolUse hook can check figures against the system of record.
Apply Agent SDK hooks for tool call interception and data normalization
- A PostToolUse hook receives tool_input and tool_response and can return updatedToolOutput to replace the result before Claude sees it, which unifies Unix and ISO 8601 dates or numeric status codes from different MCP servers. decision "block" and additionalContext only add text next to the original result. MCP tools are matched with mcp__<server>__.*.
- A PreToolUse hook reads tool_input before the tool runs and can return "deny" with a permissionDecisionReason that Claude reads and uses to take another route, such as escalating to a person. When hooks disagree the most restrictive wins: deny, then defer, ask and allow. With "defer" the turn ends with stop_reason "tool_deferred" and the pending call can resume after an external approval.
- Prompts, CLAUDE.md and skills are non-deterministic instructions: Claude usually follows them, with no guarantee. Hooks, deny rules and managed settings are applied by the harness every time. A rule with zero exceptions belongs in a command, http or mcp_tool hook (a prompt or agent hook lets another model decide) with onFailure "block" if the hook can fail; preferences stay in CLAUDE.md.
Design task decomposition strategies for complex workflows
- Prompt chaining splits a task into fixed steps, each call processes the previous output, and programmatic checks can sit between steps; it trades latency for accuracy. When the subtasks cannot be predicted, the orchestrator-workers pattern lets a central model decide them from the input, delegate them and synthesize the results. The recommendation is the simplest solution that works.
- Context is a finite resource: the more tokens, the less accurately a model recalls and relates information. Large reviews work better as a local pass per file, focused on one thing, plus a separate integration pass that receives condensed summaries (issues and changed interfaces) to catch cross-file problems. Each subagent receives only the Agent tool prompt and returns only its final message.
- An open-ended task such as adding tests to legacy code starts by exploring the structure, identifying the highest-impact areas and writing a prioritized plan that changes with what is discovered. Exploration can be delegated to a subagent and the plan reviewed in plan mode before any edit. For multi-session work, a task file with a status field and progress notes helps.
Manage session state, resumption, and forking
- Claude Code saves every conversation; claude --continue reopens the most recent one in the directory, while naming a session with claude -n or /rename lets you return with claude --resume <name> or /resume <name>. An ambiguous name opens the picker. Resuming does not restore flags such as --mcp-config, --add-dir or --allowedTools, which must be passed again; the default display name is not a resume handle.
- In the Agent SDK, resume with fork_session=True (forkSession in TypeScript) creates a new session that starts from a copy of the original history; the fork gets its own session_id and the original stays unchanged. Forking copies the conversation, not the files: one branch's edits are real in the directory. In the CLI you fork with /branch or with --resume/--continue plus --fork-session.
- Resuming a session (resume by ID, continue for the most recent one) gives the agent its whole history back, tool results included; use it when that context is still valid, for example after hitting a turn limit. If the queried data has changed, start a fresh session seeded with a summary of the conclusions. Fork copies the history to try another path without touching the original.
- A session stores the conversation, not the filesystem: when resumed, the agent keeps its old file reads as past results and does not know they changed. For targeted re-analysis, the resume prompt should name the modified files and ask the agent to re-read them and revise only the affected findings, instead of re-exploring everything or rewinding with file checkpointing.
2. Tool Design & MCP Integration
18–18%Design effective tool interfaces with clear descriptions and boundaries
- The description is the biggest factor in how Claude uses a tool: it should explain what the tool does, when to use it and when not to versus similar tools, what each parameter means and what it does not return. Parameters need unambiguous names (user_id rather than user). input_examples help with complex inputs but do not replace a clear description.
- When two tools overlap or have a vague purpose, the agent hesitates or picks the wrong one. The fix is to give them names that reflect what they really do, with service or resource prefixes where useful (tickets_search, wiki_search), and descriptions that bound their scope and point to the alternative. Then measure the change with an evaluation and transcript review.
- A generic tool whose behaviour and output depend on a string parameter forces the agent to guess what it will get back. It is better to split it into tools with a clear purpose and their own input and output contracts (in MCP, outputSchema with structuredContent), such as extracting data, summarising or verifying a claim against a source. Tools that merely wrap API endpoints are a common error.
- The system prompt and the tool definitions share the context, so a keyword rule ('if the user says X, call Y') can override a well-written description and trigger wrong calls. When reviewing a system prompt, look for these brittle rules and replace them with intent-based criteria consistent with the descriptions, instead of adding emphasis or classifiers.
Implement structured error responses for MCP tools
- In MCP, execution failures (API down, invalid input, business rule) are returned in the result with isError: true so the model can self-correct; JSON-RPC protocol errors are for problems with the request itself. The error content should state the category (transient, validation or permission), whether retrying makes sense and what failed, instead of a generic 'Error'.
- A business rule violation (outside the window, policy not active) will always fail, so the error should be marked as not retryable and carry an understandable explanation the agent can pass on to the customer. Whatever the tool returns enters the context, so internal details should stay in server logs and the output should be sanitised.
- Transient failures should be resolved inside the subagent with bounded retries; only what cannot be resolved locally should reach the coordinator. Because only the subagent's final message returns to the parent, that report must include the partial results, the outstanding error and what was attempted. After an is_error result Claude may retry, so the loop must cap retries.
- An access failure (permission denied, timeout) and a successful query with no matches mean different things and must be reported differently. The first goes with isError: true and its category, so the agent can decide whether to retry or escalate; the second is a successful result stating that there is no data. Mixing them leads to false answers or needless retries and escalations.
Distribute tools appropriately across agents and configure tool choice
- Each subagent should have only the tools of its role: in the Claude Agent SDK they are set with the AgentDefinition tools field (or removed with disallowedTools); if tools is omitted, the subagent inherits every available tool. allowedTools only auto-approves calls and does not hide other tools, and a prompt instruction does not stop a subagent from using a tool it has.
- A generic tool (fetch_url, run_sql) gives the agent more capability than its role needs. Replacing it with a constrained tool, such as a load_document that only accepts repository URLs, lets the server validate every input and reject what does not belong, and return only relevant information. It does not stop the model from trying, but it does stop the request from succeeding.
- Separating tools by role does not mean routing everything through the coordinator: for frequent, simple needs that belong to another role (checking a fact, reading a plan tier) give a scoped tool, often read-only and with a strict contract. Complex or sensitive cases, such as researching new topics or changing data, still go through the coordinator, which plans and approves.
- To guarantee a tool is called first, send tool_choice of type tool with its name on the first request only and auto afterwards, so Claude chooses the next steps; if it stays forced, it repeats every turn. any requires some tool but not a specific one. With a forced call the response starts with tool_use, and not every model or setting supports forced tool use.
- With tool_choice set to any, Claude must call one of the provided tools but still picks which; tool forces a named tool, auto lets Claude decide and none prevents tool use. With any or tool the response starts with the call, with no text before it. Combined with strict: true it also guarantees schema-valid inputs, and not every model supports forced tool use.
Integrate MCP servers into Claude Code and agent workflows
- Project-scoped MCP servers are defined in .mcp.json at the repository root, under mcpServers, and committed so the team shares them. They support ${VAR} and ${VAR:-default} in command, args, env, url and headers, so each person supplies their own token. Claude Code asks for approval in interactive sessions; a variable set to an empty string counts as set.
- Personal or experimental MCP servers are stored in ~/.claude.json. Local scope, the claude mcp add default, loads them only in the current project; --scope user makes them available in all your projects without sharing them. When a name is repeated, local wins over project and project over user, and the winning entry is used whole, without merging fields.
- Claude chooses tools mainly from their descriptions: if an MCP tool only says "finds symbols", Claude will keep using Grep. Describe what it covers, what it returns and when to use it, with the key words first, because tool search matches against the first part. Server instructions tell Claude when to search for the server's tools.
- For standard integrations such as an issue tracker or source hosting, add the MCP server that already exists with claude mcp add (Anthropic Directory, MCP Registry) instead of writing one. Reserve custom servers for team workflows nobody else covers, with a few tools that complete whole tasks rather than thin wrappers around API endpoints.
- MCP resources are read-only data with their own URI that the application lists with resources/list, or discovers as parameterized templates with resources/templates/list. Exposing a catalog this way avoids exploratory tool calls. In Claude Code they are referenced as @server:protocol://path and attached, and Claude gets tools to list and read them.
Select and apply built-in tools (Read, Write, Edit, Bash, Grep, Glob) effectively
- Grep searches for patterns inside files using ripgrep regex syntax: use it to find the callers of a function or where an error message comes from. Its modes are files_with_matches (the default), content and count, and it accepts glob and type filters. It respects .gitignore, so a gitignored file is searched by passing its path.
- Glob finds files by name pattern, not by content: **/*.test.tsx finds tests at any depth, while *.{json,yaml} matches only in the current directory. Results are sorted by modification time and capped with a truncation flag, so narrowing the pattern helps. Unlike Grep, it does not respect .gitignore by default.
- Edit replaces an old_string that must appear exactly once; when it repeats, add context or use replace_all. When no unique anchor exists, read the whole file with Read and save the complete content with Write, which overwrites and never merges. A partial read with a PARTIAL view notice is not enough: read the rest of the file first.
- Claude Code loads CLAUDE.md upfront and explores the rest just in time: it finds an entry point with Grep, such as a route or an error string, then follows imports with Read, opening only the files on the path. Reading everything upfront fills context with irrelevant code and worsens answers, even with a large context window.
- When a module wraps or re-exports functions, sometimes under aliases from a barrel file, searching for the original name or the import path falls short. First Read the wrapper and the barrel to list every exported name and alias, then Grep the whole codebase for each name to find the real call sites.
3. Claude Code Configuration & Workflows
20–20%Configure CLAUDE.md files with appropriate hierarchy, scoping, and modular organization
- CLAUDE.md instructions have scopes: managed policy, user (~/.claude/CLAUDE.md, only for you), project (./CLAUDE.md or ./.claude/CLAUDE.md, shared through git) and local (CLAUDE.local.md, personal). When a teammate does not get a rule, it usually lives in a user-level file. CLAUDE.md files in subdirectories load on demand.
- A CLAUDE.md can import other files with @path; relative paths resolve from the importing file, not the working directory. This lets each package owner include only the standards their code needs from one shared source. Note that imported files load with the CLAUDE.md and save no context; path-scoped rules are the tool for that.
- A large CLAUDE.md is split into single-topic files in .claude/rules/, such as testing.md or deployment.md, which are discovered recursively. Without frontmatter they load at launch; with paths they load only when Claude reads or edits matching files, and paths is the only field read. They are still context, not enforced configuration.
- /memory lists user and project CLAUDE.md and CLAUDE.local.md locations, even ones that do not exist yet, and opens each file in your editor; it also gives access to the auto memory folder and its toggle. To confirm what loaded in the session, use /context all (Memory files). Differences between people usually come from user-level files or auto memory.
Create and configure custom slash commands and skills
- A Markdown file in the project's .claude/commands/ defines a command shared with the team through version control: deploy.md runs as /deploy and a subfolder adds a colon prefix (/frontend:component). Commands have been merged into skills; to bundle scripts you convert the command to .claude/skills/<name>/SKILL.md, while ~/.claude/commands/ stays personal.
- With context: fork in the frontmatter, the skill runs in a new subagent (its type set by agent, general-purpose by default) that receives the SKILL.md content as its task, does not see the conversation history and returns a summary. It isolates verbose or exploratory output; it runs in the background unless background: false, and Explore starts without CLAUDE.md.
- In Claude Code, a skill's allowed-tools frontmatter pre-approves the listed tools only for the turn that invokes it, without limiting other tools: they stay available under the permission settings. To restrict tools while the skill is active use disallowed-tools, and to block them everywhere use deny rules; a project skill can grant itself broad access, so review it.
- The argument-hint frontmatter field shows during autocomplete the arguments a skill expects, such as [issue-number], after the command name. It is only a hint: it does not validate input; indexed placeholders without an argument stay literal and those declared in arguments become empty. It is a Claude Code extension that claude.ai uploads and the Skills API reject.
- CLAUDE.md loads in every session and holds the facts and rules Claude must always have: build commands, conventions and never-do-X rules. Skills load on demand and suit reference material or workflows triggered with /name; a common pattern pairs one line in CLAUDE.md with the full guide in a skill. @path imports do not reduce context.
Apply path-specific rules for conditional convention loading
- A Markdown file in .claude/rules/ with YAML paths frontmatter (for example paths: ["terraform/**/*"]) loads only when Claude reads, writes or edits a matching file, including through cat or head in Bash. paths is the only field Claude Code reads from a rule; without it the rule loads at launch like .claude/CLAUDE.md. Rules are guidance, not enforced configuration.
- A rule's paths field takes glob patterns relative to the directory containing the .claude folder: **/*.test.tsx reaches every test file in any folder, while src/components/*.tsx matches only files directly in that folder and /*.md only those in the base. You can list several patterns and use braces, as in src/**/*.{ts,tsx}.
- Both a per-directory CLAUDE.md and a rule with paths in .claude/rules/ target instructions at part of the tree. A subdirectory CLAUDE.md lives beside the code, is maintained by its owners and loads when any file in that folder is touched; the rule lives in the central .claude/ and fits when the same convention applies to many scattered paths or to a file type.
Determine when to use plan mode vs direct execution
- Plan mode has Claude read files, run exploration commands and propose a plan without editing source until you approve it. It suits tasks with architectural implications, such as migrations touching dozens of files or choosing between integration approaches, because it avoids re-work when the initial direction is wrong. Enter it with Shift+Tab, /plan, --permission-mode plan or defaultMode in .claude/settings.json.
- Direct execution suits well-understood changes with clear scope, such as a single-file fix with a stack trace or one specific validation: a specific prompt with the file, the rule and the test command lets Claude work with few file reads and verify the result. Plan mode, /batch or agent teams add overhead that only pays off for complex or many-file work.
- Explore is a read-only built-in subagent (Write and Edit denied) for file discovery and code search: it works in its own context window and returns only a summary, which avoids exhausting the main context in multi-phase tasks. It starts without CLAUDE.md or git status, so essential rules must be restated when delegating; for exploring and modifying, use general-purpose.
- A common pattern is to investigate in plan mode and then execute: Claude explores and proposes a plan, you can ask for changes with No, keep planning or edit it with Ctrl+G, and approving it exits plan mode so Claude starts editing. With showClearContextOnPlanAccept you can approve and clear the planning context, and the plan is re-injected from disk after compaction.
Apply iterative refinement techniques for progressive improvement
- When a natural-language description produces inconsistent results, a few concrete input and output examples (few-shot) are usually the most reliable way to pin down the expected format and transformation. They should be relevant, diverse enough to cover edge cases without teaching unintended patterns, and wrapped in example tags inside an examples block to keep them apart from instructions.
- Writing tests for expected behaviour, edge cases and performance requirements first gives Claude a definition of done: with a pass or fail check it can change the code, run the check, read the failures and fix them. Put the test command in CLAUDE.md and ask for the command and its output as evidence; a Stop hook exiting with code 2 makes the harness enforce it.
- In unfamiliar domains, ask Claude to interview you before implementing: it asks about what you have not decided, such as cache invalidation strategies or failure modes, until it can write a spec to SPEC.md. A fresh session then builds from that file; scheduled tasks cannot ask clarifying questions, so the interview comes first.
- When an edge case fails, such as nulls in a migration script, state the output you expect for concrete inputs and turn them into tests, so Claude has a pass or fail check to iterate against. If it is still wrong after two corrections, use /clear and one new prompt that folds in what you learned, and make clear that tests verify the rule rather than replace it, to avoid hard-coded values.
- When two fixes interact, describe them together in one detailed message that explains their relationship and the expected combined result, with a scenario that works as a test. Independent issues are better handled one at a time, each with its own check and /clear between unrelated tasks. After two failed corrections, start again with one prompt that folds in what you learned.
Integrate Claude Code into CI/CD pipelines
- In CI, run Claude Code with -p (--print): it processes the prompt without an interactive session, prints the result and exits with a status code the script can check. Calls that would need approval are denied unless something approves them, so pre-approve what the job needs with --allowedTools or a permission mode, and use --permission-prompts none when nobody can answer a permission host.
- To post findings as inline comments, run claude -p with --output-format json and --json-schema: the response includes session metadata and schema-conforming data in the structured_output field. If the run ends without valid output that field is missing, so check it before posting; an invalid schema causes an error and the format keyword is not enforced.
- A claude -p run on a fresh runner does not remember the earlier review, so to avoid duplicate comments include the prior findings and the author's replies in the prompt and ask for only new or still-unaddressed issues. The managed Code Review does the same: the next review resolves fixed threads and reads the replies on its earlier findings.
- Claude can only avoid duplicate test scenarios if it sees the existing tests: pass it the files that exercise the changed module or ask it to read them, and ask only for scenarios they do not cover. A context focused on those files works better than the whole suite; bare mode does not load CLAUDE.md, so instructions must go in the prompt.
- Document in CLAUDE.md what Claude cannot work out from the code: which tests add value, what to skip and which fixtures to use, with concrete instructions in a short file. If the guidance only matters under tests/, put it in .claude/rules/ with paths so it loads when Claude works on those files. In CI with --bare, CLAUDE.md is not loaded, so pass the standards with --append-system-prompt-file.
4. Prompt Engineering & Structured Output
20–20%Design prompts with explicit criteria to improve precision and reduce false positives
- To reduce false positives, define explicitly what to report (logic bugs, security, data leaks) and what to skip (style, what CI already enforces, generated files), and require a file:line citation for behaviour claims. If one category produces a lot of noise, exclude it temporarily in REVIEW.md while you improve its criteria, without turning off the rest of the review.
- For consistent severity classification, define each level with concrete code examples, including borderline cases and why they belong there, because examples work better than abstract instructions. An enum in the schema only guarantees a valid label, not the right one. In Code Review, calibration is set in REVIEW.md by stating what is Important and what is Nit at most.
Apply few-shot prompting to improve output consistency and quality
- For ambiguous cases, add a few targeted examples that show the situation, the chosen action and why the plausible alternatives were rejected, since Claude generalizes from the explanation. Examples should mirror the real use case, vary enough not to teach surface patterns, and sit in example tags inside examples, apart from the instructions.
- A few example findings in the exact format (location as file:line, issue, severity and a concrete fix) give more consistency than describing the format in the abstract. If a parser needs the fields always present, use structured outputs or strict: true, which guarantee the schema; examples are still needed so that the content of each field has the desired style.
- To reduce false positives without losing real bugs, use contrasting examples: an acceptable pattern and a similar one that is a genuine issue, each with the principle that decides it. Vary services and code shapes so Claude does not latch onto surface patterns; a single acceptable example, or near-identical copies, teaches the shape of the snippet rather than the rule.
- When documents vary in structure, such as inline citations versus bibliographies or a dedicated methods section versus details embedded in the text, include examples of each structure with the correct extraction. For long documents, place them at the top of the prompt, above instructions and examples, wrapped in tags, and ask Claude to quote the relevant passages before extracting.
- When a field comes back empty or null although the value is in the document, the cause is usually a format Claude has not seen: add examples of those formats with the correct value and describe in the schema what the field looks like. Also include an example where the value is genuinely missing and null is correct. strict: true only guarantees the shape, not which value is extracted.
Enforce structured output using tool use and JSON schemas
- To extract data with tool use, define a tool whose input_schema describes the fields and read the input object of the tool_use block in the response (stop_reason tool_use), finding it by type and name because a text block can come first. With strict: true, sampling is constrained so inputs always match the schema, with no validate-and-retry loops.
- With several extraction schemas and an unknown document type, tool_choice {"type": "any"} makes Claude call one of the tools without dictating which, so it never answers with plain text alone. Combined with strict: true on the tools, it also guarantees schema-valid inputs. Under any, Claude writes no text before the tool_use block.
- tool_choice {"type": "tool", "name": "extract_metadata"} forces Claude to call that tool, which ensures extraction runs before enrichment; later requests go back to auto. The response starts with the tool_use block, with no preceding text and no thinking block, and manual extended thinking is not compatible with forcing a tool.
- Structured outputs guarantee that required fields are present with their type, so a required field with no data in the source invites fabrication. When information may be missing, declare the field with a type that allows null (type ["string", "null"] or anyOf with null) and say when to use it. Required properties are emitted before optional ones.
- A strict enum only allows the listed values, so cases that do not fit are forced into the closest category. Adding "unclear" for ambiguous cases and "other" with a detail field makes the taxonomy extensible while keeping data machine-readable. Enum capitalisation is not guaranteed, so compare values case-insensitively.
Implement validation, retry, and feedback loops for extraction quality
- A useful retry does not repeat the same request: it includes the original document, the failed extraction and the specific validation error, so Claude rereads the source and corrects against a criterion. In tool loops, the failure goes back as a tool_result with is_error set to true and an instructive message, and retries must be capped.
- A retry only helps when the cause is within Claude's reach: wrong formats and structural errors are fixed with the specific error, and a truncated output (stop_reason max_tokens) with a higher max_tokens. If the data exists only in a document that was not sent, retrying will not produce it: supply the source or route the case to human review.
- A detected_pattern field on each structured finding, ideally an enum with "other" plus detail, labels which rule produced it. When developer dismissals are logged against that label, you can see which patterns concentrate false positives and tune the prompt, or REVIEW.md in Code Review, for those patterns only, then measure the effect.
- To validate extractions, the schema should capture both what the document states and what follows from it: stated_total next to calculated_total exposes invoices that do not add up, and a required conflict_detected boolean flags inconsistent source data. Doubtful cases then go to human review instead of being silently corrected.
Design efficient batch processing strategies
- The Message Batches API processes requests asynchronously with higher throughput and lower cost, but a batch can take up to 24 hours. It suits overnight or weekly analysis, evaluations and bulk re-classification, not checks that block a merge or responses someone is waiting for: those use the synchronous Messages API.
- With the Message Batches API, a guaranteed deadline must budget the worst case: queue wait until the next submission plus up to 24 hours of processing and any later step. With a 30-hour SLA you must submit at least every 6 hours (4 leaves margin). Requests that come back as expired may need the synchronous path to meet the deadline.
- Each batch result carries its request's custom_id and order is not guaranteed, so failures are identified by custom_id and resubmitted on their own in a new batch, since a submitted batch cannot be modified. Invalid requests, such as an over-long document, are fixed first (for example by chunking); expired or server-error requests are resubmitted unchanged.
- Before launching a large batch, refine the prompt on a representative sample that mirrors the real distribution and includes edge cases, and grade it automatically. The documentation also advises a dry run of one request shape with the Messages API to avoid validation errors. The batch then succeeds on the first pass and costly resubmissions are avoided.
Design multi-instance and multi-pass review architectures
- A reviewer that shares the generator's conversation inherits its reasoning and tends to confirm it. For an independent review use another instance: a second session or a non-fork subagent, which starts with a clean context. A fork or a resumed subagent does not work, because both inherit history. In Claude Code, tools: Read, Grep, Glob makes the reviewer unable to edit.
- In large reviews, a single context holding many files dilutes attention and depth declines. Review each file in a focused pass (for example, in subagents with their own context) for local issues, and add a separate integration pass that examines changed interfaces and cross-file data flow, which no single-file pass can see.
- A verification pass can return a confidence level next to each finding, in its own field of a JSON-schema structured output, so code can route uncertain findings to human review. Require a supporting quote or line for each finding, retract those without one, and check routing thresholds against labeled cases.
5. Context Management & Reliability
15–15%Manage conversation context to preserve critical information across long interactions
- Summarizing or compacting a long conversation can turn amounts, dates, order numbers and statuses into vague phrases. To avoid this, code extracts those values from tool results into a case facts block that is included in every request, outside the history that gets summarized, instead of trusting the summary or the model to keep them.
- When a customer raises several issues in one session, keep each one as a structured record (order ID, amount, status) in a separate context layer that is sent on every turn and updated by code from tool results. Structured formats such as JSON make the state schema explicit and keep data from bleeding between issues.
- Tool results accumulate in context, and an order lookup with dozens of fields spends tokens that add nothing. If you own the tool, make it return only the relevant fields (for example with a concise or detailed response_format parameter); if not, in the Claude Agent SDK a PostToolUse hook can replace the output with updatedToolOutput before Claude sees it.
- With long inputs that aggregate many results, recall drops as context grows and findings in the middle are easily missed. It helps to open the aggregated input with a key findings summary, organize the detail into labeled sections (for example XML tags per document with its source), and place the long data at the top with the query and instructions at the end.
- The coordinator should give each subagent an objective and an output format, and that format should carry, next to each finding, metadata such as the date of the data, the exact source location and the methodological context. Without them, the synthesis agent cannot tell old figures from recent ones or explain why two sources disagree, and citations lose precision.
Design effective escalation and ambiguity resolution patterns
- A vague instruction such as escalate complex cases leads to both over- and under-escalation. It works better to write explicit escalation criteria in the system prompt and add a few diverse, canonical few-shot examples, wrapped in example tags, that show cases to escalate and cases the agent resolves on its own, instead of a long list of rules for every edge case.
- When a customer explicitly asks to speak to a person, the agent should escalate in that same turn, without first running lookups or trying to resolve the case. Escalation accuracy is a key metric for a support agent, and the handoff should carry a structured summary of what the conversation already contains so the customer does not have to repeat it.
- Frustration alone is not a reason to escalate: if the issue is within the agent's capability, it should acknowledge the frustration and offer the resolution. If the customer reiterates that they want a person, escalate without pushing again. Escalating on negative sentiment floods the human queue and lowers the deflection rate, two metrics the support guide proposes tracking.
- If the policy is silent or ambiguous about the customer's specific request, the agent should neither improvise an exception nor deny by default: it should escalate to a person with authority to decide. The escalation criterion is the policy gap, not complexity or amount, and it should be written explicitly along with limits on what the agent is not authorized to promise.
- If a customer or order lookup returns several matches, the agent should not pick one by heuristic (most recent, first in the list): it should ask for an additional identifier such as the order number or email. The tool should make it clear that there are multiple matches instead of returning only the first, and the prompt should say not to guess missing parameters.
Implement error propagation strategies across multi-agent systems
- A generic error such as search unavailable or failed leaves the coordinator nothing to decide on. The subagent or tool should return a structured error: failure type, what was attempted, partial results and possible alternatives. In the Claude API this goes in a tool_result block with is_error set to true and an instructive message; in MCP, in the result with isError.
- A query that finds nothing is a valid result; a query that could not run (timeout, service down, permissions) is an access failure. If both look the same, the coordinator either reports false absences or retries for no reason. Mark the failure as an error (is_error in the Claude API, isError in MCP) and the empty case as a success with zero results.
- Transient failures, such as a timeout or a momentary rate limit, are best handled inside the subagent with bounded retries. Only errors it cannot resolve, such as a denied permission or exhausted retries, should reach the coordinator, together with what was attempted and the partial results. This keeps noise out of the coordinator and preserves work already done.
- When some sources were unavailable, the synthesis report should not read as complete. Structure it with coverage annotations per section or finding: what is well supported by several sources, what rests on a single one, and which areas have gaps because sources were down. Explicit permission to say information is missing reduces invented claims.
Manage context effectively in large codebase exploration
- During long code exploration, delegate specific questions (locating test files, tracing a flow's dependencies) to subagents such as Claude Code's built-in Explore. Each works in its own context window and returns only a summary, while the main conversation keeps the plan. A subagent does not inherit the history: whatever it needs must go in the delegation prompt.
- In long exploration sessions the agent starts giving inconsistent, generic answers because specific findings get buried or summarized away. Structured note-taking prevents this: the agent writes classes, paths and decisions to a file (for example NOTES.md) as it discovers them and reads it back before answering later questions or after a compaction.
- Between exploration phases, the coordinator should summarize the key findings of the finished phase, store them in external memory if needed, and pass that summary in the initial prompt of the next phase's subagents. They then start with a clean but informed context, without redoing work or inheriting the full history, which is what a fork would do.
- To recover from a crash without starting over, each agent exports its state (tasks done, tasks pending, result paths) to a known location, and on resume the coordinator loads that manifest and injects each agent's share into its prompt. Use JSON with explicit fields, since the model is less likely to rewrite JSON than Markdown, alongside git and progress notes.
- In Claude Code, /compact summarizes the conversation to free context without abandoning the task, and accepts focus instructions such as /compact focus on the auth module. /clear starts an empty conversation. After compaction the project-root CLAUDE.md and rules without paths: are re-injected from disk, so anything that must always survive belongs there or in a Compact instructions section.
Design human review workflows and confidence calibration
- If high-confidence extractions are approved without review, nobody measures their real error rate or sees new failure patterns appear. Send a random sample of those extractions, stratified by document type or vendor, to human review on an ongoing basis. Human review catches edge cases that automated evaluation misses, and the sample should reflect the real distribution of documents.
- Before reducing human review, measure accuracy on a labeled set broken down by document type and by field: a high overall figure can hide a segment far below target. Automate only the segments that meet the threshold, keep review on the rest and re-measure them after every change. Structured outputs guarantee the schema, not that the values are correct.
- Ask the model for a confidence score per field in the structured output, not one per document, so that only doubtful values go to review. That score is not an accuracy: compare it with a labeled validation set and set each threshold where observed accuracy reaches the target. Structured outputs guarantee the format, not that the values are correct.
- With limited reviewers, the human queue should receive only extractions with a concrete sign of error: fields below a calibrated threshold and documents where the model flags ambiguous or contradictory source values. Order the queue by impact. Random sampling or an overly high blanket threshold wastes capacity, and asking the model to pick one value hides the conflict.
Preserve information provenance and handle uncertainty in multi-source synthesis
- Provenance is lost when subagents return unstructured summaries: ask for each finding as a claim with its URL or document name and the supporting excerpt, and have synthesis preserve those mappings. In the API, Citations returns the exact cited_text and valid pointers into the document; it cannot be combined with structured outputs, so ask for one line per field and parse it in code.
- A multi-source report should use explicit sections to separate well-established findings from contested ones, and keep how each source describes its result (preliminary estimate, small pilot, audited survey) and its method. Subagents should flag speculation and source problems instead of presenting everything as fact, and synthesis must not strip those hedges when summarizing.
- When sources disagree and the subagent cannot reconcile them, it should finish the analysis and include every value with its source and an explicit conflict annotation. The decision belongs to the coordinator, which sees all subagents' results, before anything goes to synthesis. Silently picking one value, averaging or stopping at the first conflict hides information or leaves the work unfinished.
- An undated figure cannot be placed in time: subagents should include the publication date and data collection period in each finding, and the prompt should give the current date. Synthesis can then tell old baselines from recent data and apply recency when resolving conflicts. When passing several documents, add the date as metadata next to each document's source.
- In synthesis reports each content type has its own form: comparable financial figures in tables, news in prose and technical findings in structured lists. State this in the prompt per content type and in positive terms ("write this section in prose paragraphs") rather than blanket prohibitions such as "do not use markdown", which also remove the tables you need.