Sub topic 11
Collecting and merging subagent results
This chapter assumes you have read the chapters on the orchestrator-worker pattern and on writing delegation briefs. You should also be comfortable with Git branches and basic Python. Once subagents finish, the orchestrator has to turn several separate outputs into one coherent result. This step is called result aggregation. Done badly, it hides failures, floods the parent's context, or produces a merged change that no single agent ever tested.
What aggregation has to do
Aggregation has four jobs:
- Collect every result, including failures and timeouts.
- Normalize results into one shape so the orchestrator can compare them.
- Merge the code changes that the subagents produced.
- Decide what goes forward to verification, retry, or the user.
The orchestrator should do these jobs on summaries and diffs. It should not read each subagent's full transcript. Keeping transcripts out of the parent is the reason context isolation exists, so aggregation should not undo it.
Ask for a structured return
The delegation brief should say what format the reply takes. A free-form reply such as "I did the thing, it went well" is hard to combine with others. A fixed shape is easy to check by code and easy for a model to read.
A useful result has these fields:
| Field | Purpose |
|---|---|
| `name` | Which task the result belongs to |
| `status` | `ok`, `failed`, or `partial` |
| `summary` | Two or three sentences on what changed |
| `files` | Paths the subagent touched |
| `checks` | Commands it ran and their outcome |
| `open_issues` | Anything it could not finish or is unsure about |
The files field matters most for merging. You can compare it against the scope you gave in the brief. If a subagent was told to edit only tests/test_cli.py and reports changes under src/, you have found a scope violation before any merge happens.
Treat the summary and checks fields as claims, not facts. A subagent can report "tests pass" without having run them. The verification chapter covers how to confirm such claims. At this stage, record them and keep them separate from what you have observed yourself.
Collecting results without losing failures
The orchestration example from earlier in this tutorial uses asyncio.gather with return_exceptions=True. That argument is what makes aggregation safe. Without it, the first exception propagates out of gather and the orchestrator loses the results of tasks that finished. With it, every outcome comes back in order, and exceptions arrive as values.
import asyncio
from dataclasses import dataclass
@dataclass
class Task:
name: str
brief: str
async def run_subagent(task: Task) -> dict:
# Placeholder: replace with a call to your agent runtime.
# The subagent receives only the brief, not the parent's history.
await asyncio.sleep(0.1)
return {"name": task.name, "status": "ok", "summary": f"finished {task.name}"}
async def orchestrate(tasks: list[Task]) -> list[dict]:
outcomes = await asyncio.gather(
*(run_subagent(t) for t in tasks), return_exceptions=True
)
results = []
for task, outcome in zip(tasks, outcomes):
if isinstance(outcome, Exception):
results.append({"name": task.name, "status": "failed", "summary": str(outcome)})
else:
results.append(outcome)
return results
if __name__ == "__main__":
tasks = [
Task("update-docs", "Update README usage section for the new --verbose flag."),
Task("add-tests", "Add unit tests for parse_args in tests/test_cli.py."),
]
for result in asyncio.run(orchestrate(tasks)):
print(result)Note the zip(tasks, outcomes) step. gather returns results in the same order as the inputs, so the zip pairs each outcome with the task that produced it. This is how a failed task keeps its name.
One gap remains. An exception is not the only way to fail. A subagent can return normally with status: "ok" while having done nothing useful, or with status: "partial". Your aggregator should look at the status field and the open_issues list, not just at whether an exception occurred.
Normalizing before you compare
Subagents rarely return identical shapes, even when briefed with the same format. Before comparing, put each result through a small validation step. It should confirm that required fields exist, that status has an allowed value, and that every path in files is inside the task's scope.
A result that fails validation is treated as a failed task with a clear reason, such as "missing field: checks". This is better than guessing what the subagent meant. It also gives you a concrete message to include in a retry brief.
Merging code changes
The merge strategy depends on how you isolated the workspaces.
- Separate branches or worktrees. Each subagent committed to its own branch. You merge the branches one at a time with Git. Conflicts appear as ordinary merge conflicts.
- Shared working tree with disjoint files. The subagents edited different files in one checkout. There is nothing to merge, but you should still confirm with
git statusthat nobody touched a file outside their scope. - Reply-only results. Subagents returned text or patches rather than editing files. The orchestrator applies each patch itself.
The worktree approach from the isolation chapter gives the cleanest merges, because each branch has a clear author and a clear diff.
# Merge reviewed subagent branches one at a time, testing after each
git switch main
git merge --no-ff agent/docs
# run the project's checks here before continuing
git merge --no-ff agent/tests
# run the project's checks again
# Clean up after merging
git worktree remove ../wt-docs
git worktree remove ../wt-testsMerge one branch at a time and run the project's checks after each merge. If you merge all branches and then find a test failing, you have to work out which branch caused it. If you test after each merge, the failure points at the branch you just added.
The --no-ff flag keeps a merge commit even when Git could fast-forward. That preserves a record of which commits came from which subagent, which helps when you review or revert later.
Handling conflicts
Even with careful decomposition, two subagents sometimes change the same file. Conflicts fall into two kinds.
Textual conflicts are the ones Git reports. Two branches changed the same lines. These are visible and can be resolved by a person or by a dedicated resolver subagent that receives both diffs and the intended outcome of each task.
Semantic conflicts are silent. Git merges cleanly, but the combined code is wrong. For example, one subagent renames a function while another adds a new call to the old name. Neither branch has a conflict, and each passes its own tests. The merged code fails.
Only running the full test suite on the merged result catches semantic conflicts. This is the main reason aggregation and verification are separate steps: each subagent's checks cover only its own branch.
Resolving overlap and contradictions
Sometimes results disagree rather than conflict. Two research subagents might give different answers about where a bug lives. An orchestrator can handle this in three ways:
- Prefer the result with evidence, such as a failing test, a stack trace, or a file and line reference.
- Run a tiebreak task that asks a new subagent to test both claims.
- Report the disagreement to the user instead of choosing silently.
Do not average or blend contradictory claims. A summary that says "the bug may be in either module" is not a result.
Reporting back
The final report to the user should be built from the aggregated data, not from memory of the run. Include what succeeded, what failed and why, which branches were merged, which checks the orchestrator ran itself, and which items still need human attention. Keep claims reported by subagents separate from checks the orchestrator ran. This separation lets the reader see how much of the result has been independently confirmed.
Common errors
- Dropping failed tasks. Calling
gatherwithoutreturn_exceptions=True, or filtering out non-okresults, makes a run look more successful than it was. - Pasting full transcripts into the parent. This refills the parent's context and removes the benefit of isolation. Ask for summaries.
- Trusting
checksas evidence. The orchestrator should re-run the important ones. - Merging everything at once. One failing branch then blocks diagnosis of all the others.
- Skipping scope checks. Comparing
filesagainst the brief's scope is cheap and catches stray edits early.
Exercise
Two subagents each pass their own tests on separate branches. You merge both with no Git conflicts, but the project's full test suite fails afterward. What kind of conflict is this, why did neither subagent catch it, and what should the orchestrator do?
Show answer
This is a semantic conflict. Each subagent tested only its own branch, so neither saw the other's changes. For example, one may have renamed a function while the other added a call to the old name. The orchestrator should merge one branch at a time and run the full suite after each merge to find which branch introduced the failure. It should then either fix the issue itself or send a focused brief to a resolver subagent that includes both diffs and the intended behavior.
Exercise
In the Python example, what would happen to the results of finished tasks if return_exceptions=True were removed and one subagent raised an error, and which field of a result would you check to catch a subagent that returned normally but did not finish its job?
Show answer
Without return_exceptions=True, the first exception would propagate out of asyncio.gather, and the orchestrator would not receive the collected results of the tasks that had finished. To catch a subagent that returned without raising, check the status field (for partial or failed) and the open_issues list, rather than relying only on the absence of an exception.