🎓 Claude Certification Prep

Home › CCDV-F › M01

Agents and Workflows

Domain 1 17% of exam 60 practice questions ~18 min read

Choose a workflow or an agent based on business requirements, decompose work into orchestrator and subagents, choose a runtime (self-hosted harness or Managed Agents), build agents with the Agent SDK using deterministic hooks, and read traces to diagnose missing patterns.

Skills measured in this domain:
  • Architecture and Runtime Selection: workflow vs agentic, self-hosted harness vs managed sandboxed runtime; orchestrator/subagent decomposition
  • Agent SDK Construction and Hooks: agent definitions, custom loops and harnesses, hooks so required actions execute deterministically
  • Agent Pattern Diagnosis from traces: missing or misapplied patterns (tool-use loop termination, subagent isolation, memory, context management)

Domain overview

Domain 1, Agents and Workflows, accounts for 17% of the CCDV-F exam version effective Dec 7 (about 10 of the 60 scored items) and covers three skills:

Skill (Exam Guide) What the exam measures
Architecture and Runtime Selection Choosing a workflow or an agent based on business requirements, error tolerance, and audit constraints; orchestrator/subagent decomposition; choosing a self-hosted harness or a managed, sandboxed runtime
Agent SDK Construction and Hooks Writing agent definitions, custom loops/harnesses, and hook configurations so that required actions execute deterministically rather than at the model's discretion
Agent Pattern Diagnosis Reading a trace to identify a missing or misapplied pattern: tool-use loop termination, subagent isolation, memory, context-window management

The old version (through Dec 6) weighted this domain at 14.7% and also covered third-party frameworks (Strands, LangGraph, PydanticAI); the new version focuses on architecture decisions and diagnosis. Items typically present a constrained scenario or a trace excerpt and ask for the best option — wrong options usually "work" but violate a constraint.

(Sources: CCDV-F Exam Guide from Dec 7, Domain 1; CCDV-F Exam Guide through Dec 6)

Choosing an architecture: workflow or agent

Two core concepts

  • Workflow (predefined process): a sequence of Claude calls following steps you design in advance — use one when you can map out the entire flow.
  • Agent: Claude runs in a loop, is given a goal and a set of tools, and decides the next step itself. Claude Platform 101 sums it up: "You own the loop and the tools. Claude owns the reasoning."

The recommendation from the Building with the Claude API course: use workflows whenever you can, and agents only when you truly need them.

Criterion Workflow Agent
Control flow Known in advance, fixed Not known in advance, depends on the data
Predictability and audit High — every step has a clear log Lower — the path changes on every run
Eval and testing Easy, test each step, higher accuracy Hard, lower completion rate
Token cost Low, stable High (about 4× chat)

Four workflow patterns

Pattern How it works Signals in the item
Chaining Sequential steps; non-LLM processing (validation, formatting) can be inserted between steps A later step depends on an earlier one; intermediate checks are needed
Routing Classify the input, then send it to exactly one specialized pipeline Several request types that need different prompts
Parallelization Split out independent parts, run them in parallel, merge the results Several independent criteria; latency must be reduced
Evaluator-optimizer A producer generates, a grader scores and returns feedback, repeat until it passes Quality criteria that can be checked

Business requirements drive the architecture

  • Low error tolerance, irreversible actions (money transfers, data deletion): a workflow, or an agent with a human-in-the-loop checkpoint before the irreversible action.
  • Audit constraints: deterministic logging at the code layer (workflow steps, hooks), not relying on the model to "remember to log".
  • Open-ended input, unpredictable number of steps (incident investigation, research): an agent.

When you build an agent, give it abstract, composable tools (bash, read, write, edit, glob, grep) and a way to verify the environment (read before writing, take a screenshot after an action) — ask yourself "How will Claude know if this action worked?"

Key point

An agent is not "smarter" than a workflow; it trades predictability for flexibility. When an item describes a process with clear steps and strict audit requirements, the "free-roaming agent" option is almost certainly wrong.

