
Parallel Worktrees
- 4 installs
- 11 repo stars
- Updated December 29, 2025
- spillwavesolutions/parallel-worktrees
Helps with ai & agent building tasks during AI-assisted development.
About
parallel-worktrees is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- parallel-worktrees
- AI & Agent Building
- AI-coding skill
Parallel Worktrees by the numbers
- 4 all-time installs (skills.sh)
- Ranked #13,348 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/spillwavesolutions/parallel-worktrees --skill parallel-worktreesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 4 |
|---|---|
| repo stars | ★ 11 |
| Last updated | December 29, 2025 |
| Repository | spillwavesolutions/parallel-worktrees ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Parallel Worktrees with Claude Code Subagents
Run multiple Claude Code agents simultaneously across git worktrees to transform a single developer into a team of AI engineers. LLM non-determinism becomes an advantage: running N parallel agents produces multiple valid solutions to choose from.
Table of Contents
- Core Workflow
- Git Worktrees Essentials
- Claude Code Subagents
- Spawning Parallel Subagents
- Workflow Patterns
- Dependency Management
- Common Pitfalls
- When to Use Parallel vs Sequential
- Resource Considerations
- Background Subagents with Worktree Coordination
Core Workflow
1. Create isolated worktrees for each task 2. Spawn independent Claude sessions in each 3. Cycle through to monitor progress and approve permissions 4. Merge the best results
Git Worktrees Essentials
Worktrees create additional working directories sharing a single .git database. Unlike cloning, they save disk space and keep history unified.
Key Commands
# Create worktree with new branch from main
git worktree add ../project-feature-a -b feature-a main
# Create worktree for existing branch
git worktree add ../project-bugfix bugfix-123
# Organized subdirectory pattern (recommended)
mkdir -p .worktrees && echo ".worktrees/" >> .gitignore
git worktree add .worktrees/feature-auth -b feature/auth main
# List all worktrees
git worktree list
# Remove worktree (use --force if uncommitted changes)
git worktree remove ../project-feature-a
# Clean stale metadata
git worktree pruneDirectory Patterns
Adjacent folders: my-project/, my-project-feature-a/, my-project-bugfix/
Subdirectory pattern (keeps things organized):
my-project/
├── .worktrees/
│ ├── feature-auth/
│ ├── feature-api/
│ └── bugfix-login/
└── (main working tree)Claude Code Subagents
Subagents are specialized AI assistants with isolated context windows, custom prompts, and configurable tool access.
Built-in Subagents
| Subagent | Model | Tools | Purpose |
|---|---|---|---|
| General-Purpose | Sonnet | All (read/write) | Complex multi-step operations |
| Plan | Sonnet | Read-only | Gather info before planning |
| Explore | Haiku | Read-only | Fast code analysis |
Creating Custom Subagents
Interactive: /agents command opens management menu (recommended)
File-based: Place markdown with YAML frontmatter in:
.claude/agents/*.md(project-scoped)~/.claude/agents/*.md(user-scoped)
---
name: code-reviewer
description: Expert code review specialist. Use PROACTIVELY after changes.
tools: Read, Grep, Glob, Bash
model: inherit
---
Acts as a senior code reviewer. When invoked:
1. Run git diff to see changes
2. Focus on modified files
3. Prioritize: Critical → Warnings → SuggestionsNote: Including "PROACTIVELY" or "MUST BE USED" in descriptions increases automatic invocation.
Spawning Parallel Agents
True parallelism requires separate Claude processes in different worktrees. Within a single REPL, subagents execute sequentially.
# Terminal 1
cd ../project-feature-a && claude
# Terminal 2
cd ../project-feature-b && claude
# Terminal 3
cd ../project-refactor && claudeQuick Setup Script
#!/bin/bash
# spawn-parallel.sh FEATURE_NAME NUM_AGENTS
FEATURE=$1
NUM=${2:-3}
for i in $(seq 1 $NUM); do
git worktree add ".worktrees/${FEATURE}-${i}" -b "${FEATURE}-${i}" main
cp .env ".worktrees/${FEATURE}-${i}/" 2>/dev/null || true
done
echo "Worktrees created. Start Claude in each:"
for i in $(seq 1 $NUM); do
echo " cd .worktrees/${FEATURE}-${i} && claude"
doneCustom Slash Commands
Create .claude/commands/init-parallel.md:
Create $NUM git worktrees for parallel development of $FEATURE.
1. Create .worktrees/ directory if needed
2. For each tree (1 to $NUM):
- Create worktree at `.worktrees/$FEATURE-{i}/`
- Create branch `$FEATURE-{i}`
- Copy environment files
3. Print commands to start Claude in eachWorkflow Patterns
Pattern 1: Parallel Feature Implementation
Create 3-4 worktrees for the same feature, give each identical instructions, compare results, merge best implementation.
Pattern 2: Explore, Plan, Code, Commit
1. Ask Claude to read relevant files (no writes) 2. Use thinking keywords ("think hard", "ultrathink") for extended reasoning 3. Have Claude create a plan document 4. Implement and commit
Pattern 3: Test-Driven Parallel
1. First Claude writes tests, confirms they fail, commits 2. Second Claude (or /clear) implements to pass tests 3. Third independent review catches overfitting
Pattern 4: Dual Claude Verification
1. One Claude writes code 2. After /clear or in different session, another Claude reviews 3. Fresh context catches issues original session missed
Essential CLI Reference
See references/cli-reference.md for the complete CLI command reference.
Key commands:
claude- Start interactive session/clear- Reset context window/agents- Manage subagents
Dependency Management
Each worktree needs its own node_modules, venvs, etc.
# Fast copy (APFS/btrfs copy-on-write)
cp -c -r ../main/node_modules . # macOS
cp --reflink=auto -r ../main/node_modules . # Linux
# Deterministic install from lockfile
npm ci
# Copy environment files
cp ../main/.env . 2>/dev/null || trueCommon Pitfalls
| Issue | Solution |
|---|---|
| "Branch already checked out" | Use different branch name or --force |
| Port conflicts | Configure different ports per worktree |
| Missing dependencies | Run setup process in each new worktree |
| Outdated worktrees | git fetch origin && git rebase origin/main |
| Claude can't create worktrees | Use shell scripts outside Claude, then start Claude within |
| Context confusion | One terminal tab per worktree, clear naming |
When to Use Parallel vs Sequential
Use parallel worktrees when:
- Multiple valid solutions exist (UI, algorithms)
- Complex tasks have failure risk (run 3, pick winner)
- Clear detailed plan exists for independent execution
- Features don't overlap in file modifications
Use sequential when:
- Critical refactors requiring consistency
- Tightly coupled changes to same files
- Merge conflicts would cost more than parallelism saves
Resource Considerations
- Token usage: ~15x higher with multi-agent workflows
- Subagents cannot spawn other subagents (no infinite nesting)
- Each subagent starts with clean context, needs codebase orientation
- Factor token consumption into subscription limits
Background Agents with Worktree Coordination
Claude Code natively supports background agents via the Task tool with run_in_background: true. This section codifies how background agents coordinate work across git worktrees for parallel task execution.
Architecture
Main Worktree (Orchestrator)
├── .agent-status/ # Coordination hub (tracked in .gitignore)
│ ├── task-api.json # {"status": "RUNNING|COMPLETE|FAILED", "started": "...", "result": "..."}
│ └── task-ui.json
├── .agent-tasks/ # Task prompts for retry/reference
│ ├── task-api.md
│ └── task-ui.md
└── .worktrees/
├── task-api/ # Background agent 1
│ └── RESULTS.md # Agent writes summary here
└── task-ui/ # Background agent 2
└── RESULTS.mdUsing Claude Code's Native Background Agents
Background agents are launched via the Task tool:
Task tool with:
- run_in_background: true
- prompt: "Work in .worktrees/task-api/. Implement the REST API..."
- subagent_type: "general-purpose"Use TaskOutput to check status and retrieve results when ready.
Worktree Setup for Background Agents
Before spawning background agents, prepare worktrees:
# Create worktrees for parallel tasks
./scripts/spawn-parallel.sh feature-api 1 # Creates .worktrees/feature-api-1/
./scripts/spawn-parallel.sh feature-ui 1 # Creates .worktrees/feature-ui-1/
# Or manually
git worktree add .worktrees/task-api -b task-api main
git worktree add .worktrees/task-ui -b task-ui mainStatus File Convention
Background agents write status to .agent-status/TASK_NAME.json:
{
"status": "COMPLETE",
"started": "2024-01-15T10:30:00Z",
"completed": "2024-01-15T10:45:00Z",
"worktree": ".worktrees/task-api",
"branch": "task-api",
"summary": "Implemented 5 endpoints, 12 tests passing",
"files_changed": ["src/api/users.ts", "tests/api.test.ts"]
}Status values: RUNNING, COMPLETE, FAILED, BLOCKED
Agent Task Instructions Template
Include these instructions when spawning background agents:
## Task: [Task Name]
Work in the worktree at `.worktrees/[task-name]/`
### Requirements
[Specific task requirements]
### On Completion
1. Write a summary to `RESULTS.md` in the worktree
2. Commit all changes: `git add -A && git commit -m "[task-name]: [summary]"`
3. Update status file: Write to `../.agent-status/[task-name].json`:
{"status": "COMPLETE", "summary": "[summary of accomplishments]"}
### On Failure
1. Document the issue in `RESULTS.md`
2. Update status: {"status": "FAILED", "error": "[what went wrong]"}Orchestration Patterns
Pattern 1: Delegate and Continue
Orchestrator workflow:
1. Create worktrees for each task
2. Launch background agents with Task tool (run_in_background: true)
3. Continue working on primary task
4. Periodically check .agent-status/*.json files
5. When agents complete, review RESULTS.md and mergePattern 2: Fan-Out/Fan-In
1. Spawn N background agents for N independent subtasks
2. Each works in its own worktree
3. Use TaskOutput to wait for all to complete
4. Run ./scripts/sync-worktrees.sh to merge all resultsPattern 3: Pipeline with Dependencies
1. Background Agent A: Schema changes (no dependencies)
2. Wait for A to complete (check status file)
3. Background Agents B, C: API and UI (depend on schema)
4. Wait for B, C to complete
5. Merge in dependency order: A → B → CSyncing and Merging Results
# Review all worktree changes
./scripts/sync-worktrees.sh --status
# Merge completed work to main
./scripts/sync-worktrees.sh --merge
# Interactive mode: review each before merging
./scripts/sync-worktrees.sh --interactiveGit-Based Signaling (Alternative)
For distributed setups or when status files aren't accessible:
# Background agent signals via branch push
git push origin task-api
# Main agent monitors
git fetch --all
git branch -r | grep -E "origin/(task-|feature-)"
# Check if branch has new commits
git log main..origin/task-api --onelineBest Practices
1. One worktree per background agent: Ensures complete isolation 2. Non-overlapping file assignments: Prevents merge conflicts 3. Always write RESULTS.md: Provides context for merging 4. Commit before signaling complete: Ensures work is preserved 5. Use descriptive branch names: Makes merge history readable 6. Clean up after merge: Remove worktrees and status files 7. Set timeouts: Prevent runaway agents consuming resources
Checking Agent Status from Main Session
The main Claude session can monitor background agents:
# Quick status check
cat .agent-status/*.json | jq -r '.status'
# Detailed view
for f in .agent-status/*.json; do
echo "=== $(basename $f .json) ==="
cat "$f" | jq .
done
# Check if all complete
if grep -L '"status": "COMPLETE"' .agent-status/*.json; then
echo "Some agents still running"
else
echo "All agents complete - ready to merge"
fiParallel Worktrees Skill for Claude Code
  
Run multiple Claude Code agents simultaneously across git worktrees - transform a single developer into a team of AI engineers.
Overview
This skill enables parallel AI-assisted development by combining git worktrees (isolated working directories sharing a single .git database) with Claude Code agents (independent Claude sessions or background Task agents). It exploits LLM non-determinism as a feature: running N parallel agents gives you N valid solutions to choose from.
Two modes of operation: 1. Interactive Parallel: Multiple terminal sessions with Claude in separate worktrees 2. Background Orchestration: Main agent delegates to background agents in worktrees, continues working, syncs results when complete
Features
- Parallel Development - Spawn multiple Claude agents working simultaneously on the same task
- Competitive Solutions - Leverage LLM non-determinism to get N different implementations
- Background Orchestration - Delegate work to background agents while continuing main task
- Easy Merging - Compare implementations and merge the best solution
- Resource Efficiency - Worktrees share
.gitdatabase, saving disk space - Workflow Scripts - Ready-to-use scripts for spawning, syncing, and cleanup
Installation
Installing with Skilz (Recommended)
The easiest way to install this skill is using the Skilz Universal Installer:
# Install Skilz (one-time setup)
curl -fsSL https://raw.githubusercontent.com/SpillwaveSolutions/skilz/main/install.sh | bash
# Install this skill
skilz install SpillwaveSolutions_parallel-worktrees/parallel-worktreesView on the Skilz Marketplace: parallel-worktrees
Manual Installation
Clone directly into your Claude Code skills directory:
# Navigate to your skills directory
cd ~/.claude/skills
# Clone the repository
git clone https://github.com/SpillwaveSolutions/parallel-worktrees.gitVerify Installation
After installation, verify the skill is available:
# List installed skills
ls ~/.claude/skills/parallel-worktrees
# Or ask Claude Code
# "List my installed skills"Trigger Phrases
Claude Code automatically activates this skill when you mention:
- "parallel agents" / "background agents"
- "worktrees" / "agent coordination"
- "subagents" / "parallel tasks"
- "async Claude" / "spawn agents"
- "parallel development" / "multi-agent workflow"
Quick Start
1. Create Parallel Worktrees
# Create 3 worktrees for a feature
./scripts/spawn-parallel.sh user-dashboard 3
# Output:
# cd .worktrees/user-dashboard-1 && claude
# cd .worktrees/user-dashboard-2 && claude
# cd .worktrees/user-dashboard-3 && claude2. Start Claude in Each
Open separate terminals and run Claude in each worktree:
# Terminal 1
cd .worktrees/user-dashboard-1 && claude
# Terminal 2
cd .worktrees/user-dashboard-2 && claude
# Terminal 3
cd .worktrees/user-dashboard-3 && claude3. Give Identical Instructions
In each session, provide the same prompt. Each Claude instance works independently with its own context window.
4. Compare and Merge
# Compare implementations
cd .worktrees/user-dashboard-1 && git diff main
cd .worktrees/user-dashboard-2 && git diff main
# Merge the winner
git checkout main
git merge user-dashboard-25. Clean Up
./scripts/cleanup-worktrees.sh user-dashboard --delete-branchesWorkflow Patterns
| Pattern | Description | Use Case |
|---|---|---|
| Competitive Implementation | N agents on same task, pick best | UI components, algorithms |
| Divide and Conquer | Split feature into parallel tracks | Large features with independent parts |
| Redundant Safety Net | Multiple agents as backup | Critical/risky changes |
| Exploration Sprint | Each agent tries different approach | Architecture decisions (WebSocket vs SSE vs polling) |
| Test-First Parallel | One writes tests, others implement | TDD workflows |
| Review Pipeline | Separate implementation and review | Fresh-eyes code review |
See references/workflow-patterns.md for detailed examples.
Scripts
spawn-parallel.sh
Creates parallel git worktrees for multi-agent development.
./scripts/spawn-parallel.sh <feature-name> [num-agents] [base-branch]| Parameter | Description | Default |
|---|---|---|
feature-name | Name for the feature (used in branch names) | Required |
num-agents | Number of parallel worktrees | 3 |
base-branch | Branch to base worktrees on | main |
Example:
./scripts/spawn-parallel.sh auth-refactor 4 developcleanup-worktrees.sh
Removes parallel worktrees and optionally their branches.
./scripts/cleanup-worktrees.sh <feature-name> [--delete-branches]- Detects uncommitted changes and prompts before force-removing
- Prunes stale worktree metadata
- Shows remaining worktrees when done
sync-worktrees.sh
Reviews and merges completed worktree work back to main.
./scripts/sync-worktrees.sh [--status|--merge|--interactive]| Option | Description |
|---|---|
--status, -s | Show status of all worktrees and agents |
--merge, -m | Merge all completed work to current branch |
--interactive, -i | Review each worktree before merging |
Example workflow:
# Check what's ready
./scripts/sync-worktrees.sh --status
# Interactively review and merge
./scripts/sync-worktrees.sh --interactiveBackground Agent Orchestration
Use Claude Code's native background agents (Task tool with run_in_background: true) combined with worktrees to delegate work while you continue on your main task.
Architecture
Main Worktree (Orchestrator)
├── .agent-status/ # Status tracking (JSON files)
│ ├── task-api.json # {"status": "COMPLETE", "summary": "..."}
│ └── task-ui.json
└── .worktrees/
├── task-api/ # Background agent 1's workspace
│ └── RESULTS.md # Agent writes summary here
└── task-ui/ # Background agent 2's workspace
└── RESULTS.mdOrchestration Workflow
1. Prepare worktrees for each parallel task:
git worktree add .worktrees/task-api -b task-api main
git worktree add .worktrees/task-ui -b task-ui main2. Launch background agents via Task tool:
- Each agent works in its assigned worktree
- Agent writes
RESULTS.mdwhen complete - Agent updates
.agent-status/<task>.jsonwith status
3. Continue main work while agents run in background
4. Monitor progress: Check .agent-status/*.json or use TaskOutput
5. Sync results when complete:
./scripts/sync-worktrees.sh --interactiveStatus File Convention
Background agents should write status to .agent-status/<task-name>.json:
{
"status": "COMPLETE",
"started": "2024-01-15T10:30:00Z",
"completed": "2024-01-15T10:45:00Z",
"summary": "Implemented 5 endpoints, 12 tests passing",
"files_changed": ["src/api/users.ts", "tests/api.test.ts"]
}Status values: RUNNING, COMPLETE, FAILED, BLOCKED
Task Instructions Template
When spawning background agents, include:
## Task: [Task Name]
Work in `.worktrees/[task-name]/`
### Requirements
[Specific requirements]
### On Completion
1. Write summary to `RESULTS.md`
2. Commit: `git add -A && git commit -m "[task]: [summary]"`
3. Update: `../.agent-status/[task].json` with status: "COMPLETE"When to Use
Use parallel worktrees when:
- Multiple valid solutions exist (UI, algorithms)
- Complex tasks have failure risk (run 3, pick winner)
- Clear detailed plan exists for independent execution
- Features don't overlap in file modifications
Use sequential when:
- Critical refactors requiring consistency
- Tightly coupled changes to same files
- Merge conflicts would cost more than parallelism saves
Resource Considerations
- Token usage: ~15x higher with multi-agent workflows
- Subagent nesting: Subagents cannot spawn other subagents
- Context isolation: Each subagent starts fresh, needs codebase orientation
- Subscription limits: Factor token consumption into your plan
Directory Structure
parallel-worktrees/
├── README.md # This file
├── SKILL.md # Skill definition and documentation
├── scripts/
│ ├── spawn-parallel.sh # Create parallel worktrees
│ ├── cleanup-worktrees.sh # Remove worktrees
│ └── sync-worktrees.sh # Merge completed work
└── references/
└── workflow-patterns.md # Detailed pattern documentationGit Worktrees Quick Reference
# Create worktree with new branch
git worktree add .worktrees/feature-auth -b feature/auth main
# List all worktrees
git worktree list
# Remove worktree
git worktree remove .worktrees/feature-auth
# Force remove (uncommitted changes)
git worktree remove --force .worktrees/feature-auth
# Clean stale metadata
git worktree pruneClaude Code Quick Reference
| Command | Purpose |
|---|---|
claude | Start interactive session |
claude -p "prompt" | Headless mode |
claude --continue | Resume conversation |
/clear | Reset context window |
/agents | Manage subagents |
/compact | Compress context |
Shift+Tab | Toggle Plan Mode |
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository 2. Create your feature branch (git checkout -b feature/amazing-feature) 3. Commit your changes (git commit -m 'Add amazing feature') 4. Push to the branch (git push origin feature/amazing-feature) 5. Open a Pull Request
License
This skill is provided under the MIT License. See LICENSE for details.
Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Consult the documentation in
SKILL.mdandreferences/
---
Made with care for parallel AI development
CLI Reference
Complete command reference for Claude Code CLI operations in parallel worktree workflows.
Shell Commands
| Command | Purpose |
|---|---|
claude | Start interactive session |
claude -p "prompt" | Headless mode for automation |
claude --continue | Resume most recent conversation |
claude --dangerously-skip-permissions | Skip prompts (containers only) |
Keyboard Shortcuts
| Shortcut | Purpose |
|---|---|
Shift+Tab | Toggle Plan Mode (read-only) |
Ctrl+C | Cancel current operation |
REPL Commands
| Command | Purpose |
|---|---|
/clear | Reset context window |
/agents | Manage subagents |
/compact | Compress context preserving summary |
/init | Orient Claude with codebase |
/help | Display available commands |
Git Worktree Commands
| Command | Purpose |
|---|---|
git worktree add PATH -b BRANCH BASE | Create worktree with new branch |
git worktree add PATH BRANCH | Create worktree for existing branch |
git worktree list | List all worktrees |
git worktree remove PATH | Remove a worktree |
git worktree prune | Clean stale metadata |
Subagent Invocation
Invoke subagents using the Task tool:
Task tool parameters:
- prompt: Instructions for the subagent
- subagent_type: "general-purpose", "plan", or "explore"
- run_in_background: true (for async execution)Status Monitoring
# Check background agent status
cat .agent-status/*.json | jq -r '.status'
# Detailed status view
for f in .agent-status/*.json; do
echo "=== $(basename $f .json) ==="
cat "$f" | jq .
doneWorkflow Patterns Reference
Detailed patterns for multi-agent parallel development with git worktrees and Claude Code.
Pattern 1: Competitive Implementation
Run N agents on the same task, pick the best result.
Setup
./scripts/spawn-parallel.sh user-dashboard 3Execution
In each worktree, give Claude identical instructions:
Implement a user dashboard component with:
- User profile summary
- Recent activity feed
- Quick actions sidebar
Follow our React/TypeScript conventions.
Save results summary to RESULTS.md when complete.Selection Criteria
Compare implementations across:
- Code quality and readability
- Test coverage
- Performance characteristics
- Edge case handling
Merge Strategy
# Review each implementation
cd .worktrees/user-dashboard-1 && git diff main
cd .worktrees/user-dashboard-2 && git diff main
cd .worktrees/user-dashboard-3 && git diff main
# Cherry-pick best parts or merge winner
git checkout main
git merge user-dashboard-2 # Assuming #2 was bestVerification Checklist
- [ ] All worktrees have RESULTS.md with implementation summary
- [ ] Tests pass in selected implementation:
npm test - [ ] No merge conflicts:
git statusshows clean state - [ ] Build succeeds:
npm run build
Pattern 2: Divide and Conquer
Split large features into independent parallel tracks.
Task Decomposition Example
Feature: "Add multi-tenant support"
| Worktree | Task | Dependencies |
|---|---|---|
| tenant-1 | Database schema + migrations | None |
| tenant-2 | Authentication middleware | Schema |
| tenant-3 | API route updates | Schema |
| tenant-4 | Frontend context provider | API |
Execution Order
1. Start tenant-1 first (no dependencies) 2. Once schema is committed and pushed, start tenant-2, tenant-3 3. Once API is ready, start tenant-4
Coordination
# In tenant-2 worktree, after tenant-1 completes
git fetch origin
git rebase origin/tenant-1 # Get schema changesVerification Checklist
- [ ] Schema migrations run successfully:
npm run migrate - [ ] Each stage rebased on dependencies:
git log --oneline -5 - [ ] Integration tests pass after merge:
npm run test:integration
Pattern 3: Redundant Safety Net
For critical/risky changes, run multiple agents as backup.
Use Cases
- Database migrations
- Authentication system changes
- Payment processing updates
- Core infrastructure refactors
Execution
./scripts/spawn-parallel.sh payment-refactor 3Each Claude instance works independently. If one fails or produces bugs, the other instances provide backups.
Validation
# Run tests in each worktree
for i in 1 2 3; do
(cd .worktrees/payment-refactor-$i && npm test)
done
# Compare test resultsVerification Checklist
- [ ] At least one implementation passes all tests
- [ ] Selected implementation has no regressions:
npm run test:e2e - [ ] Code review completed on critical paths
Pattern 4: Exploration Sprint
When unsure of the best approach, explore multiple architectures.
Scenario
"We need to add real-time notifications. Options: WebSockets, SSE, or polling."
Setup
./scripts/spawn-parallel.sh notifications 3Instructions Per Worktree
Worktree 1:
Implement real-time notifications using WebSockets.
Document tradeoffs in APPROACH.mdWorktree 2:
Implement real-time notifications using Server-Sent Events.
Document tradeoffs in APPROACH.mdWorktree 3:
Implement real-time notifications using long-polling.
Document tradeoffs in APPROACH.mdDecision Framework
Compare APPROACH.md files for:
- Implementation complexity
- Server resource usage
- Browser compatibility
- Scaling characteristics
Pattern 5: Test-First Parallel
One agent writes tests, others implement.
Phase 1: Test Creation
git worktree add .worktrees/tests -b feature-tests main
cd .worktrees/tests
claudePrompt:
Write comprehensive tests for a user search feature:
- Full-text search across name and email
- Filtering by role, status, created date
- Pagination support
- Permission-based result filtering
Tests should fail initially. Commit when complete.Phase 2: Parallel Implementation
git push origin feature-tests
./scripts/spawn-parallel.sh search-impl 2 feature-testsBoth implementations start from the test branch, race to make tests pass.
Pattern 6: Review Pipeline
Separate implementation and review phases.
Implementation Phase
cd .worktrees/feature-1
claude
# Claude implements feature
git add -A && git commit -m "Implement feature"Review Phase
# Clear context or use fresh session
/clear
# Now Claude reviews with fresh eyes
Prompt: Review the most recent commit. Focus on:
- Security vulnerabilities
- Performance issues
- Missing edge cases
- Code style violationsAlternative: Dual Session Review
# Terminal 1: Implementation
cd .worktrees/feature-1 && claude
# Terminal 2: Review (different session)
cd .worktrees/feature-1 && claude --resume different-sessionCoordination Patterns
Shared State via Files
Each agent writes status to a shared location:
.worktrees/
├── feature-1/STATUS.md # "IN_PROGRESS: Implementing API"
├── feature-2/STATUS.md # "BLOCKED: Waiting for schema"
├── feature-3/STATUS.md # "COMPLETE: Ready for review"Git-Based Coordination
# Agent signals completion via branch
git push origin feature-1 # Other agents can now rebase
# Main orchestrator monitors
watch -n 5 'git fetch --all && git branch -r'Results Aggregation
Each agent writes to RESULTS.md:
# Results: feature-1
## Summary
Implemented user search with Elasticsearch.
## Files Changed
- src/services/search.ts
- src/api/users/search.ts
- tests/search.test.ts
## Metrics
- Tests: 24 passing
- Coverage: 87%
- Build time: 12sAggregation script:
for dir in .worktrees/feature-*; do
echo "=== $(basename $dir) ==="
cat "$dir/RESULTS.md"
echo ""
done > COMPARISON.mdBackground Agent Patterns
These patterns use Claude Code's native background agents (Task tool with run_in_background: true) for asynchronous parallel work.
Pattern 7: Delegate and Continue
Main agent spawns background agents for independent tasks, continues its own work, then integrates results.
Setup
# Prepare worktrees
git worktree add .worktrees/docs -b docs-update main
git worktree add .worktrees/tests -b test-coverage main
mkdir -p .agent-statusMain Agent Orchestration
1. Launch background agent for docs:
Task tool (run_in_background: true):
"Work in .worktrees/docs/. Update API documentation for new endpoints.
Write RESULTS.md when done. Update ../.agent-status/docs.json with status."
2. Launch background agent for tests:
Task tool (run_in_background: true):
"Work in .worktrees/tests/. Add integration tests for auth module.
Write RESULTS.md when done. Update ../.agent-status/tests.json with status."
3. Continue main implementation work...
4. Periodically check: cat .agent-status/*.json
5. When complete: ./scripts/sync-worktrees.sh --interactivePattern 8: Fan-Out/Fan-In
Decompose a large task into parallel subtasks, wait for all to complete, then integrate.
Fan-Out Phase
# Create worktrees for each subtask
for task in api frontend database migrations; do
git worktree add ".worktrees/feature-$task" -b "feature-$task" main
done
# Spawn background agent for each
# Each agent gets identical instructions adapted to their componentAgent Task Template
## Task: Implement [component] for user authentication feature
Work in `.worktrees/feature-[component]/`
### Scope
- [Component-specific requirements]
- Do NOT modify files outside the designated component
### Dependencies
- Database schema will be in feature-database branch
- Wait for schema before implementing queries
### On Completion
1. Ensure all tests pass
2. Write RESULTS.md with summary
3. Commit all changes
4. Update ../.agent-status/feature-[component].jsonFan-In Phase
# Wait for all agents
while grep -q '"status": "RUNNING"' .agent-status/*.json 2>/dev/null; do
echo "Waiting for agents..."
sleep 30
done
# Review and merge in dependency order
./scripts/sync-worktrees.sh --interactivePattern 9: Pipeline with Dependencies
Sequential stages where later stages depend on earlier ones.
Stage Definition
| Stage | Task | Depends On |
|---|---|---|
| 1 | Database migrations | None |
| 2a | API implementation | Stage 1 |
| 2b | Frontend types | Stage 1 |
| 3 | Integration tests | Stage 2a, 2b |
Execution
Stage 1: Launch background agent for migrations
- Works in .worktrees/migrations/
- No dependencies, starts immediately
Wait for Stage 1 to complete (check status file)
Stage 2: Launch agents for API and Frontend in parallel
- Each rebases on migrations branch first
- git fetch && git rebase migrations
Wait for Stage 2 to complete
Stage 3: Launch integration test agent
- Rebases on both API and Frontend branchesPattern 10: Supervisor with Auto-Retry
Monitor background agents and automatically retry failures.
Supervisor Script
#!/bin/bash
# supervisor.sh - Monitor and retry failed agents
MAX_RETRIES=3
while true; do
for status_file in .agent-status/*.json; do
[ -f "$status_file" ] || continue
task=$(basename "$status_file" .json)
status=$(jq -r '.status' "$status_file")
retries=$(jq -r '.retries // 0' "$status_file")
case "$status" in
FAILED)
if [ "$retries" -lt "$MAX_RETRIES" ]; then
echo "Retrying $task (attempt $((retries + 1)))"
# Update retry count
jq ".retries = $((retries + 1)) | .status = \"RUNNING\"" "$status_file" > tmp && mv tmp "$status_file"
# Re-launch agent (implementation depends on the specific setup)
else
echo "Max retries reached for $task"
fi
;;
COMPLETE)
echo "$task completed successfully"
;;
esac
done
# Exit if all complete or max retried
if ! grep -q '"status": "RUNNING"' .agent-status/*.json 2>/dev/null; then
echo "All agents finished"
break
fi
sleep 30
donePattern 11: Review Gate
Background agents do implementation, then a review agent validates before merge.
Implementation Phase
1. Spawn implementation agent in .worktrees/feature/
2. Agent implements feature, commits, marks COMPLETE
3. Main agent continues other workReview Phase
1. When implementation complete, spawn review agent
2. Review agent:
- Checks .worktrees/feature/ for the implementation
- Runs tests
- Reviews code quality
- Creates .agent-status/feature-review.json with verdict
3. If APPROVED:
- ./scripts/sync-worktrees.sh --merge
4. If REJECTED:
- Review agent documents issues in REVIEW.md
- Either fix manually or re-spawn implementation agentBest Practices for Background Agents
1. Clear boundaries: Each agent should have non-overlapping file responsibilities 2. Idempotent tasks: Design so agents can be safely restarted 3. Status discipline: Always update status files on completion/failure 4. Result documentation: RESULTS.md should explain what was done 5. Dependency awareness: Later stages must rebase on earlier work 6. Timeout handling: Set reasonable limits to prevent runaway agents 7. Commit frequently: Background agents should commit often to preserve work 8. Clean exit: Agents should clean up temporary files before marking complete
#!/bin/bash
# cleanup-worktrees.sh - Remove parallel worktrees and optionally their branches
#
# Usage: cleanup-worktrees.sh <feature-name> [--delete-branches]
# feature-name: Name of the feature to clean up
# --delete-branches: Also delete the associated git branches
#
# Example: cleanup-worktrees.sh auth-refactor --delete-branches
set -e
FEATURE="${1:?Error: Feature name required. Usage: cleanup-worktrees.sh <feature-name> [--delete-branches]}"
DELETE_BRANCHES="${2:-}"
WORKTREE_DIR=".worktrees"
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo "Cleaning up worktrees for: ${FEATURE}"
echo ""
# Find and remove matching worktrees
for worktree in "${WORKTREE_DIR}/${FEATURE}"-*; do
if [ -d "$worktree" ]; then
BRANCH_NAME=$(basename "$worktree")
# Check for uncommitted changes
if [ -n "$(cd "$worktree" && git status --porcelain)" ]; then
echo -e "${YELLOW}⚠ Uncommitted changes in ${worktree}${NC}"
read -p "Force remove? (y/N): " confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
git worktree remove --force "$worktree"
echo -e "${GREEN}✓ Removed worktree: ${worktree}${NC}"
else
echo "Skipped: ${worktree}"
continue
fi
else
git worktree remove "$worktree"
echo -e "${GREEN}✓ Removed worktree: ${worktree}${NC}"
fi
# Optionally delete the branch
if [ "$DELETE_BRANCHES" = "--delete-branches" ]; then
if git branch --list "$BRANCH_NAME" | grep -q .; then
git branch -D "$BRANCH_NAME" 2>/dev/null || true
echo -e "${GREEN}✓ Deleted branch: ${BRANCH_NAME}${NC}"
fi
fi
fi
done
# Prune stale worktree metadata
git worktree prune
echo ""
echo -e "${GREEN}✓ Cleanup complete${NC}"
# Show remaining worktrees
echo ""
echo "Remaining worktrees:"
git worktree list
#!/bin/bash
# spawn-parallel.sh - Create parallel git worktrees for multi-agent Claude development
#
# Usage: spawn-parallel.sh <feature-name> [num-agents] [base-branch]
# feature-name: Name for the feature/task (used in branch names)
# num-agents: Number of parallel worktrees to create (default: 3)
# base-branch: Branch to base worktrees on (default: main)
#
# Example: spawn-parallel.sh auth-refactor 4 develop
set -e
FEATURE="${1:?Error: Feature name required. Usage: spawn-parallel.sh <feature-name> [num-agents] [base-branch]}"
NUM="${2:-3}"
BASE_BRANCH="${3:-main}"
WORKTREE_DIR=".worktrees"
# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}Creating ${NUM} parallel worktrees for: ${FEATURE}${NC}"
echo "Base branch: ${BASE_BRANCH}"
echo ""
# Create worktrees directory if needed
if [ ! -d "$WORKTREE_DIR" ]; then
mkdir -p "$WORKTREE_DIR"
echo ".worktrees/" >> .gitignore 2>/dev/null || true
echo -e "${GREEN}✓ Created ${WORKTREE_DIR} directory${NC}"
fi
# Ensure base branch is up to date
git fetch origin "$BASE_BRANCH" 2>/dev/null || true
# Create worktrees
for i in $(seq 1 "$NUM"); do
BRANCH_NAME="${FEATURE}-${i}"
WORKTREE_PATH="${WORKTREE_DIR}/${FEATURE}-${i}"
if [ -d "$WORKTREE_PATH" ]; then
echo "⚠ Worktree already exists: ${WORKTREE_PATH}"
continue
fi
git worktree add "$WORKTREE_PATH" -b "$BRANCH_NAME" "$BASE_BRANCH"
# Copy environment files if they exist
[ -f ".env" ] && cp .env "$WORKTREE_PATH/" 2>/dev/null || true
[ -f ".env.local" ] && cp .env.local "$WORKTREE_PATH/" 2>/dev/null || true
echo -e "${GREEN}✓ Created worktree: ${WORKTREE_PATH} (branch: ${BRANCH_NAME})${NC}"
done
echo ""
echo -e "${BLUE}Start Claude in each worktree:${NC}"
echo ""
for i in $(seq 1 "$NUM"); do
echo " cd ${WORKTREE_DIR}/${FEATURE}-${i} && claude"
done
echo ""
echo -e "${BLUE}Or use tmux/screen to run all in parallel:${NC}"
echo ""
echo " for i in \$(seq 1 ${NUM}); do"
echo " tmux new-window -n \"${FEATURE}-\$i\" \"cd ${WORKTREE_DIR}/${FEATURE}-\$i && claude\""
echo " done"
echo ""
echo -e "${BLUE}When done, clean up with:${NC}"
echo ""
echo " ./scripts/cleanup-worktrees.sh ${FEATURE}"
#!/bin/bash
# sync-worktrees.sh - Review and merge completed worktree work
#
# Usage: sync-worktrees.sh [--status|--merge|--interactive]
# --status: Show status of all worktrees and agents
# --merge: Merge all completed work to current branch
# --interactive: Review each worktree before merging
#
# Example: sync-worktrees.sh --interactive
set -e
MODE="${1:---status}"
WORKTREE_DIR=".worktrees"
STATUS_DIR=".agent-status"
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'
# Get current branch
CURRENT_BRANCH=$(git branch --show-current)
show_status() {
echo -e "${BLUE}=== Worktree Status ===${NC}"
echo ""
# Show git worktrees
echo -e "${BLUE}Git Worktrees:${NC}"
git worktree list
echo ""
# Show agent status files if they exist
if [ -d "$STATUS_DIR" ] && [ "$(ls -A $STATUS_DIR 2>/dev/null)" ]; then
echo -e "${BLUE}Agent Status:${NC}"
for status_file in "$STATUS_DIR"/*.json; do
if [ -f "$status_file" ]; then
task_name=$(basename "$status_file" .json)
if command -v jq &> /dev/null; then
status=$(jq -r '.status // "UNKNOWN"' "$status_file" 2>/dev/null || echo "PARSE_ERROR")
summary=$(jq -r '.summary // ""' "$status_file" 2>/dev/null || echo "")
else
status=$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$status_file" | cut -d'"' -f4)
fi
case "$status" in
COMPLETE) color=$GREEN ;;
RUNNING) color=$YELLOW ;;
FAILED) color=$RED ;;
BLOCKED) color=$YELLOW ;;
*) color=$NC ;;
esac
echo -e " ${task_name}: ${color}${status}${NC}"
[ -n "$summary" ] && echo " $summary"
fi
done
echo ""
fi
# Show changes in each worktree
echo -e "${BLUE}Worktree Changes:${NC}"
for worktree in "$WORKTREE_DIR"/*/; do
if [ -d "$worktree" ]; then
worktree_name=$(basename "$worktree")
branch_name=$(cd "$worktree" && git branch --show-current 2>/dev/null || echo "detached")
# Count commits ahead of main
commits_ahead=$(cd "$worktree" && git rev-list --count "$CURRENT_BRANCH"..HEAD 2>/dev/null || echo "0")
# Check for uncommitted changes
has_changes=$(cd "$worktree" && git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
echo -e " ${worktree_name} (${branch_name}):"
echo " Commits ahead: $commits_ahead"
[ "$has_changes" -gt 0 ] && echo -e " ${YELLOW}Uncommitted changes: $has_changes files${NC}"
# Show RESULTS.md summary if exists
if [ -f "${worktree}RESULTS.md" ]; then
echo " Has RESULTS.md"
fi
fi
done
}
merge_worktree() {
local worktree_path="$1"
local worktree_name=$(basename "$worktree_path")
local branch_name=$(cd "$worktree_path" && git branch --show-current 2>/dev/null)
if [ -z "$branch_name" ]; then
echo -e "${RED}Cannot merge: worktree is in detached HEAD state${NC}"
return 1
fi
# Check for uncommitted changes
if [ -n "$(cd "$worktree_path" && git status --porcelain)" ]; then
echo -e "${YELLOW}Warning: Uncommitted changes in $worktree_name${NC}"
read -p "Commit them first? (y/N): " confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
(cd "$worktree_path" && git add -A && git commit -m "WIP: Auto-commit before merge")
else
echo "Skipping merge for $worktree_name"
return 1
fi
fi
# Perform merge
echo -e "${BLUE}Merging $branch_name into $CURRENT_BRANCH...${NC}"
if git merge "$branch_name" -m "Merge $branch_name from parallel worktree"; then
echo -e "${GREEN}Successfully merged $branch_name${NC}"
# Ask about cleanup
read -p "Remove worktree and branch? (y/N): " cleanup
if [ "$cleanup" = "y" ] || [ "$cleanup" = "Y" ]; then
git worktree remove "$worktree_path"
git branch -d "$branch_name" 2>/dev/null || true
# Clean up status file
[ -f "$STATUS_DIR/${worktree_name}.json" ] && rm "$STATUS_DIR/${worktree_name}.json"
echo -e "${GREEN}Cleaned up $worktree_name${NC}"
fi
return 0
else
echo -e "${RED}Merge conflict! Resolve manually.${NC}"
return 1
fi
}
merge_all() {
echo -e "${BLUE}Merging all completed worktrees...${NC}"
echo ""
for worktree in "$WORKTREE_DIR"/*/; do
if [ -d "$worktree" ]; then
worktree_name=$(basename "$worktree")
# Check agent status if available
if [ -f "$STATUS_DIR/${worktree_name}.json" ]; then
status=$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$STATUS_DIR/${worktree_name}.json" 2>/dev/null | cut -d'"' -f4)
if [ "$status" != "COMPLETE" ]; then
echo -e "${YELLOW}Skipping $worktree_name (status: $status)${NC}"
continue
fi
fi
merge_worktree "$worktree"
fi
done
}
interactive_merge() {
echo -e "${BLUE}Interactive merge mode${NC}"
echo ""
for worktree in "$WORKTREE_DIR"/*/; do
if [ -d "$worktree" ]; then
worktree_name=$(basename "$worktree")
branch_name=$(cd "$worktree" && git branch --show-current 2>/dev/null || echo "detached")
echo ""
echo -e "${BLUE}=== $worktree_name ($branch_name) ===${NC}"
# Show diff summary
echo "Changes:"
(cd "$worktree" && git diff --stat "$CURRENT_BRANCH"..HEAD 2>/dev/null) || echo " (no commits)"
# Show RESULTS.md if exists
if [ -f "${worktree}RESULTS.md" ]; then
echo ""
echo "RESULTS.md:"
head -20 "${worktree}RESULTS.md"
echo "..."
fi
echo ""
read -p "Merge this worktree? (y/n/s=skip/q=quit): " choice
case "$choice" in
y|Y) merge_worktree "$worktree" ;;
q|Q) echo "Quitting."; exit 0 ;;
*) echo "Skipped." ;;
esac
fi
done
}
# Main
case "$MODE" in
--status|-s)
show_status
;;
--merge|-m)
merge_all
;;
--interactive|-i)
interactive_merge
;;
*)
echo "Usage: sync-worktrees.sh [--status|--merge|--interactive]"
echo ""
echo "Options:"
echo " --status, -s Show status of all worktrees"
echo " --merge, -m Merge all completed work"
echo " --interactive, -i Review each before merging"
exit 1
;;
esac