AgentStack
SKILL verified MIT Self-run

Orchestrated Execution

skill-dsifry-metaswarm-orchestrated-execution · by dsifry

4-phase execution loop for work units - IMPLEMENT, VALIDATE, ADVERSARIAL REVIEW, COMMIT

No reviews yet
0 installs
11 views
0.0% view→install

Install

$ agentstack add skill-dsifry-metaswarm-orchestrated-execution

✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access Used
  • Filesystem access Used
  • Shell / process execution No
  • Environment & secrets Used
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Orchestrated Execution? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Orchestrated Execution Skill

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.


Coordination Mode Note

This skill is mode-agnostic — the 4-phase execution loop works identically in both Task Mode and Team Mode. The differences:

  • Phase 1 (IMPLEMENT): In Team Mode, the coding subagent may be a persistent teammate (retains context across work units). In Task Mode, it's a fresh Task() per work unit.
  • Phase 3 (ADVERSARIAL REVIEW): ALWAYS a fresh Task() instance in BOTH modes. Never a teammate, never resumed.
  • All quality gates: Unchanged regardless of mode.

See ./guides/agent-coordination.md for full mode detection and coordination details.


Plan Review Gate

After drafting an implementation plan (Step 1: Plan Validation), submit it to the Plan Review Gate before presenting to the user. The gate spawns 3 adversarial reviewers (Feasibility, Completeness, Scope & Alignment) — all must PASS. See skills/plan-review-gate/SKILL.md for details.


When to Use This Skill

  • Complex tasks decomposed into multiple work units
  • Tasks with a written spec containing Definition of Done (DoD) items
  • Multi-agent orchestration where subagents produce work that needs verification
  • High-stakes changes where self-reported "it works" is insufficient

Do NOT use for: Single-file bug fixes, copy changes, or tasks without a spec.


1. Plan Validation (Pre-Flight Checklist)

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 Plan subagent type cannot write files (it has read-only access by design). If you spawn an Architect as a Plan subagent, it will return the plan as text in its response. The orchestrator must write the plan to PLAN.md itself.

Architecture Checklist

  • [ ] Every data access goes through a service layer (no direct DB calls from routes/handlers)
  • [ ] Each work unit has a single responsibility (max ~5 files created/modified)
  • [ ] Error handling strategy specified (typed error hierarchy, how errors cross layer boundaries)
  • [ ] No hard-coded configuration — environment variables for all external service config

Dependency Graph Checklist

  • [ ] Each WU's dependencies are minimal (only depends on what it actually imports/uses)
  • [ ] No unnecessary serialization — WUs that CAN be parallel ARE marked parallel
  • [ ] No circular dependencies
  • [ ] Integration WUs exist to wire components into the app shell (not just built in isolation)

API Contract Checklist

If the plan includes HTTP endpoints or WebSocket protocols, verify:

  • [ ] Every HTTP endpoint specifies: method, path, request schema, all response status codes, error response shapes
  • [ ] WebSocket message types fully specified (client-to-server AND server-to-client message type tables)
  • [ ] Protocol concerns documented: heartbeat, reconnection, acknowledgment strategy
  • [ ] Response codes are explicit (not "returns the todo" but "returns 201 with the created todo")

Security Checklist

  • [ ] Trust boundaries identified (which inputs are untrusted?)
  • [ ] Input validation specified for every endpoint/handler (schema, max size)
  • [ ] Rate limiting specified for expensive operations (AI API calls, file uploads)
  • [ ] Authentication/authorization requirements documented
  • [ ] Secrets management documented (.env pattern, .gitignore verification)

UI/UX Checklist

If the plan includes a user interface:

  • [ ] User flows documented with trigger, steps, and visible outcome (see UI-FLOWS.md template)
  • [ ] Text-based wireframes for each screen showing layout and interactive elements
  • [ ] Empty states, loading states, and error states defined for each view
  • [ ] Integration work units explicitly created to wire components into the app shell
  • [ ] Component hierarchy documented (what renders what, where)

External Dependencies Checklist

  • [ ] All external services identified (APIs, SDKs, third-party services)
  • [ ] Required credentials/config documented (env var names, how to obtain)
  • [ ] Human checkpoint planned BEFORE work units that depend on external services
  • [ ] Graceful degradation specified for when credentials are missing
  • [ ] .env.example includes all required env vars

Completeness Checklist

  • [ ] All human checkpoints from the spec are included
  • [ ] All features from the spec have at least one work unit
  • [ ] Tooling is consistent (one package manager, matching config files across WUs)
  • [ ] No WU exceeds ~5 files or ~3 distinct concerns
  • [ ] WUs that are too large are split with explicit dependencies between parts

If any checklist item fails, fix the plan BEFORE submitting to Design Review Gate.

Required Plan Sections

Every plan submitted for Design Review MUST include these sections:

  1. Work Unit Decomposition — WU list with DoD items, file scopes, dependencies
  2. API Contract (if applicable) — structured endpoint/protocol specs:

