Domain 1 · 27% of exam
Agentic Architecture & Orchestration cheat sheet
1.1 — Agentic Loops
| stop_reason | Handling |
|---|---|
tool_use | Run the tool(s), return result(s), continue loop |
end_turn | Use the response — loop terminates |
pause_turn | Append assistant response to messages, re-request — NOT done |
max_tokens | Raise max_tokens or continue the response |
stop_sequence | Read stop_sequence field to see which fired |
refusal | Read stop_details, retry on a fallback model |
model_context_window_exceeded | Treat as truncated |
- Loop exits on any value other than
tool_use. Exit ≠ task complete. tool_useblock:id,name,input.tool_resultblock:tool_use_id,content,is_error.tool_resultlives in a user message; must immediately follow thetool_usemessage; alltool_resultblocks before any text.- Parallel calls: one
tool_resultpertool_use, all in one user message. Skipped call still needsis_error: true. - Anti-patterns: NL parsing of "I'm done"; iteration caps as primary stop mechanism (safety net only — SDK:
max_turns); checkingcontent[0].type == "text"(text can accompanytool_use).
1.2 — Orchestration Patterns
- Orchestrator-workers = hub-and-spoke. Defining trait: subtasks determined dynamically, not pre-defined (that's parallelization instead).
- All inter-subagent comms flow through the coordinator → observability, consistent error handling, controlled information flow.
- Token cost: agents ≈ 4x chat; multi-agent ≈ 15x chat. Only justified when task value clears that premium.
- Effort scaling: simple fact = 1 agent/3-10 calls · comparison = 2-4 subagents/10-15 calls each · complex research = 10+ subagents.
- Two parallelization levels: lead spins 3-5 subagents in parallel; each subagent runs 3+ tools in parallel.
- Narrow decomposition failure: coordinator never assigns a whole category → no subagent can cover it. Root cause = coordinator, not subagents.
- Duplicated-work failure: vague per-subagent task descriptions → same topic researched twice, another missed. Fix: objective + output format + source guidance + boundaries per subagent.
- Poor fit: shared-context/high-dependency domains, most coding tasks, real-time cross-agent coordination.
1.3 — Subagent Invocation & Context Passing
allowedToolsmust includeTask/Agentor the coordinator cannot spawn subagents at all.AgentDefinition:description(req),prompt(req, notsystemPrompt),tools(opt — omit = all tools available to subagents),model(opt —fable/opus/sonnet/haiku/inherit/full ID).- 3 ways to define: programmatic (
agentsoption) > filesystem (.claude/agents/) > built-ingeneral-purpose. Programmatic wins name clashes. - Claude auto-selects a subagent from its
description; can also be named explicitly. - Context isolation: only the Agent tool's prompt string crosses parent→subagent. No history, no system prompt, nothing else unless written into that prompt. Intermediate tool calls stay inside the subagent — only the final message returns.
- Parallel subagents finish in time of the slowest, not the sum — spawn via multiple Agent/Task calls in one coordinator response.
- Structured context passing: separate content (claim) from metadata (source_url, document_name, page_number) or downstream agents can't attribute claims.
fork_session/forkSession(bool, defaultfalse): forksresumeto a new session ID; copies history to that point; original ID/history unchanged → two independent sessions.
1.4 — Workflow Enforcement & Handoff
- Permission evaluation order: hooks → deny rules → ask rules → permission mode → allow rules →
canUseTool. - Deny rule blocks even under
bypassPermissions. Hookallowdoes NOT skip deny/ask rules. canUseToolonly fires when the flow falls through to a prompt — skipped byacceptEdits/bypassPermissions/allow rules. For a check that must run on every call → use aPreToolUsehook instead (runs before every other step; deny applies even underbypassPermissions).disallowedTools: ["Bash"]removes the tool entirely.disallowedTools: ["Bash(rm *)"]keeps it visible, denies only matching calls, in every mode.- Decision rule: single-failure cost = financial/security/compliance → programmatic enforcement (hooks/gates). Formatting/style → prompt guidance is fine.
- Handoff summary must include: customer ID, conversation summary, root cause, refund amount, recommended action — human agent has NO transcript access.
- Multi-concern requests: decompose → investigate in parallel with shared context → synthesise one unified resolution.
1.5 — Agent SDK Hooks
- Both Python + TypeScript:
PreToolUse,PostToolUse,PostToolUseFailure,UserPromptSubmit,Stop,SubagentStart,SubagentStop,PreCompact,PermissionRequest,Notification. - TypeScript-only:
SessionStart,SessionEnd. HookMatcher.matchertests against the tool name (e.g."Write|Edit", or regex^mcp__); no matcher = fires for every event of that type.PreToolUseoutput:permissionDecision∈ {allow,deny,ask,defer},permissionDecisionReason,updatedInput.updatedInput+allow→ auto-approves the rewritten call.updatedInputalone (no decision) → still applies, flows through normal evaluation.
PostToolUseoutput:additionalContext(appends alongside original) vsupdatedToolOutput(replaces result before Claude sees it — right choice for normalisation).- Decision priority:
deny>defer>ask>allow. Any hookdenyblocks the op regardless of others. {}= allow unchanged. Every hook output can carrysystemMessageandcontinue/continue_.- PostToolUse = after exec (normalise data). PreToolUse = before exec (block/redirect). Using PostToolUse to block is always wrong — the action already happened.
1.6 — Task Decomposition Strategies
| Pattern | Anthropic name | Use when |
|---|---|---|
| Fixed sequential pipeline | Prompt chaining | Predictable, structured (code review, extraction) |
| Dynamic adaptive decomposition | Orchestrator-workers | Open-ended, unknown scope (legacy exploration, audits) |
| Classify + dispatch | Routing | Distinct categories handled differently (cheap vs capable model) |
| Independent subtasks in parallel | Parallelization — sectioning | e.g. guardrail screening separate from main response |
| Same task run N times | Parallelization — voting | Diverse outputs / confidence (multiple vuln reviews) |
| Generate + critique loop | Evaluator-optimizer | Clear eval criteria, refinement adds value (translation) |
- Prompt chaining trades latency for accuracy; supports gates (programmatic checks between steps).
- Adaptive decomposition needs ground truth from the environment each step, plus a stopping condition (safety bound, not completion signal).
- Attention dilution: too many items in one pass → inconsistent depth, same pattern flagged in one file/approved in another. NOT fixed by a bigger model or context window — fix is multi-pass: per-item local passes + a separate cross-item integration pass.
- Batching without a cross-file integration pass still misses cross-cutting issues.
1.7 — Session State, Resumption & Forking
- Storage:
~/.claude/projects/<encoded-cwd>/*.jsonl(cwd with non-alphanumerics →-). Wrong directory = most common cause of "resume returns empty session." - Resume restores: full history (tool calls + results), model, agent, permission mode, goals, unexpired scheduled tasks.
planandbypassPermissionsare NEVER restored. --continue: most recent session in cwd, no ID tracking.--resume <id|name>: specific session, ID must be tracked (capture via--output-format json→.session_id).- Fork = new session ID + copy of history to the fork point; original ID/history unchanged → two independently resumable sessions, separate picker rows.
- Sessions persist conversation only, not files. File revert = checkpointing (separate system; one checkpoint per prompt; does NOT track Bash-made changes, only Claude's own edit tools).
- Stale context problem: resuming after file edits leaves old tool results in history — agent gives contradictory advice even after re-reading changed files.
- Fix: fresh session + injected structured summary + explicit list of changed files for targeted re-analysis.
fork_sessiondoes NOT fix this (it inherits the same stale history). - Decision rule: prior context still valid → resume. Comparing divergent approaches → fork. Tool results stale/context degraded → fresh start + summary.