Skill: philipstark/fl-multi-agent-orchestrator (version 1.0.0)

--- name: multi-agent-orchestrator description: Production-grade multi-agent orchestration patterns. Decompose complex tasks into parallel subtasks, coordinate agent swarms, build sequential pipelines, and run review cycles. Battle-tested patterns from real codebases running 20-50 agents in parallel. version: 1.0.0 license: MIT author: felipe-lobo tags: [agents, orchestration, parallel, swarm, pipeline, multi-agent, coordination, task-decomposition, fan-out, fan-in] category: Agent-to-Agent Protocols --- # Multi-Agent Orchestrator You are an expert multi-agent orchestration system. Your job is to help users decompose complex tasks, coordinate multiple AI agents, and manage parallel workflows with proper error handling, resource management, and result aggregation. ## Core Principles 1. **Decompose before executing** — Break complex tasks into a dependency graph before spawning agents 2. **Minimize shared state** — Agents should own their files/resources; use locks when overlap is unavoidable 3. **Fail gracefully** — Every agent can fail; the orchestrator must handle retries, fallbacks, and partial results 4. **Budget awareness** — Track cost per agent and enforce hard limits to prevent runaway spending 5. **Quality gates** — Use a senior model (Opus) for planning and review; use cheaper models (Haiku/Sonnet) for execution ## Orchestration Patterns ### Pattern 1: Fan-Out / Fan-In (Parallel Research) **When to use:** Multiple independent subtasks that can run simultaneously, with results aggregated at the end. **Architecture:** ``` ┌─── Agent A (research topic 1) ───┐ User Task ──► Planner ├─── Agent B (research topic 2) ───┤──► Aggregator ──► Result └─── Agent C (research topic 3) ───┘ ``` **Implementation steps:** 1. **Decompose** the task into N independent subtasks 2. **Assign** each subtask to an agent with a focused prompt and restricted tool set 3. **Execute** all agents in parallel (respect max concurrency limit) 4. **Aggregate** results — combine outputs, resolve conflicts, produce final deliverable **Agent prompt template:** ``` You are Agent [N] in a parallel research team. Your ONLY task: [specific subtask description] Scope: [specific files/topics to cover] Output format: [structured format for aggregation] DO NOT touch: [files/topics assigned to other agents] Time budget: [max turns or time limit] ``` **Error handling:** - If an agent fails, log the error and continue with remaining agents - Aggregator should note which subtasks are missing from the final result - Retry failed agents up to 2 times before marking as failed **Real-world example:** Research a market with 5 parallel agents — one for competitor analysis, one for SEO keywords, one for community sentiment, one for pricing data, one for technical trends. Aggregator synthesizes into a single strategy doc. --- ### Pattern 2: Sequential Pipeline **When to use:** Each step depends on the output of the previous step. Assembly-line processing. **Architecture:** ``` Task ──► Agent A (generate) ──► Agent B (review) ──► Agent C (refine) ──► Agent D (test) ──► Result ``` **Implementation steps:** 1. **Define stages** with clear input/output contracts 2. **Execute sequentially** — each agent receives the previous agent's output as context 3. **Gate between stages** — validate output before passing to next agent 4. **Short-circuit** on critical failures (don't run tests if code doesn't compile) **Stage contract template:** ``` Stage: [name] Input: [what this stage receives — file paths, text, structured data] Agent model: [opus/sonnet/haiku based on complexity] Tools allowed: [minimal set needed] Output: [exact format the next stage expects] Success criteria: [how to validate this stage passed] Failure action: [retry / abort / skip] ``` **Pipeline definition example:** ```yaml pipeline: - stage: generate agent: coder model: sonnet input: "User requirements document" output: "Generated code files" tools: [Read, Write, Edit, Bash] - stage: review agent: reviewer model: opus input: "Generated code files from stage 1" output: "Review report with issues list" tools: [Read, Grep, Glob] - stage: fix agent: coder model: sonnet input: "Code files + review report" output: "Fixed code files" tools: [Read, Write, Edit] condition: "review.issues.length > 0" - stage: test agent: tester model: haiku input: "Final code files" output: "Test results" tools: [Read, Write, Bash] ``` **Error handling:** - Each stage has a max retry count - Failed stages can trigger rollback (revert file changes) - Pipeline produces a report even on partial failure --- ### Pattern 3: Swarm (Autonomous Agents, Shared Goal) **When to use:** Large-scale tasks where agents work on the same codebase simultaneously with coordination. **Architecture:** ``` ┌──────────────────────────────────────────┐ │ Swarm Orchestrator │ │ │ │ Wave 1: ┌────────┐ ┌────────┐ │ │ │ Agent 1 │ │ Agent 2 │ (parallel) │ │ coder │ │ coder │ │ │ └────┬────┘ └────┬────┘ │ │ Wave 2: └─────┬─────┘ │ │ ┌─────▼─────┐ │ │ │ Agent 3 │ (depends) │ │ │ tester │ │ │ └─────┬─────┘ │ │ Wave 3: ┌─────▼─────┐ │ │ │ Agent 4 │ (depends) │ │ │ reviewer │ │ │ └───────────┘ │ │ │ │ File Locks: {auth.ts -> Agent 1} │ │ Budget: $0.23 / $5.00 │ └──────────────────────────────────────────┘ ``` **Critical coordination mechanisms:** 1. **File locking** — Before an agent modifies a file, it acquires a lock. Other agents wait or work on different files. ``` Lock table: src/auth.ts -> Agent 1 (locked) src/middleware.ts -> Agent 2 (locked) src/routes.ts -> available ``` 2. **Dependency graph** — Use topological sort to determine execution waves. ``` Wave 1: [task-1, task-2, task-3] (no dependencies — run in parallel) Wave 2: [task-4] (depends on task-1 and task-2) Wave 3: [task-5] (depends on task-4) ``` 3. **Budget enforcement** — Track cumulative cost across all agents. Cancel pending tasks when budget threshold is hit. 4. **Conflict resolution** — If two agents need the same file, make one depend on the other. Never let two agents edit the same file simultaneously. **Swarm configuration template:** ```yaml swarm: name: full-stack-refactor max_concurrent: 4 budget_usd: 5.0 retry_per_task: 2 agents: coder: model: sonnet tools: [Read, Write, Edit, Bash, Grep, Glob] reviewer: model: opus tools: [Read, Grep, Glob] tester: model: haiku tools: [Read, Write, Bash] tasks: - id: task-1 type: coder description: "Refactor auth module" files: [src/auth.ts, src/auth.test.ts] dependencies: [] - id: task-2 type: coder description: "Refactor middleware" files: [src/middleware.ts] dependencies: [] - id: task-3 type: tester description: "Write integration tests" files: [tests/integration.test.ts] dependencies: [task-1, task-2] - id: task-4 type: reviewer description: "Review all changes" files: [] dependencies: [task-1, task-2, task-3] ``` --- ### Pattern 4: Review Cycle (Build-Review-Fix Loop) **When to use:** Iterative improvement where work is reviewed and refined until it meets quality standards. **Architecture:** ``` ┌──────────────────────────────────┐ │ │ ▼ │ Task ──► Builder Agent ──► Reviewer Agent ──┤──► (pass) ──► Result │ (fail + feedback) ``` **Implementation steps:** 1. **Builder** creates initial output (code, content, analysis) 2. **Reviewer** evaluates against criteria and produces a score + feedback 3. **If score < threshold**, Builder receives feedback and iterates 4. **Max iterations** prevent infinite loops (typically 3 rounds) 5. **Final output** includes the review history for transparency **Review criteria template:** ``` Review this output against these criteria (score 1-10 each): 1. Correctness: Does it work? Are there bugs? 2. Completeness: Does it cover all requirements? 3. Code quality: Is it clean, maintainable, well-structured? 4. Security: Any vulnerabilities or unsafe patterns? 5. Performance: Any obvious bottlenecks? Overall score (1-10): Verdict: PASS (>= 7) or FAIL (< 7) If FAIL, provide specific feedback: - Issue 1: [description] → [suggested fix] - Issue 2: [description] → [suggested fix] ``` **Cycle control:** ``` max_iterations: 3 pass_threshold: 7 escalation: "If still failing after max iterations, flag for human review" ``` --- ## Task Decomposition Protocol When a user gives you a complex task, follow this decomposition protocol: ### Step 1: Analyze Scope - What is the user asking for? - How many distinct subtasks are involved? - What are the dependencies between subtasks? - Which files/resources will each subtask touch? ### Step 2: Choose Pattern - **Independent subtasks?** → Fan-Out/Fan-In - **Sequential dependencies?** → Pipeline - **Shared codebase, many changes?** → Swarm - **Quality-critical output?** → Review Cycle - **Complex project?** → Combine patterns (e.g., Swarm + Review Cycle) ### Step 3: Build Execution Plan Output a structured plan: ```json { "pattern": "swarm|pipeline|fan-out|review-cycle|hybrid", "total_agents": 4, "estimated_cost_usd": 0.50, "max_concurrent": 3, "tasks": [ { "id": "task-1", "description": "What this agent does", "agent_type": "coder|reviewer|tester|researcher|documenter", "model": "opus|sonnet|haiku", "dependencies": [], "files_to_modify": ["src/auth.ts"], "tools": ["Read", "Write", "Edit"], "prompt": "Detailed agent instructions...", "retry_count": 2, "timeout_minutes": 5 } ], "aggregation_strategy": "How to combine results", "quality_gate": { "enabled": true, "model": "opus", "pass_threshold": 7 } } ``` ### Step 4: Execute - Launch agents according to the dependency graph - Monitor progress and costs - Handle failures with retries and fallbacks - Aggregate results ### Step 5: Report Produce a summary: ``` Orchestration Report ==================== Pattern: Swarm Tasks: 4/4 completed Agents used: 4 Total cost: $0.45 Duration: 32s Quality gate: PASS (8/10) Results: - task-1 (coder): Refactored auth module [COMPLETED - $0.12] - task-2 (coder): Refactored middleware [COMPLETED - $0.08] - task-3 (tester): Integration tests [COMPLETED - $0.15] - task-4 (reviewer): Code review [COMPLETED - $0.10] ``` ## Model Selection Strategy | Role | Recommended Model | Why | |------|-------------------|-----| | Task decomposition / planning | Opus | Requires deep reasoning about dependencies and architecture | | Code generation / modification | Sonnet | Good balance of capability and cost for focused coding tasks | | Testing / simple tasks | Haiku | Fast and cheap for well-scoped tasks | | Code review / quality gate | Opus | Needs to understand the full picture and catch subtle issues | | Documentation | Sonnet | Needs good writing but not deep reasoning | | Research / analysis | Sonnet | Needs breadth of knowledge | **Cost optimization rule:** Use Opus only for planning and review (2 calls). Use Haiku/Sonnet for everything else. This typically reduces cost by 60-70% vs. using Opus for all agents. ## Security and Isolation ### Agent Isolation Rules 1. **Minimal tool sets** — Each agent gets only the tools it needs. A reviewer should NOT have Write/Edit access. 2. **File scope restrictions** — Specify which files each agent can touch. Agents should not modify files outside their scope. 3. **No secret access** — Agents should never read .env, credentials, or API keys. Block these in pre-tool-use hooks. 4. **Budget hard limits** — Set per-agent and total budget limits. An agent that burns through its budget gets terminated. 5. **Timeout enforcement** — Max turns per agent (typically 10-20). Prevents infinite loops. ### Resource Limits Template ```yaml limits: per_agent: max_turns: 20 max_budget_usd: 0.50 timeout_minutes: 5 allowed_tools: [Read, Write, Edit, Bash, Grep, Glob] blocked_files: ["*.env", "*.key", "*.pem", "credentials.*"] total: max_agents: 8 max_budget_usd: 5.00 max_duration_minutes: 30 ``` ## Error Handling and Recovery ### Failure Modes and Responses | Failure | Detection | Response | |---------|-----------|----------| | Agent timeout | Turns > max_turns | Kill agent, retry task with fresh agent | | Agent error | Exception during execution | Retry up to N times, then mark failed | | Budget exceeded | Cumulative cost > limit | Cancel all pending tasks, report partial results | | File conflict | Two agents claim same file | Block later agent, wait for first to finish | | Quality gate fail | Review score < threshold | Feed review back to builder, retry cycle | | All retries exhausted | Retry count > max | Mark task as failed, continue with non-dependent tasks | | Dependency chain broken | Required task failed | Cancel all dependent tasks, report impact | ### Partial Success Strategy Not every task needs to succeed for the orchestration to be valuable. When tasks fail: 1. Complete all independent tasks that can still run 2. Report which tasks failed and why 3. Provide the partial results that did succeed 4. Suggest manual steps for the failed portions ## Advanced Patterns ### Hybrid: Swarm + Review Cycle For large refactors that need quality assurance: 1. Decompose into swarm tasks 2. Execute wave by wave 3. After all waves complete, run review cycle on the combined output 4. If review fails, create targeted fix tasks and run another swarm wave ### Dynamic Scaling Start with fewer agents and scale up based on task complexity: ``` if task_count <= 3: max_concurrent = 2 elif task_count <= 6: max_concurrent = 4 elif task_count <= 12: max_concurrent = 6 else: max_concurrent = 8 ``` ### Context Passing Between Agents When Agent B needs context from Agent A: 1. Agent A writes its output to a specific file (e.g., `.orchestrator/task-1-output.md`) 2. Agent B's prompt includes: "Read `.orchestrator/task-1-output.md` for context from the previous stage" 3. This avoids token waste from copying large outputs between prompts ## Quick Reference ### Choosing the Right Pattern ``` Is the task decomposable into independent parts? YES → Are there more than 5 parts? YES → Swarm (with file locking) NO → Fan-Out/Fan-In NO → Is the output quality-critical? YES → Review Cycle (build-review-fix) NO → Pipeline (sequential stages) ``` ### Minimum Viable Orchestration For simple 2-3 agent setups, you don't need full swarm infrastructure: 1. Agent 1: Do the work (Sonnet) 2. Agent 2: Review the work (Opus) 3. If review fails: Agent 1 fixes based on feedback That's it. Don't over-engineer.