```markdown ### 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)

```

  1. Security Considerations — trust boundaries, input validation table, rate limiting table, secrets management
  2. User Flows (if UI exists) — text wireframes and interaction flows (use UI-FLOWS.md template)
  3. External Dependencies — services, credentials, setup instructions
  4. Human Checkpoints — named pause points with review criteria

2. Work Unit Decomposition

A work unit is the atomic unit of orchestrated execution. Before entering the 4-phase loop, decompose the implementation plan into work units.

Work Unit Structure

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 |

Constructing Dependency Graphs

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:

  1. Each work unit has a single responsibility — one logical change
  2. File scopes should not overlap between parallel work units
  3. Dependencies must be explicit — no implicit ordering assumptions
  4. Work units at the same depth with no interdependencies run in parallel
  5. Each DoD item must be independently verifiable (not "code looks good")

Decomposition Template

# Create work units as BEADS tasks under the epic
bd create "WU-001: " --type task --parent  \
  --description "Spec: \nDoD:\n- [ ] \n- [ ] \nFile scope: \nCheckpoint: "

# Set up dependencies
bd dep add  
bd dep add  

3. The 4-Phase Execution Loop

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               │                      │
│        └─────────────────────────────────┘                      │
│                                                                 │
│   On FAIL: fix → re-validate → FRESH review → max 3 → escalate │
└─────────────────────────────────────────────────────────────────┘

Phase 1: IMPLEMENT

The coding subagent executes against the work unit spec.

Orchestrator actions:

  1. Spawn a coding subagent with the work unit spec, DoD items, file scope, and the Project Context Document
  2. The subagent implements the change following TDD (test first, then implementation)
  3. The subagent reports completion — but the orchestrator does NOT trust this report

Subagent spawn template:

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}

## 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
- 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.

Phase 2: VALIDATE

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 

# 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:

  • All gates pass → proceed to Phase 3
  • Any gate fails → return to Phase 1 (the coding subagent fixes the issue)
  • File scope violated → return to Phase 1 (subagent must revert out-of-scope changes)

Critical rule: The orchestrator runs validation commands directly. The orchestrator does NOT ask the coding subagent "did the tests pass?" and accept the answer.

Phase 3: ADVERSARIAL REVIEW

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:

  1. Spawn a new review subagent in adversarial mode
  2. Pass: the spec, the DoD items, and the diff (NOT the coding subagent's self-assessment)
  3. The reviewer checks each DoD item with evidence (file:line references)

Reviewer spawn template:

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(' ')}

## Rules
- Check EACH DoD item. Cite file:line evidence for PASS or expected-vs-found for FAIL.
- Any single BLOCKING issue means overall FAIL.
- You have NO context from previous reviews. Judge fresh.
- Do NOT suggest improvements. Only report PASS or FAIL with evidence.

Phase 3 outcomes:

  • PASS (zero BLOCKING issues) → proceed to Phase 4
  • FAIL (any BLOCKING issue) → return to Phase 1 with the failure report

Fresh reviewer rule: On re-review after FAIL, the orchestrator MUST spawn a new review subagent. Never pass previous findings to the new reviewer. Never reuse the same reviewer instance. This prevents anchoring bias and ensures independent verification.

Phase 4: COMMIT

Only after PASS from adversarial review.

Orchestrator actions:

# Stage only files within the work unit's file scope
git add 

# Commit with reference to work unit
git commit -m "feat(wu-${wuId}): 

DoD items verified:
$(dodItems.map((item, i) => `- [x] ${item}`).join('\n'))

Reviewed-by: adversarial-review (PASS)"

After commit:

  • Update BEADS task status: bd close --reason "4-phase loop complete. PASS."
  • If this work unit has a human checkpoint flag, pause and report before continuing
  • Update the Project Context Document with completed work unit details

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.


4. Quality Gate Enforcement

Quality gates are BLOCKING STATE TRANSITIONS, not advisory recommendations. The orchestrator CANNOT advance to the next phase without gate passage.

State Machine

IMPLEMENT ──→ VALIDATE ──→ REVIEW ──→ COMMIT
                 │            │
                 ↓            ↓
              FAIL:         FAIL:
           fix + re-run   fix + re-validate
                          + FRESH re-review
                 │            │
              (max 3)      (max 3)
                 │            │
                 ↓            ↓
              ESCALATE     ESCALATE
             (to human)   (to human)

Transition Rules (MUST, not SHOULD)

  1. IMPLEMENT → VALIDATE: Always. No exceptions.
  2. VALIDATE → REVIEW: ONLY if ALL validation checks pass:
  • Tests pass (exit code 0)
  • Coverage meets .coverage-thresholds.json thresholds
  • Type checking passes
  • Lint passes
  • File scope respected
  1. REVIEW → COMMIT: ONLY if adversarial review returns PASS
  2. FAIL → retry: Fix the issue, then re-run the FAILED gate (not skip it)
  3. Re-review after fix: MUST spawn a FRESH reviewer (new instance, no memory)
  4. Max retries: 3 attempts per gate, then ESCALATE to human with full failure history

On FAIL: Mandatory Re-Review Protocol

  1. Fix the issue identified by the reviewer
  2. Re-run Phase 2 (VALIDATE) — ALL quality gates, not just the one that failed

3.

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.