Exam trap

"A single agent with enough tools to handle every case" sounds modern but is wrong when the flow is known in advance. Conversely, forcing an open-ended investigation into fixed chaining breaks as soon as it hits a case outside the script.

(Sources: Anthropic Academy: Building with the Claude API (workflows & agents); Anthropic Academy: Claude Platform 101)

Orchestrator–subagent decomposition

When subagents help

In the orchestrator-worker pattern, the lead agent plans and delegates; each subagent has its own context window, receives only its own system prompt plus the task description, and returns only a summary. The noisy exploration stays in the subagent's context, and the orchestrator's context stays clean.

Figures from Anthropic's multi-agent research system: the multi-agent system (Opus 4 lead, Sonnet 4 subagents) outperformed a single Opus 4 agent by 90.2%; token usage explains 80% of the performance variance; the multi-agent system uses about 15× the tokens of chat. Multi-agent is worth the cost when the task is high-value, parallelizable, and exceeds a single context window; it is a poor fit when agents need shared context or depend heavily on each other — most coding tasks fall into this group.

The deciding question and anti-patterns

The Introduction to Subagents course boils it down to one question: "Does the intermediate work matter?" If you only need the conclusion → subagent; if you need to see each step → keep it in the main context. Three anti-patterns: subagents only to "play an expert" (expert claims); sequential pipelines with dependencies (information is lost at every handoff); subagents that run tests (they hide the failure output the main agent needs).

Delegating properly

The orchestrator must give each subagent an objective, an output format, the tools/sources to use, and task boundaries — without them, subagents duplicate work or leave gaps. Effort must also scale with complexity: a simple lookup needs 1 agent with 3–10 tool calls; a comparison needs 2–4 subagents; only complex research needs more than 10. Classic failure: spawning 50 subagents for a simple question. For Claude Code/Agent SDK subagents, the description determines when the subagent is invoked; restrict tools (a reviewer is read-only) and require structured output so there is a natural stopping point.

Multi-agent in Managed Agents

The orchestrator declares multiagent: {"type": "multiagent_20261001"}. All agents share the sandbox, the filesystem, and credentials from the vault, but each agent runs in its own session thread with isolated context; a subagent's thread keeps its history for later exchanges. Only one level of delegation is allowed: referencing an agent that itself has multiagent returns a 400 error.

Scenario example

A team creates 5 subagents to edit 5 files of one module in parallel, and those files constantly call each other; the result is broken code because each subagent is unaware of the others' changes. Reasoning: tightly coupled coding is a poor case for multi-agent; let a single agent hold the full context, and use subagents only for reading/exploration (finding call sites) that return summaries.

Exam trap

"Adding subagents always improves accuracy" is wrong. Subagents cost many times more tokens, lose information at handoffs, and hide intermediate output. Choose them only when the work is parallelizable and the parent agent does not need to see intermediate results.

(Sources: Anthropic Engineering: How we built our multi-agent research system; Anthropic Academy: Introduction to subagents; Claude Docs: Multiagent orchestration)

Choosing a runtime: self-hosted harness or managed sandboxed runtime

Three options

  1. Write your own loop on the Messages API (or use the Tool Runner, client.beta.messages.tool_runner(...)): full control over the loop, tools, and state.
  2. Claude Agent SDK: the Claude Code harness as a Python/TypeScript library. You host it yourself: query() spawns a claude CLI subprocess over stdio; transcripts, CLAUDE.md, and the working directory live on local disk and are lost when the container restarts — unless you configure a SessionStore to mirror transcripts externally.
  3. Claude Managed Agents: Anthropic hosts both the harness and the sandbox. Four primitives: Agent (model, system prompt, toolset), Environment (cloud or self-hosted; networking limited with allowed_hosts, or unrestricted), Session (a unit of work with its own sandbox), Events (agent.message, agent.tool_use, session.status_idle…).
