Skip to content
CCAF Preparation

Domain 1 · 27% of exam

Agentic Architecture & Orchestration cheat sheet

1.1 — Agentic Loops

stop_reasonHandling
tool_useRun the tool(s), return result(s), continue loop
end_turnUse the response — loop terminates
pause_turnAppend assistant response to messages, re-request — NOT done
max_tokensRaise max_tokens or continue the response
stop_sequenceRead stop_sequence field to see which fired
refusalRead stop_details, retry on a fallback model
model_context_window_exceededTreat as truncated
  • Loop exits on any value other than tool_use. Exit ≠ task complete.
  • tool_use block: id, name, input. tool_result block: tool_use_id, content, is_error.
  • tool_result lives in a user message; must immediately follow the tool_use message; all tool_result blocks before any text.
  • Parallel calls: one tool_result per tool_use, all in one user message. Skipped call still needs is_error: true.
  • Anti-patterns: NL parsing of "I'm done"; iteration caps as primary stop mechanism (safety net only — SDK: max_turns); checking content[0].type == "text" (text can accompany tool_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

  • allowedTools must include Task/Agent or the coordinator cannot spawn subagents at all.
  • AgentDefinition: description (req), prompt (req, not systemPrompt), tools (opt — omit = all tools available to subagents), model (opt — fable/opus/sonnet/haiku/inherit/full ID).
  • 3 ways to define: programmatic (agents option) > filesystem (.claude/agents/) > built-in general-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, default false): forks resume to 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. Hook allow does NOT skip deny/ask rules.
  • canUseTool only fires when the flow falls through to a prompt — skipped by acceptEdits/bypassPermissions/allow rules. For a check that must run on every call → use a PreToolUse hook instead (runs before every other step; deny applies even under bypassPermissions).
  • 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.matcher tests against the tool name (e.g. "Write|Edit", or regex ^mcp__); no matcher = fires for every event of that type.
  • PreToolUse output: permissionDecision ∈ {allow, deny, ask, defer}, permissionDecisionReason, updatedInput.
    • updatedInput + allow → auto-approves the rewritten call.
    • updatedInput alone (no decision) → still applies, flows through normal evaluation.
  • PostToolUse output: additionalContext (appends alongside original) vs updatedToolOutput (replaces result before Claude sees it — right choice for normalisation).
  • Decision priority: deny > defer > ask > allow. Any hook deny blocks the op regardless of others.
  • {} = allow unchanged. Every hook output can carry systemMessage and continue/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

PatternAnthropic nameUse when
Fixed sequential pipelinePrompt chainingPredictable, structured (code review, extraction)
Dynamic adaptive decompositionOrchestrator-workersOpen-ended, unknown scope (legacy exploration, audits)
Classify + dispatchRoutingDistinct categories handled differently (cheap vs capable model)
Independent subtasks in parallelParallelization — sectioninge.g. guardrail screening separate from main response
Same task run N timesParallelization — votingDiverse outputs / confidence (multiple vuln reviews)
Generate + critique loopEvaluator-optimizerClear 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. plan and bypassPermissions are 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_session does 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.