---
description: Multi-agent parallel development — spec, test, decompose, implement in parallel, integrate
allowed-tools: Bash, Read, Edit, Write, Glob, Grep, Agent, recall_my_memory, ask_team_memory, store_memory, create_task, update_task, list_tasks
argument-hint: [--auto] [--agents N] [--skip-spec] [--skip-tests] "<feature description>"
---

Multi-agent parallel development workflow. Yoshi specs and writes tests, spawns sub-agents to implement in parallel, then integrates and commits.

**FULLY AUTONOMOUS.** Each phase has a mechanical checkpoint that verifies completion and self-heals on failure. Never ask the user for help — fix it yourself.

## Checkpoint protocol (mandatory for every phase)

After completing each phase, run the checkpoint. The pattern:

```
1. Run VERIFY command (bash — returns pass/fail)
2. If PASS → proceed to next phase
3. If FAIL → run FIX action (the action is defined per-phase)
4. Re-run VERIFY
5. Repeat up to 3 times
6. After 3 failures → log error with store_memory, continue to next phase
```

**NEVER ask the user.** Fix it yourself or log and move on.

---

## Parse arguments

Extract flags and feature description from $ARGUMENTS:

- `--auto` — skip approval checkpoint before spawning agents (default: ask)
- `--agents N` — max parallel sub-agents (default: 3)
- `--skip-spec` — reuse existing spec from `exe/output/{slug}/spec.md`
- `--skip-tests` — reuse existing tests (dangerous)
- Everything else is the feature description

Derive `{slug}` by kebab-casing the feature description (e.g., "Add rate limiting" → "add-rate-limiting").

Write build state tracker:
```bash
mkdir -p exe/output/{slug}
echo '{"phase":0,"slug":"{slug}","startedAt":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","feature":"{feature}"}' > exe/output/{slug}/build-state.json
```

---

## Phase 1: Spec (sequential)

**Skip if `--skip-spec` and `exe/output/{slug}/spec.md` exists.**

1. Read `exe/ARCHITECTURE.md` for system context
2. Use `recall_my_memory` to search for related past work on this feature area
3. Identify:
   - Which existing files need modification (read them)
   - What new files need creation
   - API contracts, data types, interfaces
   - Constraints from ARCHITECTURE.md invariants
   - Test framework in use (check for vitest.config, jest.config, etc.)
4. Write the spec to `exe/output/{slug}/spec.md`:

```markdown
# Feature: {feature description}

## Summary
{1-2 sentence overview}

## Files to modify
{list of existing files with what changes}

## Files to create
{list of new files with purpose}

## API / Interface contracts
{types, function signatures, data shapes}

## Constraints
{from ARCHITECTURE.md, invariants that must not be violated}

## Test framework
{vitest/jest/other — detected from config}
```

### Checkpoint 1: Spec exists

**VERIFY:**
```bash
[ -f "exe/output/{slug}/spec.md" ] && grep -q "## Files to" "exe/output/{slug}/spec.md" && echo "CHECKPOINT_PASS" || echo "CHECKPOINT_FAIL"
```

**FIX:** Write the spec file. You have all the context from steps 1-3. Write it now.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=1; s.specFile='exe/output/{slug}/spec.md'; require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 2: Test (sequential)

**Skip if `--skip-tests`.**