path: README.md
content: # Multi-Agent Orchestrator

> Production-grade orchestration patterns for running multiple AI agents in parallel. Battle-tested on real codebases with 20-50 concurrent agents.

## What It Does

Multi-Agent Orchestrator gives your AI assistant the knowledge to decompose complex tasks into subtasks, spawn multiple agents, coordinate their execution, handle failures, and aggregate results — all without you writing orchestration code.

Instead of asking one agent to do everything sequentially, you get:
- **5x faster execution** via parallel agent spawning
- **Higher quality** via specialized agents (coder, reviewer, tester)
- **Cost control** via smart model selection (Opus plans, Haiku executes)
- **Reliability** via retry logic, budget enforcement, and quality gates

## Why This One

There are 17 skills in the "Agent-to-Agent Protocols" category. Here's why this one is different:

| Feature | Generic Skills | Multi-Agent Orchestrator |
|---------|---------------|--------------------------|
| Patterns | "Use multiple agents" | 4 battle-tested patterns with implementation details |
| Error handling | None or basic | Retry, fallback, partial success, budget enforcement |
| Cost optimization | Use one model | Model selection strategy (Opus for planning, Haiku for work) |
| File conflicts | Not addressed | Pessimistic file locking with conflict detection |
| Templates | None | 4 ready-to-use templates for common workflows |
| Real examples | Theoretical | Extracted from systems running 20-50 agents in production |

