# Swarm

> Execute implementation plans with parallel worker agents in git worktrees. Spawns agents, monitors progress, coordinates merges. Use after /skill:plan completes.

- Skill: `l3wi/swarm` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add l3wi/swarm`
- Raw SKILL.md: https://api.skillmd.com/api/skills/l3wi/swarm/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: l3wi (https://skillmd.com/u/l3wi)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/l3wi/swarm

---


# Swarm Skill

Unified execution engine for the implementation phase. Loads validated plans from `/skill:plan`, spawns parallel worker agents in git worktrees, monitors progress, and coordinates merges. Second step in the three-prong workflow: **Plan → Implement → Validate**.

## Workflow

```
/skill:swarm {feature-name}
    ↓
Phase 1: Load & validate plan artifacts
    ↓
Phase 2: Initialize feature branch
    ↓
Phase 3: Execute batches (spawn → monitor → merge)
    ↓
Phase 4: Create PR → Complete
```

## Usage

```bash
/skill:swarm <feature-name>             # Execute implementation plan
/skill:swarm <feature-name> --status    # Check orchestration status only
/skill:swarm <feature-name> --resume    # Resume interrupted orchestration
/skill:swarm <feature-name> --dry-run   # Preview execution without spawning
/skill:swarm <feature-name> --max-parallel 3  # Limit concurrent agents
```

## Prerequisites

- **Planning complete**: `/skill:plan {feature-name}` must have run
- **Plan file**: `docs/plans/{feature-name}.md`
- **Task files**: `docs/tasks/{feature-name}-phase-*.md`
- **Spec file**: `docs/specs/{feature-name}-spec.md`
- **Worktrunk CLI**: Configured for worktree management
- **Clean working directory**: No uncommitted changes

### Missing Artifacts Check

If planning artifacts are missing:
```
❌ Planning artifacts not found!

Missing:
- docs/plans/{feature-name}.md
- docs/tasks/{feature-name}-*.md

Run the planning phase first:
  /skill:plan {feature-name}
```

## Phase 1: Load & Validate Plan

1. Read plan from `docs/plans/{feature-name}.md`
2. Verify all referenced task files exist in `docs/tasks/`
3. For each phase, extract these fields (used to construct `agent_spawn` calls):
   - **Branch** → `agent_spawn.branch`
   - **Tasks** → `agent_spawn.task_file`
   - **Agent** → `agent_spawn.agent` (default: `worker`)
   - **Base** → `agent_spawn.base` (always the feature branch)
4. Extract execution batches and dependency order
5. Check plan status is not "completed"

## Phase 2: Initialize Feature Branch Worktree

```bash
Tool: orchestration_init
  feature_branch: feat/{feature-name}
  base: dev
```

Creates a worktree for the feature branch at `.worktrees/feat-{feature-name}/`. The main repository stays on `dev`, enabling parallel work in other terminal sessions.

**Returns:**
- `worktree_path`: Path to the feature worktree (e.g., `.worktrees/feat-user-avatar/`)
- `feature_branch`: The branch name

The orchestrator should note the `worktree_path` — all subsequent operations happen within worktrees, not the main repo.

## Phase 3: Execute Batches

> **Before starting execution**, read the [Orchestration Guide](references/orchestration-guide.md).

For each batch defined in the plan:

### Determine Current State

Check existing worktrees and agent status to determine where we are:

| State | Condition | Action |
|-------|-----------|--------|
| Fresh start | No phase worktrees | Start from Batch 1 |
| In progress | Agents running | Resume monitoring |
| Batch complete | All agents done | Proceed to merge |
| Blocked/failed | Agent error | Pause for user input |

### Execute Batch Loop

1. **Spawn agents** for each phase in the batch. Read the **Agent** and **Tasks** fields from the plan file to populate the call:
   ```
   Tool: agent_spawn
     branch: feat/{feature}-phase-{n}            ← from plan: Phase.Branch
     task_file: docs/tasks/{feature}-phase-{n}.md ← from plan: Phase.Tasks
     agent: researcher | worker | reviewer        ← from plan: Phase.Agent (default: worker)
     base: feat/{feature}                         ← CRITICAL: always the feature branch, not dev
   ```
   The `task_file` gives the agent structured acceptance criteria, file lists, and instructions. Always pass it in orchestrated flows.

2. **Monitor** — poll `agent_status` every 30s until batch completes:
   ```
   Batch 2 of 3:
     feat/{feature}-phase-2a  🤖 60% - Implementing API endpoints
     feat/{feature}-phase-2b  🤖 45% - Building UI components
   ```

3. **Handle events** — completion (✅), failure (❌, offer retry/skip), timeout (30min alert)

4. **Pre-merge validation** — lint, test, build in each completed worktree

5. **Merge** to feature branch in dependency order:
   ```
   Tool: worktree_merge
     branch: feat/{feature}-phase-{n}
     target: feat/{feature}
   ```

6. **Update plan status** with merge commit hash and timestamp

7. **Next batch** — wait for all merges before spawning next batch

### Feature Branch Strategy (Worktree-Based)

All work happens in worktrees inside `.worktrees/`. The main repo stays on `dev`:

**Directory Structure:**
```
/repo/                                    # Main repo — ALWAYS on dev
  .worktrees/                             # Gitignored worktree directory
    feat-user-avatar/                     # Feature branch worktree (orchestrator)
    feat-user-avatar-phase-1/             # Phase 1 worktree (worker agent)
    feat-user-avatar-phase-2a/            # Phase 2a worktree (worker agent)
    feat-user-avatar-phase-2b/            # Phase 2b worktree (worker agent)