1. Read the spec from Phase 1
2. Write failing tests that define the acceptance criteria:
   - One test file per logical module/concern
   - Tests must import from the expected source paths (even if files don't exist yet)
   - Tests must be runnable and RED (failing because implementation doesn't exist)
   - Group tests by which subtask will make them pass
3. Write test files to the codebase (e.g., `tests/lib/{feature}.test.ts`)
4. Create a test manifest at `exe/output/{slug}/test-manifest.md`:

```markdown
# Test Manifest

## Group 1: {module name}
- File: tests/lib/{file}.test.ts
- Tests: {count}
- Covers: {what this group validates}

## Group 2: ...
```

### Checkpoint 2: Tests exist and fail (red phase)

**VERIFY:**
```bash
TEST_FILES=$(grep -oP '(?<=File: ).*\.test\.ts' "exe/output/{slug}/test-manifest.md" 2>/dev/null)
if [ -z "$TEST_FILES" ]; then echo "CHECKPOINT_FAIL:no_manifest"; exit 0; fi
ALL_EXIST=true
for f in $TEST_FILES; do [ -f "$f" ] || ALL_EXIST=false; done
if [ "$ALL_EXIST" = false ]; then echo "CHECKPOINT_FAIL:missing_test_files"; exit 0; fi
# Tests should FAIL (red phase — no implementation yet). Passing tests means they're too weak.
npx vitest run $TEST_FILES --reporter=verbose 2>&1 | tail -5
RESULT=$(npx vitest run $TEST_FILES 2>&1 | tail -1)
echo "$RESULT" | grep -q "fail" && echo "CHECKPOINT_PASS:tests_failing_as_expected" || echo "CHECKPOINT_WARN:tests_not_failing"
```

**FIX:** If no manifest: write it. If missing test files: write them. If tests pass unexpectedly: the tests are too weak — add assertions that test the actual new behavior.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=2; s.testManifest='exe/output/{slug}/test-manifest.md'; require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 3: Decompose (sequential)

1. Read the spec and test manifest
2. Break implementation into N independent subtasks where each subtask:
   - Has a clear, bounded scope (1-3 files)
   - Is responsible for making specific test group(s) pass
   - Lists exact files to create/modify
   - Includes relevant architecture context (copy the relevant section, don't reference)
   - Declares `blocked_by` if it depends on another subtask's output
3. Create subtasks via `create_task` MCP with `parent_task_id` set to the build-adv parent task:

For each subtask, call create_task with:
- `title`: "build-adv/{slug}: {subtask title}"
- `assigned_to`: configured principal engineer name (or next available engineer)
- `project_name`: current project
- `priority`: "p1"
- `context`: Full subtask spec including test files to make pass, files to modify, constraints
- `parent_task_id`: the parent task ID (if this build-adv was triggered from a task)
- `blocked_by`: subtask ID of dependency (if any)

4. Write subtask specs to `exe/output/{slug}/subtask-{N}.md` as reference copies

5. Determine the execution waves:
   - Wave 1: all subtasks with no dependencies
   - Wave 2: subtasks unblocked after wave 1
   - Wave N: remaining

**If `--auto` is NOT set:** Present the subtask breakdown and wave plan to the user. Ask: "Proceed with implementation? (y/n)". Wait for approval.

**If `--auto` IS set:** Proceed immediately.

### Checkpoint 3: Subtasks exist in DB

**VERIFY:**
```bash
SUBTASK_COUNT=$(node -e "
  const {getClient}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/database.js'));
  const {initStore}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/store.js'));
  (async()=>{await initStore();const {sessionScopeFilter}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/task-scope.js'));const s=sessionScopeFilter();const c=getClient();const r=await c.execute({sql:\"SELECT COUNT(*) as cnt FROM tasks WHERE title LIKE 'build-adv/{slug}%' AND status != 'done'\"+s.sql,args:[...s.args]});console.log(Number(r.rows[0]?.cnt??0))})()
" 2>/dev/null)
[ "$SUBTASK_COUNT" -gt 0 ] 2>/dev/null && echo "CHECKPOINT_PASS:${SUBTASK_COUNT}_subtasks" || echo "CHECKPOINT_FAIL:no_subtasks_in_db"
```

**FIX:** Run `create_task` MCP for each subtask from the decomposition. You have the specs from step 2.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=3; s.subtaskCount=${SUBTASK_COUNT:-0}; require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 4: Parallel Implementation (sub-agents)

For each wave, spawn sub-agents in parallel (respecting `--agents N` limit):

1. Read each subtask spec
2. Read the test file(s) the subtask must make pass
3. Read any source files the subtask needs to modify
4. Launch Agent for each subtask in the wave:

Use Agent tool with these parameters:
- `subagent_type`: "general-purpose"
- `description`: "Implement: {subtask title}"
- `prompt`: Include the following in the prompt:
  - The subtask spec (full content)
  - The test file contents (full content)
  - The current content of any files to modify
  - Clear rules: make tests pass, don't modify tests, don't touch other files, report changes and test results

**Launch all agents in the same wave as parallel tool calls in a single message.**

5. Collect results from each agent
6. After wave completes, check if next wave's dependencies are met, launch next wave

### Checkpoint 4: Sub-agents completed work

**VERIFY:**
```bash
# Check git diff shows changes from sub-agents
CHANGED=$(git diff --stat HEAD 2>/dev/null | tail -1)
[ -n "$CHANGED" ] && echo "CHECKPOINT_PASS:$CHANGED" || echo "CHECKPOINT_FAIL:no_changes"
```

**FIX:** If no changes detected, re-launch failed agents. Read their error output and provide more context in the prompt.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=4; require('fs').writeFileSync(f,JSON.stringify(s))"
```

Print after each wave: `Wave {W} complete: {N}/{N} subtasks succeeded`

---

## Phase 5: Integration (sequential)

1. Review what each sub-agent changed (git diff or read modified files)
2. Run the full test suite:

```bash
npx vitest run --reporter=verbose 2>&1 | tail -40
```

3. Run typecheck:

```bash
npx tsc --noEmit 2>&1 | head -40
```

### Checkpoint 5: Tests pass and typecheck clean

**VERIFY:**
```bash
npx tsc --noEmit 2>&1 && npx vitest run 2>&1 | tail -3
TSC_EXIT=$?
VITEST_RESULT=$(npx vitest run 2>&1 | tail -1)
echo "$VITEST_RESULT" | grep -q "passed" && [ $TSC_EXIT -eq 0 ] && echo "CHECKPOINT_PASS" || echo "CHECKPOINT_FAIL"
```

**FIX:** Read the test failures and type errors. Fix the code — resolve integration conflicts, missing imports, type mismatches. Do NOT modify test files. Re-run verification.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=5; s.testsPass=true; require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 6: Commit

1. Stage all changed files:

```bash
git add -u && git add .
```

2. Commit with message: `feat: {feature description}`

### Checkpoint 6: Git clean after commit

**VERIFY:**
```bash
git status --porcelain | head -5
[ -z "$(git status --porcelain)" ] && echo "CHECKPOINT_PASS" || echo "CHECKPOINT_FAIL"
```

**FIX:** Stage and commit any remaining files: `git add -u && git add . && git commit -m "feat: {feature} (remaining files)"`

**Update state:**
```bash
COMMIT_HASH=$(git rev-parse --short HEAD)
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=6; s.commitHash='${COMMIT_HASH}'; require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 7: Close

1. Use `store_memory` to record:
   - What was built
   - Key decisions made during spec
   - Subtask breakdown pattern (useful for future decomposition)
   - Any integration issues encountered

2. If system structure changed, update `exe/ARCHITECTURE.md`

3. Mark subtasks as done via `update_task` MCP

### Checkpoint 7: All subtasks done in DB

**VERIFY:**
```bash
OPEN_COUNT=$(node -e "
  const {getClient}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/database.js'));
  const {initStore}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/store.js'));
  (async()=>{await initStore();const {sessionScopeFilter}=require(require('path').join(require('child_process').execSync('npm root -g',{encoding:'utf8'}).trim(),'@askexenow/exe-os/dist/lib/task-scope.js'));const s=sessionScopeFilter();const c=getClient();const r=await c.execute({sql:\"SELECT COUNT(*) as cnt FROM tasks WHERE title LIKE 'build-adv/{slug}%' AND status NOT IN ('done','cancelled')\"+s.sql,args:[...s.args]});console.log(Number(r.rows[0]?.cnt??0))})()
" 2>/dev/null)
[ "$OPEN_COUNT" -eq 0 ] 2>/dev/null && echo "CHECKPOINT_PASS" || echo "CHECKPOINT_FAIL:${OPEN_COUNT}_subtasks_still_open"
```

**FIX:** Call `update_task(done)` for each remaining open subtask with a result summary.

**Update state:**
```bash
node -e "const f='exe/output/{slug}/build-state.json'; const s=JSON.parse(require('fs').readFileSync(f,'utf8')); s.phase=7; s.completedAt=new Date().toISOString(); require('fs').writeFileSync(f,JSON.stringify(s))"
```

---

## Phase 8: Summary

Print final summary:

```
## /exe-build-adv Complete

Feature: {description}
Phases: spec -> test -> decompose -> {N} subtasks in {W} waves -> integrate -> commit
Tests: {pass}/{total} pass
Files changed: {count}
Commit: {hash}

Checkpoints: {passed}/{total} passed, {failed} self-healed, {skipped} skipped
```

---

## Build status

At any point, check the current state of a build-adv run:

```bash
cat exe/output/{slug}/build-state.json 2>/dev/null | node -e "
  const s=JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));
  const phases=['parse','spec','test','decompose','implement','integrate','commit','close'];
  console.log('Build: '+s.feature);
  console.log('Phase: '+s.phase+'/7 ('+phases[s.phase]+')');
  console.log('Started: '+s.startedAt);
  if(s.completedAt) console.log('Completed: '+s.completedAt);
  if(s.commitHash) console.log('Commit: '+s.commitHash);
  if(s.subtaskCount) console.log('Subtasks: '+s.subtaskCount);
  if(s.testsPass) console.log('Tests: passing');
"
```

---

## Error handling

- If daemon/embed fails during recall: continue without memory context
- If a sub-agent times out: note it, proceed with remaining agents, attempt manual fix in Phase 5
- After 3 checkpoint failures: log error with `store_memory`, continue to next phase — never block on user input
- Never silently skip a failing test — report it explicitly
