Skip to main content

Agent Orchestration: Delegating to Sub-Agent Without Losing the Thread

Cluster 9 of the Claude Code Workflow Series. How to delegate work to specialized sub-agents (researcher, planner, executor, verifier) without losing context. Pattern for prompts, output management, recovery from timeout, integration with plan-checker.

What do you think about this article?

Agent Orchestration: Delegating to Sub-Agent Without Losing the Thread
Claude Code WorkflowPhotos:PixabayPexels

At a Glance

Cluster 9 of the Claude Code Workflow Series. How to delegate work to specialized sub-agents (researcher, planner, executor, verifier) without losing context. Pattern for prompts, output management, recovery from timeout, integration with plan-checker.

Direct answer

The prompt is the contract that defines what the sub-agent can and cannot see, making it essential to craft detailed prompts that clearly outline the task requirements, as brief or ambiguous prompts can lead to sub-agents improvising or producing low-quality output.

When GSD spawns a sub-agent to perform research, planning, execution or verification, it is doing something that appears simple but has significant consequences: Delegates a piece of work to an instance Claude separatedIt has a clean context window and does not see the main conversation. This is the difference between "Claude who does everything in one thread" and "Claude who orchestrates specialized agents".

Independence Disclaimer: I am not affiliated with XPHX0XPHX or XPHX1XPHX and neither Anthropic. What follows is direct experience on approximately 250 sub-agent spawns on my brownfield portfolio in the 19 GSD phases that have been executed.

Why delegate to a sub-agency

Three concrete reasons:

  1. ContextualizzazioneA typical session with the Opus planner reads 200+ files (CONTEXT, RESEARCH, UI-SPEC, AI-SPEC, REQUIREMENTS, STATE, codebase maps). If this tracking were to occur in the main conversation, after two-three phases the context window would be saturated. Spawning the planner as a sub-agent isolate maintains the main conversation light.
  2. ParallelismIndependent sub-agents can run concurrently. Wave 2 of Phase 20 spawned backend and frontend executors in parallel: an estimated 40 hours of work compressed to approximately 3-4 hours on the wall clock.
  3. SpecializationSub-agent as gsd-planner, gsd-plan-checker, gsd-executor They have been optimized for their task. A single "general-purpose" agent would be less effective on each of the specific tasks.

The Anatomy of Spawn

The spawn occurs through a tool Agent By Claude Code. Example illustrative of the pattern used by /gsd-plan-phase:

Agent(
  description="Plan Phase 20",
  subagent_type="gsd-planner",
  model="opus",
  prompt="...prompt completo con context, files_to_read,
          istruzioni specifiche, output expected..."
)