Criterion Self-hosted (Messages API / Agent SDK) Managed Agents
Who runs the loop Your code and infrastructure Anthropic; the harness is decoupled from the sandbox
Session state You persist it (the Agent SDK needs SessionStore) Server-side append-only log; reconnect by listing past events
Credentials You manage them, preferably through a proxy Vault; credentials never sit in the sandbox
Long tasks, surviving failures You build checkpoint/resume yourself Long-lived sessions, checkpointed when idle
Data must stay in the VPC Naturally Self-hosted environment: code, filesystem, and egress stay in the VPC
Loop control Maximum Lower, in exchange for less operational work

Claude Platform 101: choose Managed Agents when the loop runs long, does a lot of work, and must survive hiccups; write your own loop when you need full control. The Managed Agents blog calls this "decoupling the brain from the hands": the harness is independent of the sandbox, so time to first token drops (about 60% at p50, more than 90% at p95).

Agent SDK in production

  • One session maps to one subprocess; a starting point is 1 GiB RAM, 5 GiB disk, 1 CPU; token costs usually exceed infrastructure costs.
  • Session types: ephemeral (one-shot, with max_turns), long-running (ClaudeSDKClient in Python), hybrid (continue with resume=session_id plus session_store).
  • Multi-tenant: setting_sources=[], CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, a separate CLAUDE_CONFIG_DIR and cwd per tenant; credentials through a proxy (ANTHROPIC_BASE_URL) instead of putting the key in the container.

Exam trap

The Agent SDK is not hosted by Anthropic. "The container restarts and the agent loses its entire session history" → state lives on local disk; fix it with SessionStore (or move to Managed Agents), not by raising max_turns.

Exam tip

"Runs for hours", "don't want to operate a sandbox", "reconnect after a network drop" → Managed Agents. "Full control over the loop" → write your own loop. "Code must not leave the VPC" → a self-hosted Agent SDK or a self-hosted environment.

(Sources: Anthropic Academy: Claude Platform 101; Claude Blog: The evolution of agentic surfaces: building with Claude Managed Agents; Claude Code Docs: Hosting the Agent SDK)

Building agents with the Agent SDK

Configuration through ClaudeAgentOptions

options = ClaudeAgentOptions(
    model="claude-opus-5-5",
    system_prompt=SRE_PROMPT,
    mcp_servers={"sre": sre_server},
    allowed_tools=["mcp__sre__read_config", "Agent"],
    disallowed_tools=["Bash"],
    max_turns=20,
    max_budget_usd=2.0,
    setting_sources=[],
    agents={"log-reader": AgentDefinition(
        description="Reads and summarizes logs when investigating errors.",
        prompt=LOG_READER_PROMPT,
        tools=["Read", "Grep"])},
)
async for message in query(prompt="Investigate the pool size error", options=options):
    ...
  • allowed_tools is a pre-approved list (runs without asking), not a restriction. To keep a tool away from the model → disallowed_tools (removes it from context); tools determines which built-in tools exist. MCP tool names: mcp__{server}__{tool}.
  • permission_mode: default, acceptEdits, bypassPermissions, plan, dontAsk.
  • Subagents: AgentDefinition(description, prompt, tools) in agents={...}, and the Agent tool (formerly Task) must be allowed. The orchestrator delegates but keeps control (unlike a handoff mechanism, which transfers control entirely). On the filesystem: .claude/agents/*.md with frontmatter name, description, tools, model.
  • Exceeding max_turns/max_budget_usd → an error result, error_max_turns/error_max_budget_usd; the budget is checked after spending, so it can be slightly exceeded.
  • Message flow: SystemMessage, AssistantMessage, UserMessage (carries tool results), ResultMessage always last (result, usage, total_cost_usd, session_id, is_error).
  • Since SDK 0.2, if setting_sources is not set, the SDK loads user/project settings; hooks in .claude/settings.local.json run only when the "local" source is included.

Custom harness for long-running tasks

From "Effective harnesses for long-running agents": compaction is not enough; an agent working across many context windows still tries to do everything in one go and runs out of context midway, declares the job done too early, or marks features complete without testing them. The two-role solution:

  • Initializer agent: creates init.sh, a progress file claude-progress.txt, the first git commit, and a JSON feature list with "passes": false (JSON is less likely than Markdown to be overwritten arbitrarily).
  • Coding agent, in each session: reads the progress file and git log, runs a basic end-to-end test, works on one feature at a time, commits with notes, and tests with browser automation before marking a feature as passing.

Key point

The harness is the code around the model: loop, tools, state, stop conditions. The harness must evolve with the model — the context-reset mechanism that cured "context anxiety" in Sonnet 4.5 became unnecessary with Opus 4.5.

(Sources: Claude Cookbooks: Claude Agent SDK; Anthropic Engineering: Effective harnesses for long-running agents)

Hooks: making required actions deterministic

CLAUDE.md and the system prompt are requests: the model follows them most of the time but can skip them. A hook is code that runs at a fixed point in the agent lifecycle — Claude cannot skip it. Hard rules (never push to main, write audit logs, validate before editing config) belong in hooks.

Event When Used to
PreToolUse Before a tool runs Block, allow, ask, modify input — the main enforcement point
PostToolUse After a tool runs successfully Log, format, check; too late to block
Stop / SubagentStop When the agent is about to end its turn Refuse to stop until the conditions are met
UserPromptSubmit When the user submits a prompt Block or add context
SessionStart (matcher compact) The session restarts after compaction Reload critical context
{"hooks": {"PreToolUse": [{
  "matcher": "mcp__sre__edit_config_file",
  "hooks": [{"type": "command",
             "command": "bash ${CLAUDE_PROJECT_DIR}/hooks/validate_pool_size.sh"}]
}]}}
  • Exit codes: 0 = success; 2 = block, and stderr is fed back to Claude so it can correct itself; any other code (including 1) is a non-blocking error.
  • PreToolUse can print JSON {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}} with allow, deny, ask, or defer; updatedInput replaces the entire tool input rather than merging.
  • A matcher can carry an if, for example "if": "Bash(curl *)"; the /hooks command shows which hooks are loaded.
  • Agent SDK: hooks are callbacks, hooks={"PreToolUse": [HookMatcher(matcher=..., hooks=[fn])]}. A Stop hook runs after the response and cannot rewrite the output.
  • Plugin hooks add to your hooks; neither replaces the other.

Exam trap

Three common mistakes: putting the blocking check in PostToolUse (the tool has already run); a script exiting with code 1 and assuming it blocked (only code 2 blocks); reloading context after compaction with PostCompact (the correct choice is SessionStart with matcher compact).

Scenario example

Audit requirement: every process_refund call must check the limit and be logged. The system prompt already says "always call check_limit first," but traces show 3% of turns skip it. Reasoning: a mandatory requirement with a nonzero miss rate → a PreToolUse hook matching process_refund that blocks when no check result exists; PostToolUse for logging. Adding "IMPORTANT" to the prompt does not make the requirement deterministic.

(Sources: Anthropic Academy: Claude Code in action (hooks, CLAUDE.md, plugins); Claude Cookbooks: Claude Agent SDK)

Diagnosing patterns from traces

Tool-use loop that does not terminate correctly

The loop must branch on stop_reason: end_turn → done; tool_use → run the tool, send a tool_result, call again; any other value (max_tokens, refusal…) → exit or handle separately. Without this branching, a response cut off at max_tokens adds nothing to messages, so the loop resends the exact same request and you pay every time. Other signs:

  • stop_reason: "pause_turn" (a long-running server tool) treated as the end → send the response content back as the assistant turn so Claude can continue.
  • 400 error tool_use ids were found without tool_result blocks immediately after → each tool_use needs exactly one tool_result, placed before any text.
  • A tool fails → return a tool_result with is_error: true; do not skip it.
  • An Agent SDK agent loops forever → set max_turns and read ResultMessage to tell success from error_max_turns.

Subagent isolation and memory

Missing isolation: the main agent's context bloats with exploration output. Wrong isolation: subagents duplicate work (vague delegation) or information gets distorted across many handoffs — have subagents write results to the filesystem and pass on only lightweight references. Subagents in Managed Agents share a filesystem; in Claude Code, isolate files with git worktrees.

The context window is not long-term memory. The right mechanisms: a progress file + a JSON feature list + git log; the memory tool memory_20250818 (Claude reads and writes a memory directory through tool calls; you implement the client-side storage); Managed Agents memory stores; SessionStore for the Agent SDK. In multi-tenant systems, auto memory can leak data between tenants → turn it off.

Context-window management

Mechanism Identifier / beta Problem it solves
Server-side compaction compact_20260112, beta compact-2026-01-12 The whole conversation is too long → summarize the entire transcript (lossy)
Tool-result clearing clear_tool_uses_20250919, beta context-management-2025-06-27 Old tool results that can be re-fetched → replaced with a placeholder, keeping the tool_use record
Memory tool memory_20250818 Information that must survive across sessions/resets
Just-in-time context, fresh subagents Design pattern Load data only when needed; for long tasks, summarize each phase and spawn a subagent with a clean context
Symptom in the trace Missing / misapplied pattern
The same request repeats, cost climbs The loop does not handle max_tokens/refusal
The next session doesn't know what the previous one did Missing memory / progress file
After compaction, the agent forgets project rules Missing SessionStart with matcher compact
Reads many large documents, quality gradually declines Missing tool-result clearing or subagents
Reports "done" but tests have not run Missing verification step (Stop hook, e2e test)

Key point

Errors in agent systems are stateful and compound. Production needs full tracing, resuming from checkpoints instead of rerunning from scratch, and rainbow deployments so that in-flight agents don't break.

Scenario example

A research agent's trace: turns 1–12 call fetch_document, each result about 40K tokens; from turn 9 onward the answers contradict data already read, with no API errors. Reasoning: old tool results fill the window and degrade quality (context rot), and they can be re-fetched → tool-result clearing, or hand the reading to a subagent that returns summaries. Raising max_tokens is irrelevant because it is an output limit.

(Sources: Anthropic Academy: Claude Platform 101; Claude Cookbooks: Tool use; Claude Docs: Troubleshooting tool use)

Quick summary

  • Domain 1 = 17%: Architecture and Runtime Selection, Agent SDK Construction and Hooks, Agent Pattern Diagnosis.
  • Workflows first, agents second; four workflow patterns: chaining, routing, parallelization, evaluator-optimizer.
  • Irreversible actions need a human-in-the-loop checkpoint; audit needs deterministic logging at the code layer.
  • Multi-agent costs about 15× the tokens of chat; it suits parallelizable tasks and performs poorly on tightly coupled coding.
  • Delegating to subagents: objective, output format, tools/sources, boundaries; scale the number of subagents to the complexity.
  • Managed Agents: Agent, Environment, Session, Events; subagents share the sandbox but have separate context; one level of delegation.
  • The Agent SDK is self-hosted, with state on local disk → SessionStore; multi-tenant: setting_sources=[], turn off auto memory.
  • allowed_tools is pre-approval, not a restriction; hide tools with disallowed_tools.
  • Hooks are deterministic, CLAUDE.md is a request; hard rules → PreToolUse; only exit code 2 blocks.
  • Reload context after compaction: SessionStart with matcher compact.
  • The loop must branch on stop_reason; a missing max_tokens branch → the old request repeats and costs money.
  • Compaction for the whole conversation, clearing for old tool results, memory for cross-session information.