Module 3: Parallel Sub-Agent Delegation

5. Project — Parallel Refactor of 4 Modules

5. Project — Parallel Refactor of 4 Modules

Project Description

You've learned to launch subagents in parallel with background: true, to isolate them with isolation: worktree so they don't conflict when editing files, to design dependency graphs to identify independent tasks, to coordinate results with a merge coordinator, and to handle errors with fallback strategies. Now you're going to integrate everything into a functional system.

In this project you build a parallel refactoring flow where 4 worker subagents refactor independent modules simultaneously — each in its own git worktree — and a merge coordinator verifies the consistency of the changes and produces a unified report. The flow includes pre-flight checks before launching workers, resilient error handling that lets you continue if a worker fails, and post-merge validation that verifies the tests still pass.

The scenario is concrete: you have a project with 4 modules (auth, products, orders, notifications) that need the same refactoring — standardize error handling to a uniform pattern of custom exceptions. The 4 modules are independent of each other for this refactoring, which makes them perfect candidates for parallel execution.

This is the culminating project of Module 3 and of all of Phase 1. If the 4 workers run in parallel, the coordinator verifies consistency, and the result is a coherent refactoring — you've mastered advanced subagents.


Project Objective

Build a parallel refactoring flow with 4 workers isolated in worktrees, a merge coordinator, pre-flight checks, and post-merge validation.

By the end of this project:

  • ✅ You'll have 4 worker subagent files with background: true and isolation: worktree
  • ✅ You'll have 1 merge coordinator subagent file with a consistency checklist
  • ✅ The 4 workers will run in parallel, each in its own worktree
  • ✅ The merge coordinator will verify that the changes are consistent
  • ✅ Pre-flight checks will validate the project state before the refactoring
  • ✅ Post-merge validation will run tests to confirm there are no regressions
  • ✅ The flow will be resilient — if a worker fails, the others continue
  • ✅ You'll have run the complete flow at least once with verifiable results

Estimated duration: 1.5-2 hours (setup: 20 min + subagents: 30 min + first run: 20 min + verification: 15 min + iteration: 15 min + final validation: 15 min).


Technical Specifications

Technology Stack

  • Tool: Claude Code v2.1.63+
  • Subagent files: Markdown with YAML frontmatter
  • Location: .claude/agents/ (project scope)
  • Models: haiku (pre-flight, coordinator), sonnet (workers)
  • Isolation: git worktrees for each worker
  • Base project: Any project with 4+ modules in src/, tests, and git

Base Project Requirements