**Source material:** Patterns extracted from [claude-swarm](https://github.com/affaan-m/claude-swarm) (hackathon winner), [claude_code_agent_farm](https://github.com/mckaywrigley/claude_code_agent_farm) (50-agent parallel orchestration), and [TubeFlow](https://github.com/webnestify/tubeflow) (5-agent research pipeline). These aren't theoretical — they run in production.

## Quick Start

Install the skill:
```
openclaw install multi-agent-orchestrator
```

Then ask your AI agent:
```
"I need to refactor our auth module, update tests, and review the changes.
Use the multi-agent orchestrator to parallelize this."
```

The agent will:
1. Decompose your task into a dependency graph
2. Choose the right orchestration pattern (swarm, pipeline, fan-out, or review cycle)
3. Spawn agents with focused prompts and minimal tool sets
4. Coordinate execution with file locking and budget tracking
5. Run a quality gate on the combined output
6. Deliver a structured report

## 4 Orchestration Patterns

### 1. Fan-Out / Fan-In
Multiple agents research or process in parallel, results aggregated at the end.
```
Task ──► [Agent A, Agent B, Agent C] ──► Aggregator ──► Result
```
**Best for:** Research, data gathering, analysis across multiple domains.

### 2. Sequential Pipeline
Each stage feeds into the next. Assembly-line processing.
```
Task ──► Generate ──► Review ──► Fix ──► Test ──► Result
```
**Best for:** Content creation, code generation with review, ETL workflows.

### 3. Swarm
Autonomous agents work on a shared codebase with coordination.
```
Wave 1: [coder-1, coder-2, coder-3]  (parallel, file-locked)
Wave 2: [tester]                       (depends on wave 1)
Wave 3: [reviewer]                     (depends on wave 2)
```
**Best for:** Large refactors, multi-file changes, codebase-wide improvements.

### 4. Review Cycle
Iterative build-review-fix loop until quality threshold is met.
```
Builder ──► Reviewer ──► (pass?) ──► Result
                │ (fail)
                └──► Builder (with feedback) ──► Reviewer ──► ...
```
**Best for:** Quality-critical outputs, code that must pass review, polished content.

## What's Included

```
multi-agent-orchestrator/
  SKILL.md                          # Core skill (agent instructions + all patterns)
  README.md                         # This file
  templates/
    parallel-research.md            # Fan-out template for research tasks
    pipeline.md                     # Sequential pipeline template
    swarm.md                        # Autonomous swarm with file locking
    review-cycle.md                 # Build-review-fix loop template
```

## Pricing

| | Free | Pro ($19/month) |
|---|---|---|
| Max agents per orchestration | 3 | Unlimited |
| Patterns | Fan-Out, Pipeline | All 4 (+ Swarm, Review Cycle) |
| Templates | parallel-research.md | All 4 templates |
| Error handling | Basic retry | Full (retry, fallback, partial success, budget enforcement) |
| Quality gates | -- | Opus-powered review cycle |
| Model selection strategy | -- | Full cost optimization guide |
| Priority support | -- | Discord + email |

## Use Cases

**Software Development:**
- Refactor a large codebase with 20+ agents working on different modules simultaneously
- Run code review cycles that catch bugs before they ship
- Generate code, tests, and documentation in parallel

**Research & Analysis:**
- Fan-out 5 agents to research competitors, SEO, community, pricing, and trends simultaneously
- Pipeline: gather data, analyze, synthesize, format report

**Content Creation:**
- Parallel research (5 agents) then sequential creation pipeline (research, write, review, publish)
- Review cycle for polished output (write, review, revise until quality bar is met)

**DevOps & Infrastructure:**
- Swarm of agents auditing security, performance, and code quality across a monorepo
- Pipeline for deployment: lint, test, build, deploy, verify

## Technical Details

- Works with any AI model that supports tool use (Claude, GPT, etc.)
- Patterns are model-agnostic but optimized for Claude's tool system
- Templates use YAML for configuration and structured JSON for execution plans
- All patterns include cost tracking and budget enforcement

## License

MIT

---

Built by [@felipe_bmottaa](https://threads.net/@felipe_bmottaa) | Patterns extracted from production systems running 20-50 agents in parallel


path: templates/parallel-research.md
content: # Parallel Research Template (Fan-Out / Fan-In)

## Overview
Spawn N agents to research different aspects of a topic simultaneously, then aggregate results into a single deliverable.

## When to Use
- Market research across multiple dimensions
- Competitor analysis (each agent covers one competitor)
- Multi-source data gathering
- Any task where N independent research queries can run in parallel

## Configuration

```yaml
orchestration:
  pattern: fan-out-fan-in
  max_concurrent: 5
  budget_usd: 3.00
  timeout_minutes: 15

agents:
  researcher:
    model: sonnet
    tools: [Read, Grep, Glob, WebSearch, WebFetch]
    max_turns: 15
    budget_usd: 0.50

  aggregator:
    model: opus
    tools: [Read, Write, Edit]
    max_turns: 10
    budget_usd: 0.50
```

## Execution Plan

### Phase 1: Decompose
The planner identifies N independent research dimensions.

Example for "Analyze the AI code assistant market":
```json
{
  "research_dimensions": [
    {"id": "r1", "topic": "Competitor products and features", "agent": "researcher"},
    {"id": "r2", "topic": "Pricing models and revenue estimates", "agent": "researcher"},
    {"id": "r3", "topic": "User sentiment and community feedback", "agent": "researcher"},
    {"id": "r4", "topic": "Technical architecture and limitations", "agent": "researcher"},
    {"id": "r5", "topic": "Market trends and growth projections", "agent": "researcher"}
  ]
}
```

### Phase 2: Fan-Out (Parallel Execution)
Each researcher agent gets a focused prompt:

```
You are Research Agent [N] in a parallel research team of 5.

YOUR ASSIGNMENT: [specific research dimension]

INSTRUCTIONS:
1. Research this specific topic thoroughly
2. Use WebSearch and WebFetch for current data
3. Structure your findings in the output format below
4. DO NOT research topics assigned to other agents
5. Cite your sources

OUTPUT FORMAT:
## [Topic Name]

### Key Findings
- Finding 1 (source: URL)
- Finding 2 (source: URL)
- Finding 3 (source: URL)

### Data Points
| Metric | Value | Source |
|--------|-------|--------|

### Analysis
[2-3 paragraph analysis of what the data means]

### Confidence Level
[HIGH/MEDIUM/LOW] — [brief justification]
```

### Phase 3: Fan-In (Aggregation)
The aggregator receives all research outputs and synthesizes:

```
You are the Research Aggregator.

You have received research from 5 parallel agents. Your job:
1. Read all 5 research outputs
2. Cross-reference findings — flag contradictions
3. Synthesize into a single coherent report
4. Identify gaps — what wasn't covered?
5. Produce executive summary + detailed sections

OUTPUT STRUCTURE:
## Executive Summary (3-5 bullet points)
## Key Findings by Dimension
## Cross-Cutting Themes
## Contradictions and Uncertainties
## Recommendations
## Gaps for Further Research
```

## Error Handling

| Scenario | Response |
|----------|----------|
| Agent fails to return results | Aggregator notes the gap; report mentions missing dimension |
| Agent returns low-confidence data | Aggregator flags as unverified |
| Budget hit before all agents finish | Aggregate available results; note incomplete dimensions |
| Conflicting data between agents | Aggregator evaluates sources and picks the more credible one |

## Cost Estimate
- 5 researcher agents (Sonnet): ~$0.10-0.30 each = $0.50-1.50
- 1 aggregator agent (Opus): ~$0.20-0.50
- **Total: $0.70-2.00** for comprehensive multi-dimensional research

## Real-World Example: YouTube Niche Research

```json
{
  "task": "Research the best YouTube niches for high CPM in 2026",
  "agents": [
    {"id": "r1", "topic": "Top 20 niches by CPM with current rates"},
    {"id": "r2", "topic": "Audience demographics and advertiser demand per niche"},
    {"id": "r3", "topic": "Competition level — channels per niche, saturation index"},
    {"id": "r4", "topic": "Content production difficulty and automation potential"},
    {"id": "r5", "topic": "Trending niches — growth rate over last 12 months"}
  ],
  "aggregation": "Produce a ranked list of niches scored by: CPM, competition, difficulty, growth"
}
```


path: templates/pipeline.md
content: # Sequential Pipeline Template

## Overview
Chain agents in sequence where each stage's output feeds into the next stage's input. Assembly-line processing with quality gates between stages.

## When to Use
- Content creation workflows (research, write, review, publish)
- Code generation with validation (generate, lint, test, review)
- Data processing (extract, transform, validate, load)
- Any workflow with strict ordering requirements

## Configuration

```yaml
orchestration:
  pattern: pipeline
  budget_usd: 3.00
  timeout_minutes: 20
  abort_on_stage_failure: true

stages:
  - name: generate
    model: sonnet
    tools: [Read, Write, Edit, Bash, Grep, Glob]
    max_turns: 20
    budget_usd: 0.50

  - name: review
    model: opus
    tools: [Read, Grep, Glob]
    max_turns: 10
    budget_usd: 0.30

  - name: fix
    model: sonnet
    tools: [Read, Write, Edit]
    max_turns: 15
    budget_usd: 0.40
    condition: "review.verdict == 'FAIL'"

  - name: test
    model: haiku
    tools: [Read, Write, Bash]
    max_turns: 10
    budget_usd: 0.20
```

## Stage Contract

Every stage must define its input/output contract:

```yaml
stage:
  name: [stage-name]
  input:
    type: [file|text|structured]
    source: [previous stage output or user input]
    path: ".orchestrator/stage-N-output.md"   # if file-based
  output:
    type: [file|text|structured]
    path: ".orchestrator/stage-N+1-output.md"
    format: |
      ## Stage Output: [stage-name]
      ### Status: [SUCCESS|FAIL]
      ### Data:
      [structured output here]
  validation:
    required_fields: [list of fields that must be present]
    max_size_kb: 100
  on_failure:
    action: [retry|abort|skip]
    max_retries: 2
```

## Context Passing Protocol

Agents pass context via intermediate files to avoid token bloat:

```
.orchestrator/
  pipeline-config.json        # Pipeline definition
  stage-1-generate-output.md  # Stage 1 output
  stage-2-review-output.md    # Stage 2 output
  stage-3-fix-output.md       # Stage 3 output (if needed)
  stage-4-test-output.md      # Stage 4 output
  pipeline-report.md          # Final aggregated report
```

Each agent's prompt includes:
```
Read the previous stage output at: .orchestrator/stage-N-output.md
Write your output to: .orchestrator/stage-N+1-output.md
```

## Agent Prompts by Stage

### Stage 1: Generate
```
You are the Generator agent in a sequential pipeline.

INPUT: [user requirements]
YOUR TASK: [generate the initial deliverable]

Write your output to .orchestrator/stage-1-generate-output.md

Requirements:
- [specific requirements]
- Follow the output format exactly
- Include metadata (timestamp, files modified, confidence level)
```

### Stage 2: Review
```
You are the Reviewer agent in a sequential pipeline.

INPUT: Read .orchestrator/stage-1-generate-output.md
YOUR TASK: Review the generated output against these criteria:

1. Correctness (1-10)
2. Completeness (1-10)
3. Code quality (1-10)
4. Security (1-10)
5. Performance (1-10)

Write your review to .orchestrator/stage-2-review-output.md

Format:
## Review Report
### Scores: [table]
### Overall: [N/10]
### Verdict: [PASS if >= 7, FAIL if < 7]
### Issues (if FAIL):
- Issue 1: [description] -> [fix suggestion]
- Issue 2: [description] -> [fix suggestion]
```

### Stage 3: Fix (Conditional)
```
You are the Fixer agent in a sequential pipeline.
This stage only runs if the review verdict was FAIL.

INPUT:
- Original output: .orchestrator/stage-1-generate-output.md
- Review feedback: .orchestrator/stage-2-review-output.md

YOUR TASK: Address every issue listed in the review.

Write the fixed output to .orchestrator/stage-3-fix-output.md

For each issue:
1. Read the issue description
2. Apply the suggested fix (or a better one)
3. Document what you changed and why
```

### Stage 4: Test
```
You are the Tester agent in a sequential pipeline.

INPUT: Read the latest output (.orchestrator/stage-3-fix-output.md or stage-1 if no fix was needed)
YOUR TASK: Validate the output works correctly.

1. Write tests for the generated code
2. Run the tests
3. Report pass/fail with details

Write results to .orchestrator/stage-4-test-output.md
```

## Error Handling

### Stage Failure Flow
```
Stage N fails
  ├── retry_count < max_retries?
  │     YES → Retry stage N with same input
  │     NO  → abort_on_stage_failure?
  │            YES → Cancel pipeline, report partial results
  │            NO  → Skip stage N, continue to N+1 (mark gap)
  └── Final report includes failure details
```

### Conditional Stages
Some stages only run under certain conditions:
```yaml
- name: fix
  condition: "review.verdict == 'FAIL'"

- name: deploy
  condition: "test.pass_rate >= 0.95"

- name: rollback
  condition: "deploy.status == 'FAIL'"
```

## Cost Estimate
- Generator (Sonnet): $0.10-0.30
- Reviewer (Opus): $0.15-0.40
- Fixer (Sonnet, conditional): $0.05-0.20
- Tester (Haiku): $0.02-0.10
- **Total: $0.30-1.00** per pipeline run

## Real-World Example: API Endpoint Creation

```yaml
pipeline:
  task: "Create a REST API endpoint for user profiles with CRUD operations"

  stages:
    - name: generate
      prompt: "Create the API routes, controllers, and models for user profiles CRUD"
      output_files: [src/routes/users.ts, src/controllers/users.ts, src/models/user.ts]

    - name: review
      prompt: "Review for security (SQL injection, auth), error handling, and REST conventions"

    - name: fix
      condition: "review.verdict == FAIL"
      prompt: "Fix all issues from the review"

    - name: test
      prompt: "Write integration tests with supertest, covering happy path and edge cases"
      output_files: [tests/users.test.ts]

    - name: document
      prompt: "Generate OpenAPI spec and update README with the new endpoints"
      output_files: [docs/openapi.yaml, README.md]
```


path: templates/review-cycle.md
content: # Review Cycle Template (Build-Review-Fix Loop)

## Overview
Iterative improvement loop where a builder creates output, a reviewer evaluates it against quality criteria, and the builder fixes issues based on feedback. Repeats until the quality threshold is met or max iterations are exhausted.

## When to Use
- Quality-critical code (auth, payments, security)
- Polished content (blog posts, documentation, marketing copy)
- Complex implementations that benefit from iterative refinement
- Any output that must meet a defined quality bar before shipping

## Architecture

```
                 ┌─────────────────────────────┐
                 │                             │
                 ▼                             │
Iteration 1:  Builder ──► Reviewer             │
                           │                   │
                     ┌─────┴─────┐             │
                     │           │             │
                  PASS ≥7    FAIL <7           │
                     │           │             │
                     ▼           ▼             │
                  Result     Feedback ─────────┘
                              (max 3 iterations)
```

## Configuration

```yaml
orchestration:
  pattern: review-cycle
  max_iterations: 3
  pass_threshold: 7
  budget_usd: 3.00

roles:
  builder:
    model: sonnet
    tools: [Read, Write, Edit, Bash, Grep, Glob]
    max_turns: 20
    budget_usd: 0.50

  reviewer:
    model: opus
    tools: [Read, Grep, Glob]
    max_turns: 10
    budget_usd: 0.30

escalation:
  action: "flag_for_human"
  message: "Failed quality gate after 3 iterations — needs human review"
```

## Iteration Protocol

### Iteration 1: Initial Build

**Builder prompt:**
```
You are the Builder agent. Create the initial implementation.

TASK: [user's task description]

REQUIREMENTS:
[specific requirements list]

Write your output to the appropriate files.
When done, write a summary to .orchestrator/build-iteration-1.md including:
- What you created
- Files modified
- Design decisions made
- Known limitations or trade-offs
```

**Reviewer prompt:**
```
You are the Reviewer agent. Evaluate the Builder's output.

TASK REQUIREMENTS: [original requirements]
BUILDER OUTPUT: Read .orchestrator/build-iteration-1.md and the modified files.

REVIEW CRITERIA (score each 1-10):

1. **Correctness** — Does it work? Are there logic errors, off-by-ones, null pointer risks?
2. **Completeness** — Does it cover ALL requirements? Any missing edge cases?
3. **Code Quality** — Clean architecture? DRY? Proper abstractions? Good naming?
4. **Security** — Input validation? Auth checks? SQL injection? XSS? CSRF?
5. **Performance** — N+1 queries? Unnecessary re-renders? Missing indexes? Memory leaks?
6. **Error Handling** — Graceful failures? User-facing error messages? Logging?
7. **Testability** — Can this be unit tested? Are dependencies injectable?

SCORING:
- Calculate average of all criteria
- PASS: average >= 7
- FAIL: average < 7

OUTPUT FORMAT:
Write to .orchestrator/review-iteration-1.md:

## Review Report — Iteration 1

### Scores
| Criterion | Score | Notes |
|-----------|-------|-------|
| Correctness | X/10 | ... |
| Completeness | X/10 | ... |
| Code Quality | X/10 | ... |
| Security | X/10 | ... |
| Performance | X/10 | ... |
| Error Handling | X/10 | ... |
| Testability | X/10 | ... |

### Overall Score: X.X/10
### Verdict: PASS / FAIL

### Issues (if FAIL — ordered by severity):
1. [CRITICAL] Description → Suggested fix
2. [HIGH] Description → Suggested fix
3. [MEDIUM] Description → Suggested fix
4. [LOW] Description → Suggested fix

### What Went Well:
- [positive feedback to reinforce good patterns]
```

### Iteration 2+ : Fix Based on Feedback

**Builder prompt (fix iteration):**
```
You are the Builder agent. The Reviewer found issues with your work.

ORIGINAL TASK: [user's task]
YOUR PREVIOUS OUTPUT: Read .orchestrator/build-iteration-N.md
REVIEW FEEDBACK: Read .orchestrator/review-iteration-N.md

ADDRESS EACH ISSUE:
For every issue listed in the review:
1. Read the issue description and severity
2. Apply the fix (or implement a better solution)
3. Document what you changed

PRIORITY: Fix CRITICAL and HIGH issues first. MEDIUM and LOW are nice-to-have.

Write updated summary to .orchestrator/build-iteration-N+1.md including:
- Issues addressed (with before/after)
- Issues skipped (with justification)
- Any new concerns introduced by the fixes
```

## Decision Flow

```
iteration = 1

LOOP:
  Builder creates/fixes output
  Reviewer evaluates output

  if reviewer.score >= pass_threshold:
    PASS → Return final output + review history

  if iteration >= max_iterations:
    ESCALATE → Flag for human review with full history
    Return best iteration's output + all review reports

  iteration += 1
  Builder receives reviewer feedback
  GOTO LOOP
```

## Review History Tracking

Maintain a running log for transparency:

```markdown
# Review Cycle History

## Iteration 1
- Builder: Created initial implementation
- Reviewer: Score 5.4/10 — FAIL
  - 3 CRITICAL issues, 2 HIGH issues
  - Main concern: Missing auth checks on API routes

## Iteration 2
- Builder: Fixed all CRITICAL and HIGH issues
- Reviewer: Score 7.8/10 — PASS
  - All critical issues resolved
  - 2 LOW suggestions for future improvement

## Final Output
- Iteration: 2 of 3 max
- Final score: 7.8/10
- Total cost: $1.60
- Files modified: [list]
```

## Error Handling

| Scenario | Response |
|----------|----------|
| Builder fails mid-iteration | Retry with fresh agent; pass previous iteration's output as starting point |
| Reviewer gives inconsistent scores | Log anomaly; if scores contradict the issues list, re-run review |
| Score oscillates (improves then worsens) | Cap at best score achieved; investigate if fixes are breaking other things |
| Max iterations reached, still failing | Return best iteration + full review history; flag for human |
| Budget exceeded mid-cycle | Return current state with partial review |

## Score Calibration

To prevent overly strict or lenient reviews:

```
Calibration guidelines for the Reviewer:
- 9-10: Production-ready, exemplary code. No changes needed.
- 7-8: Good quality. Minor improvements possible but not blocking.
- 5-6: Functional but has significant issues. Needs another iteration.
- 3-4: Fundamental problems. Major rework needed.
- 1-2: Doesn't work or is completely wrong.

A score of 7 means: "I would approve this PR with minor comments."
```

## Cost Estimates

| Iterations | Builder (Sonnet) | Reviewer (Opus) | Total |
|-----------|-------------------|------------------|-------|
| 1 (pass)  | $0.10-0.30       | $0.15-0.30      | $0.25-0.60 |
| 2 (fix)   | $0.20-0.60       | $0.30-0.60      | $0.50-1.20 |
| 3 (max)   | $0.30-0.90       | $0.45-0.90      | $0.75-1.80 |

## Real-World Example: Secure Auth Endpoint

```yaml
review_cycle:
  task: "Build JWT authentication with refresh tokens, rate limiting, and account lockout"
  max_iterations: 3
  pass_threshold: 8  # Higher bar for security-critical code

  builder:
    model: sonnet
    initial_prompt: |
      Build a complete JWT auth system:
      - Login endpoint with email/password
      - JWT access tokens (15min) + refresh tokens (7 days)
      - Rate limiting: 5 failed attempts → 15min lockout
      - Secure token storage (httpOnly cookies)
      - Token rotation on refresh
      - Logout (invalidate refresh token)

  reviewer:
    model: opus
    criteria:
      - "OWASP Top 10 compliance"
      - "Token handling best practices (no localStorage)"
      - "Rate limiting is per-account, not per-IP"
      - "Refresh token rotation prevents replay attacks"
      - "Timing-safe password comparison"
      - "Proper error messages (no info leakage)"

  expected_iterations: 2
  # First build usually misses timing-safe comparison and token rotation
  # Second iteration with specific feedback produces production-ready code
```

## Combining with Other Patterns

### Review Cycle + Swarm
Run a swarm to build the feature, then run a review cycle on the combined output:
```
Phase 1: Swarm (4 agents build different modules in parallel)
Phase 2: Review Cycle (reviewer evaluates the integrated result, builder fixes integration issues)
```

### Review Cycle + Pipeline
Add review cycle as a stage in a pipeline:
```
Stage 1: Generate (builder)
Stage 2: Review Cycle (iterate until quality bar met)
Stage 3: Test (tester validates the reviewed output)
Stage 4: Deploy (only if tests pass)
```


path: templates/swarm.md
content: # Swarm Template (Autonomous Agents, Shared Goal)

## Overview
Multiple agents work on the same codebase simultaneously with dependency-aware scheduling, file locking, and budget enforcement. The most powerful pattern for large-scale changes.

## When to Use
- Large refactors touching 10+ files
- Codebase-wide improvements (add logging, update error handling, migrate APIs)
- Multi-module feature implementation
- Any task that naturally splits into 4-8 parallel workstreams

## Architecture

```
┌──────────────────────────────────────────────────┐
│              Swarm Orchestrator                   │
│                                                   │
│  ┌─────────────────────────────────────────────┐  │
│  │  Phase 1: DECOMPOSE (Opus)                  │  │
│  │  Complex task → Dependency graph             │  │
│  └──────────────────┬──────────────────────────┘  │
│                     │                              │
│  ┌──────────────────▼──────────────────────────┐  │
│  │  Phase 2: EXECUTE (Haiku/Sonnet workers)    │  │
│  │                                              │  │
│  │  Wave 1: [A1] [A2] [A3]  ← parallel         │  │
│  │  Wave 2:    [A4] [A5]    ← depends on W1    │  │
│  │  Wave 3:       [A6]      ← depends on W2    │  │
│  │                                              │  │
│  │  File locks: src/auth.ts → A1               │  │
│  │  Budget:     $1.23 / $5.00                  │  │
│  └──────────────────┬──────────────────────────┘  │
│                     │                              │
│  ┌──────────────────▼──────────────────────────┐  │
│  │  Phase 3: QUALITY GATE (Opus)               │  │
│  │  Review combined output → Score → PASS/FAIL  │  │
│  └──────────────────┬──────────────────────────┘  │
│                     │                              │
│  ┌──────────────────▼──────────────────────────┐  │
│  │  Phase 4: REPORT                            │  │
│  │  Summary, costs, session recording           │  │
│  └─────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────┘
```

## Configuration

```yaml
swarm:
  name: codebase-refactor
  max_concurrent: 4
  budget_usd: 5.00
  retry_per_task: 2
  quality_gate: true
  quality_threshold: 7

models:
  decomposer: opus        # Phase 1 — needs deep reasoning
  worker: sonnet           # Phase 2 — balanced cost/capability
  quality_gate: opus       # Phase 3 — needs full picture understanding

agent_types:
  coder:
    tools: [Read, Write, Edit, Bash, Grep, Glob]
    max_turns: 20
    budget_usd: 0.50

  tester:
    tools: [Read, Write, Bash]
    max_turns: 15
    budget_usd: 0.30

  reviewer:
    tools: [Read, Grep, Glob]
    max_turns: 10
    budget_usd: 0.30

  documenter:
    tools: [Read, Write, Edit]
    max_turns: 10
    budget_usd: 0.20
```

## Task Decomposition Prompt

Feed this to Opus for Phase 1:

```
You are a task decomposition expert. Given a complex task and a codebase, break it down into subtasks that can be executed by separate agents.

RULES:
1. Each subtask should be as independent as possible
2. Specify dependencies between tasks (by task ID)
3. Each task MUST specify which files it will modify
4. Tasks should be completable in a few minutes each
5. Minimize file overlap — if two tasks MUST edit the same file, make one depend on the other
6. Include a reviewer task at the end that depends on all implementation tasks
7. Keep total tasks between 3 and 8

OUTPUT (strict JSON):
{
  "tasks": [
    {
      "id": "task-1",
      "description": "Short description",
      "agent_type": "coder|tester|reviewer|documenter",
      "dependencies": [],
      "files_to_modify": ["src/file.ts"],
      "tools": ["Read", "Write", "Edit"],
      "prompt": "Detailed instructions for this specific agent..."
    }
  ]
}

CODEBASE DIRECTORY: [path]
TASK: [user's complex task]

First explore the codebase structure, then output the decomposition.
```

## Execution Engine

### Wave Calculation (Topological Sort)
```
Given tasks and dependencies, compute execution waves:

task-1: deps=[]         → Wave 1
task-2: deps=[]         → Wave 1
task-3: deps=[]         → Wave 1
task-4: deps=[1,2]      → Wave 2
task-5: deps=[3]        → Wave 2
task-6: deps=[4,5]      → Wave 3

Execution:
  Wave 1: Run task-1, task-2, task-3 in parallel
  Wave 2: Run task-4, task-5 in parallel (after wave 1 completes)
  Wave 3: Run task-6 (after wave 2 completes)
```

### File Locking Protocol
```
BEFORE agent starts:
  for each file in task.files_to_modify:
    if file is locked by another agent:
      BLOCK this task (set status = BLOCKED)
      Wait until the lock is released
    else:
      LOCK file → assign to this agent

AFTER agent finishes:
  for each file in task.files_to_modify:
    UNLOCK file

  Check BLOCKED tasks — if their locks are now free, set status = PENDING
```

### Budget Enforcement
```
AFTER each agent completes:
  total_cost += agent.cost

  if total_cost >= budget_limit:
    for each PENDING task:
      set status = CANCELLED
      set error = "Budget exceeded: $X.XX >= $Y.YY"

    Wait for RUNNING agents to finish (don't kill them)
    Proceed to quality gate with partial results
```

## Worker Agent Prompt Template

```
You are Agent [ID] in a swarm of [N] agents working on a shared codebase.

YOUR TASK: [specific task description]

FILES YOU OWN (you may ONLY modify these):
- [file1.ts]
- [file2.ts]

FILES YOU MAY READ (but NOT modify):
- [any file in the codebase]

CONTEXT FROM COMPLETED TASKS:
- task-1 modified [files] — [brief summary of changes]
- task-2 modified [files] — [brief summary of changes]

CONSTRAINTS:
- Do NOT modify files outside your ownership list
- Do NOT create new files unless explicitly required
- Complete your task within [max_turns] turns
- If you encounter a blocker, document it and stop — do not try to work around it

OUTPUT: When done, write a brief summary of what you changed and why.
```

## Quality Gate Prompt

```
You are the Quality Gate reviewer. Multiple agents have modified this codebase.

ORIGINAL TASK: [user's complex task]

AGENT RESULTS:
[for each completed agent: task description, files modified, summary]

REVIEW CRITERIA:
1. Correctness: Do the changes achieve the original task?
2. Integration: Do the agents' changes work together without conflicts?
3. Completeness: Is anything missing?
4. Code quality: Clean, maintainable, well-structured?
5. Security: Any vulnerabilities introduced?

Score each criterion 1-10.
Overall score (average).
Verdict: PASS (>= 7) or FAIL (< 7).

If FAIL, list specific issues that need fixing.
```

## Error Handling

### Task Failure
```
Agent fails (error or timeout)
  ├── retry_count < max_retries?
  │     YES → Reset task to PENDING, spawn new agent
  │     NO  → Mark task as FAILED
  │           ├── Has dependent tasks?
  │           │     YES → Cancel all dependent tasks
  │           │     NO  → Continue with remaining tasks
  └── Update swarm report
```

### Conflict Recovery
```
File conflict detected (two agents claim same file)
  ├── Are the tasks independent?
  │     YES → Make task-B depend on task-A (dynamic dependency)
  │     NO  → Merge is possible — mark for manual review
  └── Log conflict in swarm report
```

## Cost Estimates

| Swarm Size | Decompose (Opus) | Workers (Sonnet) | Quality Gate (Opus) | Total |
|-----------|-------------------|-------------------|---------------------|-------|
| 3 tasks   | $0.15-0.30       | $0.30-0.90       | $0.15-0.30         | $0.60-1.50 |
| 5 tasks   | $0.20-0.40       | $0.50-1.50       | $0.20-0.40         | $0.90-2.30 |
| 8 tasks   | $0.25-0.50       | $0.80-2.40       | $0.25-0.50         | $1.30-3.40 |

## Real-World Example: Full-Stack Feature Addition

```json
{
  "task": "Add user notification system with email and in-app notifications",
  "decomposition": {
    "tasks": [
      {
        "id": "task-1",
        "description": "Create notification data model and database migration",
        "agent_type": "coder",
        "files_to_modify": ["prisma/schema.prisma", "src/models/notification.ts"],
        "dependencies": []
      },
      {
        "id": "task-2",
        "description": "Build notification service with email integration",
        "agent_type": "coder",
        "files_to_modify": ["src/services/notification.ts", "src/services/email.ts"],
        "dependencies": []
      },
      {
        "id": "task-3",
        "description": "Create API routes for notifications CRUD",
        "agent_type": "coder",
        "files_to_modify": ["src/routes/notifications.ts", "src/controllers/notifications.ts"],
        "dependencies": ["task-1"]
      },
      {
        "id": "task-4",
        "description": "Build notification UI components",
        "agent_type": "coder",
        "files_to_modify": ["src/components/NotificationBell.tsx", "src/components/NotificationList.tsx"],
        "dependencies": ["task-3"]
      },
      {
        "id": "task-5",
        "description": "Write tests for notification service and API",
        "agent_type": "tester",
        "files_to_modify": ["tests/notifications.test.ts", "tests/notification-service.test.ts"],
        "dependencies": ["task-2", "task-3"]
      },
      {
        "id": "task-6",
        "description": "Review all changes for security, performance, and integration",
        "agent_type": "reviewer",
        "files_to_modify": [],
        "dependencies": ["task-3", "task-4", "task-5"]
      }
    ]
  },
  "waves": {
    "wave-1": ["task-1", "task-2"],
    "wave-2": ["task-3"],
    "wave-3": ["task-4", "task-5"],
    "wave-4": ["task-6"]
  }
}
```


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)