```

**Branch Flow:**
```
dev ──────────────────────────────────────────► dev (unchanged until PR)
  │                                                ▲
  └─► feat/{feature} ─────────────────────────────┘ (single PR)
        ├─► phase-0 (researcher) ─► merge ──┐
        ├─► phase-1 (worker) ─────► merge ──┤
        ├─► phase-2a (worker) ────► merge ──┤
        ├─► phase-2b (worker) ────► merge ──┤
        ├─► phase-3 (worker) ─────► merge ──┤
        └─► review (reviewer) ────► merge ──┘
```

**Benefits:**
- New terminal sessions in `/repo` start on `dev` — can work on other features
- Multiple swarms can run in parallel (different feature worktrees)
- Clean separation between orchestrator and main codebase

## Phase 4: Completion

### Generate Summary

```
✅ Orchestration Complete: {feature}

| Phase | Files | Tests | Duration |
|-------|-------|-------|----------|
| 1     | 3     | 12    | 15m      |
| 2a    | 5     | 18    | 22m      |
| 2b    | 4     | 15    | 18m      |
| 3     | 2     | 8     | 12m      |

All phases merged to feat/{feature}.
```

### Create Pull Request

```bash
gh pr create --base dev --head feat/{feature} \
  --title "feat({feature}): {description}"
```

### Next Steps

```
Orchestration complete! Next:
  /skill:validate-plan {feature-name}    # Verify spec compliance
```

## Context Management

The `swarm-context` extension automatically:
- Loads plan summary from planning phase
- Creates clean session branch for orchestration context
- Saves state to `.swarm-{feature}.json` for resume

### Session Tree

```
main
├── planning-{feature}       (Planning conversation)
└── orchestration-{feature}  (Clean execution context)
```

## Resume Mode

`/skill:swarm {feature} --resume` skips spawning and goes directly to monitoring:
- Checks existing worktrees and agent states
- Resumes monitoring from current batch
- Useful after disconnect or crash

## Dry Run Mode

`/skill:swarm {feature} --dry-run` shows execution plan without spawning:
```
[DRY RUN] Would execute:

Batch 1 (1 agent):
  → feat/{feature}-phase-1 with docs/tasks/{feature}-phase-1.md

Batch 2 (2 agents, parallel):
  → feat/{feature}-phase-2a with docs/tasks/{feature}-phase-2a.md
  → feat/{feature}-phase-2b with docs/tasks/{feature}-phase-2b.md

Merge order: phase-1 → phase-2a → phase-2b → phase-3
```

## Error Handling

| Error | Resolution |
|-------|------------|
| Plan not found | "Run `/skill:plan {feature}` first" |
| Task file missing | "Regenerate tasks with `/skill:plan {feature}`" |
| Agent failure | Offer: retry, skip, terminate |
| Merge conflict | Pause, guide manual resolution |
| Timeout (30min) | Alert, offer: extend, check, terminate |
| Dirty working dir | Auto-commit before orchestration |

## Complete Development Lifecycle

```bash
/skill:plan feature-name       # Plan: PRD → Spec → Tasks
/skill:swarm feature-name      # Implement: Spawn → Monitor → Merge → PR
/skill:validate-plan feature-name   # Validate: Tests + spec compliance
```

## Related Skills

- `/skill:plan` — Planning workflow that produces execution artifacts (prerequisite)
- `/skill:validate-plan` — Spec compliance verification (next step)
- `/skill:feature` — Single-phase implementation (simpler alternative)