RequirementMinimumIdeal
Modules in src/4 directories4 directories with 3+ files each
Existing tests5+15+ covering the 4 modules
Commits in git3+10+
CLAUDE.mdBasicWith style and error handling conventions
Current error handlingHTTPException or similarMixed (what we're going to standardize)

If your project doesn't have exactly 4 modules, adapt the number of workers. What matters is that there are at least 2 independent modules for parallelization to make sense.

Final Project Structure

By the end, your project will have this additional structure:

your-project/
├── .claude/
│   └── agents/
│       ├── pre-flight-checker.md     ← Verifies before launching workers
│       ├── error-handling-worker.md   ← Worker for refactoring (×4)
│       ├── merge-coordinator.md       ← Verifies consistency post-merge
│       ├── code-reviewer.md           ← (from Module 1, optional)
│       ├── code-implementer.md        ← (from Module 1, optional)
│       └── code-tester.md             ← (from Module 1, optional)
├── src/
│   ├── auth/                          ← Worker 1 refactors
│   ├── products/                      ← Worker 2 refactors
│   ├── orders/                        ← Worker 3 refactors
│   └── notifications/                 ← Worker 4 refactors
├── tests/
├── CLAUDE.md
└── ...

Step-by-Step Guide

Step 1: Verify the Project State

Before creating the subagents, verify that your project is ready:

cd your-project

ls src/

git status

claude --version

Verify that you have at least 4 module directories in src/ and that there are no uncommitted changes. If there are pending changes, commit or stash them before continuing.

git stash

Create the agents directory if it doesn't exist:

mkdir -p .claude/agents

Step 2: Create the Pre-Flight Checker

The pre-flight checker verifies that the project is ready for parallel refactoring. It runs before launching the workers.

Create .claude/agents/pre-flight-checker.md:

---
name: pre-flight-checker
description: Verifies project state before parallel refactoring. Checks modules exist, git is clean, tests pass, and CLAUDE.md has conventions.
tools: Read, Glob, Grep, Bash
disallowedTools: Write, Edit
model: haiku
maxTurns: 12
---

## Role

You are a pre-flight checker. Before parallel workers launch, you verify
that the project is ready. You NEVER modify any file. If any check fails,
the parallel refactoring MUST NOT proceed.

## Process

Run these checks in order. Stop at the first FAIL.

### Check 1: Module directories exist
Verify that the specified module directories exist in src/.

### Check 2: Git status is clean
Run `git status --porcelain`. If output is not empty, FAIL.
Uncommitted changes will conflict with worktrees.

### Check 3: Tests pass (baseline)
Run the test suite. If tests fail, FAIL.
We don't want to refactor on top of broken tests.

### Check 4: CLAUDE.md exists
Verify CLAUDE.md exists in the project root.
Workers need conventions to follow.

### Check 5: No cross-module imports for the refactored concern
For each module pair, check if one imports the error handling
utilities from another. If they share error handling code,
parallel refactoring of error handling could conflict.

## Output Format

Follow this EXACT structure:

Pre-Flight Check Report

Check Results

#CheckStatusDetail
1Module directories[PASS/FAIL][detail]
2Git status clean[PASS/FAIL][detail]
3Tests pass[PASS/FAIL][n] passed, [n] failed
4CLAUDE.md exists[PASS/FAIL][detail]
5No cross-module error imports[PASS/FAIL][detail]

Verdict

[ALL_PASS — Ready for parallel refactoring | BLOCKED — Fix issues first]

Issues to Fix (if any)

  • [issue] — How to fix: [recommendation]

Step 3: Create the Error Handling Worker

This is the subagent that refactors an individual module. It's reused for each module — Claude launches it 4 times in parallel, each time with a different module as the target.

Create .claude/agents/error-handling-worker.md:

---
name: error-handling-worker
description: Refactors error handling in a specific module to use custom exception classes. Runs in isolated worktree for parallel execution.
tools: Read, Write, Edit, Grep, Glob
model: sonnet
background: true
isolation: worktree
maxTurns: 25
memory: project
---

## Role

You are a module refactoring specialist. You refactor error handling in ONE
specific module to use a consistent custom exception pattern. You work in
an isolated git worktree — your changes don't affect other workers.

## Target Exception Pattern

Every module should follow this pattern:

```python
# src/{module}/exceptions.py

class ModuleBaseError(Exception):
    """Base exception for the {module} module."""
    def __init__(self, message: str, code: str = "UNKNOWN_ERROR"):
        self.message = message
        self.code = code
        super().__init__(self.message)

class NotFoundError(ModuleBaseError):
    """Resource not found."""
    def __init__(self, resource: str, identifier: str):
        super().__init__(
            message=f"{resource} with id '{identifier}' not found",
            code=f"{MODULE}_NOT_FOUND"
        )

class ValidationError(ModuleBaseError):
    """Validation failed."""
    def __init__(self, field: str, reason: str):
        super().__init__(
            message=f"Validation failed for '{field}': {reason}",
            code=f"{MODULE}_VALIDATION_ERROR"
        )

class PermissionError(ModuleBaseError):
    """Permission denied."""
    def __init__(self, action: str):
        super().__init__(
            message=f"Permission denied for action: {action}",
            code=f"{MODULE}_PERMISSION_DENIED"
        )

Constraints

  • ONLY modify files inside the specified module directory (src/{module}/)
  • NEVER modify files outside your module
  • NEVER modify test files
  • NEVER modify shared config or utils outside your module
  • Follow existing code style in the project
  • If you need a shared utility that doesn't exist, note it in your report but DO NOT create it outside your module

Process

  1. Read your MEMORY.md for project conventions
  2. List all files in the target module
  3. Read each file to understand current error handling
  4. Create src/{module}/exceptions.py with the custom exception classes
  5. Update each file to use the new exceptions instead of raw HTTPException or generic Exception
  6. Verify no imports break (grep for the old patterns)
  7. Produce the refactoring report
  8. Update your MEMORY.md with new conventions discovered

Refactoring Rules

  • Replace raise HTTPException(status_code=404, ...) with raise NotFoundError(...)
  • Replace raise HTTPException(status_code=422, ...) with raise ValidationError(...)
  • Replace raise HTTPException(status_code=403, ...) with raise PermissionError(...)
  • Keep HTTPException(status_code=500, ...) for truly unexpected errors
  • Add exception handler registration in the module's __init__.py if applicable

Output Format

Follow this EXACT structure:

## Refactoring Report: [module name]

**Module:** src/[module]/
**Files modified:** [list]
**Files created:** [list]
**Exceptions defined:** [list of exception classes]

### Changes Made

1. **[file]** — [what changed]
   - Before: `raise HTTPException(status_code=X, detail="...")`
   - After: `raise CustomError(...)`
   - Lines changed: [n]

2. ...

### Exception Hierarchy

ModuleBaseError ├── NotFoundError ├── ValidationError └── PermissionError


### Potential Conflicts

- [any shared file that might need updating but is outside this module]
- [any convention question that the coordinator should verify]

### Not Changed

- [files or patterns left unchanged, with reason]

### Status: [COMPLETE | PARTIAL (reason)]

### Step 4: Create the Merge Coordinator

The merge coordinator runs after the 4 workers finish. It verifies that the changes are consistent across modules.

Create `.claude/agents/merge-coordinator.md`:

```markdown
---
name: merge-coordinator
description: Reviews results from parallel error-handling workers. Verifies consistency across modules and produces unified report.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: sonnet
maxTurns: 20
---

## Role

You are a merge coordinator. After 4 parallel workers refactor error handling
in their respective modules, you verify that the changes are consistent across
all modules. You NEVER modify files — you only analyze and report.

## Process

1. Read the refactoring report from each worker
2. For each module, read the new exceptions.py file
3. Run the consistency checks below
4. Verify no shared files were modified by multiple workers
5. Run the test suite to check for regressions
6. Produce the coordination report

## Consistency Checks

### 1. Exception Class Structure
All modules MUST follow the same hierarchy:
- ModuleBaseError(message, code)
- NotFoundError(resource, identifier)
- ValidationError(field, reason)
- PermissionError(action)

Check: same constructor signatures, same base class pattern.

### 2. Error Code Format
All error codes MUST follow: {MODULE}_{ERROR_TYPE}
- AUTH_NOT_FOUND, PRODUCTS_VALIDATION_ERROR, etc.
- Check that MODULE prefix matches the actual module name

### 3. Exception Message Format
All messages MUST be human-readable English sentences.
- "User with id '123' not found" ✅
- "NOT_FOUND_USER_123" ❌

### 4. Import Pattern
All modules MUST import exceptions the same way:
- `from src.{module}.exceptions import NotFoundError, ValidationError`
- NOT: `from src.{module}.exceptions import *`

### 5. No Shared File Conflicts
Verify that workers only modified files inside their own module.
Run: `git diff --name-only` and verify all changes are scoped correctly.

## Output Format

Follow this EXACT structure:

Merge Coordination Report

Workers completed: [n] of 4 Modules: [list] Total files modified: [n]

Per-Module Summary

ModuleFiles ChangedExceptions DefinedStatus
auth[n][n][COMPLETE/PARTIAL]
products[n][n][COMPLETE/PARTIAL]
orders[n][n][COMPLETE/PARTIAL]
notifications[n][n][COMPLETE/PARTIAL]

Consistency Check Results

#CheckStatusDetail
1Exception class structure[PASS/FAIL][detail]
2Error code format[PASS/FAIL][detail]
3Message format[PASS/FAIL][detail]
4Import pattern[PASS/FAIL][detail]
5No shared file conflicts[PASS/FAIL][detail]

Inconsistencies Found

(If any — otherwise write "None found.")

  • [inconsistency]
    • Modules affected: [list]
    • Detail: [specific difference]
    • Recommendation: [how to fix]

Test Results (Post-Merge)

  • Tests passed: [n]
  • Tests failed: [n]
  • New failures: [list, if any]

Final Verdict

[MERGE_READY | NEEDS_FIXES]

If NEEDS_FIXES:

  • [fix 1]
  • [fix 2]

Step 5: Verify the 3 Subagents

Before running the flow, verify that the 3 subagent files are detected correctly.

/agents

You should see:

Project agents (.claude/agents/):
  pre-flight-checker      — Verifies project state before parallel refactoring...
  error-handling-worker   — Refactors error handling in a specific module...
  merge-coordinator       — Reviews results from parallel error-handling workers...

Verify the capabilities table:

Toolpre-flight-checkererror-handling-workermerge-coordinator
Read✅✅✅
Write❌✅❌
Edit❌✅❌
Grep✅✅✅
Glob✅✅✅
Bash✅❌✅
background❌✅❌
isolation❌worktree❌

Each subagent has exactly the tools it needs for its role.

Step 6: Run Pre-Flight Checks

Before launching the workers, verify that the project is ready:

Use the pre-flight-checker to verify that the project is ready
for a parallel refactoring of error handling in these 4 modules:
src/auth/, src/products/, src/orders/, src/notifications/

What to verify in the output:

  • ✅ The 4 module directories exist
  • ✅ Git status is clean
  • ✅ The tests pass (baseline)
  • ✅ CLAUDE.md exists
  • ✅ There are no cross-module error handling imports between modules

If any check fails:

  • Module doesn't exist: Verify the names of your modules and adjust
  • Git isn't clean: git add . && git commit -m "pre-refactor state" or git stash
  • Tests fail: Fix the tests first — don't refactor over broken tests
  • CLAUDE.md doesn't exist: Create a basic one with your project conventions
  • Cross-module imports: Identify the imports and decide whether you need a previous sequential phase

Step 7: Run the 4 Workers in Parallel

This is the central step of the project. Launch the 4 workers simultaneously:

Run the error-handling-worker for these 4 modules IN PARALLEL,
each in an isolated worktree:

1. src/auth/ — refactor error handling to custom exceptions (AuthBaseError)
2. src/products/ — refactor error handling to custom exceptions (ProductsBaseError)
3. src/orders/ — refactor error handling to custom exceptions (OrdersBaseError)
4. src/notifications/ — refactor error handling to custom exceptions (NotificationsBaseError)

Each worker should:
- Create an exceptions.py file in its module
- Replace HTTPException with custom exceptions
- Report all the changes made

If any worker fails, continue with the others (resilient strategy).
When they all finish, give me the 4 individual reports.

What to observe during execution:

  1. Claude launches 4 instances of the error-handling-worker in the background
  2. Each worker operates in its own git worktree
  3. The workers finish at different times (the largest module takes longer)
  4. Claude waits for all of them to finish before presenting results

Expected time: 2-4 minutes (depends on the size of the modules). Compared to sequential execution, which would take 8-16 minutes.

Step 8: Review the Workers' Reports

After the 4 workers finish, review the individual reports:

For each worker, verify:

  • ✅ src/{module}/exceptions.py was created with the exception classes
  • ✅ The module's files were updated to use the custom exceptions
  • ✅ Only files inside the corresponding module were modified
  • ✅ The report lists all the changes and possible conflicts
  • ✅ The status is COMPLETE (not PARTIAL)

If a worker reports PARTIAL:

Review the reason. If it was due to insufficient maxTurns, you can re-run only that worker with more turns:

The orders worker ended up partial. Re-run the error-handling-worker
only for src/orders/ with extended maxTurns. The other 3 modules
are already complete.

Step 9: Run the Merge Coordinator

With the 4 workers completed, launch the merge coordinator:

Use the merge-coordinator to verify the consistency of the changes
made by the 4 error handling workers.

Verify that the 4 modules (auth, products, orders, notifications) use
the same exception pattern, the same error code format,
and the same message style.

Run the tests after verifying consistency.

What to verify in the output:

  • ✅ The 4 workers report COMPLETE
  • ✅ All the consistency checks are PASS
  • ✅ There are no inconsistencies found (or the ones found are minor)
  • ✅ The tests pass after the merge
  • ✅ The verdict is MERGE_READY

If the coordinator reports NEEDS_FIXES:

The most common inconsistencies:

  1. Different constructor signatures — one module uses (message, code) and another (code, message):
Fix the inconsistency: the products module has the NotFoundError
constructor with the parameters in a different order than auth.
Use the order (resource, identifier) for all modules.
  1. Different error code format — one module uses AUTH_NOT_FOUND and another uses auth_not_found:
Standardize the error codes to UPPER_CASE across all modules.
All 4 must follow the pattern {MODULE}_NOT_FOUND, not {module}_not_found.
  1. Different import patterns — one module uses from .exceptions import *:
Update src/notifications/ to use explicit imports:
from .exceptions import NotFoundError, ValidationError
instead of from .exceptions import *

Step 10: Post-Merge Validation

After resolving any inconsistency, run a final validation:

Run the post-merge validation:
1. Run the linter on the modified files
2. Run the complete test suite
3. Verify there are no broken imports

Report the final result.

Manual verification:

git diff --stat

git diff --name-only

All the modified files must be inside the 4 modules. If there are files outside src/auth/, src/products/, src/orders/, or src/notifications/, a worker violated its scope restriction.

python -m pytest -v --tb=short 2>&1

If the tests pass: the parallel refactoring was successful.

Step 11: Commit the Result

If everything is correct, commit the changes:

git add .

git diff --cached --stat

git commit -m "Refactor error handling to custom exceptions across 4 modules

- auth: AuthBaseError, NotFoundError, ValidationError, PermissionError
- products: ProductsBaseError, NotFoundError, ValidationError, PermissionError
- orders: OrdersBaseError, NotFoundError, ValidationError, PermissionError
- notifications: NotificationsBaseError, NotFoundError, ValidationError, PermissionError

All modules follow consistent exception hierarchy, error code format,
and message pattern. Refactored in parallel with 4 isolated workers."

The Complete Visual Flow

Your prompt
    │
    ▼
┌─────────────────────────────────────────────┐
│           Claude (main conversation)         │
│                                              │
│  Phase 0: Pre-flight checks                 │
│  ├── pre-flight-checker                      │
│  └── Result: ALL_PASS ✅                     │
│                                              │
│  Phase 1: Parallel workers                   │
│  ├── worker auth         ─── worktree 1 ──┐ │
│  ├── worker products     ─── worktree 2 ──┤ │
│  ├── worker orders       ─── worktree 3 ──┤ │
│  └── worker notifications ── worktree 4 ──┘ │
│       (4 workers running simultaneously)     │
│                                              │
│  Phase 2: Merge coordination                 │
│  ├── merge-coordinator                       │
│  ├── Consistency checks: 5/5 PASS           │
│  └── Tests: ALL_PASS ✅                     │
│                                              │
│  Phase 3: Final result                       │
│  └── Consolidated report                    │
└─────────────────────────────────────────────┘

Validation Checklist

Files created

  • .claude/agents/pre-flight-checker.md exists and has valid frontmatter
  • .claude/agents/error-handling-worker.md exists with background: true and isolation: worktree
  • .claude/agents/merge-coordinator.md exists with disallowedTools: Write, Edit

Pre-flight

  • The 4 modules exist in src/
  • Git status is clean
  • Tests pass before the refactoring (baseline)
  • CLAUDE.md exists
  • There are no cross-module error handling imports

Parallel workers

  • The 4 workers ran in parallel (not sequentially)
  • Each worker created exceptions.py in its module
  • Each worker only modified files inside its module
  • Each worker reported COMPLETE (or PARTIAL with a reason)
  • The 4 workers produced structured reports

Merge coordination

  • The merge coordinator verified the 5 consistency checks
  • The error codes follow the format {MODULE}_{ERROR_TYPE}
  • The constructors have the same signature in the 4 modules
  • The imports are explicit (no import *)
  • There are no modified files outside the 4 modules

Post-merge validation

  • The tests pass after the refactoring
  • There are no broken imports
  • The linter doesn't report new errors
  • The changes are committed

Timing

  • The parallel execution was significantly faster than sequential
  • (Optional) You recorded the time: parallel = ___ min, sequential estimate = ___ min

Common Errors and Solutions

Error 1: "The workers don't run in parallel"

Symptom: The workers run one after another.

Possible causes:

  • background: true isn't in the worker's frontmatter
  • CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 is active in the environment
  • The prompt doesn't clearly indicate that they should run in parallel

Solution:

echo $CLAUDE_CODE_DISABLE_BACKGROUND_TASKS

If it returns 1, disable it:

unset CLAUDE_CODE_DISABLE_BACKGROUND_TASKS

Verify that the worker's frontmatter has background: true. Use an explicit prompt:

Run these 4 workers IN PARALLEL, simultaneously, each one
as an independent subagent in the background.

Error 2: "A worker modifies files outside its module"

Symptom: git diff --name-only shows files outside src/{module}/.

Cause: The system prompt says "ONLY modify files inside src/{module}/" but the restriction isn't technically enforced.

Solution: Add a stronger restriction to the system prompt:

CRITICAL RULE: If the file path does not start with "src/{module}/",
you MUST NOT edit it. Not even if it seems necessary. Instead, report
it as a "Potential Conflict" in your output.

If changes were already made outside the scope:

git checkout -- src/shared/
git checkout -- src/config.py

This reverts the files that shouldn't have been modified.

Error 3: "The worktrees aren't cleaned up"

Symptom: git worktree list shows orphaned worktrees.

Cause: A worker crashed before completing normally.

Solution:

git worktree list
git worktree prune
git worktree list

prune cleans up worktrees whose directories no longer exist.

Error 4: "The merge coordinator finds inconsistencies"

Symptom: The report says NEEDS_FIXES with inconsistencies between modules.

Cause: The workers didn't have enough context about the convention to follow.

Solution: Fix the inconsistencies manually or with a targeted prompt:

The merge coordinator found that the products module uses error codes
in lowercase (products_not_found) while the other 3 use UPPERCASE
(AUTH_NOT_FOUND). Fix products to use UPPERCASE.

To prevent: include a complete example of the target pattern in the worker's system prompt, with the exact error code format.

Error 5: "The tests fail after the refactoring"

Symptom: Tests that passed before the refactoring now fail.

Cause: The tests expect HTTPException but now the code raises custom exceptions. The tests need to be updated to catch the new exceptions, or you need an exception handler that converts custom exceptions to HTTP responses.

Solution:

The tests fail because they expect HTTPException but the code now
raises custom exceptions. There are two options:
1. Add an exception handler in FastAPI that converts
   ModuleBaseError → JSONResponse
2. Update the tests to catch the custom exceptions

Recommend option 1 (exception handler) and implement it.

Option 1 is better because it keeps the separation between the business logic (custom exceptions) and the HTTP framework (FastAPI responses).

Error 6: "A worker ends as PARTIAL due to maxTurns"

Symptom: A worker reports "PARTIAL — reached turn limit."

Cause: The module is larger than expected and 25 turns weren't enough.

Solution: Re-run only that worker with more turns:

Re-run the error-handling-worker only for src/orders/
with maxTurns 35. The other 3 modules are already complete.
Continue from where it left off — don't redo the changes already applied.

Error 7: "I don't have 4 modules in my project"

Symptom: Your project has 2 or 3 modules, not 4.

Solution: Adapt the project to your situation:

  • 2 modules: Run 2 workers in parallel. The gain is smaller but the concept applies.
  • 3 modules: Run 3 workers. It works perfectly.
  • 6+ modules: Run the 4 most important ones in parallel. You can do a second round for the remaining ones.

Error 8: "The worker and the merge coordinator don't communicate"

Symptom: The merge coordinator doesn't have the workers' reports.

Cause: Subagents don't share context directly. Claude (main) acts as the intermediary.

Solution: Be explicit in the orchestration prompt:

When the 4 workers finish, pass the 4 COMPLETE reports
to the merge-coordinator as context. Include all the details
of each report — modified files, changes made,
and potential conflicts.

Project Variations

Variation 1: Parallel analysis (read-only)

If you don't want to make changes yet, run only an analysis:

Analyze the 4 modules in parallel to identify what error handling
currently exists in each one. Don't modify anything — only report.
Then, give me a unified refactoring plan.

Variation 2: Incremental refactor

Instead of refactoring the 4 modules at once, do it in 2 rounds:

Round 1: Refactor auth and products in parallel
Round 2: Refactor orders and notifications in parallel

After each round, verify consistency and tests.

Variation 3: Competitive refactoring

Launch 2 workers with different strategies for the same module:

Worker A: Refactor auth with custom exception classes
Worker B: Refactor auth with a decorator pattern for error handling

Compare both approaches and recommend which one to adopt.

Project Resources

  1. Create Custom Subagents (Anthropic Docs) — Official documentation with background, isolation: worktree, and maxTurns
  2. Claude Code Sub-agents — Background Execution — Reference for pre-approved permissions and background execution
  3. Claude Code Sub-agents — Worktree Isolation — Reference for git worktrees for isolation
  4. Git Worktrees Documentation — Official git worktrees reference
  5. Claude Code Best Practices — Delegation and error handling patterns
  6. Claude Code CLI Reference — Environment variables like CLAUDE_CODE_DISABLE_BACKGROUND_TASKS

Connection to the Next Module

You've built a parallel refactoring system with 4 isolated workers, a merge coordinator, and a robust flow with pre-flight checks and post-merge validation. It works. But you coordinated it manually — you wrote the prompt that orchestrates the 3 phases, you decided when to launch the coordinator, you decided the fallback strategy.

Module 4: Agent Teams formalizes exactly this coordination. What you did here with manual prompts, Agent Teams does with a team lead that manages a task board, declares dependencies between tasks, and coordinates teammates automatically. The team lead knows that the 4 workers are parallel and that the coordinator waits for all of them. It knows because the dependencies are declared, not because you told it in a prompt.

The analogy: this module taught you to be the project manager who manually coordinates a team of 4 developers. Agent Teams gives you a project management system (Jira, Linear) where the dependencies are explicit and the flow runs automatically.

The subagents you created here — specialized workers with worktree isolation, merge coordinators with consistency checklists — are exactly the ones you'll turn into teammates of an Agent Team. The transition is direct: the same Markdown files, the same YAML frontmatter, but now orchestrated by a team lead instead of by your prompts.


Summary

  • You built a complete parallel refactoring flow: pre-flight → 4 parallel workers → merge coordination → post-merge validation
  • The 4 workers use background: true and isolation: worktree for parallel execution without conflicts
  • The merge coordinator verifies 5 aspects of consistency: exception structure, error code format, message format, import pattern, and change scope
  • Pre-flight checks prevent predictable failures by verifying the project state before launching workers
  • The resilient error handling strategy lets you continue if a worker fails without affecting the others
  • The result is a coherent refactoring of 4 modules with a uniform pattern of custom exceptions
  • Parallel execution reduces the total time from ~12 sequential minutes to ~4 minutes
  • The subagents created here are the building blocks of Agent Teams (Module 4) — the same functionality, but with automated coordination
  • This project closes Phase 1 — you master custom subagents (M1), persistent memory (M2), and parallel delegation (M3)

Next module: Module 4 (Agent Teams) takes everything you built in Phase 1 — specialized subagents, shared memory, parallel delegation — and formalizes it with a team lead, task board, declared dependencies, and automatic coordination. The subagents you created here become teammates. The manual coordination you did here becomes a declarative system. You go from being the project manager to configuring the project management system.