Agentic Architecture & Orchestration
The stop_reason-driven agentic loop, coordinator–subagent patterns, passing context to subagents, hook-based enforcement, task decomposition, and session management (resume/fork) with the Claude Agent SDK.
- 1.1 Design and implement agentic loops for autonomous task execution
- 1.2 Orchestrate multi-agent systems with coordinator-subagent patterns
- 1.3 Configure subagent invocation, context passing, and spawning
- 1.4 Implement multi-step workflows with enforcement and handoff patterns
- 1.5 Apply Agent SDK hooks for tool call interception and data normalization
- 1.6 Design task decomposition strategies for complex workflows
- 1.7 Manage session state, resumption, and forking
Domain overview
Domain 1 makes up 27% of the CCAR-F exam and is the heaviest domain (about 16 of 60 questions). Questions come mostly from Scenario 1 – Customer Support Resolution Agent (enforcement, handoff, hooks), Scenario 3 – Multi-Agent Research System (coordinator, subagents, context passing), and Scenario 4 – Developer Productivity (task decomposition, sessions).
The exam rarely asks for definitions. Typical stems are "what is the root cause", "which change is most effective", "which approach satisfies every constraint". One question resolves most of this domain: should this be decided by the model (probabilistic) or by code (deterministic)?
| Task | Content | Common keywords |
|---|---|---|
| 1.1 | Agentic loop | stop_reason, tool_use, end_turn |
| 1.2 | Coordinator–subagent | hub-and-spoke, overly narrow decomposition |
| 1.3 | Subagent invocation | Task/Agent tool, allowedTools, AgentDefinition |
| 1.4 | Multi-step workflows | prerequisite gate, handoff |
| 1.5 | Hooks | PreToolUse, PostToolUse |
| 1.6 | Task decomposition | prompt chaining, integration pass |
| 1.7 | Sessions | --resume, fork_session |
1.1 Agentic loop
Lifecycle
The agentic loop works like this: send a request → inspect stop_reason → if it is "tool_use", run the tools → append the results to the history → send the next request. When stop_reason is "end_turn", Claude has its final answer and the loop stops. The Agent SDK and Claude Code run this loop for you. If you use the Messages API directly, you have to write it yourself.
while True:
resp = client.messages.create(model=MODEL, max_tokens=4096,
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
break # end_turn (handle other stop_reason values separately)
results = [run_tool(b) for b in resp.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results}) # a single message
Rules for appending tool results:
- Append the entire
resp.content(text and tool_use blocks), not just the text. - Each
tool_useneeds exactly onetool_resultwith a matchingtool_use_id. All results go in one user message, before any text. If you split each result into its own message, Claude will make fewer parallel tool calls. - When a tool fails, return a
tool_resultwithis_error: trueand a clear message; don't let an exception break the loop. - The next request must still include the
toolsparameter.
Key point
Tool results go into the context so that the model decides the next step itself based on the new information. This is what separates an agent (model-driven) from a decision tree or a pre-configured tool sequence.
Model-driven vs fixed workflows
| Criterion | Agent (model-driven) | Fixed workflow |
|---|---|---|
| Who chooses the next step | Claude, based on context and tool results | Code, in a predefined order |
| Best for | Steps that can't be predicted | Well-understood, repeatable processes |
| Strengths | Flexible, handles novel situations | Stable, easy to test and evaluate |
| Weaknesses | Harder to predict and measure | Solves only the tasks it was designed for |
The Building with the Claude API course recommends preferring workflows where possible and using agents only when you truly need the flexibility.
Stopping-condition anti-patterns
- Parsing natural language to decide when to stop, e.g. looking for "DONE" in the response.
- Using an arbitrary iteration cap as the primary stopping mechanism. The Agent SDK's
max_turnsormax_budget_usdare only safety nets: when exceeded, the run ends witherror_max_turns/error_max_budget_usd. - Treating the presence of text as a completion signal. A single response can contain both text ("Let me check…") and a tool_use block.
Exam trap
The option "cap the loop at 10 iterations so the agent doesn't run forever" sounds safe. But if the question asks for the primary stopping mechanism, the correct answer is stop_reason. max_tokens doesn't control the loop either: it limits the length of a single response. If stop_reason is max_tokens, the tool input may be truncated, and that tool must not be executed.
Other stop_reason values need their own handling: pause_turn (send the response back to continue) and refusal (don't run the tools from that turn).
(Sources: CCAR-F Exam Guide, Task 1.1; Anthropic Academy: Building with the Claude API — Tool use with Claude, Agents and tools, Environment inspection, Workflows vs agents; Anthropic Academy: Tool use with the Messages API — Parallel tool calling; Claude Docs: Troubleshooting tool use)
1.2 Coordinator–subagent
Hub-and-spoke
The coordinator (lead agent, orchestrator) is the central hub. It manages all communication between subagents and also handles errors and routing. Subagents don't talk to each other directly. Each subagent runs in an isolated context and does not inherit the coordinator's history.
Anthropic's Research system (closely matching Scenario 3) works like this: the lead agent plans a strategy, saves the plan to memory (context beyond 200,000 tokens gets truncated), then spawns subagents that run in parallel. Each subagent condenses its results before returning them. On internal evals, the multi-agent system (Claude Opus 4 as lead, Claude Sonnet 4 as subagents) outperformed single-agent Claude Opus 4 by 90.2%. The tradeoff is that it uses about 15× the tokens of a chat (a single agent uses about 4×). This architecture is a poor fit for work with many cross-dependencies, such as most coding tasks.
The coordinator selects subagents by complexity
The coordinator decomposes, delegates, and aggregates. It selects subagents based on query complexity instead of always running the full pipeline. Early versions of the Research system spawned 50 subagents for simple questions, so Anthropic added scaling rules to the prompt:
| Query type | Number of subagents | Tool calls |
|---|---|---|
| Fact lookup | 1 agent | 3–10 |
| Comparison | 2–4 subagents | 10–15 each |
| Complex research | More than 10, with clearly divided responsibilities | Depends on scope |
Overly narrow decomposition and duplication
- Too narrow: a broad topic is split into items that all belong to a single branch. Every subagent does exactly what it was assigned, yet the report still misses whole areas. The subtask list in the coordinator's log reveals the root cause.
- Duplication: vague task descriptions ("research the chip shortage") make subagents run the same queries. The fix is to partition the scope by subtopic or source type, with clear boundaries.
Exam trap
Every subagent "completes successfully", yet the report still misses an area of content: don't fix the search or synthesis subagent. The fault is upstream, in the coordinator's decomposition step. Downstream fixes can't make up for work that was never assigned.
Iterative refinement and observability
The coordinator should evaluate the synthesis for gaps, re-delegate targeted queries, and run synthesis again until coverage is sufficient. This is a variant of the evaluator–optimizer pattern. Routing all communication through the coordinator gives you observability of the information flow and consistent error handling. When output is large, a subagent can write artifacts to external storage and send only a reference back to the coordinator.
Scenario example
The research system receives "What year was Company X founded?" but still runs all four subagents, taking several minutes. The fix is to update the coordinator's prompt so it classifies complexity and invokes only the subagents it needs. Adding a cache or switching subagents to a cheaper model doesn't address the cause: the coordinator always runs the full pipeline.
(Sources: CCAR-F Exam Guide, Task 1.2; Anthropic Engineering: How we built our multi-agent research system; Claude Cookbooks: Building Effective Agents — Research lead agent prompt)
1.3 Subagent invocation and context passing
The Task tool and AgentDefinition
The coordinator spawns subagents with the Task tool. Per the Exam Guide, the coordinator's allowedTools must include "Task". Anthropic's cookbook notes that as of claude-agent-sdk 0.2 this tool was renamed to Agent, and the old name Task is still accepted. The call's input includes description, prompt, and subagent_type.
web_searcher = AgentDefinition(
description="Searches the web for ONE assigned subtopic. Returns claims with source URLs.",
prompt="Stay inside the assigned scope. Return JSON findings with sources.",
tools=["WebSearch", "WebFetch"])
options = ClaudeAgentOptions(
allowed_tools=["Agent"], # "Task" per the Exam Guide / older SDK
agents={"web-searcher": web_searcher, "synthesizer": synthesizer})
The three fields of AgentDefinition (in Claude Code, a .claude/agents/<name>.md file with frontmatter):
descriptiondetermines when the subagent is invoked, and influences what the coordinator writes in its prompt. If a subagent is rarely invoked, fix the description first.promptis the system prompt. Specify an output format so the subagent has a natural stopping point, and add an "Obstacles encountered" section.toolsrestricts permissions: a research subagent usesGlob,Grep,Read; a reviewer addsBashbut gets noEdit/Write.
Explicit context passing
A subagent starts with only its own system prompt and the task description the coordinator writes. It cannot see the coordinator's history and there is no shared memory between invocations. So you must include the complete findings from prior steps in the prompt, e.g. search results and document analysis for the synthesis subagent. Use a structure that separates content from metadata to preserve source attribution:
{"claim": "New solar installed capacity grew 35%",
"evidence_excerpt": "…installed capacity grew 35%…",
"source": {"url": "https://example.org/report", "page": 12, "published_date": "2026-03-01"}}
Exam trap
"The synthesis subagent automatically sees the search subagent's results because they are in the same system" is false. Data reaches a subagent only through the prompt it receives. Claude Code does have a forked subagent that inherits the full context, but that is a mode you must invoke explicitly, not the default.
Parallel spawning and prompt writing
To run in parallel, the coordinator emits multiple Task tool calls in a single response. The Research system spawns 3–5 subagents in parallel and cut time by up to 90% on complex queries. A subagent prompt should state the goal, quality criteria, output format, and boundaries, not a step-by-step procedure. A rigid procedure leaves the subagent unable to adapt when reality differs from expectations.
Exam tip
Coordinator never invokes subagents → check allowedTools. Subagent returns generic results → context wasn't passed in full. Citations lost → you need a structure that separates metadata. Slow because calls run one after another → emit multiple Task calls in one response.
(Sources: CCAR-F Exam Guide, Task 1.3; Claude Cookbooks: Claude Agent SDK — The Chief of Staff Agent, Migrating from the OpenAI Agents SDK; Anthropic Academy: Introduction to subagents — What are subagents?, Creating a subagent, Designing effective subagents; Claude Code Docs: Run agents in parallel)
1.4 Multi-step workflows: enforcement and handoff
Prompt-based vs programmatic enforcement
| Criterion | Prompt (system prompt, few-shot) | Programmatic (hook, prerequisite gate) |
|---|---|---|
| Nature | Probabilistic: the model usually complies | Deterministic: code always blocks |
| Failure rate | Non-zero even with a good prompt | Zero for the conditions you have implemented |
| Best for | Judgment, tone | Mandatory ordering, financial thresholds |
When a violation has financial or legal consequences, such as issuing a refund before verifying identity, relying on the prompt alone is not enough.
Prerequisite gate
In Scenario 1, process_refund is blocked until get_customer has returned a verified customer ID. The "verified" state is recorded by code from the tool result, not from the model's own claim.
async def require_verified(input_data, tool_use_id, context):
if input_data["tool_input"].get("customer_id") not in verified:
return {"hookSpecificOutput": {"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Call get_customer first."}}
return {}
hooks = {"PreToolUse": [HookMatcher(matcher="mcp__support__process_refund",
hooks=[require_verified])]}
The reason for the block is returned to Claude, so the agent knows to complete the prerequisite step instead of getting stuck.
Multi-issue requests and handoff
When a customer raises several issues at once (broken item, double charge, address change), the agent should separate each issue, investigate them in parallel using shared context (the same customer ID), then deliver one unified resolution.
The person receiving an escalation has no transcript. So escalate_to_human must carry a self-contained summary: customer ID, root cause, refund amount, what has been done, why it was blocked, and the recommended action.
Scenario example
The system prompt already says "always verify the customer before issuing a refund" and includes few-shot examples, yet 3% of refunds still skip verification. The right fix is a programmatic prerequisite gate. A stronger prompt only lowers the failure rate; it doesn't bring it to zero.
(Sources: CCAR-F Exam Guide, Task 1.4, Exercise 1; Anthropic Academy: Claude Code 101 — Hooks; Claude Cookbooks: Claude Agent SDK — The SRE Incident Response Agent)
1.5 Agent SDK hooks
Main events
A hook is deterministic code that runs at a fixed point in the loop. The Agent SDK declares hooks through ClaudeAgentOptions(hooks=...) with HookMatcher.
| Event | When | Used for |
|---|---|---|
PreToolUse |
Before the tool runs | allow / deny / ask, rewrite input (updatedInput) |
PostToolUse |
After the tool runs successfully | Normalize results, audit logging; cannot block |
UserPromptSubmit |
When a prompt is submitted | Validate user input |
Stop / SubagentStop |
When the agent is about to finish | Refuse to finish if conditions aren't met |
PreToolUse uses deny with a permissionDecisionReason to block and redirect, e.g. "Refund exceeds $500 USD; call escalate_to_human". updatedInput replaces the entire input object. For script hooks, only exit code 2 blocks (stderr is sent to Claude); exit 1 is just a non-blocking error.
PostToolUse normalizes heterogeneous data before the model processes it. For example, one MCP tool returns Unix timestamps, another returns ISO 8601, and a third returns numeric status codes; the hook converts them all to a single format.
Exam trap
To prevent an action with side effects you must use PreToolUse, because PostToolUse runs after the tool has already executed. Also, an Edit|Write hook matcher does not fire when the agent edits files with shell commands through Bash.
Key point
"If something must happen every time, without exception, put it in a hook, not a prompt." Prompts, CLAUDE.md, and skills are advisory controls; hooks are the deterministic layer.
(Sources: CCAR-F Exam Guide, Task 1.5; Anthropic Academy: Claude Code in action — Hooks; Anthropic Academy: Claude Code 101 — Hooks; Anthropic Academy: The AI-native SDLC playbook — Skills as institutional knowledge; Claude Cookbooks: Claude Agent SDK — The SRE Incident Response Agent, Migrating from the OpenAI Agents SDK)
1.6 Decomposing complex tasks
| Criterion | Prompt chaining (fixed) | Dynamic (adaptive) decomposition |
|---|---|---|
| Structure | Predefined sequence of steps | Subtasks generated from what each step discovers |
| Best for | Predictable, checklist-style reviews | Open-ended investigation, exploring unfamiliar codebases |
| Risk | Misses anything outside the plan | Cost is hard to predict |
The orchestrator–workers pattern in the cookbook is dynamic decomposition: the orchestrator decides the subtasks at runtime. Don't use this pattern when the subtasks are always the same or when latency is the deciding factor.
Multi-file PR review: reviewing everything in one pass causes attention dilution: some files get scrutinized, others get skipped. The right approach is a per-file pass for each file, plus an integration pass that examines cross-file data flow and interfaces. A bigger context window does not solve the attention problem.
Open-ended tasks such as "add comprehensive tests to a legacy codebase": map the structure first, identify high-impact areas, create a prioritized plan, and adapt as dependencies are discovered. The Effective harnesses article suggests creating a JSON feature list (every item starts as "passes": false) and a claude-progress.txt file. Each session handles just one feature and then commits, avoiding attempts to do everything at once or declaring the work done too early.
Exam trap
A sequential subagent pipeline "reproduce bug → debug → fix" tends to fail: each step depends on what the previous step found, and information is lost at every handoff. Subagents suit work where the intermediate process doesn't matter, such as research or review.
Scenario example
The per-file passes on a 12-file PR are all thorough, yet a bug still slips through: calc_tax() changed its parameters in tax.py, but invoice.py still calls it the old way. What's missing is a cross-file integration pass. Re-running the per-file passes or using a model with a larger context won't catch this class of bug.
(Sources: CCAR-F Exam Guide, Task 1.6; Anthropic Academy: Building with the Claude API — Agents and workflows; Claude Cookbooks: Building Effective Agents; Anthropic Engineering: Effective harnesses for long-running agents; Anthropic Academy: Introduction to subagents — Using subagents effectively)
1.7 Sessions: resume and fork
- CLI:
claude --resume <session-name>continues a named investigation session. - Agent SDK:
query()is stateless;ClaudeSDKClientkeeps the conversation in memory. SaveResultMessage.session_id, then useClaudeAgentOptions(resume=session_id). Transcripts live on local disk (~/.claude/projects/); they survive a restart but are not shared to other machines automatically. fork_sessioncopies the transcript into a new session and leaves the original unchanged; you can fork at a specific point withup_to_message_id. A fork doesn't run on its own: you mustresume=fork.session_id. Use case: branch two ways from a shared analysis to compare two testing or refactoring strategies.
| Option | When | Example |
|---|---|---|
| Resume | Prior context is mostly still valid | Nightly dependency audit compared with the previous run |
| New session + summary | Old tool results are stale; only the conclusions are needed | Checking last week's TODOs |
| Completely new session | Each run must be evaluated independently | CI reviewer that blocks PRs |
When resuming after code changes, state exactly which files changed so the agent re-analyzes the right places. Otherwise the agent may answer from content it read in an earlier turn and miss the new files.
Key point
Durable state for long-running tasks should live outside the context window: progress files, manifests, plans in memory, git commits. After a crash, the system resumes from a checkpoint instead of starting over.
Exam tip
Compare two directions from the same analysis → fork_session. Continue yesterday's investigation → --resume. A large refactor has made old tool results stale → new session with a summary.
(Sources: CCAR-F Exam Guide, Task 1.7; Claude Cookbooks: Claude Agent SDK — Migrating from the OpenAI Agents SDK, Building a Session Browser, Build a Scheduled Repository Reviewer; Anthropic Academy: Claude Code in action — Scheduled tasks and headless)
Quick summary
- Continue the loop when
stop_reason == "tool_use", stop on"end_turn". Don't parse text, and don't use an iteration cap as the primary stopping mechanism. - Each
tool_useneeds onetool_resultwith the same id. All results go in one user message. A failed tool returnsis_error: true. max_turns/max_budget_usdare only safety nets. Astop_reasonofmax_tokensmeans the tool input may be truncated.- Hub-and-spoke: the coordinator handles all communication, errors, and routing. Subagents have isolated context.
- The coordinator selects subagents by query complexity: a simple lookup uses 1 agent with 3–10 tool calls.
- Report misses areas of content → the coordinator decomposed too narrowly. Duplication → partition by subtopic or source type.
- The coordinator's
allowedToolsneeds"Task"(new name"Agent").descriptiondetermines when a subagent is invoked. - Pass context explicitly in the subagent prompt, and separate content from metadata to preserve citations.
- Parallel spawning = multiple Task calls in one response. Subagent prompts state goals and criteria, not individual steps.
- Rules with financial consequences → prerequisite gate or
PreToolUse, because prompts have a non-zero failure rate. - Self-contained handoff: customer ID, root cause, amount, recommended action.
PostToolUsenormalizes results before the model processes them. Script hooks block only on exit code 2.- Multi-file review: per-file passes plus an integration pass.
fork_sessionto branch and compare. Stale tool results → new session with a summary.