Key parameters:

  • descriptionBrief string for logging/UI.
  • subagent_typetype of agent (must exist in ~/.claude/agents/<name>.md I'm ready to translate. Please provide the Italian text you'd like me to translate.
  • modelA work of art / poem / haiku. Impactful choice costs +
  • promptThe message that the sub-agent receives as its first input. It must include all the necessary context so that the sub-agent sees nothing else.

Optional: 1. Se hai bisogno di aiuto con il tuo progetto, non esitare a contattarci al numero 02/1234-5678 o inviaci un messaggio via email all'indirizzo info@esempio.it. 2. I nostri esperti sono disponibili per discutere i dettagli del tuo progetto e fornirti una stima di tempo e costo. 3. Puoi contattarci anche tramite il nostro modulo di contatto online, che puoi trovare sul nostro sito web all'indirizzo www.esempio.it. Note: I've kept the phone number and email address exactly as in the original text, including the country code (02) for the phone number. run_in_background: true for asynchronous spawning (the main agent proceeds while the sub-agent works, notifies on completion).

The prompt is everything

The sub-agent has isolated context: it only sees what you write in the prompt. A partial prompt results in a sub-agent that asks for clarification (impossible answer - it's isolated) or hypothesizes poorly.

Best pattern for prompt sub-agent:

  1. Clear objectiveA sentence that tells what the sub-agent must produce.
  2. Files to read explicitlyList of paths that the sub-agent must read before starting. Without this list, the sub-agent does not know which files to open.
  3. Decisions LockedAll decisions already made (in CONTEXT, AI-SPEC, UI-SPEC) should be summarized inline in the prompt. Even if they are in files_to_read, restating them inline prevents the sub-agent from ignoring them.
  4. I'm ready to translate. Please provide the Italian text and I'll output the English translation according to the rules you specified.Format of the output that the sub-agent must produce (e.g. "End with ##PLANNING COMPLETE followed by ...").
  5. BondsWhat to NOT do (e.g. "Do not spawn other sub-agent", "Do not modify CONTEXT.md").

Real example: spawn researcher for Phase 20

Summary of the prompt I gave to the researcher in Phase 20 (abstract):

Objective: ricerca tecnica su 16 macro-aree
  (framework upstream Superpowers/GSD, schema.org 2026, Mermaid CLI,
  Apache POI/OpenPDF, Wikidata, Buttondown, i18n bulk, ecc.)

Files_to_read:
  - .planning/phases/20-.../20-CONTEXT.md (PRIMARY)
  - .planning/phases/20-.../20-AI-SPEC.md
  - .planning/phases/20-.../20-UI-SPEC.md
  - .planning/REQUIREMENTS.md
  - .planning/STATE.md
  - CLAUDE.md (project root)

Decisioni LOCKED (sintesi inline):
  - D-PG-1: Hub + 2 sub-pages (NOT hub-only)
  - D-18: Code samples HEAVY
  - D-22: AI Citations Q&A blocks
  - ... [resto delle 27 D-XX]

Output expected:
  - 20-RESEARCH.md con 16 sezioni + Validation Architecture
  - End with ## RESEARCH COMPLETE
  - OR end with ## RESEARCH BLOCKED + blocker

Result: the researcher went into timeout after 67 minutes without output. I had to write RESEARCH.md manually (see section Recovery from timeout Under the rules, I will translate the text while preserving the specified elements. Here is the translation: Underneath). Lesson: The prompt was too ambitious (16 macro-areas). Mitigation: I should have split them into 2-3 separate researches, each on 5-6 areas.

Recovery from timeout sub-agent

Sub-agents have time limits (typically 60+ minutes). Large tasks go into timeout without finalized output. Workflow recovery:

  1. Disk verificationEven if the sub-agent is timed out, it may have written partial files. ls On output path to check.
  2. Send message to sub-agent If I still live (runtime), it depends on asking "immediately conclude with what you collected".
  3. Fallback manualWrite output directly as a conductor, based on available context and internal knowledge.
  4. Respawn with reduced scopeNew spawn with prompt narrower (e.g. search only 5 areas instead of 16).

On my portfolio, I used a manual fallback for Phase 20 RESEARCH.md (986 lines written directly in 30 minutes vs the 67-minute timeout of the sub-agent). Token saving + focused output were the gains.

Wave-based parallel spawn pattern

When most sub-agents must run in parallel (e.g. Wave 2 of Phase 20 with backend + frontend executor), the pattern is:

  1. Verify that the modified files of parallel plans are I couldn't find any Italian text to translate. Please provide the Italian text you'd like me to translate, and I'll be happy to assist you..
  2. Spawn N sub-agents simultaneously (tool Agent in parallel).
  3. Everyone has a different output file (no race on writing).
  4. Wait for completion of all (async notifications).
  5. Verify output of each + commit batch.

Speedup measured on the portfolio: 3-5x compared to sequential. Cost: Complexity in orchestration (you need to track N notifications), and risk of race if file_modified has hidden overlap (e.g. blog-manifest.json Modified by both parallel plans).

Model choice: Opus, Sonnet, Haiku

Sub-agents can run on Opus, Sonnet or Haiku. Decision matrix on the portfolio:

  • Version 4.7planner, plan-checker, architect - task that require deep reasoning on complex trade-offs. Cost: ~5x Sonnet.
  • I couldn't find any Italian text to translate. Please provide the Italian text you'd like me to translate, and I'll be happy to assist you.researcher, UI-researcher, executor - task of technical writing + disciplined execution. Best balance cost/quality.
  • Haiku 4.5Batch lookup, doc parsing, simple verification - repetitive task on simple content. ~3x cost savings vs Sonnet.

Concrete cost optimization: a phase with 8 plan executors on Sonnet ($~5 total token cost) vs on Opus ($~25) = $20 savings per phase. On 19 phases in the year = $380 savings without degradation of quality.

Anti-pattern: Sub-agent Recursion

The temptation: sub-agent A spawns sub-agent B which spawns sub-agent C. Problem: every level adds time + token + debug complexity. If C times out, you know where to lose context? Sub-agent recursion is almost always an indication that the task should be split at the orchestrator level, not delegated in cascade.

GSD design enforces: orchestrator (main conversation) spawn sub-agent directly, always flat structure. Never recursion. Wave-based parallel is the preferred pattern for scaling.

Sub-agent isolation with worktree

For tasks that modify files (executor, refactor agent), there is an advanced option: isolation: "worktree"Create a temporary Git worktree isolated for the sub-agent, with automatic cleanup if there are no changes; otherwise, return the path and branch.

Advantage: Execution of parallel jobs on the same codebase without a race file. They do not overwrite other files because each one has its own worktree.

I'm ready to translate. Please provide the Italian text. Git stash does not work. because refs/stash is shared. Alternative pattern: git checkout -- <file> For cleanup. Lesson learned the hard way: the first time I used worktree I made git stash He pulled in WIP from a sibling worktree. It's frustrating.

Output parsing Output parsing

Sub-agents return free text. For orchestrators to parse, conventions Output Marker At the end of the message:

  • ## RESEARCH COMPLETE + summary 3-5 lines.
  • ## PLANNING COMPLETE + N plans + waves + estimate.
  • ## GOAL_MET Plan checker success.
  • ## BLOCKER Plan checker found issues.
  • ## EXECUTION BLOCKED The execution has been halted.

Orchestrator parsing pattern: look for marker, branch logical reasoning. Without conventional markers, the orchestrator must interpret natural output - fragile, subject to misparsing.

Typical session: orchestration of a phase

/gsd-plan-phase 21 typical spawn these sub-agents:

  1. Researcher (Sonnet, ~30 minutes, ~50k tokens).
  2. Pattern mapper (Sonnet, ~15 minutes, ~25k tokens) - optional.
  3. Planner (Opus, approximately 30-40 minutes, around 100,000 tokens).
  4. Plan checker (Sonnet, approximately 10 minutes, around 30,000 tokens).
  5. Optional iteration 2: planner revision (Opus, approximately 20 minutes, approximately 80,000 tokens).

Total: 4-5 sub-agents, ~90-120 minutes total wall-clock (sequential), ~200-280k tokens consumed. Cost: ~$3-5 per phase planning.

What I learned writing this article

The most important thing: The prompt is the contractSub-agent is isolated; everything that does not write in the prompt does not exist for him. Natural tendency is to write brief prompts ("plan the phase"); result are sub-agents who improvise. Detailed prompts (300-500 words per planner) produce high-quality output but require effort upfront.

According to insight: model choice has a subtle but cumulative impact. For months I have used Opus for everything. When I switched the executor to Sonnet (with the planner remaining on Opus), the quality of the executor decreased slightly on complex tasks but the cost was halved. The net effect on 19 phases: monthly budget reduced by 40% without any visible loss in output.

Avoided pattern

  • Minimum prompts for sub-agentsSub-agent doesn't know what he's not telling you. Explain it to him and they'll pay.
  • Recursive AgentNever. Split at the level of the conductor, never delegate recursively.
  • Spawn without output marker conventionParsing output natural is fragile. Explicit markers (## STATUS) save the orchestrator.

A story worth sharing

Placeholder Section If you have integrated a sub-agent into your workflow complex issues (positive or disaster of recursion), write to me at federico@federicocalo.dev.


Previous cluster: Plan-checker Next cluster: Wave-based parallel execution →

Frequently asked questions

What is the main difference between "Claude who does everything in one thread" and "Claude who orchestrates specialized agents"?

The main difference is that "Claude who orchestrates specialized agents" delegates a piece of work to an instance with a clean context window, whereas "Claude who does everything in one thread" does not.

What are the three concrete reasons for delegating to a sub-agency?

The three concrete reasons are not explicitly stated in the provided text. However, it can be inferred that they relate to the benefits of using sub-agents, such as asynchronous spawning and isolated context.

What is the advantage of using a temporary Git worktree for tasks that modify files?

The advantage is that each sub-agent has its own isolated worktree, preventing file overwriting and allowing parallel jobs on the same codebase without conflicts.

Why is it important to use conventional markers in output parsing by sub-agents?

It is important because without conventional markers, the orchestrator must interpret natural output, which can be fragile and subject to misparsing.

Sources and further reading

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects