/metaswarm:orchestrated-executionfrom metaswarm
Defines a 4-phase execution loop (IMPLEMENT, VALIDATE, ADVERSARIAL REVIEW, COMMIT) for orchestrating work units with independent validation and adversarial review against a written spec.
Ships in metaswarm. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Core principle: Trust nothing. Verify everything. Review adversarially.
This skill defines a generalized 4-phase execution loop that any orchestrator can invoke when implementing work units. It replaces linear "implement then review" flows with a rigorous cycle that independently validates results and adversarially reviews against a written spec contract.
This skill is mode-agnostic — the 4-phase execution loop works identically in both Task Mode and Team Mode. The differences:
Task() per work unit, and each review-fix round spawns a FRESH coder of the chosen tier with a complete fix brief. A coder is never resumed for a new round. The only exception is messaging an old agent to resend a lost report. Role type: roleType("coder") by default; roleType("mechanical-coder") or roleType("supercoder") per Coder Selection. A security-critical work unit uses roleType("security-coder"), which takes precedence over supercoder.Task() instance (roleType("adversarial-reviewer")) in BOTH modes. Never a teammate, never resumed.See ./guides/agent-coordination.md for full mode detection and coordination details.
After drafting an implementation plan (Step 1: Plan Validation), submit it to the Plan Review Gate before writing-plans presents the plan (or before you present it to the user); see ./guides/workflow-enforcement.md. In full orchestration there is no separate design doc, so after the Plan Review Gate passes the plan goes to the Design Review Gate (two pipelines). The Plan Review Gate spawns 3 adversarial reviewers (Feasibility, Completeness, Scope & Alignment) — all must PASS. See skills/plan-review-gate/SKILL.md for details.
Before giving the user any milestone date or estimate, the orchestrator MUST:
bd dep / bd show), not just the next one or two units.State the date together with the blockers it rests on. Why: a milestone date was given from the next one or two units and was wrong twice.
Do NOT use for: Single-file bug fixes, copy changes, or tasks without a spec.
Before submitting a plan to the Design Review Gate, the orchestrator MUST verify every item on this checklist. This prevents expensive design review cycles on fundamentally broken plans.
Note: the Architect is spawned as
roleType("planner"), which can writePLAN.mditself (it is not read-only, unlike the reviewer types). Role types are resolved per Role type resolution.
If the plan includes HTTP endpoints or WebSocket protocols, verify:
If the plan includes a user interface:
.env.example includes all required env varsIf any checklist item fails, fix the plan BEFORE submitting to Design Review Gate.
Every plan submitted for Design Review MUST include these sections:
### POST /api/todos
- **Request Body**: `{ title: string }` (required, 1-500 chars, trimmed)
- **Success**: `201 Created` -> `{ id, title, completed, createdAt, updatedAt }`
- **Errors**: `400` (validation) / `500` (internal)
A work unit is the atomic unit of orchestrated execution. Before entering the 4-phase loop, decompose the implementation plan into work units.
Each work unit contains:
| Field | Description | Example |
|---|---|---|
| ID | Unique identifier (BEADS task ID) | bd-wu-001 |
| Title | Human-readable name | "Implement auth middleware" |
| Spec | Written specification with acceptance criteria | Link to design doc section |
| DoD Items | Enumerated, verifiable done criteria | [ ] Middleware rejects expired tokens |
| Dependencies | Other work units that must complete first | [bd-wu-000] |
| File Scope | Files this work unit may touch | src/middleware/auth.ts, src/middleware/auth.test.ts |
| Human Checkpoint | Whether to pause for human review after completion | true for risky changes |
Work units form a directed acyclic graph (DAG):
wu-001 (schema changes) ───┐
├──→ wu-003 (API endpoints) ───→ wu-005 (integration tests)
wu-002 (shared utilities) ──┘ │
▼
wu-004 (UI components) ────────────────────────────────────→ wu-006 (e2e tests)
Rules for decomposition:
# Create work units as BEADS tasks under the epic
bd create "WU-001: <title>" --type task --parent <epic-id> \
--description "Spec: <spec-section>\nDoD:\n- [ ] <item-1>\n- [ ] <item-2>\nFile scope: <files>\nCheckpoint: <yes/no>"
# Set up dependencies
bd dep add <wu-003> <wu-001>
bd dep add <wu-003> <wu-002>
For each work unit, execute these four phases in sequence. Do not skip phases. Do not combine phases. Do not proceed to the next phase until the current phase produces a clear outcome.
┌─────────────────────────────────────────────────────────────────┐
│ 4-PHASE EXECUTION LOOP │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌──────┐ │
│ │ IMPLEMENT│───→│ VALIDATE │───→│ ADVERSARIAL │───→│COMMIT│ │
│ │ │ │ │ │ REVIEW │ │ │ │
│ └──────────┘ └──────────┘ └──────┬───────┘ └──────┘ │
│ ▲ │ │
│ │ FAIL │ │
│ └─────────────────────────────────┘ │
│ │
│ FAIL: fix → re-validate → FRESH review → severity rule (cap 10) │
└─────────────────────────────────────────────────────────────────┘
The coding subagent executes against the work unit spec.
Orchestrator actions:
./guides/coder-selection.md: roleType("mechanical-coder") only when every mechanical condition holds, roleType("supercoder") when any super condition holds, otherwise roleType("coder") (when unsure, coder). roleType("security-coder") when any security-coder condition holds; it takes precedence over supercoder. A debugger condition in the rubric (a recurrence, a flaky or racy failure, a cross-component failure nobody can place, or a coder BLOCKED on "can't find why") sends roleType("debugger") first, with one narrow question; its fix design then goes to a fresh coder of the tier the rubric picks, and a debugger condition takes precedence over supercoder escalation until the root cause is knownroleType("coder") unless the rubric chose another tier) with the work unit spec, DoD items, file scope, and the Project Context DocumentSubagent spawn template (role type roleType("coder")):
You are the CODER AGENT for work unit ${wuId}.
## Spec
${spec}
## Definition of Done
${dodItems.map((item, i) => `${i+1}. ${item}`).join('\n')}
## File Scope
You may ONLY modify these files: ${fileScope.join(', ')}
## Project Context
${projectContext}
## Gate Commands
${gateCommands.join('\n')}
(The exact commands for the files in scope: tests, type check, lint, and project registration gates such as lint allow-lists, service inventories and CI gate tables.)
## Rules
- Follow TDD: write failing test first, then implement to make it pass
- Do NOT modify files outside your file scope
- Do NOT self-certify — the orchestrator will validate independently
- When complete, report what you changed and what tests you added
- Run EVERY gate command above and paste the raw last lines of each into your hand-back. "Passes" without pasted output is not a hand-back
- NEVER use --no-verify on git commits — pre-commit hooks are mandatory
- NEVER use git push --force
- NEVER suppress linter/type errors with eslint-disable, @ts-ignore, or as any
- NEVER skip tests or claim "tests pass" without actually running them
Phase 1 output: List of changed files and new tests.
The orchestrator independently runs quality gates. Never trust subagent self-reports.
Orchestrator actions (run these yourself, NOT via the coding subagent):
# 1. Type checking
npx tsc --noEmit
# 2. Linting
npx eslint <changed-files>
# 3. Run tests (full suite, not just new tests)
npx vitest run
# 4. Coverage enforcement (BLOCKING — read .coverage-thresholds.json)
# If .coverage-thresholds.json exists, read the enforcement command and run it
# This is NOT optional. Coverage below threshold = VALIDATION FAIL.
if [ -f .coverage-thresholds.json ]; then
CMD=$(node -e "console.log(JSON.parse(require('fs').readFileSync('.coverage-thresholds.json','utf-8')).enforcement.command)")
eval "$CMD"
fi
# 5. Verify file scope was respected
git diff --name-only | while read file; do
echo "$file" # Check each file is within the work unit's declared scope
done
Phase 2 outcomes:
Critical rule: The orchestrator runs validation commands directly. The orchestrator does NOT ask the coding subagent "did the tests pass?" and accept the answer.
A separate review subagent checks the implementation against the spec contract. This is NOT the same as a collaborative code review — it's adversarial verification.
Key differences from collaborative review:
| Collaborative Review | Adversarial Review |
|---|---|
| APPROVED / CHANGES REQUIRED | PASS / FAIL |
| Subjective quality assessment | Binary spec compliance check |
| Reviewer suggests improvements | Reviewer finds contract violations |
| Same reviewer can re-review | Fresh reviewer required on re-review |
Uses code-review-rubric.md | Uses adversarial-review-rubric.md |
Orchestrator actions:
roleType("adversarial-reviewer"))Reviewer spawn template (role type roleType("adversarial-reviewer")):
You are the ADVERSARIAL REVIEWER for work unit ${wuId}.
## Mode
Adversarial — your job is to FIND FAILURES, not to approve.
## Rubric
Read and follow: ./rubrics/adversarial-review-rubric.md
## Spec
${spec}
## Definition of Done
${dodItems.map((item, i) => `${i+1}. ${item}`).join('\n')}
## What to Review
Run: git diff main..HEAD -- ${fileScope.join(' ')}
## Findings
Report every finding with the 6 fields defined in `./guides/delivery-scope.md`:
- title: <short label, ≤ ~80 chars>
- description: <1-3 sentences: what is wrong and why it matters>
- severity: critical | major | minor | nit
- protects: <credible user scenario | explicit requirement | DoD item> # required for critical/major
- evidence: <file:line or expected-vs-found>
- blocker: yes | no # yes only if severity ∈ {critical, major} AND protects is non-empty
- theme: <short label> # on every finding; reuse an earlier theme label when one fits
- needs_user: yes | no # blockers only: yes only if just the user can answer it, or the fix is a requirement choice (see the guide)
- origin: implementation | requirement | assumption # blockers only
- assumption: <ledger id such as A3, or a quoted decision> # required when origin is assumption
## Earlier Theme Labels
${themeLabels}
(Round 1: none. From round 2 on these are the canonical theme labels from earlier rounds, labels only. Reuse one in `theme` when it fits; otherwise use a new short label.)
## Confirmed Answers
${confirmedAnswers}
(The current Confirmed list and open Assumptions (ids A1, A2, ...) from the design or plan's assumption ledger, copied verbatim. Use these ids in `assumption`.)
## Rules
- Check EACH DoD item. Cite file:line evidence for PASS or expected-vs-found for FAIL.
- Required check, sibling paths: for every fix or new behaviour, check the paths that handle the same data or event (replay or recovery after restart, resume, retry, rollback, restore).
- Required check, production wiring: tests must exercise the production constants and wiring, not a hand-built config that differs from production.
- Any `blocker: yes` finding means overall FAIL. A critical or major finding without `protects` is advisory (`blocker: no`).
- You have NO context from previous reviews. Judge fresh.
- Report every finding with the 6 fields; minor/nit findings are recorded as follow-ups, not suggestions.
- Do not mark `needs_user` when the Confirmed section (the Confirmed Answers above) already answers the question. Add `theme` to every finding and the other signal fields to each blocker.
Security work units. When the work unit meets any security-coder condition in Coder Selection (whichever tier built it, including a supercoder fallback), or touches a security boundary, the reviewer brief also names ./rubrics/security-implementation-rubric.md (when review is routed to external tools, see Review in skills/external-tools/SKILL.md: the same rubric goes with the spec and the S1-S8 block is required in the result) (add a line Also read and follow: ./rubrics/security-implementation-rubric.md under Rubric), and the review appends the S1-S8 verdict block defined there.
Phase 3 outcomes:
blocker: yes finding) → proceed to Phase 4; file any minor/nit findings as follow-upsblocker: yes finding) → apply the severity rule in On FAIL: iterate (return to Phase 1 with the failure report), clarify (stop and ask the user) or escalateFresh reviewer rule: On re-review after FAIL, the orchestrator MUST spawn a new review subagent (role type roleType("adversarial-reviewer")). Never pass previous findings to the new reviewer. Never reuse the same reviewer instance. This prevents anchoring bias and ensures independent verification.
Only after PASS from adversarial review.
Orchestrator actions:
# Stage only files within the work unit's file scope
git add <file-scope-files>
# Commit with reference to work unit
git commit -m "feat(wu-${wuId}): <description>
DoD items verified:
$(dodItems.map((item, i) => `- [x] ${item}`).join('\n'))
Reviewed-by: adversarial-review (PASS)"
After commit:
bd close <wu-task-id> --reason "4-phase loop complete. PASS."After commit, update SERVICE-INVENTORY.md:
If this work unit created or modified services, factories, database tables, or shared modules, update SERVICE-INVENTORY.md with the new entries. This document is read by subsequent coder agents to avoid duplicating existing services.
Quality gates are BLOCKING STATE TRANSITIONS, not advisory recommendations. The orchestrator CANNOT advance to the next phase without gate passage.
IMPLEMENT ──→ VALIDATE ──→ REVIEW ──→ COMMIT
│ │
↓ ↓
FAIL: FAIL: severity rule (cap 10):
fix + re-run fix + re-validate
+ FRESH re-review
│ │
(max 3 VALIDATE) │
│ │
↓ ↓
ESCALATE ESCALATE when the rule says so
(to human) (to human, with a recommendation)
.coverage-thresholds.json thresholdsroleType("adversarial-reviewer") instance, no memory)A review FAIL (at least one blocker: yes finding) is not retried on a fixed count. After each review round the orchestrator applies the severity rule from ./guides/delivery-scope.md: SAFETY_CAP = 10 rounds per work unit, and the first line that matches wins. "Re-validate" means running Phase 2 (VALIDATE) again.
after each review round (round = 1, 2, ...):
file every minor/nit finding as a follow-up (see Follow-ups)
1. no blocker: yes findings → PASS, advance
2. a Clarify signal (C1–C4) fires → stop: misunderstanding analysis, Clarification report, wait for the user
3. round >= 10 (SAFETY_CAP) → escalate; report "cap hit" as an overengineering signal
4. the same critical/major finding recurs after a fix attempt for it,
or two reviewers rate the same finding blocker vs. non-blocker → escalate
5. an overengineering signal is present → restate the DoD and re-classify each blocker against the policy;
any still names a credible scenario → escalate with a recommendation;
otherwise downgrade them to follow-ups and advance
6. this round fixed ≥1 critical/major, or ≥2 independent reviewers reported blockers
→ fix blockers, re-validate, FRESH review
7. otherwise → fix blockers, re-validate, FRESH review
needs_user or origin gets one re-request too; if they are still missing they are treated as unknown, which triggers nothing. A review without a Criteria applied: line is re-requested once too; if it is still missing, it is accepted and the gap becomes a follow-up, so it never blocks (see the guide).bd is available, file each as a BEADS task (bd create --type task) linked to the work unit. Otherwise, or if bd create fails, list them under a ### Follow-ups heading in the work unit's report; the PR body carries them (see 8.5).bd update <task-id> --status blocked and bd label add <task-id> waiting:human), and set status: clarify-pending with pendingClarify in the history file. Line 2 never uses the escalation report; the Clarification report's options are in the guide and none of them approves..beads/context/review-history/orchestrated-execution-<slug>-<occurrence>.json (the format, the status lifecycle and pendingClarify are in the guide's Round history section). <occurrence> is the next free integer for that gate and slug, starting at 1. For this gate the slug is <plan-slug>-<wu-id>, so the file is orchestrated-execution-<plan-slug>-<wu-id>-<occurrence>.json. <plan-slug> is the issue number or a short slug of the title in the # Plan: heading of .beads/plans/active-plan.md (for example 103), so different issues do not collide. Store the artifact path (here .beads/plans/active-plan.md#<wu-id>) in the file, set reviewers to 1, and use stable role names as reviewer labels.fix_induced on each new blocker that matches the lastFix stored before this round's review (the changes made since the previous review). Then map each blocker's theme to a canonicalTheme, and merge duplicate blockers (the same canonical theme and the same defect) by setting mergedInto on each duplicate. Then classify requirement choices: check every blocker against the requirement choice definition in the guide's Signal fields, and for each one set needs_user: yes, origin: requirement and classifiedBy: orchestrator on the recorded finding, even when the reviewer said no, so C1 fires this round. Remove any assumption id from a finding you reclassify this way (record an unconfirmed assumption as its own origin: assumption finding). Before running the helper, check that a new requirement-choice blocker's canonical theme is not already in ackFindings unless it re-asks the same answered question; if it is a different question, give it a new canonical theme. The Clarification report gives the options with pros and cons and a recommended default; questions never block independent work. Run the rule. When you then fix the blockers, overwrite lastFix with that fix before the next review.HISTORY to the review-history file path, then run the rule with RR=lib/review-rule.js; { [ -f ./lib/review-rule.js ] && grep -q '"name": *"metaswarm"' package.json 2>/dev/null; } || { RR="${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$(command -v metaswarm-agents.sh 2>/dev/null)")")}/lib/review-rule.js"; [ -f "$RR" ] || RR=lib/review-rule.js; }; node "$RR" "$HISTORY" (HISTORY is the path of the review-history file, for example HISTORY=.beads/context/review-history/<file>.json). It prints {line, action, signals, capHit}. Recurring or disputed (line 4) and overengineering (line 5) need your judgement, so set the round's recurring, disputed and overengineering flags first. If the path does not resolve or Node is unavailable, apply the rule by hand. On exit 2, fix the history file and run it again.When the rule says iterate:
blocker: yes finding identified by the reviewer. Choose the coder tier for the round with ./guides/coder-selection.md and spawn a FRESH coder of that tier (roleType("coder"), roleType("supercoder"), roleType("security-coder") or roleType("mechanical-coder")) with a complete fix brief. Never resume the previous coder for a new round. The only exception is messaging an old agent to resend a lost report. Never step down a tier within a round. If a debugger condition in the rubric holds (recurrence or C4, a flaky or racy failure, tests pass but the integrated system fails, a cross-component failure, or a coder BLOCKED on "can't find why"), spawn roleType("debugger") first with one narrow question and give its fix design to the fresh coder; the debugger takes precedence over supercoder escalation until the root cause is known. If the coder STOPs on a requirement choice instead of finishing, that is a Clarify stop: record it as a needs_user: yes, origin: requirement blocker, send the Clarification report with the options, pros, cons and recommended default, mark the work unit waiting on the user, and do not spawn another coder for that question until the user answers.roleType("adversarial-reviewer"), fresh instance, no memory of previous review)escalation.coder.after_failures failed VALIDATE attempts (default 2, read from .metaswarm/models.yaml), re-spawn with roleType("supercoder"). The supercoder role is the one definition of the Opus coder; its model comes from roles.supercoder.claude in .metaswarm/models.yaml (default opus). escalation.coder.claude is still honoured as the supercoder model when roles.supercoder.claude is not set. There is no per-call model override on coder. Escalation of a security-critical work unit goes to roleType("security-coder") instead; everything else stays supercoder.Fix-brief checklist. Every fix-round spawn (and every tier change) gets a complete brief, because the fresh coder has no memory of earlier rounds:
Track each round visibly: "Review round 1/10", "Review round 2/10", etc.
When the rule says clarify (line 2), use the Clarification report from the Clarify section of the guide, not this one. When it says escalate (lines 3, 4 or 5), report:
## Review Escalation: Phase 3 ADVERSARIAL REVIEW — WU-<id>
**Rule line**: <3 cap hit | 4 recurring/disputed | 5 overengineering signal>
### Remaining findings
- **Critical**: <title>: <description> — protects: <...> — evidence: <...>
- **Major**: <title>: <description> — protects: <...> — evidence: <...>
- **Minor**: <title> (follow-up filed)
- **Nit**: <title> (follow-up filed)
### Round history
| Round | Verdict | Blockers (critical/major) | Fixed this round | Signals (C1–C4) | Themes | Rule decision |
|-------|---------|---------------------------|------------------|-----------------|--------|---------------|
| 1 | FAIL | 0 / 2 | — | — | <theme-a> | 7: iterate |
| 2 | FAIL | 0 / 1 | 0 / 2 | — | <theme-b> | 6: iterate |
| 3 | FAIL | 0 / 1 | 0 / 0 | — | <theme-a>, <theme-c> | 4: escalate (recurring) |
### Options
Use the decision-request format (see Decision requests in `delivery-scope.md`): mark exactly one option (Recommended) and give only that option a Why recommended line.
**Decision 1: <what must be decided>**
<one or two lines of context>
**Option A: Revise** (Recommended)
fix the remaining blockers (or the requirement they protect), then run a fresh review round
- Pros: <pros>
- Cons: <cons>
- Why recommended: <reason from the rule, tied to the user's goals or constraints>
**Option B: Narrow scope**
move the contentious items to a new issue, then run a fresh review round on what remains
- Pros: <pros>
- Cons: <cons>
**Option C: Defer**
shelve this work for later; nothing advances
- Pros: <pros>
- Cons: <cons>
**Option D: Cancel**
abandon this work
- Pros: <pros>
- Cons: <cons>
**Option E: Clarify the requirement / re-brainstorm**
answer the open questions about the requirement; a new gate occurrence starts
- Pros: <pros>
- Cons: <cons>
Reply with the decision number and a letter, like `1 A` (option E is `1 E`; a bare `E` is the explain shortcut). If there's no answer: nothing advances; the gate stays escalated and the work waits.
blocker: yes finding anyway"blocker: yes findings. Severity rule line 7: fixing, re-validating, spawning fresh reviewer. Review round 2/10."blocker: yes findings. 1 minor finding filed as a follow-up. Committing."When multiple work units have no dependencies on each other, execute them in parallel — but with structured convergence points.
┌──── WU-001: IMPLEMENT ────┐
│ │
Fan-out ──────┼──── WU-002: IMPLEMENT ────┼──── Converge for VALIDATE
│ │
└──── WU-003: IMPLEMENT ────┘
│
┌──── WU-001: REVIEW ────────┤
│ │
Fan-out ──────┼──── WU-002: REVIEW ────────┼──── Sequential COMMIT
│ │
└──── WU-003: REVIEW ────────┘
Rules for parallel execution:
roleType("coder")) for independent work units simultaneouslyroleType("adversarial-reviewer")) for each work unit simultaneouslyStale notification handling: When parallel subagent results arrive after the orchestrator has moved past their work unit (e.g., at a checkpoint), acknowledge them briefly in one line. Do NOT print a full "still waiting at checkpoint" block for each stale notification — this clutters the conversation and wastes context window.
The orchestrator MUST maintain a project context document that grows with each work unit. This is passed to every coder subagent to prevent context loss.
# Project Context (Maintained by Orchestrator)
## Tooling
- Package manager: <npm/pnpm/yarn>
- Test runner: <vitest/jest> (<config-file>)
- Linter: <eslint> (<config-file>)
- Build: <vite/webpack/tsc> (<config-file>)
## Completed Work Units
| WU | Title | Key Files | Services Created |
|----|-------|-----------|-----------------|
## Established Patterns
- <pattern-1>: <description>
- <pattern-2>: <description>
## Active Services
See SERVICE-INVENTORY.md
Update rules:
The Project Context Document MUST be written to .beads/context/project-context.md and kept in sync with the in-memory version. This ensures the context survives context compaction and session boundaries.
# Create directory if needed
mkdir -p .beads/context
# Write/update after each Phase 4 (COMMIT) and at orchestration start
# The file should always reflect the current state of execution
When to write:
The file is NOT committed to git during execution — it's a working document. It gets cleaned up after the PR is created (or left for the next session if interrupted).
Approved plans and execution state are persisted to .beads/ so agents can recover after context compaction or session interruption.
| File | Contents | Written When |
|---|---|---|
.beads/plans/active-plan.md | The adversarially-reviewed, user-approved implementation plan | After plan review gate PASS + user approval |
.beads/context/project-context.md | Project Context Document (tooling, completed WUs, patterns) | After each Phase 4 COMMIT |
.beads/context/execution-state.md | Current work unit, phase, VALIDATE attempts, review round | After each phase transition |
.beads/context/review-history/orchestrated-execution-<plan-slug>-<wu-id>-<occurrence>.json | Review round history for the work unit's Phase 3 (format in ./guides/delivery-scope.md) | After every review round |
After the Plan Review Gate approves a plan AND the user approves it, persist immediately:
mkdir -p .beads/plans
# Write the approved plan with metadata header
cat > .beads/plans/active-plan.md << 'PLAN_EOF'
# Active Plan
<!-- approved: <timestamp> -->
<!-- gate-iterations: <N> -->
<!-- user-approved: true -->
<!-- status: in-progress -->
<full plan text including work unit decomposition, DoD items, file scopes, dependencies>
PLAN_EOF
After each phase transition, update the execution state:
cat > .beads/context/execution-state.md << 'STATE_EOF'
# Execution State
<!-- updated: <timestamp> -->
## Current Position
- Active work unit: <wu-id>
- Current phase: <IMPLEMENT|VALIDATE|REVIEW|COMMIT>
- VALIDATE attempts: <0-3> (consecutive failed VALIDATE runs; resets to 0 on PASS)
- Review round: <1-10>
- Review history: <.beads/context/review-history/orchestrated-execution-<plan-slug>-<wu-id>-<occurrence>.json, or none>
## Work Unit Status
| WU | Status | Phase | VALIDATE attempts (0-3) | Review rounds (0-10) |
|----|--------|-------|-------------------------|----------------------|
| WU-001 | COMPLETE | COMMITTED | 0 | 1 |
| WU-002 | IN-PROGRESS | VALIDATE | 1 | 0 |
| WU-003 | PENDING | — | 0 | 0 |
## Open Findings (orchestrator only, never passed to reviewers)
| Finding | Title | Description | Evidence | Severity | Protects | First round | Fix attempts | Status |
|---------|-------|-------------|----------|----------|----------|-------------|--------------|--------|
| WU-002-F1 | Expired token not rejected | <finding description> | <expected vs. found> | major | <scenario/requirement> | 1 | 1 | open |
## Blocked / Escalated
<any blocked or escalated work units with context>
STATE_EOF
When the orchestrator detects it has lost context (after compaction or in a new session), it recovers by reading persisted state:
1. Check: Does `.beads/plans/active-plan.md` exist with `status: in-progress`?
- YES → Context was lost mid-execution. Recover.
- NO → No active execution. Start fresh.
2. Recovery steps:
a. Read `.beads/plans/active-plan.md` — reload the approved plan
b. Read `.beads/context/project-context.md` — reload completed work and patterns
c. Read `.beads/context/execution-state.md` — find where execution stopped, and reload its Open Findings table (title, description, evidence, severity, protects, fix attempts) so rule line 4 can still detect a recurring blocker — match each fresh finding by its title/description and protects, and use evidence only as a secondary signal, because a fix can move file:line references. A saved finding without a title (written before this change) falls back to description plus protects; this history is for the orchestrator only — never pass them to a fresh reviewer. A state file written before the column split has a single legacy `Retries` column: read that value as VALIDATE attempts, and take the review round from the Current Position `Review round` line
d. Read the review history file named by the `Review history` line (the non-closed `.beads/context/review-history/orchestrated-execution-<plan-slug>-<wu-id>-*.json`; if several are non-closed, use the newest and set the rest to `closed`). If its `status` is `clarify-pending`, re-ask the `pendingClarify` questions with the Clarification report and do not iterate. Otherwise run the helper on the history and act on its result for the last recorded round: on `escalate`, re-send the escalation report and wait for the user's choice (if that choice is already recorded in the BEADS task or the conversation, apply it); on `overengineering-check`, redo the line-5 check first and re-send the escalation report only if a blocker still names a credible scenario, otherwise downgrade the blockers to follow-ups and advance; only `iterate` continues at the next round. See the Round history section of `./guides/delivery-scope.md`.
e. Run `/prime` (metaswarm knowledge priming) for the current work unit — reload relevant knowledge base facts.
The full recovery order is: if bd is installed, `bd prime` (bd context); then read `.beads/plans/active-plan.md` and `.beads/context/*.md`; then `/prime` for knowledge.
f. Resume from the current work unit and phase
3. Announce recovery to user:
"Recovered execution context from BEADS. Resuming from WU-<id>, Phase <phase>."
When to trigger recovery: The orchestrator should check for .beads/plans/active-plan.md at the start of any orchestrated execution. If the file exists with status: in-progress and the orchestrator has no plan in its current context, it's a recovery scenario.
After the PR is created (or the plan is abandoned):
# Mark plan as completed (cross-platform sed)
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' 's/status: in-progress/status: completed/' .beads/plans/active-plan.md
else
sed -i 's/status: in-progress/status: completed/' .beads/plans/active-plan.md
fi
# Archive execution state (don't delete — useful for post-mortem)
mv .beads/context/execution-state.md .beads/context/execution-state-<timestamp>.md
# Project context can be kept for reference
Human checkpoints are planned pauses, not reactive escalations. They are defined in the spec before execution begins.
When reaching a checkpoint, present this report and wait for explicit human approval:
## Checkpoint: <checkpoint-name>
### Completed Work Units
| WU | Title | Status | Review |
| --- | --- | --- | --- |
| WU-001 | Schema migration | PASS | Adversarial PASS |
| WU-002 | Service layer | PASS | Adversarial PASS |
### Key Decisions Made
- <decision-1>: <rationale>
- <decision-2>: <rationale>
Record significant decisions persistently with `bd create "<decision>" --type decision -d "<rationale>"` so they survive compaction and are available across sessions.
### What Comes Next
- WU-003: <description>
- WU-004: <description>
### Questions for Human (if any)
- <question>
---
**Action required**: Reply to continue, or provide feedback to adjust course.
Do NOT continue past a checkpoint without human response. This is not a notification — it's a gate.
After ALL work units are complete and committed, run a final comprehensive review across the entire change set. This catches cross-unit integration issues that per-unit reviews miss.
# 1. Combined diff — see the full picture
git diff main..HEAD
# 2. Full test suite — not just changed files
npx vitest run
# 3. Type check — catch cross-unit type conflicts
npx tsc --noEmit
# 4. Lint — catch cross-unit style issues
npx eslint .
# 5. Coverage — verify overall coverage thresholds
if [ -f .coverage-thresholds.json ]; then
CMD=$(node -e "console.log(JSON.parse(require('fs').readFileSync('.coverage-thresholds.json','utf-8')).enforcement.command)")
eval "$CMD"
fi
# 6. Commit history — verify clean, logical commits
git log main..HEAD --oneline
## Final Comprehensive Review
### Overall Verdict: PASS / FAIL
### Work Units Summary
| WU | Title | Impl | Validate | Review | Commit |
| --- | --- | --- | --- | --- | --- |
| WU-001 | <title> | Done | Pass | Pass | <sha> |
| WU-002 | <title> | Done | Pass | Pass | <sha> |
### Quality Gates
- [ ] All tests pass
- [ ] Type check clean
- [ ] Lint clean
- [ ] Coverage thresholds met
- [ ] No cross-unit integration issues
### Remaining Issues
<any issues found during final review>
### Follow-ups
<minor/nit findings from every gate and work unit: BEADS task IDs, or the items themselves>
### Ready for PR: YES / NO
After the final comprehensive review passes but BEFORE creating the PR, run /self-reflect to extract learnings into the knowledge base. This captures implementation insights, debugging discoveries, and architectural decisions while context is freshest — not deferred to post-merge when details have faded.
## Pre-PR Knowledge Capture
Final review PASSED. Before creating the PR, extracting learnings...
/self-reflect
Learnings captured: [N] items added to knowledge base.
Instruction review (REQUIRED, Step 7 of /self-reflect):
Instruction changes proposed: [list, or "none, because ..."]
Asked the user as one decision request: [approved / rejected per item]
Committing knowledge base updates and approved instruction edits...
Proceeding to PR creation.
Why before PR, not after merge? By the time a PR is merged, the implementing agent's context may be gone (session ended, context compacted). The richest insights — why a certain approach was chosen, what debugging dead-ends were hit, which patterns emerged — exist NOW, immediately after implementation. Capture them now.
Follow-ups go in the PR body. Collect every follow-up recorded by the gates and work units (BEADS task IDs, or the ### Follow-ups lists kept when bd was unavailable) and include them in the PR body under a ### Follow-ups heading, so non-blocking findings are not lost.
The instruction review is required. Every /self-reflect run includes the instruction review (Step 7 of commands/self-reflect.md): an "Instruction changes proposed" list covering the project's CLAUDE.md, agent and skill prompts, and metaswarm itself, asked of the user as one decision request (see Decision requests in guides/delivery-scope.md). The list may say "none, because ..." but is never skipped. Do not create the PR until the user has answered it, unless the list is none, because ... (nothing to ask; proceed to the PR, with no commit if there is nothing to commit). If this skill runs in a subagent, it cannot ask: it RETURNS the list to its parent before gh pr create, and the main session asks and commits the approved edits (see "When running as a subagent" in commands/self-reflect.md). If the session must hand off before an answer, the items stay unapplied by default and are listed in the PR body as open questions. There is no timer. For changes to metaswarm itself, offer an issue or PR on dsifry/metaswarm; never file one automatically.
Knowledge base changes are part of the PR. After self-reflect updates the knowledge base files, commit them, together with the approved project-instruction edits from the instruction review, alongside the implementation. Rejected instruction changes are recorded as rejected. This ensures learnings are reviewed as part of the PR and land atomically with the code that generated them. Do NOT defer knowledge base commits to a separate PR or post-merge step.
When IMPLEMENT or VALIDATE goes wrong during the 4-phase loop, follow this structured recovery. Its 3-attempt cap applies to VALIDATE failures (tests, coverage, lint, typecheck, file scope). REVIEW failures don't use it: they follow the severity rule in On FAIL (cap 10 rounds).
Identify what failed and gather evidence:
# Capture the failure
# - Which phase failed? (IMPLEMENT or VALIDATE; a REVIEW failure follows the severity rule in On FAIL instead)
# - What was the error message or FAIL reason?
# - Which DoD items are affected?
Categorize the failure:
| Classification | Description | Action |
|---|---|---|
| Fixable | Clear error, known fix | Retry with specific fix instructions |
| Ambiguous | Unclear root cause | Investigate before retrying |
| External | Dependency, access, or environment issue | Escalate immediately |
VALIDATE attempts count consecutive failed VALIDATE runs for the work unit; a VALIDATE PASS resets the count to 0, so each review round's re-validation starts fresh. The number of review rounds is governed separately by the severity rule and its 10-round cap.
For fixable and ambiguous VALIDATE failures:
Coder escalation. Retrying alone never changes the model. After escalation.coder.after_failures failed VALIDATE attempts (default 2, from .metaswarm/models.yaml), re-spawn a fresh coder with roleType("supercoder"), the one definition of the Opus coder (model from roles.supercoder.claude, default opus). escalation.coder.claude is still honoured as the supercoder model when roles.supercoder.claude is not set. Escalation of a security-critical work unit re-spawns roleType("security-coder") instead; everything else stays supercoder. See Coder Selection for the full rubric, including when a mechanical-coder attempt moves up to coder.
Track VALIDATE attempts with labels, and remove the retry:N label when VALIDATE passes (review rounds are tracked in .beads/context/execution-state.md, not labels):
bd label add <task-id> retry:1 # or retry:2, retry:3
After 3 failed VALIDATE attempts, escalate to human with full context:
## Escalation: Work Unit <wu-id> Failed VALIDATE After 3 Attempts
### Failure History
| Attempt | Phase | Error | Fix Tried |
| --- | --- | --- | --- |
| 1 | VALIDATE | Tests fail: auth.test.ts:34 | Fixed mock setup |
| 2 | VALIDATE | Coverage 94%, threshold 100% | Added edge case test |
| 3 | VALIDATE | Type error in cross-module import | Restructured imports |
### Root Cause Assessment
<best understanding of why this keeps failing>
### Options
Use the decision-request format (see Decision requests in `./guides/delivery-scope.md`): mark exactly one option (Recommended) and give only that option a Why recommended line.
**Decision 1: <what must be decided>**
<one or two lines of context>
**Option A: <option-a>** (Recommended)
<what it does, in one line>
- Pros: <pros>
- Cons: <cons>
- Why recommended: <why, tied to the user's goals or constraints>
**Option B: <option-b>**
<what it does, in one line>
- Pros: <pros>
- Cons: <cons>
**Option C: Abandon this work unit and restructure**
<what it does, in one line>
- Pros: <pros>
- Cons: <cons>
Reply with the decision number and a letter, like `1 A`. If there's no answer: the work unit stays blocked and nothing else on it proceeds.
These are explicit DON'Ts. Violating any of these undermines the entire orchestration pattern.
| # | Anti-Pattern | Why It's Wrong | What to Do Instead |
|---|---|---|---|
| 1 | Self-certifying — coding subagent says "tests pass" and you believe it | Subagents can hallucinate, skip tests, or misinterpret results | Orchestrator runs validation commands independently |
| 2 | Skipping adversarial review — "the code looks fine, let's commit" | Visual inspection misses spec violations; confirmation bias | Always run adversarial review against DoD items |
| 3 | Reusing a reviewer — same subagent re-reviews after FAIL | Anchoring bias: reviewer remembers previous findings and checks for those specifically instead of reviewing fresh | Spawn a new reviewer instance with no prior context |
| 4 | Passing previous findings to new reviewer — "last reviewer found X, check if fixed" | Creates anchoring bias; new reviewer should find issues independently | Pass only: spec, DoD items, diff. Nothing about previous reviews |
| 5 | Trusting subagent file scope claims — "I only changed the files in scope" | Subagents may accidentally modify files outside scope | Run git diff --name-only and verify each file independently |
| 6 | Combining phases — "implement and validate in one step" | Removes the independence that makes validation meaningful | Run each phase as a distinct step with its own output |
| 7 | Continuing past a checkpoint without human response | Defeats the purpose of proactive checkpoints | Wait. If urgent, escalate — don't skip |
| 8 | Skipping final comprehensive review — "all units passed individually" | Per-unit reviews can't catch cross-unit integration issues | Always run the final review after all units are committed |
| 9 | Skipping coverage enforcement — "tests pass, coverage doesn't matter" | Coverage thresholds exist for a reason; low coverage means untested paths | Read .coverage-thresholds.json and run the enforcement command. Block on failure. |
| 10 | Building UI components in isolation — all components tested but never wired into the app | Users can't interact with components that aren't rendered | Plan must include integration WUs that wire components into the app shell |
| 11 | Proceeding without external credentials — building features that require API keys without verifying the user has them | Features will fail at runtime; user discovers this after 10+ commits | Checkpoint before external-service WUs to verify credentials are configured |
| 12 | Advisory quality gates — treating a blocker: yes FAIL as advisory, or a failed VALIDATE check as a suggestion | Undermines the entire trust model; equivalent to skipping the gate | Quality gates are state transitions. FAIL means retry, iterate under the severity rule, or escalate, never skip. |
| 13 | Using --no-verify — bypassing pre-commit hooks on git commits | Pre-commit hooks catch lint errors, type errors, and formatting issues before they enter history | Never use --no-verify. Fix the underlying issue instead. |
| 14 | Skipping design review gate for a project-sized design doc — going directly from a committed design doc to writing-plans | Expensive implementation work begins on unreviewed designs | Run the 6-agent design review gate between a committed project-sized design doc and planning (see ./guides/workflow-enforcement.md) |
| 15 | Skipping plan review gate — presenting a plan to the user without adversarial review | Plans with feasibility gaps, missing requirements, or scope creep reach implementation | Always run the 3-reviewer plan review gate before presenting any plan |
Before execution (Plan Validation):
For each work unit:
roleType("coder")) with spec, DoD, file scope, and Project Context Documentgit diff --name-onlyroleType("adversarial-reviewer")) with spec and DoDroleType("adversarial-reviewer"); escalate when the rule says so, at most 10 rounds)### Follow-ups)Quality Gate Rules:
After all work units:
/self-reflect to capture learnings (BEFORE PR creation)/self-reflect): proposed list shown to the user as one decision requestguides/agent-coordination.md (opens in a new tab)guides/coder-selection.md (opens in a new tab)guides/delivery-scope.md (opens in a new tab)guides/research-selection.md (opens in a new tab)guides/workflow-enforcement.md (opens in a new tab)rubrics/adversarial-review-rubric.md (opens in a new tab)rubrics/security-implementation-rubric.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
15 skills in this plugin
/brainstorming-extensionLoads the assumption ledger and misreadings checklist at the start of brainstorming, and enforces the design review gate when a project-sized design doc is committed — bridges superpowers:brainstorming into the metaswarm quality pipeline/create-issueCreate comprehensive GitHub issues with TDD plans, acceptance criteria, and agent instructions for autonomous PR lifecycle management/design-review-gateAutomatic review gate that runs when brainstorming commits a project-sized design doc - spawns PM, Architect, Designer, Security, UX Reviewer and CTO agents in parallel, iterates under the severity rule until all approve or it escalatesmetaswarm@metaswarm-marketplace is listed by dsifry/metaswarm-marketplace — review the source before installing
npx claudepluginhub dsifry/metaswarm-marketplace --plugin metaswarmOther plugins' skills for the same job