D1 · Agentic Architecture & Orchestration

27% of the exam · ≈16 of 60 questions · plain-language lesson first, full notes at the end

Step 2 of 9~25 min
The big idea An agent is Claude placed in a loop with access to tools. Think of a capable new colleague who can't touch anything directly — they can only ask for things to be done ("look up this order"), read the result, and decide what to ask next. This domain is about running that loop safely, splitting big jobs across several agents, and knowing when a rule is too important to leave to politeness.

How one agent works

Your code calls Claude with the conversation plus a list of available tools. Claude answers either with a final reply or with a request to use a tool. Your code runs the tool, appends the result, and calls Claude again — around and around until the job is done.

Flowchart of the agentic tool-use loop
🔁

The loop has exactly one steering wheel

Every reply carries a stop_reason field. Your loop reads it and does what it says — nothing else decides when to continue or stop.

Exit when stop_reason = end_turn. Never by spotting "done" in the text, never by an iteration counter (that's only a safety backstop).
🧠

Claude remembers nothing between calls

The API is stateless — there is no session on Anthropic's side. The "memory" of a conversation is just your app re-sending the whole history every call. That's also why very long chats get slower and pricier.

No session_id exists. The app owns the history.
📬

Returning tool results — the one envelope rule

When Claude asks for several tools at once, you run them all and send everything back in one message, each result labeled with the ID of the request it answers.

Append the assistant's turn untouched, then ONE user message with ALL tool_result blocks, matched by tool_use_id.

The stop signal, decoded

Map of all stop_reason values to correct loop behavior
stop_reasonWhat it meansWhat your loop must do
end_turnFinished naturallyExit, return the answer
tool_use"Please run these tools"Execute, append results, call again
max_tokensRan out of room mid-sentenceTreat as truncated — never parse as final; raise the cap or continue
pause_turnServer paused a long turnRe-send the conversation as-is; it resumes
Classic trap: the output was cut off (max_tokens) and the code "helpfully" repairs the half-finished JSON and sends it on. It now parses — and is silently wrong. Truncated means retry, not repair.

Teams of agents

Big jobs can be split: one coordinator plans and delegates to subagents, like a project lead handing briefs to specialists.

Hub-and-spoke coordinator/subagent architecture
📄

Every subagent starts blank

A subagent inherits nothing — no conversation history, no shared memory. If the brief doesn't say it, the specialist doesn't know it.

The delegation prompt carries complete context, goals & quality criteria, tools, and the shape of the answer wanted — but NOT step-by-step procedures (those kill the specialist's judgment).
🔀

Everything routes through the boss

Specialists never talk to each other directly (hub-and-spoke). One exception the exam loves: if ~85% of an agent's needs are trivial lookups, give it ONE narrow tool for those and route only complex cases through the coordinator.

Hub-and-spoke = observability, consistent error handling, controlled information flow. Spawning requires "Task" in allowedTools; parallel = multiple Task calls in ONE response.
🗺️

Slice the work like a map, not confetti

Splitting "the renewable-energy market" into 12 hyper-specific micro-tasks leaves unowned gaps between them — the named risk is too-narrow decomposition. If the final report has holes: find the gaps, re-delegate targeted questions, re-merge.

Slice by meaningful subtopics or source types; a 30-file review = per-file passes PLUS one separate cross-file pass.
🤔

When is a team actually better?

Only when subtasks are independent (can run in parallel) or the job won't fit one agent's memory. "It's complex" is never the reason.

Default is a single agent. A strictly sequential 12-step workflow is the WORST multi-agent candidate.

Rules that must never break

Deterministic hooks vs probabilistic prompts, with hook timeline
🛡️

Politeness vs physics

Instructions in a prompt are followed almost always — that's politeness. A hook runs 100% of the time — that's physics. "Verify identity before any refund" as a prompt fails an audit; as a code gate it cannot fail.

must / never / always / audit / financial-legal-safety ⇒ hook or code gate, never a stronger prompt.
🧹

Clean the data before Claude sees it

Three tools return dates in three formats and the agent mis-compares them? Don't ask the model to juggle formats — a post-tool hook converts everything to one format first.

Deterministic conversion is a job for code (PostToolUse), not for reasoning.
🤝

Handing off to a human

When the agent escalates, the human usually can't see the chat. The handoff is a structured brief, not a transcript dump.

Include: customer/task ID · root cause · key figures (amounts, order refs) · recommended action.
⏯️

Picking up yesterday's work

Reopen the old session when its knowledge is still mostly true — and immediately say which files changed so stale facts get refreshed. Start fresh (with a written summary) when too much moved. Want to try two ideas from one baseline? Branch the session.

--resume + state what changed · fresh session + structured summary when stale · fork_session for divergent strategies.
Drill D1 now — quiz filtered to this domainAdaptive: anything you miss comes back in a new disguise until you convert it.

Flash-drill this domain (25 cards)

Tap a card to flip it — the same concepts the quiz drills adaptively.

Full study notes optional deep reading — the original study-kit text, code-free

1. The agentic loop

An agent is a model in a loop with tools. Nothing more mysterious than this:

            ┌──────────────────────────────────────────────┐
            │                                              │
   user     ▼                                              │
  request ──► call Claude (messages + tools)               │
              │                                            │
              ▼                                            │
        read stop_reason ───── "tool_use" ──► execute tools│
              │                               append results
              │ "end_turn"                          │
              ▼                                     └──────┘
        return final answer

Per iteration:

  1. Send the conversation (messages) plus tool definitions (tools).
  2. Claude responds. If it wants a tool, the response contains tool_use content blocks and stop_reason == "tool_use".
  3. You (the harness) execute the tool(s), append the assistant turn and a user turn containing tool_result blocks, and call again.
  4. Loop until stop_reason is no longer "tool_use".

The exam repeatedly probes whether you know who does what: Claude decides which tool and with what input; your code executes it. Claude never runs anything itself via the plain API — tool execution, sandboxing, and permissioning are the harness's job (this is exactly the surface where hooks and allowedTools live).

📊 Diagram — “Flowchart of the agentic tool-use loop” (a version appears earlier on this page)

2. stop_reason — the field that drives everything

stop_reason Meaning Correct loop behavior
end_turn Claude finished naturally Exit loop, return the answer
tool_use Claude requests tool call(s) Execute tools, append tool_result(s), call again
max_tokens Output hit your max_tokens cap Response is truncated — treat as incomplete; raise the cap or continue, never parse as final
stop_sequence Hit one of your custom stop_sequences Intentional early stop; handle per your design
pause_turn Server-side turn paused (long server-tool work) Re-send as-is to resume
refusal Model declined for safety Surface to user; do not blind-retry

Classic exam traps:

  • A loop that only checks end_turn/tool_use and treats max_tokens output as complete → silently truncated JSON that fails downstream. The reliable design checks for truncation explicitly.
  • A loop written as while stop_reason == "tool_use" with no iteration cap → a malformed tool can spin forever. Production loops carry a max-iteration guard.

📊 Diagram — “Map of all stop_reason values to correct loop behavior” (a version appears earlier on this page)

3. Building a complete tool-use loop

The canonical implementation — this exact shape (append assistant content → execute → append tool_result with matching tool_use_id → repeat) is what Domain 1 questions assume you know cold.

Three invariants the exam loves:

  1. Append the full assistant response.content to history (it contains the tool_use blocks Claude needs to see echoed back).
  2. Every tool_result must carry the tool_use_id of the request it answers — and all results for one turn go back in a single user message (splitting them across messages degrades parallel tool use).
  3. Cap iterations.

4. Single-agent vs multi-agent: the decision framework

The exam does not reward "more agents = better." The default is a single agent; you add agents only when the problem demands it.

Choose When Why
Single agent Sequential steps, shared context throughout, one coherent task Simplest, cheapest, no coordination overhead, no context-handoff loss
Subagents (coordinator + workers) Independent parallelizable subtasks; work that would blow the main context window; specialized roles Parallelism; context isolation keeps the coordinator lean; each worker gets a focused toolset

Decision test to apply on exam day:

  1. Can the subtasks run independently? If step B needs step A's output, parallel subagents buy nothing — sequential single-agent (or pipelined) wins.
  2. Would intermediate detail pollute the main context? Research over 50 documents → workers read documents and return summaries; coordinator context stays small.
  3. Is the added failure surface worth it? Every subagent adds error-propagation and result-merging concerns (Domain 5 overlap).

Trap: "The task is complex, so split it across multiple agents." Complexity alone is not the trigger — independence and context pressure are.

5. Coordinator/subagent patterns & context isolation

The single most-tested fact in this domain:

Subagents start with a fresh context. They inherit nothing from the coordinator — not the conversation, not earlier tool results, not the user's original phrasing.

Consequences the exam probes:

  • The coordinator's delegation prompt must explicitly pass everything the subagent needs: the goal, relevant facts, constraints, output format, and what "done" looks like.
  • A subagent asked to "continue the analysis" will fail — there is no "the analysis" in its context.
  • Subagent results return to the coordinator as tool results (in the Claude Agent SDK, spawning happens via the Task tool). The coordinator's context receives the result, not the subagent's working transcript — that's the whole point (context isolation).
  • Because results come back as data, make subagents return structured output (e.g. JSON with findings, sources, confidence) so the coordinator can merge programmatically — and so failures are explicit rather than silent (Domain 2/5 overlap).

Anatomy of a good delegation prompt:

ROLE: You are a research subagent.
GOAL: Determine whether ACME Corp's 2025 revenue grew year-over-year.
CONTEXT YOU NEED (you have no other context):
  - Parent task: due-diligence report for a client, deadline strict.
  - ACME's fiscal year ends March 31.
TOOLS: web_search only.
RETURN FORMAT (JSON): {"answer": ..., "figures": [...], "sources": [urls], "confidence": 0-1}
If you cannot find reliable figures, say so explicitly in "answer" — do not guess.

Parallel vs sequential decomposition: fan out only truly independent subtasks; run dependent steps in sequence. A common exam option is "spawn a subagent per step of a dependent pipeline" — wrong, because each spawn re-pays context setup and the steps still serialize.

📊 Diagram — “Hub-and-spoke coordinator/subagent architecture” (a version appears earlier on this page)

allowedTools — least privilege for agents

In the Claude Agent SDK (and Claude Code), allowedTools restricts which tools an agent (or subagent) may use. The exam pattern:

  • A subagent that only needs to read files gets ["Read", "Grep", "Glob"]not Bash or Write.
  • Why it matters: it's deterministic enforcement (the tool simply isn't available), unlike a prompt saying "please don't modify files" (probabilistic). Prompts guide; systems enforce.
  • Minimal tool surface also improves tool selection: fewer, sharper options → fewer mis-picks (Domain 2 overlap).

6. Hooks: deterministic enforcement vs prompt guidance

Hooks are your code that the harness runs at fixed lifecycle points — before/after tool calls, at session events. Because they are code, they execute 100% of the time: they are the canonical answer to "how do I guarantee X happens?"

Mechanism Nature Use for
System prompt instruction Probabilistic — usually followed Style, tone, approach, preferences
Hook (e.g. PreToolUse, PostToolUse) Deterministic — always runs Policy, compliance, blocking, logging, validation

Examples of hook-shaped exam answers:

  • "The agent must never call the refund tool for amounts over $500 without approval" → a PreToolUse hook that inspects the tool input and blocks/queues the call. Not a system-prompt rule.
  • "Every file write must be logged for audit"PostToolUse hook. A prompt asking Claude to "mention when you write files" can be forgotten; the hook cannot.
  • "Run the linter after every edit"PostToolUse hook on the Edit tool.

If the requirement contains must / never / always / compliance / audit, the answer is a hook (or schema/code check) — not a longer prompt. This single rule resolves several questions per exam.

📊 Diagram — “Deterministic hooks vs probabilistic prompts, with hook timeline” (a version appears earlier on this page)

7. Session management

Agent SDK / Claude Code sessions persist conversation state so work can span invocations.

Concept What it does When it's the answer
--resume / session resume Continue a previous session with its full context Long-running work interrupted (deploys, crashes, next morning)
fork_session Branch a session: same history, divergent futures Explore two approaches from one shared starting point without cross-contamination
/compact (Claude Code) Summarize the conversation to reclaim context budget Session still needed but context is nearly full (details in page 02 & 05)
Scratchpad files Persist working state to disk, outside the context window State that must survive compaction or session loss (Domain 5 overlap)

Exam angle: session features are about continuity and recovery. If a scenario says "the pipeline may be interrupted and must pick up where it left off," the answer combines session resume with durable state written to files — not "keep everything in the conversation."

8. Escalation & human-in-the-loop

Reliable agents know when to stop. The exam rewards designs with explicit, pre-defined escalation triggers:

  • Confidence-based: the agent reports confidence; below a threshold → route to a human. (Requires asking for confidence in the output schema — you can't threshold what you don't collect.)
  • Attempt-based: N failed tool calls / N loop iterations → escalate. Never unbounded retry.
  • Policy-based: certain actions (refund > $X, deleting data, contacting a customer) always require human approval — enforced via hooks or tool gating, not prompts.
  • Ambiguity-based: request falls outside the defined scope → hand off with a structured summary of state so the human doesn't start from zero.

Anti-patterns (frequent wrong options):

  • Retrying indefinitely "until it works".
  • Letting the model decide for itself whether policy applies, when the scenario demanded a guarantee.
  • Escalating with no context handoff (human gets a bare "agent failed").

11½. Official exam-guide addenda (v1.0)

Specifics from the official task statements (Exam Guide v1.0, July 2026) that sharpen or extend the sections above:

Loop termination (TS 1.1) — named anti-patterns. The primary stopping mechanism is stop_reason. The guide explicitly lists as anti-patterns: parsing natural-language signals to decide termination, checking assistant text for "done"-like content, and using an arbitrary iteration cap as the primary stopping mechanism. Keep the cap from §3 — but as a safety backstop, never the design.

Hub-and-spoke coordination (TS 1.2). All inter-subagent communication routes through the coordinator — for observability, consistent error handling, and controlled information flow (subagents never talk to each other directly). Two more tested ideas: the coordinator should select subagents dynamically per query (not always run the full pipeline), and beware overly narrow task decomposition — slicing a broad research topic too finely leaves coverage gaps. For synthesis quality, the guide endorses an iterative refinement loop: coordinator evaluates the synthesis for gaps → re-delegates targeted queries → re-synthesizes until coverage is sufficient.

Spawning mechanics (TS 1.3). Three concrete facts: (1) the coordinator's allowedTools must include "Task" or it cannot spawn subagents at all; (2) parallel subagents = multiple Task tool calls in a single coordinator response (not across separate turns); (3) each subagent type is configured via an AgentDefinition — description, system prompt, and tool restrictions. And delegation prompts should state goals and quality criteria, not step-by-step procedures — that's what lets subagents adapt.

Hooks for data normalization (TS 1.5). Beyond policy gates and audit logs, PostToolUse hooks are the tested answer for normalizing heterogeneous tool outputs — e.g., three MCP tools returning Unix timestamps, ISO 8601 strings, and numeric status codes get normalized to one format before the model processes them.

Decomposition patterns (TS 1.6). Two named strategies: prompt chaining (fixed sequential steps — right for predictable multi-aspect work like code review: per-file passes, then a cross-file integration pass to avoid attention dilution) vs dynamic adaptive decomposition (subtasks generated from what each step discovers — right for open-ended investigation).

Sessions (TS 1.7). Resumption is named: --resume <session-name>. Two reliability rules: when resuming after code changes, tell the agent which files changed so it re-analyzes only those; and when prior tool results have gone stale, start a fresh session seeded with a structured summary instead of resuming — stale context misleads more than it helps.

Finished this page?Mark it complete — your progress updates everywhere instantly.
Next: D3 · Claude Code Configuration & Workflows →