RBRunbook
Study

Domains · Domain 1 · 17% of scored questions

Advanced Agent Architecture and Orchestration

About 10 of the 60 scored questions come from this domain. It has 4 skills:

Lessons

Skill

Multi-Agent Orchestration

Multi-agent orchestration: delegation, isolation, and approvals

A multi-agent design is a lead agent that hands pieces of work to other agents, each with its own context window. You pay for it in tokens and coordination, so the design questions are always the same: what crosses the boundary between agents, what happens when one of them fails, and where a person must say yes.

What crosses the boundary

A subagent starts with a fresh context. In the Agent SDK the only content that passes from parent to subagent is the prompt string of the delegation call. The subagent does not see the parent's conversation, its tool results, or its system prompt. In the other direction only the subagent's final message returns, and the parent may summarise it again before the user sees it.

So when a subagent wanders, read the delegation prompt first. A good brief has four parts:

  • an objective,
  • an output format,
  • guidance on the tools and sources to use,
  • clear task boundaries.

Without them, subagents duplicate each other's work, leave gaps, or redo discovery that the lead already finished.

Trap: fixing a vague brief by adding more agents (a deduplicator, a reconciler) or by letting subagents chat with each other. Each addition is one more handoff. Fix the brief.
How results come back

Every hop through a conversation is a chance to lose detail. For large or exact outputs (tables, code, reports), have the subagent write the result to shared storage and return a short reference. This keeps figures exact and keeps the lead's context small. If a user needs a subagent's wording unchanged, tell the lead to relay it verbatim.

Check for missing results too. A subagent that ends on an API error, such as a rate limit, does not deliver a finished report: the lead gets a failure message with whatever partial output exists. A lead that only summarises what came back will report success on partial work. Have it reconcile returned results against the list of tasks it handed out.

Where to split

Split work along context boundaries, not job titles. A planner, coder, tester, reviewer chain loses the reasons behind decisions at every handoff. One agent per independent feature, which also tests that feature, does not. Parallel dispatch fits work that is independent, broad, and larger than one context window. It is a poor fit when agents need the same context or depend on each other's intermediate results.

Bounding fan-out

The model decides when to delegate and how many agents to spawn, and subagents can spawn their own. A sentence in the system prompt only steers that choice. To guarantee a bound, use the harness limits: nesting depth, concurrent subagents, and a spend cap for the whole query. In Claude Managed Agents, delegation is one level deep, and a session budget caps spend including workflow runs.

Human approval
NeedMechanism
A person must see every call of a tool before it runsManaged Agents: always_ask on that tool. The session pauses and waits.
Low friction, with the platform judging risk per callauto. It is not a human checkpoint: a call judged safe runs before anyone sees it.
Approval in an Agent SDK appThe permission callback pauses execution until your code returns allow or deny.
The approver may take longer than your process can stay aliveA pre-tool hook returns a defer decision, the process exits, and you resume the persisted session when the answer arrives.

Two details decide many incidents. First, policy changes apply to sessions created afterwards; running sessions keep the tool configuration they started with. Second, under auto the text you send as a user message counts as your intent, so relaying untrusted end-user text can get a call allowed. Content in tool results or fetched pages is not read as intent.

When an approval client reconnects to a paused Managed Agents session, it should not wait for the request to be sent again. The latest idle event lists the blocking calls in its stop reason, and the client answers each one.

Trap: asking the agent in its prompt to "wait for sign-off" before an irreversible action. Nothing enforces a prompt. Put the gate in the permission policy or the callback.

Sources
Subagents in the SDK
Create custom subagents
How we built our multi-agent research system
Building multi-agent systems: when and how to use them
Multiagent orchestration (Claude Managed Agents)
Permission policies (Claude Managed Agents)
Session event stream (Claude Managed Agents)
Handle approvals and user input
Hooks reference

Skill

Durable Execution and State Management

Durable execution: sessions, checkpoints, and surviving change

A long-running agent will be interrupted: a node is drained, a context window fills, a deploy lands, a model version changes. Durable design starts by listing the kinds of state the agent has and deciding where each one lives.

Three kinds of state
StateWhere it lives by defaultWhat preserves it
Conversation (prompts, tool calls, results)Session transcript on the local disk of the hostA session store adapter that mirrors transcripts to your own backend
Files the agent wroteThe working directoryA mounted volume or object-store sync that you provide
Task progress (what is done, what is next)Only in the model's contextArtifacts the agent writes: progress file, requirement list, commits, memory

