Sub topic 3
Collecting and Merging Subagent Results
Assume you know basic Python, asyncio, Git, and context-window limits. This chapter focuses on what happens after subagents receive their briefs.
Aggregate Results as Data
An orchestrator should collect a structured result from every worker. Each result should include the task name, status, summary, changed files, and verification evidence. Do not merge changes merely because a worker reports success.
import asyncio
async def run(name: str, delay: float, fail: bool = False) -> dict:
await asyncio.sleep(delay)
if fail:
raise RuntimeError("tests failed")
return {"task": name, "status": "ok", "summary": f"{name} completed"}
async def collect() -> list[dict]:
jobs = [run("docs", 0.2), run("tests", 0.1, fail=True)]
outcomes = await asyncio.gather(*jobs, return_exceptions=True)
results = []
for job, outcome in zip(("docs", "tests"), outcomes):
if isinstance(outcome, Exception):
results.append({"task": job, "status": "failed", "error": str(outcome)})
else:
results.append(outcome)
return results
if __name__ == "__main__":
print(asyncio.run(collect()))return_exceptions=True prevents one failed worker from hiding other results. The orchestrator can then decide whether to retry, repair, or stop.
Verify Before Merging
Verification is an independent check, not a restatement of the worker's summary. Inspect the diff, run focused tests, check formatting, and confirm that the worker stayed within scope. For code changes, a useful acceptance record includes:
- Files changed and why they changed.
- Commands run and their exit status.
- Test output or other concrete evidence.
- Remaining risks or assumptions.
Failures, Retries, and Timeouts
Set a timeout around each worker. Retry only transient failures, such as a temporary service error. Do not repeatedly retry a deterministic test failure. Limit attempts and preserve the original error for diagnosis. A retry should receive the failure details and a narrower repair task.
Cost and Latency Trade-offs
Parallel workers reduce wall-clock time when tasks are independent, but they consume more model calls and may duplicate repository exploration. Sequential execution costs less when later work depends on earlier output. Use delegation when parallel progress or separate context is worth that overhead.
When One Agent Is Better
Use one agent for a small change, tightly coupled edits, a task with many dependencies, or work requiring one coherent design. Multiple agents add coordination and merge risk.
Trace Each Run
Record a run ID, task briefs, model or agent identity, timestamps, tool permissions, statuses, retries, changed files, and verification results. These traces make failures reproducible and expose slow or wasteful steps.
Exercise
Why should verification be separate from a subagent's success message?
Show answer
A success message is a claim; independent tests, diff review, and scope checks provide evidence.