Module 3: Parallel Sub-Agent Delegation
3. Dependency Resolution and Result Merge
3. Dependency Resolution and Result Merge
Description
Launching subagents in parallel is the easy part. The hard part is coordinating the results. When 4 subagents work simultaneously, each one produces its own output, modifies its own files, and finishes at its own time. The auth subagent finishes in 30 seconds, the products one in 2 minutes, the orders one in 45 seconds, the notifications one in 20 seconds. How do you combine 4 sets of changes into a coherent result? What happens if two subagents modified a shared file like config.py? How do you verify that one's changes don't contradict the other's?
The answer has two parts. First, the dependency graph — the mental tool you use before parallelizing to identify which tasks are really independent and which have hidden dependencies. Second, the merge strategy — how you combine results, detect conflicts, and produce a unified output. Git worktrees resolve most file conflicts automatically, but logical conflicts (two agents making inconsistent decisions) require explicit coordination.
By the end of this capsule you'll know how to design dependency graphs for any set of tasks, choose the right merge strategy, and resolve conflicts that automatic merge can't handle.
Dependency Graph: The Mental Tool
What a dependency graph is
A dependency graph is a mental (or visual) model of which tasks depend on which. The arrows go from the dependency to the dependent:
No dependencies (all parallel):
[auth] [products] [orders] [notifications]
↓ ↓ ↓ ↓
──────── merge coordinator ────────
With dependencies (hybrid):
[models]
↓
├── [routes] ── parallel ── [docs]
↓
[tests]
↓
[deploy]
The graph immediately tells you what can go in parallel (nodes with no arrows between them) and what must wait (nodes with arrows).
How to build the dependency graph
For any set of tasks, ask yourself these 4 questions for each pair of tasks:
1. Does Task B need Task A's output as input?
Example: the tester needs the implementer's code
→ implementer → tester (sequential)
2. Do both tasks read/write the same file?
Example: auth and products both import from src/config.py
→ If they only read: parallel (no conflict)
→ If both write: sequential, or parallel with worktree + careful merge
3. Does Task A's result change Task B's assumptions?
Example: if A changes the User model's interface, B that generates tests for User
is working with invalid assumptions
→ A before B (sequential)
4. Can both start right now with what already exists?
Example: refactor of auth and refactor of products — both modules exist,
both have code to refactor, neither needs the other
→ parallel
Example: Planning a real refactor
You have these 6 tasks:
- Update models from Pydantic v1 to v2 in
src/models/ - Update routes that use those models in
src/routes/ - Update shared utils in
src/utils/ - Update tests in
tests/ - Regenerate the API documentation
- Run the final linter
Dependency graph:
[1. models] ──→ [2. routes] ──→ [4. tests]
│ ↓
└──→ [3. utils] [6. linter]
│
└──→ [5. docs]
Analysis:
- 1 (models) doesn't depend on anything → starts first
- 2 (routes) depends on 1 → waits for models
- 3 (utils) depends on 1 (may import models) → waits for models
- 4 (tests) depends on 2 and 3 → waits for routes and utils
- 5 (docs) depends on 1 (documents models) → waits for models
- 6 (linter) depends on everything → goes last
Optimized flow:
Phase 1: [1. models] ← sequential
Phase 2: [2. routes] ║ [3. utils] ║ [5. docs] ← parallel (3 tasks)
Phase 3: [4. tests] ← sequential
Phase 4: [6. linter] ← sequential
From 6 sequential phases to 4, with Phase 2 running 3 tasks in parallel. If each task takes 2 minutes: sequential = 12 min, optimized = 8 min.
Hidden dependencies
The most dangerous dependencies are the ones that aren't obvious:
❌ Hidden dependency: shared file
auth/ imports from shared/validators.py
products/ imports from shared/validators.py
→ If both refactors touch validators.py, there's a conflict
❌ Hidden dependency: implicit convention
auth/ decides to use snake_case for response fields
products/ decides to use camelCase for response fields
→ Without coordination, they produce inconsistent APIs
❌ Hidden dependency: shared state
auth/ creates a users table in the DB
orders/ creates an orders table with an FK to users
→ If orders is refactored without considering auth, it can break the FK
To detect them, before parallelizing ask yourself: "Do these modules share files, conventions, or state?"
Result Coordination: What Happens When They Finish
The timing problem
4 parallel subagents rarely finish at the same time:
t=0s → launches auth, products, orders, notifications
t=20s → notifications finishes (small module)
t=30s → auth finishes
t=45s → orders finishes
t=120s → products finishes (large module)
Claude handles this automatically: it waits for all the background subagents to finish before consolidating results. You don't need to poll or check status — Claude knows when they all completed.
Three merge strategies
Strategy 1: Consolidation by Claude (default)
Claude reads the results of all the subagents and produces a unified summary. It's the simplest strategy and works for analyses and reports.
Results from 3 subagents → Claude consolidates → Unified report
Prompt:
"When the 3 analyses finish, consolidate into a single report
with the top 10 observations ordered by priority."
When to use it: When the subagents produce reports or analyses (they don't edit files). Consolidation is simply combining information.
Strategy 2: Merge via git worktrees (for edits)
When the subagents edit files in isolated worktrees, the changes are merged via git. Each worktree produces a set of diffs that are applied to the main repository.
auth worktree → diff of changes in src/auth/
products worktree → diff of changes in src/products/
orders worktree → diff of changes in src/orders/
→ Automatic merge if there are no conflicts
→ Conflicts presented for manual resolution if there are any
When to use it: When the subagents edit files and you need the changes applied to the repository.
Strategy 3: Merge coordinator subagent
A dedicated subagent that reviews the results of the parallel workers, verifies consistency, and produces the final output.
---
name: merge-coordinator
description: Reviews and merges results from parallel workers. Resolves inconsistencies.
tools: Read, Grep, Glob, Bash
model: sonnet
maxTurns: 20
---
## Role
You are a merge coordinator. After parallel workers complete their tasks,
you review all changes, verify consistency, and produce a unified report.
## Process
1. Read the output of each parallel worker
2. Check for inconsistencies between workers
3. Verify shared files weren't modified inconsistently
4. Check that naming conventions are consistent across modules
5. Produce the consolidated report
## Consistency Checks
- Same naming convention across all modules
- Compatible import statements
- No conflicting changes to shared files
- Error handling patterns are consistent
When to use it: When you need active consistency verification, not just concatenation of results. It's the most robust strategy but also the most costly (an additional subagent).
Git Worktrees in Detail
The lifecycle of a worktree
1. CREATE — Claude Code creates a temporary worktree for the subagent
git worktree add /tmp/worktree-auth-xxxxx -b temp-auth HEAD
2. WORK — The subagent operates exclusively in the worktree
/tmp/worktree-auth-xxxxx/src/auth/ ← edits here
3. COMPLETE — The subagent finishes its work
(reports which files it modified)
4. MERGE — The changes are applied to the main repository
(if there are conflicts, they're resolved)
5. CLEANUP — The temporary worktree is removed
git worktree remove /tmp/worktree-auth-xxxxx
If the subagent didn't modify any file, step 4 is skipped and the worktree is cleaned up directly.
When there are merge conflicts
Merge conflicts between worktrees occur when two subagents modify the same file. This is rare if you design your dependency graphs well, but it can happen:
Subagent A (auth worktree):
Modifies src/config.py — adds AUTH_SECRET_KEY
Subagent B (products worktree):
Modifies src/config.py — adds PRODUCTS_PAGE_SIZE
→ Merge conflict in src/config.py
When this happens, Claude presents the conflict with the two versions and asks you to choose or combine manually. Preventive solutions are more effective than reactive ones:
Conflict prevention:
- Identify shared files before parallelizing
- Isolate the editing of shared files in a previous sequential phase
- Restrict the scope in the system prompt: "ONLY modify files inside src/auth/"
Phase 0 (sequential): Update src/config.py with ALL the necessary settings
Phase 1 (parallel): Each subagent works in its module without touching config.py
Worktree vs no-worktree: quick decision
| Situation | Worktree | No worktree |
|---|---|---|
| Subagents only read files | ✅ | |
| Subagents edit files in different modules | ✅ | |
| Subagents might touch shared files | ✅ | |
| A single subagent edits files | ✅ | |
| Parallel subagents edit files | ✅ |
Simple rule: if there's more than one subagent editing files in parallel, use worktrees.
Coordination Patterns
Pattern 1: Fan-out / Fan-in
The most common pattern. A coordinator launches N workers in parallel, waits for results, and produces a consolidated output.
┌── worker 1 ──┐
Prompt ──→ ├── worker 2 ──┤ ──→ Consolidation ──→ Result
├── worker 3 ──┤
└── worker 4 ──┘
Prompt:
"Analyze these 4 modules in parallel with separate subagents.
When they all finish, give me a unified report with:
- Top issues per module
- Common patterns between modules
- Refactoring priorities"
Pattern 2: Parallel-then-sequential
The parallel workers produce intermediate outputs that feed a sequential phase.
Phase 1: ┌── researcher A ──┐
(parallel) └── researcher B ──┘
↓
Phase 2: planner (sequential)
↓
Phase 3: ┌── implementer A ──┐
(parallel) └── implementer B ──┘
↓
Phase 4: tester (sequential)
Prompt:
"Phase 1: Research auth and products in parallel.
Phase 2: With the findings from both, create a unified refactoring plan.
Phase 3: Implement the refactoring of auth and products in parallel per the plan.
Phase 4: Run all the tests."
Pattern 3: Pipeline with parallel stages
A pipeline where some stages are parallel and others sequential.
[models] ──→ [routes ║ utils ║ docs] ──→ [tests] ──→ [lint ║ format]
Prompt:
"Run this flow in order:
1. Update the models (sequential — it's the base of everything)
2. When models finishes, update routes, utils, and docs IN PARALLEL
3. When the 3 from phase 2 finish, run the tests
4. When the tests pass, run lint and format in parallel"
Pattern 4: Competitive (pick the best result)
Two subagents tackle the same task with different strategies. You pick the best result.
┌── approach A (e.g., incremental refactor) ──┐
Problem ──┤ ├──→ Pick the best
└── approach B (e.g., full rewrite) ──┘
Prompt:
"Propose two approaches to refactor the auth module:
- Subagent A: incremental refactor keeping the current structure
- Subagent B: full rewrite with a new architecture
Both in parallel. When they finish, compare and recommend which to use
based on risk, time, and maintainability."
Conflict Resolution
File conflicts
When two worktrees modify the same file, git detects the conflict during the merge:
<<<<<<< HEAD (auth worktree)
AUTH_SECRET_KEY = "change-me"
AUTH_TOKEN_EXPIRY = 3600
=======
PRODUCTS_PAGE_SIZE = 20
PRODUCTS_CACHE_TTL = 300
>>>>>>> worktree-products
Resolution: In this case, both changes are compatible — both add different settings. The correct resolution is to keep both:
AUTH_SECRET_KEY = "change-me"
AUTH_TOKEN_EXPIRY = 3600
PRODUCTS_PAGE_SIZE = 20
PRODUCTS_CACHE_TTL = 300
Claude can do this merge automatically if the conflict is simple (additions in different zones). For complex conflicts (modifications to the same line), it presents it to you for manual resolution.
Logical conflicts
The hardest conflicts aren't about files — they're about logic. Two subagents make inconsistent decisions:
auth subagent: decides to use HTTPException(status_code=401, detail="...")
products subagent: decides to use custom AuthError(message="...")
There's no file conflict — each edited its own module.
But there's a logical inconsistency: two error patterns for auth.
Resolution: A merge coordinator subagent that verifies consistency:
## Consistency Checks
After all workers complete, verify:
- Same error handling pattern across all modules
- Same response format (snake_case vs camelCase)
- Same auth verification approach
- Compatible import paths
Convention conflicts
Parallel subagents without shared memory can diverge in conventions:
auth subagent: functions with Google-style docstrings
products subagent: functions with NumPy-style docstrings
Prevention (better than resolution):
- Use subagents with
memory: project(Module 2) — the conventions are in the shared memory - In each worker's system prompt, reference CLAUDE.md explicitly
- The merge coordinator verifies conventions as part of its checklist
Manual Merge vs Worktree Isolation
When to use each approach
| Aspect | Manual merge | Worktree isolation |
|---|---|---|
| Subagents only read | ✅ No merge | N/A |
| 2 subagents edit separate modules | Possible (risky) | ✅ Recommended |
| 4+ subagents edit in parallel | ❌ High risk | ✅ Necessary |
| Subagents edit shared files | ❌ Certain conflict | ⚠️ Conflict at merge |
| Simple setup, quick task | ✅ Less overhead | Unnecessary overhead |
| Project with strict CI/CD | ✅ Atomic changes |
The practical recommendation
- Parallel read-only: No worktree, no merge. Consolidate reports.
- Parallel editing of independent modules: Worktree for each worker. Automatic merge without conflicts.
- Parallel editing with shared files: Worktree + a previous sequential phase for shared files + merge coordinator.
Complete Example: Coordinated Merge of 3 Workers
Setup
3 parallel workers refactor independent modules. A merge coordinator verifies consistency at the end.
Worker subagent file (.claude/agents/module-worker.md):
---
name: module-worker
description: Refactors a specific module following project conventions. Runs in isolated worktree.
tools: Read, Write, Edit, Grep, Glob
model: sonnet
background: true
isolation: worktree
maxTurns: 20
memory: project
---
## Role
You refactor one specific module. Work ONLY in the module specified.
## Constraints
- ONLY modify files in the specified module directory
- Follow conventions from CLAUDE.md and your memory
- Use the same error handling pattern as existing modules
- Maintain existing public API — only change internals
## Output Format
### Refactor Report: [module]
**Files modified:** [list]
**Changes:** [description of each change]
**Conventions applied:** [from memory/CLAUDE.md]
**Potential conflicts:** [any shared file touched, any convention questions]
Merge coordinator (.claude/agents/merge-coordinator.md):
---
name: merge-coordinator
description: Reviews parallel worker results for consistency and produces unified report.
tools: Read, Grep, Glob, Bash
model: sonnet
maxTurns: 15
---
## Role
You are a merge coordinator. After parallel workers complete, you verify
consistency across all changes and produce a unified report.
## Process
1. Read the report from each worker
2. Run consistency checks (see below)
3. If inconsistencies found, list them with specific fix recommendations
4. Produce the unified report
## Consistency Checks
- [ ] Same naming convention (snake_case vs camelCase) across all modules
- [ ] Same error handling pattern (custom exceptions vs HTTPException)
- [ ] Same response model pattern (Pydantic, dataclass, dict)
- [ ] No conflicting changes to shared files (config, utils, __init__)
- [ ] Import paths are consistent and valid
- [ ] No circular dependencies introduced
## Output Format
### Merge Coordination Report
**Workers completed:** [n] of [n]
**Consistency status:** [CONSISTENT | INCONSISTENCIES_FOUND]
#### Per-Worker Summary
- **[module]:** [n] files changed, [summary]
#### Consistency Check Results
- [ ] Naming: [PASS/FAIL — detail]
- [ ] Error handling: [PASS/FAIL — detail]
- [ ] Response models: [PASS/FAIL — detail]
- [ ] Shared files: [PASS/FAIL — detail]
- [ ] Imports: [PASS/FAIL — detail]
- [ ] Circular deps: [PASS/FAIL — detail]
#### Inconsistencies Found
(If any)
- **[inconsistency]** — Found in [modules] — Recommendation: [fix]
#### Final Verdict
[MERGE_READY | NEEDS_FIXES]
The execution prompt
Run this flow:
Phase 1 (parallel): Use the module-worker to refactor these 3 modules
simultaneously, each in an isolated worktree:
1. src/auth/ — update error handling to custom exceptions
2. src/products/ — update error handling to custom exceptions
3. src/orders/ — update error handling to custom exceptions
Phase 2 (sequential): When the 3 workers finish, use the merge-coordinator
to verify that the changes are consistent with each other.
If the merge-coordinator reports inconsistencies, fix them before finishing.
Expected output from the merge coordinator
### Merge Coordination Report
**Workers completed:** 3 of 3
**Consistency status:** INCONSISTENCIES_FOUND
#### Per-Worker Summary
- **auth:** 4 files changed, migrated to AuthError custom exception
- **products:** 3 files changed, migrated to ProductError custom exception
- **orders:** 5 files changed, migrated to OrderError custom exception
#### Consistency Check Results
- [✅] Naming: PASS — all use snake_case
- [⚠️] Error handling: INCONSISTENCY — auth uses AuthError(code, message),
products uses ProductError(message, status_code) — different field order
- [✅] Response models: PASS — all use Pydantic v2
- [✅] Shared files: PASS — no shared files modified
- [✅] Imports: PASS
- [✅] Circular deps: PASS
#### Inconsistencies Found
- **Custom exception constructor** — auth: (code, message), products:
(message, status_code) — Recommendation: standardize to (message, code)
matching Python convention of message-first
#### Final Verdict
NEEDS_FIXES — 1 inconsistency to resolve before merge
Troubleshooting
"The consolidated results lose detail"
Cause: Claude summarizes too much when consolidating reports from multiple subagents.
Solution: Be explicit about what to preserve:
When consolidating, include ALL findings from each subagent.
Don't summarize or omit. Each individual issue must appear in the
final report with its file, line, and original description.
"The merge coordinator doesn't detect inconsistencies"
Cause: The merge coordinator doesn't have specific enough criteria.
Solution: Add concrete criteria with examples of what to verify:
Check that ALL modules use the same pattern for:
- Exception class: ClassName(message: str, code: int)
- HTTP responses: JSONResponse with {"detail": ..., "code": ...}
- Logging: logger.error(f"[MODULE] {message}")
If any module deviates, report the specific deviation.
"The worktree merge has unexpected conflicts"
Cause: The subagents modified a file they shouldn't have (outside their module).
Solution: Reinforce the scope restriction in each worker:
CRITICAL: You MUST only modify files inside [module_path].
If you need to modify a file outside this path, STOP and report it
as a "Potential conflict" in your output instead of modifying it.
"I don't know if the subagents finished in the correct order"
Cause: With parallel execution, the completion order isn't guaranteed.
Solution: You don't need to control the order. Claude waits for all of them to finish before moving to the next phase. If you need a specific subagent to finish first, make it sequential.
"Two subagents make contradictory decisions about conventions"
Cause: They don't have access to shared conventions.
Solution: Use subagents with memory: project (Module 2). The conventions recorded in the shared memory via git guarantee that everyone follows the same rules. Additionally, reference CLAUDE.md in each system prompt.
Exercises
Exercise 1: Draw a dependency graph (Easy)
Given this set of tasks, draw the dependency graph and determine what can go in parallel:
- Create SQLAlchemy models
- Create Pydantic schemas based on the models
- Create CRUD endpoints
- Create tests for the endpoints
- Add OpenAPI documentation
- Configure the CI pipeline
See solution
Dependency graph:
[1. Models]
↓
[2. Schemas] ──→ [5. OpenAPI Docs]
↓
[3. Endpoints] ──→ [4. Tests]
↓
[6. CI pipeline]
Optimized flow:
Phase 1: [1. Models] ← sequential
Phase 2: [2. Schemas] ← sequential (depends on models)
Phase 3: [3. Endpoints] ║ [5. Docs] ← parallel
Phase 4: [4. Tests] ← sequential (depends on endpoints)
Phase 5: [6. CI pipeline] ← sequential (depends on tests)
Only Phase 3 is parallel — docs and endpoints are independent if docs only documents schemas (not endpoints). If docs needs to document endpoints, then docs goes after endpoints (Phase 4 parallel with tests).
Exercise 2: Identify hidden dependencies (Easy)
These 3 refactors look independent. Identify the hidden dependency:
- Refactor
src/auth/to use JWT instead of sessions - Refactor
src/orders/to add soft delete - Refactor
src/middleware/to add rate limiting
See solution
Hidden dependency: src/middleware/ probably imports from src/auth/ to verify authentication in the middleware. If auth changes from sessions to JWT, the rate limiting middleware may need the new JWT interface to verify the user.
auth ──→ middleware (middleware depends on the auth interface)
orders (independent of both)
Correct flow:
Phase 1: [auth] ║ [orders] ← parallel (independent of each other)
Phase 2: [middleware] ← sequential (waits for auth)
Exercise 3: Design a merge coordinator (Medium)
Design the system prompt for a merge coordinator that verifies the consistency of a parallel refactor of 4 microservices. Each microservice must use the same health check pattern, the same logging format, and the same error response schema.
See solution
## Role
You verify that 4 microservices refactored in parallel follow identical patterns.
## Consistency Checks
### Health Check Pattern
Every service MUST have:
- GET /health endpoint
- Response: {"status": "healthy", "service": "[name]", "version": "[semver]"}
- No authentication required
### Logging Format
Every log statement MUST follow:
- logger.[level]("[SERVICE_NAME] [action] [detail]")
- Structured fields: service, action, user_id (if applicable), duration_ms
### Error Response Schema
Every error response MUST use:
- {"error": {"code": "[SERVICE]_[ERROR]", "message": "...", "details": {}}}
- HTTP status codes: 400 (validation), 401 (auth), 403 (forbidden), 404 (not found), 500 (internal)
## Process
1. For each microservice, grep for the health check endpoint
2. For each microservice, grep for logger.* calls
3. For each microservice, grep for error response patterns
4. Compare against the patterns above
5. Report deviations
## Output: per-check PASS/FAIL with specific file:line for failures
Exercise 4: Resolve a logical conflict (Medium)
Two subagents completed in parallel. Their reports say:
- auth worker: "I migrated to bcrypt for password hashing. Hash format: $2b$12$..."
- admin worker: "I implemented password reset. I use sha256 to generate temporary reset tokens."
Is there a logical conflict? If so, what is it and how would you resolve it?
See solution
There's no direct logical conflict — bcrypt for passwords and sha256 for reset tokens are different, compatible uses. bcrypt is for storing passwords (slow hashing, brute-force resistant). sha256 for temporary tokens is acceptable but not optimal.
However, there's an opportunity for improvement: The reset token should use secrets.token_urlsafe() instead of manual sha256. And if the admin worker verified passwords during the reset flow, it needs to use bcrypt (not sha256) for the verification.
Necessary verification: Does the admin worker import the hashing logic from auth, or did it reimplement its own? If it reimplemented, there's duplication (DRY violation) and potential inconsistency.
The merge coordinator should verify: "Do both modules use the same hashing utility, or does each have its own implementation?"
Exercise 5: Plan a complex merge (Hard)
You have 4 parallel workers that completed their tasks. Each one modified files in its module, but they all also modified src/__init__.py to add their exports. Design the merge strategy that avoids conflicts in __init__.py.
See solution
Strategy: Separate the editing of the shared file
Phase 0 (before workers):
Identify that src/__init__.py is a shared file
Phase 1 (parallel with worktrees):
Workers 1-4 refactor their modules
RESTRICTION: "Do NOT modify src/__init__.py"
Each worker REPORTS which exports it needs to add
Phase 2 (sequential — merge coordinator):
1. Read the reports from the 4 workers
2. Collect all the necessary exports
3. Modify src/__init__.py ONCE with all the exports
4. Verify that the imports are valid
The shared file is edited a single time, sequentially, after all the workers finish. The workers report what they need instead of editing it directly.
Alternative with CLAUDE.md: If all the exports follow a predictable pattern, the merge coordinator can auto-generate __init__.py based on the existing files in each module.
Exercise 6: Design a complete hybrid flow (Hard)
Design the complete flow for: "Migrate a REST API to GraphQL. The API has 4 resources: users, products, orders, payments. Each resource has its own router and model."
Define all the phases, what's parallel vs sequential, which subagents you need, and where conflicts could arise.
See solution
Dependency analysis:
- GraphQL schema setup (base) → must exist before resolvers
- The 4 resources are independent of each other for resolvers
- But they all share: schema types, context, middleware
- Tests need all the code finished
Flow:
Phase 0 — SEQUENTIAL (shared setup):
graphql-architect (sonnet)
→ Install dependencies (strawberry/ariadne)
→ Create base schema, context, middleware
→ Define the type patterns all resolvers will follow
Phase 1 — PARALLEL (4 workers with worktree):
├── resource-migrator → users (types + queries + mutations)
├── resource-migrator → products
├── resource-migrator → orders
└── resource-migrator → payments
Phase 2 — SEQUENTIAL (merge):
merge-coordinator
→ Verify that the 4 resources use the same patterns
→ Verify that the types don't conflict
→ Unify the schema registry
→ Verify imports
Phase 3 — PARALLEL (tests):
├── test-generator → tests for users + products
└── test-generator → tests for orders + payments
Phase 4 — SEQUENTIAL:
code-tester → run the complete suite
Possible conflicts:
1. schema.py — all types are registered there
→ Solution: each worker reports its types, merge-coordinator registers them
2. context.py — each resource may need dataloaders
→ Solution: phase 0 defines the pattern, workers follow it
3. Naming: UserType vs UserGraphQLType
→ Solution: phase 0 defines the convention
Summary
- The dependency graph is the essential mental tool — before parallelizing, draw (mentally) what depends on what
- The hidden dependencies (shared files, implicit conventions, shared state) are the most dangerous — asking "do they share anything?" detects them
- Three merge strategies: consolidation by Claude (reports), git worktrees (edits), merge coordinator (verified consistency)
- File conflicts are detected with git; logical conflicts require a merge coordinator with specific criteria
- Preventing conflicts is better than resolving them: identify shared files and edit them sequentially before the parallel phase
- The merge coordinator is a subagent that verifies consistency — naming, error handling, response format — with an explicit checklist
- The parallel-then-sequential pattern (fan-out/fan-in) is the most common: workers in parallel, sequential coordination at the end
- Subagents with memory: project (Module 2) reduce convention conflicts because they share context via git
Additional Resources
- Create Custom Subagents (Anthropic Docs) — Official documentation with
isolation: worktreeandbackground - Claude Code Sub-agents — Worktree Isolation — Reference for isolation via worktrees
- Git Worktrees Documentation — Official git worktrees reference
- Git Merge Documentation — Merge conflict resolution
- Claude Code Best Practices — Delegation and coordination patterns
- Prompt Engineering: Give Claude a Role — Role design for merge coordinators
- Claude Code Tips and Tricks — Tips for subagent coordination
- Claude Models Documentation — Model reference for choosing the right one for coordinators vs workers
Next capsule: In capsule 04 you'll learn what to do when things go wrong — timeout with maxTurns, background permission errors, fallback strategies, and debugging of parallel subagents. Because a parallel system that works on the happy path but collapses at the first error isn't a system — it's a demo.