A session persists the conversation, not the filesystem. After a move to another host, a resumed agent can remember writing a script that no longer exists. Forking is the same: it branches the history, and both branches still edit the same files.

Finding the right session

In the Agent SDK, continue picks the most recent session in the current directory. That is fine for one conversation at a time. With many users in one process you must keep each session ID and pass it to resume, or one user's follow-up will land in another user's history.

Resuming on another host

Session files are local to the machine that created them. There are three options:

  1. Attach a session store so any host can load the transcript. This fits when you need the full history or governed retention.
  2. Move the transcript file yourself.
  3. Do not resume. Capture the results you need as application state and pass them to a fresh session. This is often the more robust choice, especially across versions.

The store is a mirror and its writes are best effort. A failed batch is retried a few times, then dropped while the agent carries on, and a marker message is emitted. Monitor for that marker. Retries can deliver an entry twice, so the adapter should deduplicate by entry ID.

Trap: enabling file checkpointing to make a store-backed session durable. Checkpoint backups are written to local disk only, they cover edits made through the file tools and not shell commands, and rewinding files does not rewind the conversation.
Progress across context windows

Each new context window begins with no memory of the previous one, and compaction alone does not hand over clear instructions. Two failures are typical: the agent tries to do everything at once and runs out of context half way through a change, or a later session sees some progress and declares the job finished. The working pattern is:

  • A first session builds the scaffold: a structured list of every requirement, all marked as not passing, a progress file, and an initial commit.
  • Every later session does one unit of work, verifies it end to end, commits, and updates the progress file.
  • Every session begins by reading the progress notes and commit log and running a basic end-to-end check before new work. Building on a broken state makes it worse.
  • Sessions may change a requirement's status and nothing else in the list.
Surviving deploys and model changes

When you deploy, agents are part way through their work. Keep old and new versions running side by side and let running work finish on the version it started with. In Claude Managed Agents, agents are versioned: a session created with only the agent ID takes the latest version, and a session created with an explicit version is pinned, which is how you stage a rollout. A session copies its configuration when it is created, so later edits to the agent do not change it.

State that lives in files, notes, and structured lists moves across a model change far better than a long transcript. If you must carry work across, seed a fresh session with those artifacts. Managed session sandboxes are checkpointed when idle, but the sandbox state is kept for a limited period, so important outputs should be written out before then.

Sources
Work with sessions
Persist sessions to external storage
Hosting the Agent SDK
Rewind file changes with checkpointing
Effective harnesses for long-running agents
How we built our multi-agent research system
Start a session (Claude Managed Agents)
Session event stream (Claude Managed Agents)

Skill

Architecture Selection at Scale

Architecture selection: let production data choose the pattern

The question in this skill is not which pattern is best. It is which pattern the data from your running system supports, and whether a change in either direction would pay for itself. The default is the simplest design that works, with complexity added only when it measurably improves outcomes.

Workflows and agents

A workflow runs model calls and tools through code paths you wrote. An agent decides its own steps and tool use. Workflows give predictability for well-defined tasks. Agents give flexibility when the path cannot be written in advance, and they cost more, take longer, and can compound errors.

What the data showsPattern it supports
Nearly every run follows the same stepsPrompt chain with checks between steps
Distinct categories that can be classified accuratelyRouting to specialised paths
Independent pieces, or several opinions wantedParallel calls (sectioning or voting)
Subtasks that depend on the input and cannot be listed aheadOrchestrator with workers
Clear criteria, and feedback demonstrably improves the outputEvaluator and optimiser loop with a round limit
Number of steps cannot be predictedAgent loop with a stopping condition
Reading the signals

Agent to workflow. If traces show that an agent takes the same sequence on almost all runs, the autonomy is buying nothing. You are paying for re-planning in latency and in occasional loops. Move the common path to a fixed chain and route the unusual inputs to the agent.

Workflow to agent. If a fixed chain keeps growing branches for cases it did not foresee, and success on those cases stays low, the path is not predictable. Hand those cases to an agent loop. Keep the chain for the cases it handles well.

Mixed results. An overall average hides categories. A pilot that is flat overall at several times the cost can still be a large win in one category. Route by category and measure each path separately.

Single agent or several

Multi-agent systems use several times the tokens of a single agent for the same task. Three situations justify that:

  • context pollution: a subtask produces a lot of content that the main task does not need,
  • work that can run in parallel,
  • specialisation that improves tool selection or focus.

Outside these, coordination usually costs more than it returns. The value of the task also has to cover the tokens, so a multi-agent path often belongs on the high-value slice of traffic only.

Trap: splitting an agent because it has too many tools. First try keeping most tool definitions out of context with tool search and measure selection accuracy again. It costs far less than an orchestrator and specialists.

A pattern that travels well is the verification subagent: a separate agent that tests the result against clear criteria. It needs little of the history, so the handoff loses little.

Choosing a harness or framework

The Messages API gives direct model access for custom loops and fine control. A managed agent harness supplies the loop, tool execution, sandbox, and stateful sessions, and suits long-running and asynchronous work when you do not need custom loop logic. Choose by what the team must own, not by what it could build.

Frameworks speed up the start and add layers that hide the actual prompts and responses. Wrong assumptions about what a framework does underneath are a common source of errors. If you adopt one, a sensible standard is that every team can see and review the exact requests it sends.

Reusable-pattern standards

Standardise what protects reliability and leave domain choices to teams:

  • stopping conditions and spend limits in every loop,
  • one tool-definition format with reviewed descriptions,
  • tracing of prompts, tool calls, and results,
  • an evaluation set that any architecture change must pass.

Do not mandate one topology or one system prompt for every team. Those are the parts that should fit the task.

Sources
Building effective agents
Building multi-agent systems: when and how to use them
How we built our multi-agent research system
Claude Managed Agents overview

Skill

Context and Memory Architecture

Context and memory: staying under the limit without breaking the cache

Context is a finite resource. As the window fills, recall gets worse and every request costs more. For a long-running agent you need a policy for what stays in the window, what is summarised, what is stored outside, and how to change instructions or tools without paying to reprocess the whole conversation.

The options
TechniqueWhat it doesWatch for
CompactionReplaces older turns with a summarySummaries can drop details that matter later
Tool result clearingReplaces the oldest tool results with a placeholder once a threshold is passedEach clearing invalidates the cached prefix
Memory filesThe agent writes notes outside the window and reads them backYour application runs the file operations and must secure them
SubagentsExploration happens in another window; a short result returnsSeveral times the tokens
Just-in-time loadingKeep paths and queries in context, load data when neededSlower than preloaded data

Compaction is usually the first lever. Tool result clearing is the lightest form: once a file has been read and used, the raw content rarely needs to be seen again. Compaction suits long back-and-forth conversations, note-taking suits work with clear milestones, and subagents suit broad parallel exploration.

Protecting what must survive
  • If one tool's result must stay for the whole run, such as a procedure fetched at the start, exempt that tool from clearing.
  • If exact items must survive summarisation (constraints, a findings list), have the agent write them to memory. Compaction keeps the window small and memory keeps what cannot be lost.
  • If you write your own summarisation prompt, tune it on real long traces. First make it capture everything that later turns need, then cut what is superfluous. Do not start from a length target.
The cache is a prefix

Prompt caching matches a prefix in the order tools, then system, then messages. A change at one level invalidates that level and everything after it.

ChangeWhat is invalidated
Editing any tool definitionTools, system, and messages
Toggling web search or citationsSystem and messages
Changing the tool choice settingMessages only
Appending a message or tool resultNothing; the prefix is extended
Changing instructions mid-conversation

Editing the top-level system prompt changes the start of the prompt, so the whole conversation is processed again. On models that support it, append a message with the system role at the point where the new instruction applies. The cached prefix is unchanged and the instruction still carries system authority. Putting the rule in a user message is also cache-safe, but it is ordinary user text. In Claude Managed Agents the equivalent is a system message event, which applies to that turn and all later ones.

Trap: adding a cache breakpoint and then editing the text before it. A breakpoint marks where a prefix ends. It does not protect content from changes earlier in the prompt.
Clearing and the cache

Tool result clearing changes earlier content, so it breaks the cache at that point. If it fires on every request and removes a little each time, you pay cache writes continuously. Set a minimum amount to clear so that each event frees enough to be worth the rewrite. Keeping thinking blocks preserves the cache; clearing them invalidates it from that point.

Large tool catalogs

Tool definitions sit at the very front of the prefix and can take tens of thousands of tokens. Selection accuracy also falls once there are more than a few dozen tools. Tool search fixes both: send every definition, mark most as deferred, and the model searches and loads the few it needs. Discovered tools are added in the conversation, not in the prefix, so the cache is preserved.

  • Keep the three to five most-used tools loaded so they need no search.
  • Do not rebuild the tool list each turn. A changing list invalidates everything.
  • With fewer than about ten tools that are used on most requests, load them directly. Search adds a round trip.
  • In the Agent SDK, discovered tools are dropped when the messages that found them are compacted. Searching again later is expected behaviour.

Sources
Effective context engineering for AI agents
Compaction overview
Context editing
Memory tool
Prompt caching
Mid-conversation system messages and tool changes
Tool search tool
Tool use with prompt caching
Scale to many tools with tool search (Agent SDK)
Session event stream (Claude Managed Agents)

Sample questions

Sample question
A SaaS company runs a delivery pipeline of four agents: a planner, an implementer, a test writer, and a reviewer. Each agent receives a summary from the one before it. Trace data from 200 completed tasks shows:
features per task:                                    2 to 3
files touched by more than one feature in a task:     3%
tokens spent on handoff summaries and agent messages: 58%
tests asserting behaviour the implementer had
  deliberately changed:                               31%
test-writer tool calls re-reading files the
  implementer already read:                           44%
Which redesign most directly addresses this evidence?
  • AGive each feature's test writer the complete transcript of the implementer
  • BGive each feature to one agent that both implements it and writes its tests
  • CMove the reviewer to a more capable model with a longer checklist per feature
  • DAdd a fifth agent that reconciles each feature's tests with the implementer's notes
Show the answer and explanation

Answer:

  • Give each feature to one agent that both implements it and writes its tests

The evidence points at the split itself: work is divided by role, so every handoff drops the reasons behind decisions, and the next agent either guesses (stale tests) or rebuilds the context (re-reading files). The 3% file overlap shows that features within a task barely touch each other, so the context boundary runs between features, not between roles. One agent per feature that also writes that feature's tests removes the lossy handoffs. Passing the implementer's complete transcript keeps the role split and raises the 58% coordination share. A reconciling agent adds one more handoff to a design that already loses context at each one. A stronger reviewer catches some stale tests after the fact and leaves the cause in place.

Sample question
A logistics company hosts a route-planning agent built on the Agent SDK in autoscaled containers. Session transcripts are mirrored to Postgres through a session store adapter. Incident timeline:
02:14  node drained; container running session 7f3a destroyed
02:16  session 7f3a resumed on a new container; transcript loads,
       agent correctly recalls its earlier analysis
02:17  agent runs build/plan_v3.py, a script it wrote at 01:40
       -> No such file or directory
02:19  agent rewrites the script from recollection with different
       parameters; the published plan differs from the 01:55 draft
Which change most directly prevents a recurrence?
  • AEnable file checkpointing so the SDK can rewind the files after each resume
  • BPersist the working directory to shared storage and restore it before a resume
  • CSwitch follow-up calls from resume by session ID to continuing the latest session
  • DImplement the store's optional listing method so subagent transcripts are restored
Show the answer and explanation

Answer:

  • Persist the working directory to shared storage and restore it before a resume

The transcript survived, which is all a session store covers: a session persists the conversation, and files the agent wrote live in the container's working directory, which was lost with the node. The working directory needs its own storage strategy, such as a mounted volume or an object-store sync restored before the resume. Restoring subagent transcripts adds more conversation history but no files. File checkpointing keeps its backups on local disk, so they vanish with the container, and the SDK does not allow it together with a session store. Continuing the latest session changes how the session is found, and finding it was never the problem.

Sample question
A bank's analytics agent answers analysts' questions about card transactions. To make sure the agent "has everything", the harness runs three warehouse queries before each task and pastes the full results into the first user message. The agent also has a sandbox with a shell and file tools. Measurements over 400 tasks:
mean size of pasted results:              140k tokens
tasks stopped at the context limit:       37%
exact-figure errors, rows in first third:  4%
exact-figure errors, rows in last third:  19%
Analysts need exact row-level figures, and a typical question touches under 2% of the rows. Which change best addresses these results?
  • AEnable tool result clearing so that older results are removed as context grows
  • BSummarise each query result with a smaller model before it goes into the prompt
  • CMove the query results into the system prompt and place a cache breakpoint after
  • DSave the query results as files and give the agent their paths to query on demand
Show the answer and explanation

Answer:

  • Save the query results as files and give the agent their paths to query on demand

The agent is carrying 140k tokens when each question needs about 2% of them, and recall degrades as the window fills. Keeping the data outside the window and handing the agent lightweight references (file paths) lets it pull only the rows it needs with its shell and file tools, which keeps figures exact and context small. Summarising first loses the row-level figures analysts need. Tool result clearing acts on tool results, not on data pasted into a user message, and it would discard data instead of making it retrievable. Caching the results in the system prompt lowers the price of the tokens but leaves the same 140k in the window, so the limit stops and recall errors remain.

↑↓ move↵ openesc close