feat: migrate all codex team skills from spawn_agents_on_csv to spawn_agent + wait_agent architecture

- Delete 21 old team skill directories using CSV-wave pipeline pattern (~100+ files)
- Delete old team-lifecycle (v3) and team-planex-v2
- Create generic team-worker.toml and team-supervisor.toml (replacing tlv4-specific TOMLs)
- Convert 19 team skills from Claude Code format (Agent/SendMessage/TaskCreate)
  to Codex format (spawn_agent/wait_agent/tasks.json/request_user_input)
- Update team-lifecycle-v4 to use generic agent types (team_worker/team_supervisor)
- Convert all coordinator role files: dispatch.md, monitor.md, role.md
- Convert all worker role files: remove run_in_background, fix Bash syntax
- Convert all specs/pipelines.md references
- Final state: 20 team skills, 217 .md files, zero Claude Code API residuals

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
catlog22
2026-03-24 16:54:48 +08:00
parent 54283e5dbb
commit 1e560ab8e8
334 changed files with 28996 additions and 35516 deletions

View File

@@ -1,683 +1,162 @@
---
name: team-roadmap-dev
description: Roadmap-driven development with phased execution pipeline. Coordinator discusses roadmap with user, then executes plan->execute->verify cycles per phase using CSV wave execution.
argument-hint: "[-y|--yes] [-c|--concurrency N] [--continue] \"<task-description>\""
allowed-tools: spawn_agents_on_csv, spawn_agent, wait, send_input, close_agent, Read, Write, Edit, Bash, Glob, Grep, request_user_input
description: Unified team skill for roadmap-driven development workflow. Coordinator discusses roadmap with user, then dispatches phased execution pipeline (plan -> execute -> verify). All roles invoke this skill with --role arg. Triggers on "team roadmap-dev".
allowed-tools: spawn_agent(*), wait_agent(*), send_input(*), close_agent(*), report_agent_job_result(*), request_user_input(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
## Auto Mode
# Team Roadmap Dev
When `--yes` or `-y`: Auto-confirm task decomposition, skip interactive validation, use defaults.
Roadmap-driven development with phased execution pipeline. Coordinator discusses roadmap with the user and manages phase transitions. Workers are spawned as team-worker agents.
# Roadmap-Driven Development
## Usage
```bash
$team-roadmap-dev "Build authentication module with JWT tokens"
$team-roadmap-dev -c 4 "Refactor payment processing to support multiple gateways"
$team-roadmap-dev -y "Add real-time notifications feature"
$team-roadmap-dev --continue "RD-auth-module-2026-03-08"
```
**Flags**:
- `-y, --yes`: Skip all confirmations (auto mode)
- `-c, --concurrency N`: Max concurrent agents within each wave (default: 3)
- `--continue`: Resume existing session
**Output Directory**: `.workflow/.csv-wave/{session-id}/`
**Core Output**: `tasks.csv` (master state) + `results.csv` (final) + `discoveries.ndjson` (shared exploration) + `context.md` (human-readable report)
---
## Overview
Roadmap-driven development workflow that breaks down complex development tasks into phases, with each phase following a plan->execute->verify cycle. The coordinator discusses the roadmap with the user to establish phases and requirements, then executes each phase systematically using CSV wave execution for parallel task processing.
**Execution Model**: Hybrid — CSV wave pipeline (primary) + individual agent spawn (secondary)
## Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
ROADMAP-DRIVEN DEVELOPMENT WORKFLOW │
├─────────────────────────────────────────────────────────────────────────┤
│ Phase 0: Roadmap Discussion (Interactive) │
├─ Discuss requirements and scope with user
├─ Break down into logical phases │
├─ Define success criteria per phase
└─ Output: roadmap.md with phase definitions
Phase 1: Requirement → CSV + Classification │
├─ For each roadmap phase: generate plan->execute->verify tasks │
├─ Classify tasks: csv-wave (execution) | interactive (planning)
├─ Compute dependency waves (topological sort → depth grouping) │
├─ Generate tasks.csv with wave + exec_mode columns
└─ User validates task breakdown (skip if -y) │
│ Phase 2: Wave Execution Engine (Extended) │
│ ├─ For each wave (1..N): │
│ ├─ Execute pre-wave interactive tasks (planning) │
│ │ ├─ Build wave CSV (filter csv-wave tasks for this wave) │
│ │ ├─ Inject previous findings into prev_context column │
│ ├─ spawn_agents_on_csv(wave CSV) │
│ │ ├─ Execute post-wave interactive tasks (verification) │
│ │ ├─ Merge all results into master tasks.csv │
│ │ └─ Check: any failed? → skip dependents │
│ └─ discoveries.ndjson shared across all modes (append-only) │
│ │
│ Phase 3: Results Aggregation │
│ ├─ Export final results.csv │
│ ├─ Generate context.md with all findings │
│ ├─ Display summary: completed/failed/skipped per wave │
│ └─ Offer: view results | retry failed | done │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Skill(skill="team-roadmap-dev", args="<task-description>")
|
SKILL.md (this file) = Router
|
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- roadmap-discuss -> dispatch -> spawn workers -> STOP
|
+-------+-------+-------+
v v v
[planner] [executor] [verifier]
(team-worker agents)
Pipeline (per phase):
PLAN-N01 -> EXEC-N01 -> VERIFY-N01 (gap closure loop if needed)
Multi-phase:
Phase 1 -> Phase 2 -> ... -> Phase N -> Complete
```
---
## Role Registry
## Task Classification Rules
| Role | Path | Prefix | Inner Loop |
|------|------|--------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — |
| planner | [roles/planner/role.md](roles/planner/role.md) | PLAN-* | true |
| executor | [roles/executor/role.md](roles/executor/role.md) | EXEC-* | true |
| verifier | [roles/verifier/role.md](roles/verifier/role.md) | VERIFY-* | true |
Each task is classified by `exec_mode`:
## Role Router
| exec_mode | Mechanism | Criteria |
|-----------|-----------|----------|
| `csv-wave` | `spawn_agents_on_csv` | One-shot, structured I/O, no multi-round interaction |
| `interactive` | `spawn_agent`/`wait`/`send_input`/`close_agent` | Multi-round, clarification, inline utility |
Parse `$ARGUMENTS`:
- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4
- No `--role` `roles/coordinator/role.md`, execute entry router
**Classification Decision**:
## Shared Constants
| Task Property | Classification |
|---------------|---------------|
| Planning tasks (research, exploration, plan generation) | `interactive` |
| Execution tasks (code implementation, file modifications) | `csv-wave` |
| Verification tasks (testing, validation, gap detection) | `interactive` |
| Gap closure tasks (re-planning based on verification) | `interactive` |
- **Session prefix**: `RD`
- **Session path**: `.workflow/.team/RD-<slug>-<date>/`
- **Team name**: `roadmap-dev`
- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications)
- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)`
---
## Worker Spawn Template
## CSV Schema
### tasks.csv (Master State)
```csv
id,title,description,deps,context_from,exec_mode,phase,role,wave,status,findings,error
PLAN-101,Phase 1 Planning,Research and plan for authentication module,,,"interactive",1,planner,1,pending,"",""
EXEC-101,Implement auth routes,Create Express routes for login/logout/register,PLAN-101,PLAN-101,"csv-wave",1,executor,2,pending,"",""
EXEC-102,Implement JWT middleware,Create JWT token generation and validation,PLAN-101,PLAN-101,"csv-wave",1,executor,2,pending,"",""
VERIFY-101,Verify Phase 1,Test and validate phase 1 implementation,"EXEC-101;EXEC-102","EXEC-101;EXEC-102","interactive",1,verifier,3,pending,"",""
```
**Columns**:
| Column | Phase | Description |
|--------|-------|-------------|
| `id` | Input | Unique task identifier (string) |
| `title` | Input | Short task title |
| `description` | Input | Detailed task description |
| `deps` | Input | Semicolon-separated dependency task IDs |
| `context_from` | Input | Semicolon-separated task IDs whose findings this task needs |
| `exec_mode` | Input | `csv-wave` or `interactive` |
| `phase` | Input | Phase number (1-based) |
| `role` | Input | Role name: planner, executor, verifier |
| `wave` | Computed | Wave number (computed by topological sort, 1-based) |
| `status` | Output | `pending``completed` / `failed` / `skipped` |
| `findings` | Output | Key discoveries or implementation notes (max 500 chars) |
| `error` | Output | Error message if failed (empty if success) |
### Per-Wave CSV (Temporary)
Each wave generates a temporary `wave-{N}.csv` with extra `prev_context` column (csv-wave tasks only).
---
## Agent Registry (Interactive Agents)
| Agent | Role File | Pattern | Responsibility | Position |
|-------|-----------|---------|----------------|----------|
| roadmap-discusser | ~/.codex/agents/roadmap-discusser.md | 2.3 | Discuss roadmap with user, generate phase plan | pre-wave (Phase 0) |
| planner | ~/.codex/agents/roadmap-planner.md | 2.4 | Research and plan creation per phase | pre-wave (per phase) |
| verifier | ~/.codex/agents/roadmap-verifier.md | 2.4 | Test and validate phase implementation | post-wave (per phase) |
> **COMPACT PROTECTION**: Agent files are execution documents. When context compression occurs, **you MUST immediately `Read` the corresponding agent.md** to reload.
---
## Output Artifacts
| File | Purpose | Lifecycle |
|------|---------|-----------|
| `tasks.csv` | Master state — all tasks with status/findings | Updated after each wave |
| `wave-{N}.csv` | Per-wave input (temporary, csv-wave tasks only) | Created before wave, deleted after |
| `results.csv` | Final export of all task results | Created in Phase 3 |
| `discoveries.ndjson` | Shared exploration board (all agents, both modes) | Append-only, carries across waves |
| `context.md` | Human-readable execution report | Created in Phase 3 |
| `interactive/{id}-result.json` | Results from interactive tasks | Created per interactive task |
| `agents/registry.json` | Active interactive agent tracking | Updated on spawn/close |
| `roadmap.md` | Phase definitions and requirements | Created in Phase 0 |
| `phase-{N}/IMPL_PLAN.md` | Implementation plan per phase | Created by planner |
| `phase-{N}/verification.md` | Verification results per phase | Created by verifier |
---
## Session Structure
Coordinator spawns workers using this template:
```
.workflow/.csv-wave/{session-id}/
├── tasks.csv # Master state (all tasks, both modes)
├── results.csv # Final results export
├── discoveries.ndjson # Shared discovery board (all agents)
├── context.md # Human-readable report
├── roadmap.md # Phase definitions
├── wave-{N}.csv # Temporary per-wave input (csv-wave only)
├── interactive/ # Interactive task artifacts
│ ├── {id}-result.json # Per-task results
│ └── cache-index.json # Shared exploration cache
├── agents/
│ └── registry.json # Active interactive agent tracking
└── phase-{N}/ # Per-phase artifacts
├── IMPL_PLAN.md
├── TODO_LIST.md
├── .task/IMPL-*.json
└── verification.md
```
spawn_agent({
agent_type: "team_worker",
items: [
{ type: "text", text: `## Role Assignment
role: <role>
role_spec: <skill_root>/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
requirement: <task-description>
inner_loop: true
---
Read role_spec file (<skill_root>/roles/<role>/role.md) to load Phase 2-4 domain instructions.` },
## Implementation
{ type: "text", text: `## Task Context
task_id: <task-id>
title: <task-title>
description: <task-description>
pipeline_phase: <pipeline-phase>` },
### Session Initialization
```javascript
// Parse arguments
const args = parseArguments($ARGUMENTS)
const autoYes = args.yes || args.y
const concurrency = args.concurrency || args.c || 3
const continueMode = args.continue
const taskDescription = args._[0]
// Generate session ID
const slug = taskDescription.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30)
const date = new Date().toISOString().split('T')[0]
const sessionId = `RD-${slug}-${date}`
const sessionDir = `.workflow/.csv-wave/${sessionId}`
// Create session structure
Bash(`mkdir -p "${sessionDir}/interactive" "${sessionDir}/agents" "${sessionDir}/phase-1"`)
// Initialize registry
Write(`${sessionDir}/agents/registry.json`, JSON.stringify({
active: [],
closed: [],
created_at: new Date().toISOString()
}, null, 2))
// Initialize discoveries
Write(`${sessionDir}/discoveries.ndjson`, '')
```
---
### Phase 0: Roadmap Discussion (Interactive)
**Objective**: Discuss roadmap with user and generate phase plan with requirements and success criteria.
```javascript
// Spawn roadmap discusser
const discusser = spawn_agent({
message: `### MANDATORY FIRST STEPS
1. Read: ~/.codex/agents/roadmap-discusser.md
---
## Task Assignment
**Goal**: Discuss roadmap with user and generate phase plan
**Task Description**: ${taskDescription}
**Session Directory**: ${sessionDir}
**Deliverables**:
- roadmap.md with phase definitions, requirements, and success criteria
- Each phase should have: phase number, goal, requirements (REQ-IDs), success criteria
**Instructions**:
1. Analyze task description to understand scope
2. Propose phase breakdown to user via request_user_input
3. For each phase, clarify requirements and success criteria
4. Generate roadmap.md with structured phase definitions
5. Output result as JSON with roadmap_path and phase_count`
{ type: "text", text: `## Upstream Context
<prev_context>` }
]
})
// Wait for completion
const result = wait({ ids: [discusser], timeout_ms: 600000 })
if (result.timed_out) {
send_input({ id: discusser, message: "Please finalize roadmap and output current plan." })
const retry = wait({ ids: [discusser], timeout_ms: 120000 })
}
// Store result
const discusserOutput = JSON.parse(result.output)
Write(`${sessionDir}/interactive/DISCUSS-001-result.json`, JSON.stringify({
task_id: "DISCUSS-001",
status: "completed",
findings: discusserOutput.summary,
roadmap_path: discusserOutput.roadmap_path,
phase_count: discusserOutput.phase_count,
timestamp: new Date().toISOString()
}, null, 2))
close_agent({ id: discusser })
// Load roadmap
const roadmap = Read(discusserOutput.roadmap_path)
const phases = parsePhases(roadmap)
```
**Success Criteria**:
- roadmap.md created with phase definitions
- Each phase has clear requirements and success criteria
- User approved phase breakdown
After spawning, use `wait_agent({ ids: [...], timeout_ms: 900000 })` to collect results, then `close_agent({ id })` each worker.
---
**All worker roles** (planner, executor, verifier): Set `inner_loop: true`.
### Phase 1: Requirement → CSV + Classification
## User Commands
**Objective**: Generate task breakdown from roadmap phases, classify by exec_mode, compute waves.
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph (phase-grouped), no advancement |
| `resume` / `continue` | Check worker states, advance next step |
```javascript
// Read roadmap
const roadmapContent = Read(`${sessionDir}/roadmap.md`)
const phases = parseRoadmapPhases(roadmapContent)
## Session Directory
// Generate tasks for all phases
const allTasks = []
let taskCounter = 1
for (const phase of phases) {
const phaseNum = phase.number
// Planning task (interactive, pre-wave)
allTasks.push({
id: `PLAN-${phaseNum}01`,
title: `Phase ${phaseNum} Planning`,
description: `Research and plan for: ${phase.goal}\n\nRequirements:\n${phase.requirements.join('\n')}\n\nSuccess Criteria:\n${phase.success_criteria.join('\n')}`,
deps: phaseNum > 1 ? `VERIFY-${phaseNum-1}01` : "",
context_from: phaseNum > 1 ? `VERIFY-${phaseNum-1}01` : "",
exec_mode: "interactive",
phase: phaseNum,
role: "planner",
wave: 0, // Computed later
status: "pending",
findings: "",
error: ""
})
// Execution tasks (csv-wave) - will be generated by planner
// Placeholder: planner will create EXEC-{phaseNum}01, EXEC-{phaseNum}02, etc.
// Verification task (interactive, post-wave)
allTasks.push({
id: `VERIFY-${phaseNum}01`,
title: `Phase ${phaseNum} Verification`,
description: `Test and validate phase ${phaseNum} implementation against success criteria:\n${phase.success_criteria.join('\n')}`,
deps: `PLAN-${phaseNum}01`, // Will be updated after execution tasks created
context_from: `PLAN-${phaseNum}01`, // Will be updated
exec_mode: "interactive",
phase: phaseNum,
role: "verifier",
wave: 0, // Computed later
status: "pending",
findings: "",
error: ""
})
}
// Compute waves via topological sort
const tasksWithWaves = computeWaves(allTasks)
// Write master CSV
writeMasterCSV(`${sessionDir}/tasks.csv`, tasksWithWaves)
// User validation (skip if autoYes)
if (!autoYes) {
const approval = request_user_input({
questions: [{
question: `Generated ${tasksWithWaves.length} tasks across ${phases.length} phases. Proceed?`,
header: "Validate",
id: "task_approval",
options: [
{ label: "Proceed (Recommended)", description: "Start execution" },
{ label: "Cancel", description: "Abort workflow" }
]
}]
})
if (approval.answers.task_approval.answers[0] !== "Proceed (Recommended)") {
throw new Error("User cancelled workflow")
}
}
```
.workflow/.team/RD-<slug>-<date>/
+-- roadmap.md # Phase plan with requirements and success criteria
+-- state.md # Living memory (<100 lines)
+-- config.json # Session settings (mode, depth, gates)
+-- wisdom/ # Cross-task knowledge accumulation
| +-- learnings.md
| +-- decisions.md
| +-- conventions.md
| +-- issues.md
+-- phase-1/ # Per-phase artifacts
| +-- context.md
| +-- IMPL_PLAN.md
| +-- TODO_LIST.md
| +-- .task/IMPL-*.json
| +-- summary-*.md
| +-- verification.md
+-- phase-N/
| +-- ...
+-- .msg/
+-- messages.jsonl # Team message bus log
+-- meta.json # Session metadata + shared state
```
**Success Criteria**:
- tasks.csv created with valid schema, wave, and exec_mode assignments
- No circular dependencies
- User approved (or AUTO_YES)
## Completion Action
---
When the pipeline completes:
### Phase 2: Wave Execution Engine (Extended)
**Objective**: Execute tasks wave-by-wave with hybrid mechanism support and cross-wave context propagation.
```javascript
// Load master CSV
const masterCSV = readMasterCSV(`${sessionDir}/tasks.csv`)
const maxWave = Math.max(...masterCSV.map(t => t.wave))
for (let waveNum = 1; waveNum <= maxWave; waveNum++) {
console.log(`\n=== Executing Wave ${waveNum} ===\n`)
// Get tasks for this wave
const waveTasks = masterCSV.filter(t => t.wave === waveNum && t.status === 'pending')
// Separate by exec_mode
const interactiveTasks = waveTasks.filter(t => t.exec_mode === 'interactive')
const csvTasks = waveTasks.filter(t => t.exec_mode === 'csv-wave')
// Execute pre-wave interactive tasks (planners)
for (const task of interactiveTasks.filter(t => t.role === 'planner')) {
const agent = spawn_agent({
message: buildPlannerPrompt(task, sessionDir)
})
const result = wait({ ids: [agent], timeout_ms: 600000 })
if (result.timed_out) {
send_input({ id: agent, message: "Please finalize plan and output current results." })
const retry = wait({ ids: [agent], timeout_ms: 120000 })
}
// Store result
Write(`${sessionDir}/interactive/${task.id}-result.json`, JSON.stringify({
task_id: task.id,
status: "completed",
findings: parseFindings(result),
timestamp: new Date().toISOString()
}, null, 2))
close_agent({ id: agent })
// Update master CSV
updateTaskStatus(masterCSV, task.id, "completed", parseFindings(result))
// Planner generates execution tasks - read and add to master CSV
const planTasks = readPlanTasks(`${sessionDir}/phase-${task.phase}/.task/`)
for (const planTask of planTasks) {
masterCSV.push({
id: planTask.id,
title: planTask.title,
description: planTask.description,
deps: task.id,
context_from: task.id,
exec_mode: "csv-wave",
phase: task.phase,
role: "executor",
wave: waveNum + 1, // Next wave
status: "pending",
findings: "",
error: ""
})
}
}
// Build wave CSV for csv-wave tasks
if (csvTasks.length > 0) {
const waveCSV = buildWaveCSV(csvTasks, masterCSV, sessionDir)
const waveCSVPath = `${sessionDir}/wave-${waveNum}.csv`
writeWaveCSV(waveCSVPath, waveCSV)
// Execute CSV wave
spawn_agents_on_csv({
csv_file_path: waveCSVPath,
instruction_file_path: `${sessionDir}/../instructions/executor-instruction.md`,
concurrency: concurrency
})
// Merge results back to master CSV
const waveResults = readWaveCSV(waveCSVPath)
for (const result of waveResults) {
updateTaskStatus(masterCSV, result.id, result.status, result.findings, result.error)
}
// Cleanup temp wave CSV
Bash(`rm "${waveCSVPath}"`)
}
// Execute post-wave interactive tasks (verifiers)
for (const task of interactiveTasks.filter(t => t.role === 'verifier')) {
const agent = spawn_agent({
message: buildVerifierPrompt(task, sessionDir, masterCSV)
})
const result = wait({ ids: [agent], timeout_ms: 600000 })
if (result.timed_out) {
send_input({ id: agent, message: "Please finalize verification and output current results." })
const retry = wait({ ids: [agent], timeout_ms: 120000 })
}
// Store result
const verificationResult = JSON.parse(result.output)
Write(`${sessionDir}/interactive/${task.id}-result.json`, JSON.stringify({
task_id: task.id,
status: "completed",
findings: verificationResult.summary,
gaps_found: verificationResult.gaps || [],
timestamp: new Date().toISOString()
}, null, 2))
close_agent({ id: agent })
// Update master CSV
updateTaskStatus(masterCSV, task.id, "completed", verificationResult.summary)
// Handle gaps (max 3 iterations)
if (verificationResult.gaps && verificationResult.gaps.length > 0) {
const gapIteration = countGapIterations(masterCSV, task.phase)
if (gapIteration < 3) {
// Create gap closure tasks
const gapTasks = createGapClosureTasks(verificationResult.gaps, task.phase, gapIteration)
masterCSV.push(...gapTasks)
} else {
console.log(`[WARNING] Max gap iterations (3) reached for phase ${task.phase}`)
}
}
}
// Write updated master CSV
writeMasterCSV(`${sessionDir}/tasks.csv`, masterCSV)
// Check for failures and skip dependents
const failedTasks = waveTasks.filter(t => t.status === 'failed')
if (failedTasks.length > 0) {
skipDependentTasks(masterCSV, failedTasks.map(t => t.id))
}
}
```
**Success Criteria**:
- All waves executed in order
- Both csv-wave and interactive tasks handled per wave
- Each wave's results merged into master CSV before next wave starts
- Dependent tasks skipped when predecessor failed
- discoveries.ndjson accumulated across all waves and mechanisms
- Interactive agent lifecycle tracked in registry.json
---
### Phase 3: Results Aggregation
**Objective**: Generate final results and human-readable report.
```javascript
// Load final master CSV
const finalCSV = readMasterCSV(`${sessionDir}/tasks.csv`)
// Export results.csv
writeFinalResults(`${sessionDir}/results.csv`, finalCSV)
// Generate context.md
const contextMd = generateContextReport(finalCSV, sessionDir)
Write(`${sessionDir}/context.md`, contextMd)
// Cleanup active agents
const registry = JSON.parse(Read(`${sessionDir}/agents/registry.json`))
for (const agent of registry.active) {
close_agent({ id: agent.id })
}
registry.active = []
Write(`${sessionDir}/agents/registry.json`, JSON.stringify(registry, null, 2))
// Display summary
const completed = finalCSV.filter(t => t.status === 'completed').length
const failed = finalCSV.filter(t => t.status === 'failed').length
const skipped = finalCSV.filter(t => t.status === 'skipped').length
console.log(`\n=== Roadmap Development Complete ===`)
console.log(`Completed: ${completed}`)
console.log(`Failed: ${failed}`)
console.log(`Skipped: ${skipped}`)
console.log(`\nResults: ${sessionDir}/results.csv`)
console.log(`Report: ${sessionDir}/context.md`)
// Offer next steps
const nextStep = request_user_input({
request_user_input({
questions: [{
question: "Roadmap Dev pipeline complete. Choose next action.",
header: "Done",
id: "completion",
question: "Roadmap Dev pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
if (nextStep.answers.completion.answers[0] === "Archive (Recommended)") {
Bash(`tar -czf "${sessionDir}.tar.gz" "${sessionDir}" && rm -rf "${sessionDir}"`)
console.log(`Session archived to ${sessionDir}.tar.gz`)
}
```
**Success Criteria**:
- results.csv exported (all tasks, both modes)
- context.md generated
- All interactive agents closed (registry.json cleanup)
- Summary displayed to user
## Specs Reference
---
## Shared Discovery Board Protocol
All agents (both csv-wave and interactive) share a single `discoveries.ndjson` file for exploration findings.
**Discovery Types**:
| Type | Dedup Key | Data Schema | Description |
|------|-----------|-------------|-------------|
| `file_pattern` | `pattern` | `{pattern, files[], description}` | Code patterns discovered |
| `dependency` | `from+to` | `{from, to, type}` | Module dependencies |
| `risk` | `description` | `{description, severity, mitigation}` | Implementation risks |
| `test_gap` | `area` | `{area, description, priority}` | Testing gaps |
**Write Protocol**:
```bash
echo '{"ts":"2026-03-08T14:30:22Z","worker":"EXEC-101","type":"file_pattern","data":{"pattern":"auth middleware","files":["src/middleware/auth.ts"],"description":"JWT validation pattern"}}' >> ${sessionDir}/discoveries.ndjson
```
**Read Protocol**:
```javascript
const discoveries = Read(`${sessionDir}/discoveries.ndjson`)
.split('\n')
.filter(line => line.trim())
.map(line => JSON.parse(line))
```
---
- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry
## Error Handling
| Error | Resolution |
|-------|------------|
| Circular dependency | Detect in wave computation, abort with error message |
| CSV agent timeout | Mark as failed in results, continue with wave |
| CSV agent failed | Mark as failed, skip dependent tasks in later waves |
| Interactive agent timeout | Urge convergence via send_input, then close if still timed out |
| Interactive agent failed | Mark as failed, skip dependents |
| Pre-wave interactive failed | Skip dependent csv-wave tasks in same wave |
| All agents in wave failed | Log error, offer retry or abort |
| CSV parse error | Validate CSV format before execution, show line number |
| discoveries.ndjson corrupt | Ignore malformed lines, continue with valid entries |
| Lifecycle leak | Cleanup all active agents via registry.json at end |
| Continue mode: no session found | List available sessions, prompt user to select |
| project-tech.json missing | Invoke workflow:init skill |
| Verifier gaps persist (>3 iterations) | Report to user, ask for manual intervention |
---
## Core Rules
1. **Start Immediately**: First action is session initialization, then Phase 0
2. **Wave Order is Sacred**: Never execute wave N before wave N-1 completes and results are merged
3. **CSV is Source of Truth**: Master tasks.csv holds all state (both csv-wave and interactive)
4. **CSV First**: Default to csv-wave for tasks; only use interactive when interaction pattern requires it
5. **Context Propagation**: prev_context built from master CSV, not from memory
6. **Discovery Board is Append-Only**: Never clear, modify, or recreate discoveries.ndjson — both mechanisms share it
7. **Skip on Failure**: If a dependency failed, skip the dependent task (regardless of mechanism)
8. **Lifecycle Balance**: Every spawn_agent MUST have a matching close_agent (tracked in registry.json)
9. **Cleanup Temp Files**: Remove wave-{N}.csv after results are merged
10. **DO NOT STOP**: Continuous execution until all waves complete or all remaining tasks are skipped
---
## Coordinator Role Constraints (Main Agent)
**CRITICAL**: The coordinator (main agent executing this skill) is responsible for **orchestration only**, NOT implementation.
15. **Coordinator Does NOT Execute Code**: The main agent MUST NOT write, modify, or implement any code directly. All implementation work is delegated to spawned team agents. The coordinator only:
- Spawns agents with task assignments
- Waits for agent callbacks
- Merges results and coordinates workflow
- Manages workflow transitions between phases
16. **Patient Waiting is Mandatory**: Agent execution takes significant time (typically 10-30 minutes per phase, sometimes longer). The coordinator MUST:
- Wait patiently for `wait()` calls to complete
- NOT skip workflow steps due to perceived delays
- NOT assume agents have failed just because they're taking time
- Trust the timeout mechanisms defined in the skill
17. **Use send_input for Clarification**: When agents need guidance or appear stuck, the coordinator MUST:
- Use `send_input()` to ask questions or provide clarification
- NOT skip the agent or move to next phase prematurely
- Give agents opportunity to respond before escalating
- Example: `send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })`
18. **No Workflow Shortcuts**: The coordinator MUST NOT:
- Skip phases or stages defined in the workflow
- Bypass required approval or review steps
- Execute dependent tasks before prerequisites complete
- Assume task completion without explicit agent callback
- Make up or fabricate agent results
19. **Respect Long-Running Processes**: This is a complex multi-agent workflow that requires patience:
- Total execution time may range from 30-90 minutes or longer
- Each phase may take 10-30 minutes depending on complexity
- The coordinator must remain active and attentive throughout the entire process
- Do not terminate or skip steps due to time concerns
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Error with role registry list |
| Role file not found | Error with expected path (roles/{name}/role.md) |
| project-tech.json missing | Coordinator invokes /workflow:spec:setup |
| Phase verification fails with gaps | Coordinator triggers gap closure loop (max 3 iterations) |
| Max gap closure iterations (3) | Report to user, ask for guidance |
| Worker crash | Respawn worker, reassign task |
| Session corruption | Attempt recovery, fallback to manual reconciliation |

View File

@@ -1,176 +0,0 @@
# Roadmap Discusser Agent
Interactive agent for discussing roadmap with user and generating phase plan with requirements and success criteria.
## Identity
- **Type**: `interactive`
- **Role File**: `~/.codex/agents/roadmap-discusser.md`
- **Responsibility**: Roadmap discussion and phase planning
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Produce structured output following template
- Interact with user via request_user_input
- Generate roadmap.md with phase definitions
- Include requirements (REQ-IDs) and success criteria per phase
### MUST NOT
- Skip the MANDATORY FIRST STEPS role loading
- Produce unstructured output
- Execute implementation tasks
- Skip user interaction
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `request_user_input` | Human interaction | Clarify requirements, propose phase breakdown |
| `Read` | File I/O | Load project context |
| `Write` | File I/O | Generate roadmap.md |
---
## Execution
### Phase 1: Requirement Analysis
**Objective**: Analyze task description and understand scope.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Task description | Yes | User's task description from arguments |
| .workflow/project-tech.json | No | Project context if available |
**Steps**:
1. Read task description from spawn message
2. Load project context if available
3. Identify key requirements and scope
4. Detect complexity signals (multi-module, cross-cutting, integration)
**Output**: Requirement analysis summary
---
### Phase 2: Phase Breakdown Proposal
**Objective**: Propose logical phase breakdown to user.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Requirement analysis | Yes | From Phase 1 |
**Steps**:
1. Analyze requirements to identify logical phases
2. Propose phase breakdown (typically 2-5 phases)
3. For each phase, draft:
- Phase goal (one sentence)
- Key requirements (REQ-IDs)
- Success criteria (measurable)
4. Present to user via request_user_input:
```javascript
request_user_input({
questions: [{
question: "Proposed phase breakdown:\n\nPhase 1: [goal]\n- REQ-001: [requirement]\n- Success: [criteria]\n\nPhase 2: [goal]\n...\n\nApprove or request changes?",
header: "Roadmap",
id: "roadmap_approval",
options: [
{ label: "Approve (Recommended)", description: "Proceed with this breakdown" },
{ label: "Modify", description: "Request changes to phases" },
{ label: "Cancel", description: "Abort workflow" }
]
}]
})
```
5. If user requests modifications, iterate on phase breakdown
**Output**: User-approved phase breakdown
---
### Phase 3: Roadmap Generation
**Objective**: Generate roadmap.md with structured phase definitions.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Approved phase breakdown | Yes | From Phase 2 |
**Steps**:
1. Format roadmap.md with structure:
```markdown
# Roadmap: [Task Title]
## Overview
[Task description and scope]
## Phase 1: [Phase Goal]
### Requirements
- REQ-101: [Requirement description]
- REQ-102: [Requirement description]
### Success Criteria
- [Measurable criterion 1]
- [Measurable criterion 2]
## Phase 2: [Phase Goal]
...
```
2. Write roadmap.md to session directory
3. Prepare output JSON with roadmap path and phase count
**Output**: roadmap.md file + JSON result
---
## Structured Output Template
```
## Summary
- Generated roadmap with [N] phases for [task description]
## Findings
- Phase breakdown approved by user
- [N] phases defined with requirements and success criteria
- Roadmap written to: [path]
## Deliverables
- File: [session]/roadmap.md
Content: Phase definitions with REQ-IDs and success criteria
## Output JSON
{
"roadmap_path": "[session]/roadmap.md",
"phase_count": [N],
"summary": "Generated roadmap with [N] phases"
}
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| User cancels | Output partial roadmap, mark as cancelled |
| Project context not found | Continue without project context, note in findings |
| User requests too many phases (>10) | Warn about complexity, suggest consolidation |
| Ambiguous requirements | Ask clarifying questions via request_user_input |

View File

@@ -1,194 +0,0 @@
# Roadmap Planner Agent
Interactive agent for research and plan creation per roadmap phase. Gathers codebase context via CLI exploration, then generates wave-based execution plans.
## Identity
- **Type**: `interactive`
- **Role File**: `~/.codex/agents/roadmap-planner.md`
- **Responsibility**: Phase planning and task decomposition
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Produce structured output following template
- Use CLI tools for codebase exploration
- Generate IMPL_PLAN.md and task JSON files
- Define convergence criteria per task
### MUST NOT
- Skip the MANDATORY FIRST STEPS role loading
- Execute implementation tasks
- Skip CLI exploration step
- Generate tasks without convergence criteria
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `Bash` | CLI execution | Run ccw cli for exploration and planning |
| `Read` | File I/O | Load roadmap, context, prior summaries |
| `Write` | File I/O | Generate plan artifacts |
| `Glob` | File search | Find relevant files |
---
## Execution
### Phase 1: Context Loading
**Objective**: Load phase requirements and prior context.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| roadmap.md | Yes | Phase definitions from session |
| config.json | Yes | Session configuration |
| Prior summaries | No | Previous phase results |
| discoveries.ndjson | No | Shared exploration findings |
**Steps**:
1. Read roadmap.md, extract phase goal, requirements (REQ-IDs), success criteria
2. Read config.json for depth setting (quick/standard/comprehensive)
3. Load prior phase summaries for dependency context
4. Detect gap closure mode (task description contains "Gap closure")
**Output**: Phase context loaded
---
### Phase 2: Codebase Exploration
**Objective**: Explore codebase to understand implementation context.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Phase requirements | Yes | From Phase 1 |
**Steps**:
1. Launch CLI exploration with phase requirements:
```bash
ccw cli -p "PURPOSE: Explore codebase for phase requirements
TASK: • Identify files needing modification • Map patterns and dependencies • Assess test infrastructure • Identify risks
MODE: analysis
CONTEXT: @**/* | Memory: Phase goal: ${phaseGoal}
EXPECTED: Structured exploration results with file lists, patterns, risks
CONSTRAINTS: Read-only analysis" --tool gemini --mode analysis
```
2. Wait for CLI completion (run_in_background: false)
3. Parse exploration results
4. Write context.md combining roadmap requirements + exploration results
**Output**: context.md with exploration findings
---
### Phase 3: Plan Generation
**Objective**: Generate wave-based execution plan with task breakdown.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| context.md | Yes | From Phase 2 |
**Steps**:
1. Load context.md
2. Create output directory: phase-{N}/.task/
3. Delegate to CLI planning tool:
```bash
ccw cli -p "PURPOSE: Generate wave-based execution plan for phase ${phaseNum}
TASK: • Break down requirements into tasks • Define convergence criteria • Build dependency graph • Assign waves
MODE: write
CONTEXT: @${contextMd} | Memory: ${priorSummaries}
EXPECTED: IMPL_PLAN.md + IMPL-*.json files + TODO_LIST.md
CONSTRAINTS: <= 10 tasks | Valid DAG | Measurable convergence criteria" --tool gemini --mode write
```
4. Wait for CLI completion
5. CLI tool produces: IMPL_PLAN.md, .task/IMPL-*.json, TODO_LIST.md
6. If gap closure: only create tasks for gaps, starting from next available ID
**Output**: IMPL_PLAN.md + task JSON files
---
### Phase 4: Self-Validation
**Objective**: Validate generated plan for completeness and correctness.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| IMPL_PLAN.md | Yes | From Phase 3 |
| .task/IMPL-*.json | Yes | Task definitions |
**Steps**:
1. Check task JSON files exist (>= 1 IMPL-*.json found)
2. Validate required fields: id, title, description, files, implementation, convergence
3. Check convergence criteria (each task has >= 1 criterion)
4. Validate no self-dependency (task.id not in task.depends_on)
5. Validate all deps valid (every depends_on ID exists)
6. Check IMPL_PLAN.md exists (generate minimal version if missing)
7. Compute wave structure from dependency graph for reporting
**Output**: Validation report + wave structure
---
## Structured Output Template
```
## Summary
- Generated implementation plan for phase {phase} with {N} tasks across {M} waves
## Findings
- Exploration identified {X} files needing modification
- Key patterns: [pattern list]
- Risks: [risk list]
- Task breakdown validated with no circular dependencies
## Deliverables
- File: phase-{N}/IMPL_PLAN.md
Content: Wave-based execution plan
- File: phase-{N}/.task/IMPL-*.json
Content: Task definitions with convergence criteria
- File: phase-{N}/TODO_LIST.md
Content: Task checklist
## Output JSON
{
"plan_path": "phase-{N}/IMPL_PLAN.md",
"task_count": {N},
"wave_count": {M},
"files_affected": [file list],
"summary": "Generated plan with {N} tasks"
}
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI exploration fails | Use fallback file search, note limitation |
| CLI planning fails | Generate minimal plan manually, warn user |
| Circular dependency detected | Remove cycle, log warning |
| No convergence criteria | Add default criteria, log warning |
| Task count exceeds 10 | Consolidate tasks, warn about complexity |

View File

@@ -1,221 +0,0 @@
# Roadmap Verifier Agent
Interactive agent for testing and validating phase implementation against success criteria. Identifies gaps and triggers gap closure if needed.
## Identity
- **Type**: `interactive`
- **Role File**: `~/.codex/agents/roadmap-verifier.md`
- **Responsibility**: Phase verification and gap detection
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Produce structured output following template
- Test implementation against success criteria
- Identify gaps with specific remediation steps
- Limit gap closure iterations to 3 per phase
### MUST NOT
- Skip the MANDATORY FIRST STEPS role loading
- Execute implementation tasks
- Skip testing step
- Approve phase with unmet success criteria without documenting gaps
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `Bash` | CLI execution | Run tests, linters, build commands |
| `Read` | File I/O | Load implementation, success criteria |
| `Write` | File I/O | Generate verification report |
| `Glob` | File search | Find test files |
---
## Execution
### Phase 1: Context Loading
**Objective**: Load phase implementation and success criteria.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| roadmap.md | Yes | Phase success criteria |
| Execution task findings | Yes | From prev_context |
| discoveries.ndjson | No | Shared exploration findings |
**Steps**:
1. Read roadmap.md, extract phase success criteria
2. Load execution task findings from prev_context
3. Read discoveries.ndjson for implementation notes
4. Identify files modified during execution
**Output**: Verification context loaded
---
### Phase 2: Testing Execution
**Objective**: Run tests and validation checks.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Modified files | Yes | From Phase 1 |
| Test files | No | Discovered via Glob |
**Steps**:
1. Identify test files related to modified code
2. Run relevant tests:
```bash
npm test -- [test-pattern]
```
3. Run linter/type checker:
```bash
npm run lint
npm run type-check
```
4. Check build succeeds:
```bash
npm run build
```
5. Collect test results, errors, warnings
**Output**: Test execution results
---
### Phase 3: Gap Analysis
**Objective**: Compare implementation against success criteria and identify gaps.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Success criteria | Yes | From roadmap.md |
| Test results | Yes | From Phase 2 |
| Implementation findings | Yes | From execution tasks |
**Steps**:
1. For each success criterion:
- Check if met by implementation
- Check if validated by tests
- Document status: met / partial / unmet
2. Identify gaps:
- Missing functionality
- Failing tests
- Unmet success criteria
3. For each gap, define:
- Gap description
- Severity (critical / high / medium / low)
- Remediation steps
4. Check gap closure iteration count (max 3)
**Output**: Gap analysis with remediation steps
---
### Phase 4: Verification Report
**Objective**: Generate verification report and output results.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Gap analysis | Yes | From Phase 3 |
**Steps**:
1. Generate verification.md:
```markdown
# Phase {N} Verification
## Success Criteria Status
- [✓] Criterion 1: Met
- [✗] Criterion 2: Unmet - [gap description]
## Test Results
- Tests passed: {X}/{Y}
- Build status: [success/failed]
- Linter warnings: {Z}
## Gaps Identified
### Gap 1: [Description]
- Severity: [critical/high/medium/low]
- Remediation: [steps]
## Recommendation
[Approve / Gap Closure Required]
```
2. Write verification.md to phase directory
3. Prepare output JSON with gap list
**Output**: verification.md + JSON result
---
## Structured Output Template
```
## Summary
- Phase {phase} verification complete: {X}/{Y} success criteria met
## Findings
- Tests passed: {X}/{Y}
- Build status: [success/failed]
- Gaps identified: {N} ([critical/high/medium/low] breakdown)
## Gaps
- Gap 1: [description] (severity: [level])
Remediation: [steps]
- Gap 2: [description] (severity: [level])
Remediation: [steps]
## Deliverables
- File: phase-{N}/verification.md
Content: Verification report with gap analysis
## Output JSON
{
"verification_path": "phase-{N}/verification.md",
"criteria_met": {X},
"criteria_total": {Y},
"gaps": [
{
"description": "[gap description]",
"severity": "[critical/high/medium/low]",
"remediation": "[steps]"
}
],
"recommendation": "approve" | "gap_closure_required",
"summary": "Phase {phase} verification: {X}/{Y} criteria met"
}
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Tests fail to run | Document as gap, continue verification |
| Build fails | Mark as critical gap, recommend gap closure |
| No test files found | Note in findings, continue with manual verification |
| Gap closure iterations exceed 3 | Report to user, recommend manual intervention |
| Success criteria ambiguous | Document interpretation, ask for clarification |

View File

@@ -1,55 +0,0 @@
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS
1. Read shared discoveries: {session_folder}/discoveries.ndjson (if exists, skip if not)
2. Read project context: .workflow/project-tech.json (if exists)
3. Read implementation plan: {session_folder}/phase-{phase}/IMPL_PLAN.md
4. Read task details: {session_folder}/phase-{phase}/.task/{id}.json (if exists)
---
## Your Task
**Task ID**: {id}
**Title**: {title}
**Description**: {description}
**Phase**: {phase}
**Role**: {role}
### Previous Tasks' Findings (Context)
{prev_context}
---
## Execution Protocol
1. **Read discoveries**: Load {session_folder}/discoveries.ndjson for shared exploration findings
2. **Use context**: Apply previous tasks' findings from prev_context above
3. **Execute**: Implement the task following the implementation plan and task details
- Read target files listed in description
- Apply changes following project conventions
- Validate changes compile/lint correctly
- Run relevant tests if available
4. **Share discoveries**: Append exploration findings to shared board:
```bash
echo '{"ts":"<ISO8601>","worker":"{id}","type":"<type>","data":{...}}' >> {session_folder}/discoveries.ndjson
```
5. **Report result**: Return JSON via report_agent_job_result
### Discovery Types to Share
- `file_pattern`: `{pattern, files[], description}` — Code patterns discovered
- `dependency`: `{from, to, type}` — Module dependencies identified
- `risk`: `{description, severity, mitigation}` — Implementation risks
- `test_gap`: `{area, description, priority}` — Testing gaps identified
---
## Output (report_agent_job_result)
Return JSON:
{
"id": "{id}",
"status": "completed" | "failed",
"findings": "Key discoveries and implementation notes (max 500 chars)",
"error": ""
}

View File

@@ -0,0 +1,61 @@
# Analyze Task
Parse user task description for roadmap-dev domain signals. Detect phase count, depth preference, gate configuration, and pipeline mode.
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
## Signal Detection
### Phase Count
| Keywords | Inferred Phase Count |
|----------|---------------------|
| "phase 1", "phase 2", ... | Explicit phase count from numbers |
| "milestone", "milestone 1/2/3" | Count milestones |
| "first ... then ... finally" | 3 phases |
| "step 1/2/3" | Count steps |
| No phase keywords | Default: 1 phase |
### Depth Setting
| Keywords | Depth |
|----------|-------|
| "quick", "fast", "simple", "minimal" | quick |
| "thorough", "comprehensive", "complete", "full" | comprehensive |
| default | standard |
### Gate Configuration
| Keywords | Gate |
|----------|------|
| "review each plan", "approve plan", "check before execute" | plan_check: true |
| "review each phase", "approve phase", "check between phases" | phase_check: true |
| "auto", "automated", "no review", "fully automated" | all gates: false |
| default | plan_check: false, phase_check: false |
### Pipeline Mode
| Keywords | Mode |
|----------|------|
| "interactive", "step by step", "with approval" | interactive |
| default | auto |
## Output
Write coordinator state to memory (not a file). Structure:
```json
{
"pipeline_mode": "auto | interactive",
"phase_count": 1,
"depth": "quick | standard | comprehensive",
"gates": {
"plan_check": false,
"phase_check": false
},
"task_description": "<original task text>",
"notes": ["<any detected constraints or special requirements>"]
}
```
This state is passed to `commands/dispatch.md` and written to `config.json` in the session directory.

View File

@@ -0,0 +1,241 @@
# Command: dispatch
Create task chain for a specific phase. Each phase gets a PLAN -> EXEC -> VERIFY pipeline with dependency ordering.
## Purpose
Read the roadmap and create a linked task chain (PLAN -> EXEC -> VERIFY) for a given phase number. Tasks are assigned to the appropriate worker roles and linked via blockedBy dependencies. All tasks are stored in `<session>/tasks.json`.
## Parameters
| Parameter | Source | Description |
|-----------|--------|-------------|
| `phaseNumber` | From coordinator | Phase to dispatch (1-based) |
| `sessionFolder` | From coordinator | Session artifact directory |
## Execution Steps
### Step 1: Read Roadmap and Extract Phase Requirements
```javascript
const roadmap = Read(`${sessionFolder}/roadmap.md`)
const config = JSON.parse(Read(`${sessionFolder}/config.json`))
// Parse phase section from roadmap
// Extract: goal, requirements (REQ-IDs), success criteria
const phaseGoal = extractPhaseGoal(roadmap, phaseNumber)
const phaseRequirements = extractPhaseRequirements(roadmap, phaseNumber)
const phaseSuccessCriteria = extractPhaseSuccessCriteria(roadmap, phaseNumber)
```
### Step 2: Create Phase Directory
```javascript
Bash(`mkdir -p "${sessionFolder}/phase-${phaseNumber}"`)
```
### Step 3: Load or Initialize tasks.json
```javascript
let tasks = []
try {
tasks = JSON.parse(Read(`${sessionFolder}/tasks.json`))
} catch {
tasks = []
}
```
### Step 4: Create PLAN Task (Assigned to Planner)
```javascript
const planTaskId = `PLAN-${phaseNumber}01`
tasks.push({
id: planTaskId,
subject: `PLAN-${phaseNumber}01: Plan phase ${phaseNumber} - ${phaseGoal}`,
status: "pending",
owner: "planner",
blockedBy: [],
activeForm: `Planning phase ${phaseNumber}`,
description: `[coordinator] Plan creation for phase ${phaseNumber}.
## Session
- Folder: ${sessionFolder}
- Phase: ${phaseNumber}
- Depth: ${config.depth}
## Phase Goal
${phaseGoal}
## Requirements
${phaseRequirements.map(r => `- ${r}`).join('\n')}
## Success Criteria
${phaseSuccessCriteria.map(c => `- ${c}`).join('\n')}
## Deliverables
- ${sessionFolder}/phase-${phaseNumber}/context.md (research context)
- ${sessionFolder}/phase-${phaseNumber}/plan-01.md (execution plan with waves and must_haves)
## Instructions
1. Invoke Skill(skill="team-roadmap-dev", args="--role=planner")
2. Follow planner role.md research + create-plans commands
3. Use roadmap requirements as input for plan generation
4. Update this task to completed when plan is written`
})
```
### Step 5: Create EXEC Task (Assigned to Executor, Blocked by PLAN)
```javascript
const execTaskId = `EXEC-${phaseNumber}01`
tasks.push({
id: execTaskId,
subject: `EXEC-${phaseNumber}01: Execute phase ${phaseNumber} - ${phaseGoal}`,
status: "pending",
owner: "executor",
blockedBy: [planTaskId],
activeForm: `Executing phase ${phaseNumber}`,
description: `[coordinator] Execute plans for phase ${phaseNumber}.
## Session
- Folder: ${sessionFolder}
- Phase: ${phaseNumber}
## Phase Goal
${phaseGoal}
## Plan Reference
- ${sessionFolder}/phase-${phaseNumber}/plan-01.md (and any additional plans)
## Instructions
1. Invoke Skill(skill="team-roadmap-dev", args="--role=executor")
2. Follow executor role.md implement command
3. Execute all plans in wave order
4. Write summary to ${sessionFolder}/phase-${phaseNumber}/summary-01.md
5. Update this task to completed when all plans executed`
})
```
### Step 6: Create VERIFY Task (Assigned to Verifier, Blocked by EXEC)
```javascript
const verifyTaskId = `VERIFY-${phaseNumber}01`
tasks.push({
id: verifyTaskId,
subject: `VERIFY-${phaseNumber}01: Verify phase ${phaseNumber} - ${phaseGoal}`,
status: "pending",
owner: "verifier",
blockedBy: [execTaskId],
activeForm: `Verifying phase ${phaseNumber}`,
description: `[coordinator] Verify phase ${phaseNumber} against success criteria.
## Session
- Folder: ${sessionFolder}
- Phase: ${phaseNumber}
## Phase Goal
${phaseGoal}
## Success Criteria (from roadmap)
${phaseSuccessCriteria.map(c => `- ${c}`).join('\n')}
## References
- Roadmap: ${sessionFolder}/roadmap.md
- Plans: ${sessionFolder}/phase-${phaseNumber}/plan-*.md
- Summaries: ${sessionFolder}/phase-${phaseNumber}/summary-*.md
## Instructions
1. Invoke Skill(skill="team-roadmap-dev", args="--role=verifier")
2. Follow verifier role.md verify command
3. Check each success criterion against actual implementation
4. Write verification to ${sessionFolder}/phase-${phaseNumber}/verification.md
5. If gaps found: list them with gap IDs in verification.md
6. Update this task to completed with result (passed/gaps_found)`
})
```
### Step 7: Write tasks.json
```javascript
Write(`${sessionFolder}/tasks.json`, JSON.stringify(tasks, null, 2))
```
### Step 8: Update state.md
```javascript
Edit(`${sessionFolder}/state.md`, {
old_string: `- Phase: ${phaseNumber}\n- Status: ready_to_dispatch`,
new_string: `- Phase: ${phaseNumber}\n- Status: in_progress\n- Tasks: PLAN-${phaseNumber}01 -> EXEC-${phaseNumber}01 -> VERIFY-${phaseNumber}01`
})
```
### Step 9: Log Dispatch Message
```javascript
mcp__ccw-tools__team_msg({
operation: "log", session_id: sessionId,
from: "coordinator", to: "all",
type: "phase_started",
data: { ref: `${sessionFolder}/roadmap.md` }
})
```
## Task Description Format
All dispatched tasks follow this structure:
```
[coordinator] {action} for phase {N}.
## Session
- Folder: {sessionFolder}
- Phase: {N}
- Depth: {config.depth} (PLAN only)
## Phase Goal
{goal from roadmap}
## Requirements / Success Criteria
{from roadmap}
## Deliverables
{expected output files}
## Instructions
{step-by-step for the worker role}
```
## Task Naming Convention
| Task | Name Pattern | Example |
|------|-------------|---------|
| Plan | `PLAN-{phase}01` | PLAN-101 |
| Execute | `EXEC-{phase}01` | EXEC-101 |
| Verify | `VERIFY-{phase}01` | VERIFY-101 |
| Gap Plan | `PLAN-{phase}02` | PLAN-102 (gap closure iteration 1) |
| Gap Execute | `EXEC-{phase}02` | EXEC-102 |
| Gap Verify | `VERIFY-{phase}02` | VERIFY-102 |
## Dependency Chain
```
PLAN-{N}01 <-- EXEC-{N}01 <-- VERIFY-{N}01
(planner) (executor) (verifier)
```
Each task is blocked by its predecessor. Workers pick up tasks only when their blockedBy list is empty.
## Output
Returns the three task IDs as a structured result:
```javascript
{
planTaskId: planTaskId,
execTaskId: execTaskId,
verifyTaskId: verifyTaskId
}
```

View File

@@ -0,0 +1,468 @@
# Command: Monitor
Handle all coordinator monitoring events for the roadmap-dev pipeline using the async Spawn-and-Stop pattern. Multi-phase execution with gap closure expressed as event-driven state machine transitions. One operation per invocation, then STOP and wait for the next callback.
## Constants
| Key | Value | Description |
|-----|-------|-------------|
| SPAWN_MODE | background | All workers spawned via `spawn_agent()` |
| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS |
| WORKER_AGENT | team_worker | All workers spawned as team_worker agents |
| MAX_GAP_ITERATIONS | 3 | Maximum gap closure re-plan/exec/verify cycles per phase |
### Role-Worker Map
| Prefix | Role | Role Spec | inner_loop |
|--------|------|-----------|------------|
| PLAN | planner | `~ or <project>/.codex/skills/team-roadmap-dev/roles/planner/role.md` | true (cli_tools: gemini --mode analysis) |
| EXEC | executor | `~ or <project>/.codex/skills/team-roadmap-dev/roles/executor/role.md` | true (cli_tools: gemini --mode write) |
| VERIFY | verifier | `~ or <project>/.codex/skills/team-roadmap-dev/roles/verifier/role.md` | true |
### Pipeline Structure
Per-phase task chain: `PLAN-{phase}01 -> EXEC-{phase}01 -> VERIFY-{phase}01`
Gap closure creates: `PLAN-{phase}0N -> EXEC-{phase}0N -> VERIFY-{phase}0N` (N = iteration + 1)
Multi-phase: Phases execute sequentially. Each phase completes its full PLAN/EXEC/VERIFY cycle (including gap closure) before the next phase is dispatched.
### State Machine Coordinates
The coordinator tracks its position using these state variables in `meta.json`:
```
session.coordinates = {
current_phase: <number>, // Active phase (1-based)
total_phases: <number>, // Total phases from roadmap
gap_iteration: <number>, // Current gap closure iteration within phase (0 = initial)
step: <string>, // Current step: "plan" | "exec" | "verify" | "gap_closure" | "transition"
status: <string> // "running" | "paused" | "complete"
}
```
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/.msg/meta.json` | Yes |
| Task list | `<session>/tasks.json` | Yes |
| Active workers | session.active_workers[] | Yes |
| Coordinates | session.coordinates | Yes |
| Config | `<session-folder>/config.json` | Yes |
| State | `<session-folder>/state.md` | Yes |
```
Load session state:
1. Read <session-folder>/.msg/meta.json -> session
2. Read <session-folder>/config.json -> config
3. Read <session>/tasks.json -> allTasks
4. Extract coordinates from session (current_phase, gap_iteration, step)
5. Extract active_workers[] from session (default: [])
6. Parse $ARGUMENTS to determine trigger event
```
## Phase 3: Event Handlers
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[planner]`, `[executor]`, or `[verifier]` | handleCallback |
| 2 | Contains "check" or "status" | handleCheck |
| 3 | Contains "resume", "continue", or "next" | handleResume |
| 4 | Pipeline detected as complete (all phases done) | handleComplete |
| 5 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Determine which step completed via prefix, apply pipeline logic, advance.
```
Receive callback from [<role>]
+- Find matching active worker by role tag
+- Is this a progress update (not final)? (Inner Loop intermediate)
| +- YES -> Update session state -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- Update task in tasks.json: set status = "completed"
| | +- Determine completed step from task prefix:
| | |
| | +- PLAN-* completed:
| | | +- Update coordinates.step = "plan_done"
| | | +- Is this initial plan (gap_iteration === 0)?
| | | | +- YES + config.gates.plan_check?
| | | | | +- request_user_input:
| | | | | prompt: "Phase <N> plan ready. Proceed with execution?
| | | | | Options:
| | | | | 1. Proceed - Continue to execution
| | | | | 2. Revise - Create new PLAN task with incremented suffix
| | | | | 3. Skip phase - Delete all phase tasks"
| | | | | -> "Proceed": -> handleSpawnNext (spawns EXEC)
| | | | | -> "Revise": Create new PLAN task in tasks.json
| | | | | blockedBy: [] (immediate), -> handleSpawnNext
| | | | | -> "Skip phase": Remove all phase tasks from tasks.json
| | | | | -> advanceToNextPhase
| | | | +- NO (gap closure plan) -> handleSpawnNext (spawns EXEC)
| | | +- -> handleSpawnNext
| | |
| | +- EXEC-* completed:
| | | +- Update coordinates.step = "exec_done"
| | | +- -> handleSpawnNext (spawns VERIFY)
| | |
| | +- VERIFY-* completed:
| | +- Update coordinates.step = "verify_done"
| | +- Read verification result from:
| | | <session-folder>/phase-<N>/verification.md
| | +- Parse gaps from verification
| | +- Gaps found?
| | +- NO -> Phase passed
| | | +- -> advanceToNextPhase
| | +- YES + gap_iteration < MAX_GAP_ITERATIONS?
| | | +- -> triggerGapClosure
| | +- YES + gap_iteration >= MAX_GAP_ITERATIONS?
| | +- request_user_input:
| | prompt: "Phase <N> still has <count> gaps after <max> attempts.
| | Options:
| | 1. Continue anyway - Accept and advance to next phase
| | 2. Retry once more - Increment max and try again
| | 3. Stop - Pause session"
| | -> "Continue anyway": Accept, -> advanceToNextPhase
| | -> "Retry once more": Increment max, -> triggerGapClosure
| | -> "Stop": -> pauseSession
| |
| +- NO -> progress message -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process each (same logic above) -> handleSpawnNext
+- None completed -> STOP
```
**Sub-procedure: advanceToNextPhase**
```
advanceToNextPhase:
+- Update state.md: mark current phase completed
+- current_phase < total_phases?
| +- YES:
| | +- config.mode === "interactive"?
| | | +- request_user_input:
| | | prompt: "Phase <N> complete. Proceed to phase <N+1>?
| | | Options:
| | | 1. Proceed - Dispatch next phase tasks
| | | 2. Review results - Output phase summary, re-ask
| | | 3. Stop - Pause session"
| | | -> "Proceed": Dispatch next phase tasks, -> handleSpawnNext
| | | -> "Review results": Output phase summary, re-ask
| | | -> "Stop": -> pauseSession
| | +- Auto mode: Dispatch next phase tasks directly
| | +- Update coordinates:
| | current_phase++, gap_iteration=0, step="plan"
| | +- Dispatch new phase tasks (PLAN/EXEC/VERIFY with blockedBy) to tasks.json
| | +- -> handleSpawnNext
| +- NO -> All phases done -> handleComplete
```
**Sub-procedure: triggerGapClosure**
```
triggerGapClosure:
+- Increment coordinates.gap_iteration
+- suffix = "0" + (gap_iteration + 1)
+- phase = coordinates.current_phase
+- Read gaps from verification.md
+- Log: team_msg gap_closure
+- Create gap closure task chain in tasks.json:
|
| Add to tasks.json: {
| id: "PLAN-{phase}{suffix}",
| subject: "PLAN-{phase}{suffix}: Gap closure for phase {phase} (iteration {gap_iteration})",
| status: "pending",
| owner: "planner",
| blockedBy: [],
| description: includes gap list, references to previous verification
| }
|
| Add to tasks.json: {
| id: "EXEC-{phase}{suffix}",
| subject: "EXEC-{phase}{suffix}: Execute gap fixes for phase {phase}",
| status: "pending",
| owner: "executor",
| blockedBy: ["PLAN-{phase}{suffix}"]
| }
|
| Add to tasks.json: {
| id: "VERIFY-{phase}{suffix}",
| subject: "VERIFY-{phase}{suffix}: Verify gap closure for phase {phase}",
| status: "pending",
| owner: "verifier",
| blockedBy: ["EXEC-{phase}{suffix}"]
| }
|
| Write updated tasks.json
|
+- Update coordinates.step = "gap_closure"
+- -> handleSpawnNext (picks up the new PLAN task)
```
**Sub-procedure: pauseSession**
```
pauseSession:
+- Save coordinates to meta.json (phase, step, gap_iteration)
+- Update coordinates.status = "paused"
+- Update state.md with pause marker
+- team_msg log -> session_paused
+- Output: "Session paused at phase <N>, step <step>. Resume with 'resume'."
+- STOP
```
---
### Handler: handleSpawnNext
Find all ready tasks, spawn team_worker agent, update session, STOP.
```
Read tasks from <session>/tasks.json
+- completedSubjects: status = completed
+- inProgressSubjects: status = in_progress
+- readySubjects: status = pending
AND (no blockedBy OR all blockedBy in completedSubjects)
Ready tasks found?
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing in progress:
| +- More phases to dispatch? -> advanceToNextPhase
| +- No more phases -> handleComplete
+- HAS ready tasks -> take first ready task:
+- Is task owner an Inner Loop role AND that role already has active_worker?
| +- YES -> SKIP spawn (existing worker picks it up via inner loop)
| +- NO -> normal spawn below
+- Determine role from prefix:
| PLAN-* -> planner
| EXEC-* -> executor
| VERIFY-* -> verifier
+- Update task status to "in_progress" in tasks.json
+- team_msg log -> task_unblocked (team_session_id=<session-id>)
+- Spawn team_worker (see spawn call below)
+- Add to session.active_workers
+- Update session file
+- Output: "[coordinator] Spawned <role> for <subject>"
+- STOP
```
**Spawn worker call** (one per ready task):
```
spawn_agent({
agent_type: "team_worker",
items: [{
description: "Spawn <role> worker for <subject>",
team_name: "roadmap-dev",
name: "<role>",
prompt: `## Role Assignment
role: <role>
role_spec: ~ or <project>/.codex/skills/team-roadmap-dev/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: roadmap-dev
requirement: <task-description>
inner_loop: true
## Current Task
- Task ID: <task-id>
- Task: <subject>
- Phase: <current_phase>
- Gap Iteration: <gap_iteration>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
}]
})
```
Workers report results via `report_agent_job_result()`. Coordinator receives results via `wait_agent({ ids })`.
---
### Handler: handleCheck
Read-only status report. No pipeline advancement.
**Output format**:
```
[coordinator] Roadmap Pipeline Status
[coordinator] Phase: <current>/<total> | Gap Iteration: <N>/<max>
[coordinator] Progress: <completed>/<total tasks> (<percent>%)
[coordinator] Current Phase <N> Graph:
PLAN-{N}01: <status-icon> <summary>
EXEC-{N}01: <status-icon> <summary>
VERIFY-{N}01: <status-icon> <summary>
[PLAN-{N}02: <status-icon> (gap closure #1)]
[EXEC-{N}02: <status-icon>]
[VERIFY-{N}02:<status-icon>]
done=completed >>>=running o=pending x=deleted .=not created
[coordinator] Phase Summary:
Phase 1: completed
Phase 2: in_progress (step: exec)
Phase 3: not started
[coordinator] Active Workers:
> <subject> (<role>) - running [inner-loop: N/M tasks done]
[coordinator] Ready to spawn: <subjects>
[coordinator] Coordinates: phase=<N> step=<step> gap=<iteration>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
Then STOP.
---
### Handler: handleResume
Check active worker completion, process results, advance pipeline. Also handles resume from paused state.
```
Check coordinates.status:
+- "paused" -> Restore coordinates, resume from saved position
| Reset coordinates.status = "running"
| -> handleSpawnNext (picks up where it left off)
+- "running" -> Normal resume:
Load active_workers from session
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- status = completed -> mark done, remove from active_workers, log
+- status = in_progress -> still running, log
+- other status -> worker failure -> reset to pending
After processing:
+- Some completed -> handleSpawnNext
+- All still running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleComplete
All phases done. Generate final project summary and finalize session.
```
All phases completed (no pending, no in_progress across all phases)
+- Generate project-level summary:
| - Roadmap overview (phases completed)
| - Per-phase results:
| - Gap closure iterations used
| - Verification status
| - Key deliverables
| - Overall stats (tasks completed, phases, total gap iterations)
|
+- Update session:
| coordinates.status = "complete"
| session.completed_at = <timestamp>
| Write meta.json
|
+- Update state.md: mark all phases completed
+- team_msg log -> project_complete
+- Output summary to user
+- STOP
```
---
### Worker Failure Handling
When a worker has unexpected status (not completed, not in_progress):
1. Reset task -> pending in tasks.json
2. Remove from active_workers
3. Log via team_msg (type: error)
4. Report to user: task reset, will retry on next resume
## Phase 4: State Persistence
After every handler action, before STOP:
| Check | Action |
|-------|--------|
| Coordinates updated | current_phase, step, gap_iteration reflect actual state |
| Session state consistent | active_workers matches tasks.json in_progress tasks |
| No orphaned tasks | Every in_progress task has an active_worker entry |
| Meta.json updated | Write updated session state and coordinates |
| State.md updated | Phase progress reflects actual completion |
| Completion detection | All phases done + no pending + no in_progress -> handleComplete |
```
Persist:
1. Update coordinates in meta.json
2. Reconcile active_workers with actual tasks.json states
3. Remove entries for completed/deleted tasks
4. Write updated meta.json
5. Update state.md if phase status changed
6. Verify consistency
7. STOP (wait for next callback)
```
## State Machine Diagram
```
[dispatch] -> PLAN-{N}01 spawned
|
[planner callback]
|
plan_check gate? --YES--> request_user_input --> "Revise" --> new PLAN task --> [spawn]
| "Skip" --> advanceToNextPhase
| "Proceed" / no gate
v
EXEC-{N}01 spawned
|
[executor callback]
|
v
VERIFY-{N}01 spawned
|
[verifier callback]
|
gaps found? --NO--> advanceToNextPhase
|
YES + iteration < MAX
|
v
triggerGapClosure:
PLAN-{N}02 -> EXEC-{N}02 -> VERIFY-{N}02
|
[repeat verify check]
|
gaps found? --NO--> advanceToNextPhase
|
YES + iteration >= MAX
|
v
request_user_input: "Continue anyway" / "Retry" / "Stop"
advanceToNextPhase:
+- phase < total? --YES--> interactive gate? --> dispatch phase+1 --> [spawn PLAN]
+- phase = total? --> handleComplete
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-initialization |
| Worker callback from unknown role | Log info, scan for other completions |
| All workers still running on resume | Report status, suggest check later |
| Pipeline stall (no ready, no running, has pending) | Check blockedBy chains, report to user |
| Verification file missing | Treat as gap -- verifier may have crashed, re-spawn |
| Phase dispatch fails | Check roadmap integrity, report to user |
| Max gap iterations exceeded | Ask user: continue / retry / stop |
| User chooses "Stop" at any gate | Pause session with coordinates, exit cleanly |

View File

@@ -0,0 +1,90 @@
# Command: pause
Save session state and exit cleanly. Allows resumption later via resume command.
## Purpose
Persist the current execution state (phase, step, pending tasks) to state.md so the session can be resumed from exactly where it stopped. This is the coordinator's mechanism for handling user "Stop" requests at phase boundaries or gap closure gates.
## When to Use
- User selects "Stop" at any interactive gate in monitor.md
- User requests pause during roadmap discussion
- External interruption requires graceful shutdown
## Parameters
| Parameter | Source | Description |
|-----------|--------|-------------|
| `sessionFolder` | From coordinator | Session artifact directory |
| `currentPhase` | From monitor loop | Phase number at pause time |
| `currentStep` | From monitor loop | Step within phase (plan/exec/verify/gap_closure) |
| `gapIteration` | From monitor loop | Current gap closure iteration (0 = none) |
## Execution Steps
### Step 1: Capture Current State
```javascript
const state = Read(`${sessionFolder}/state.md`)
const timestamp = new Date().toISOString().slice(0, 19)
// Capture pending task states from tasks.json
const allTasks = JSON.parse(Read(`${sessionFolder}/tasks.json`))
const pendingTasks = allTasks.filter(t =>
t.status === 'pending' || t.status === 'in_progress'
)
```
### Step 2: Update state.md with Pause Marker
```javascript
// Find the current phase status line and update it
Edit(`${sessionFolder}/state.md`, {
old_string: `- Status: in_progress`,
new_string: `- Status: paused
- Paused At: ${timestamp}
- Paused Phase: ${currentPhase}
- Paused Step: ${currentStep}
- Gap Iteration: ${gapIteration}
- Pending Tasks: ${pendingTasks.map(t => t.subject).join(', ')}`
})
```
### Step 3: Log Pause Event
```javascript
mcp__ccw-tools__team_msg({
operation: "log", session_id: sessionId,
from: "coordinator", to: "all",
type: "phase_paused",
data: { ref: `${sessionFolder}/state.md` }
})
```
### Step 4: Report to User
```javascript
// Output pause summary
const summary = `[coordinator] Session paused.
- Phase: ${currentPhase}
- Step: ${currentStep}
- Gap Iteration: ${gapIteration}
- Pending Tasks: ${pendingTasks.length}
To resume: Skill(skill="team-roadmap-dev", args="--resume ${sessionFolder}")
`
```
## Output
| Artifact | Path | Description |
|----------|------|-------------|
| state.md | `{sessionFolder}/state.md` | Updated with paused status and resume coordinates |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| state.md edit fails | Write full state.md from scratch with pause info |
| Task list unavailable | Record phase/step only, skip task listing |

View File

@@ -0,0 +1,137 @@
# Command: resume
Resume a paused roadmap-dev session from its saved state. Reads pause coordinates from state.md and re-enters the monitor loop at the exact phase and step where execution was paused.
## Purpose
Restore execution context from a paused session and continue the monitor loop. This is the coordinator's mechanism for resuming long-running projects across sessions.
## When to Use
- User invokes `Skill(skill="team-roadmap-dev", args="--resume {sessionFolder}")`
- Coordinator detects a paused session during init
## Parameters
| Parameter | Source | Description |
|-----------|--------|-------------|
| `sessionFolder` | From --resume argument | Session artifact directory to resume |
## Execution Steps
### Step 1: Validate Session State
```javascript
const stateContent = Read(`${sessionFolder}/state.md`)
// Check for paused status
if (!stateContent.includes('Status: paused')) {
// Session is not paused — check if it's in_progress or completed
if (stateContent.includes('Status: completed')) {
// Session already finished
return { error: "Session already completed", sessionFolder }
}
// Not paused, not completed — treat as fresh continue
}
// Parse resume coordinates
const pausedPhase = parseInt(stateContent.match(/Paused Phase: (\d+)/)?.[1] || '1')
const pausedStep = stateContent.match(/Paused Step: (\w+)/)?.[1] || 'plan'
const gapIteration = parseInt(stateContent.match(/Gap Iteration: (\d+)/)?.[1] || '0')
```
### Step 2: Load Session Context
```javascript
const roadmap = Read(`${sessionFolder}/roadmap.md`)
const config = JSON.parse(Read(`${sessionFolder}/config.json`))
// Load project context
const projectTech = JSON.parse(Read('.workflow/project-tech.json'))
```
### Step 3: Update State to In-Progress
```javascript
const timestamp = new Date().toISOString().slice(0, 19)
Edit(`${sessionFolder}/state.md`, {
old_string: `- Status: paused`,
new_string: `- Status: in_progress
- Resumed At: ${timestamp}
- Resumed From Phase: ${pausedPhase}, Step: ${pausedStep}`
})
```
### Step 4: Log Resume Event
```javascript
mcp__ccw-tools__team_msg({
operation: "log", session_id: sessionId,
from: "coordinator", to: "all",
type: "phase_started",
data: { ref: `${sessionFolder}/state.md` }
})
```
### Step 5: Re-enter Monitor Loop
```javascript
// Delegate to monitor.md with resume context
// monitor.md receives:
// - startPhase: pausedPhase (instead of 1)
// - startStep: pausedStep (plan/exec/verify/gap_closure)
// - gapIteration: gapIteration (for gap closure continuity)
Read("commands/monitor.md")
// Monitor will:
// 1. Skip phases before pausedPhase
// 2. Within pausedPhase, skip steps before pausedStep
// 3. Continue normal execution from that point
```
### Step 6: Determine Resume Entry Point
```javascript
// Map pausedStep to monitor entry point
switch (pausedStep) {
case 'plan':
// Re-dispatch planner for current phase
// Check if PLAN task exists and is pending/incomplete
break
case 'exec':
// Re-dispatch executor for current phase
// Check if EXEC task exists and is pending/incomplete
break
case 'verify':
// Re-dispatch verifier for current phase
break
case 'gap_closure':
// Re-enter gap closure loop at gapIteration
break
case 'transition':
// Phase was complete, proceed to next phase
break
}
```
## Output
| Artifact | Path | Description |
|----------|------|-------------|
| state.md | `{sessionFolder}/state.md` | Updated with resumed status |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session folder not found | Error with available session list |
| state.md missing | Error — session may be corrupted |
| Session not paused | Check if in_progress or completed, handle accordingly |
| Roadmap.md missing | Error — session artifacts may be incomplete |
| config.json missing | Use defaults (mode=interactive, depth=standard) |
| Tasks from prior run still pending | Re-use them, don't create duplicates |

View File

@@ -0,0 +1,243 @@
# Command: roadmap-discuss
Interactive roadmap discussion with the user. This is the KEY coordinator command -- no work begins until the roadmap is agreed upon.
## Purpose
Discuss project roadmap with the user using project-tech.json + specs/*.md as context. Elicit phases, requirements, success criteria, and execution preferences. Produces `roadmap.md` and `config.json` as session artifacts.
## When to Use
- Phase 2 of coordinator lifecycle (after init prerequisites, before dispatch)
- Called exactly once per session (re-entry updates existing roadmap)
## Strategy
Direct interaction via request_user_input. No delegation to workers or CLI tools. Coordinator handles this entirely.
## Parameters
| Parameter | Source | Description |
|-----------|--------|-------------|
| `sessionFolder` | From coordinator Phase 1 | Session artifact directory |
| `taskDescription` | From coordinator Phase 1 | User's original task description |
| `projectTech` | Loaded in Phase 1 | Parsed project-tech.json |
| `projectGuidelines` | Loaded in Phase 1 | Parsed specs/*.md (nullable) |
| `autoYes` | From -y/--yes flag | Skip interactive prompts, use defaults |
## Execution Steps
### Step 1: Load Project Context
```javascript
// Already loaded by coordinator Phase 1, but verify availability
const projectTech = JSON.parse(Read('.workflow/project-tech.json'))
let projectGuidelines = null
try {
projectGuidelines = JSON.parse(Read('.workflow/specs/*.md'))
} catch {}
```
### Step 2: Present Project Overview to User
```javascript
// Summarize what we know about the project
const overview = `[coordinator] Project context loaded.
- Project: ${projectTech.project_name}
- Tech Stack: ${projectTech.tech_stack?.join(', ')}
- Task: ${taskDescription}
${projectGuidelines ? `- Guidelines: ${projectGuidelines.conventions?.length || 0} conventions loaded` : '- Guidelines: not configured'}`
// Display overview (via direct output, not request_user_input)
```
### Step 3: Confirm Project Goal and Scope
```javascript
// Skip if taskDescription is already detailed enough, or autoYes
if (!autoYes && !taskDescription) {
request_user_input({
prompt: "What is the project goal and scope for this session?"
})
}
// Store response as `projectGoal`
const projectGoal = taskDescription || userResponse
```
### Step 4: Ask Execution Mode
```javascript
if (!autoYes) {
request_user_input({
prompt: "How should phase transitions be handled?\n\nOptions:\n1. interactive - Ask for confirmation at each phase transition\n2. yolo - Auto-execute all phases without stopping\n3. custom - Choose which gates require confirmation"
})
} else {
mode = "yolo"
}
// If "custom" selected, follow up with gate selection:
if (mode === "custom") {
request_user_input({
prompt: "Which gates should require confirmation? (select multiple)\n\n1. plan_check - Review plan before execution\n2. verifier - Review verification results before next phase\n3. gap_closure - Confirm gap closure before re-execution"
})
}
```
### Step 5: Ask Analysis Depth
```javascript
if (!autoYes) {
request_user_input({
prompt: "How thorough should the analysis be?\n\nOptions:\n1. quick - Fast scan, minimal context gathering (small tasks)\n2. standard - Balanced analysis with key context (default)\n3. comprehensive - Deep analysis, full codebase exploration (large refactors)"
})
} else {
depth = "standard"
}
```
### Step 6: Analyze Codebase and Generate Phased Roadmap
```javascript
// Use Gemini CLI (or CLI exploration tool) to analyze the codebase
// and generate a phased breakdown based on goal + project context
Bash({
command: `ccw cli -p "PURPOSE: Analyze codebase and generate phased execution roadmap for: ${projectGoal}
TASK: \
- Scan project structure and identify affected modules \
- Break goal into sequential phases (max 5) \
- Each phase: goal, requirements (REQ-IDs), success criteria (2-5 testable behaviors) \
- Order phases by dependency (foundational first)
MODE: analysis
CONTEXT: @**/* | Memory: Tech stack: ${projectTech.tech_stack?.join(', ')}
EXPECTED: Phased roadmap in markdown with REQ-IDs and testable success criteria
CONSTRAINTS: Max 5 phases | Each phase independently verifiable | No implementation details" \
--tool gemini --mode analysis --rule planning-breakdown-task-steps`,
timeout: 300000
})
// Parse the CLI output into structured phases
```
### Step 7: Present Roadmap Draft for Confirmation
```javascript
// Display the generated roadmap to user
// Output the roadmap content directly, then ask for adjustments
request_user_input({
prompt: "Review the roadmap above. Any adjustments needed?\n\nOptions:\n1. Looks good, proceed - Accept roadmap as-is\n2. Adjust phases - I want to modify the phase breakdown\n3. Add requirements - I want to add missing requirements\n4. Change scope - Narrow or expand the scope"
})
// If user requests adjustments, incorporate feedback and re-present
// Loop until user confirms "Looks good, proceed"
```
### Step 8: Generate Session Artifacts
#### roadmap.md
```javascript
Write(`${sessionFolder}/roadmap.md`, roadmapContent)
```
**roadmap.md format**:
```markdown
# Roadmap: {projectGoal}
Generated: {date}
Session: {sessionFolder}
Depth: {depth}
## Phase 1: {phase title}
**Goal**: {one-line goal}
**Requirements**:
- REQ-101: {requirement description}
- REQ-102: {requirement description}
**Success Criteria**:
- [ ] {testable behavior 1}
- [ ] {testable behavior 2}
- [ ] {testable behavior 3}
**Plan Count**: TBD
---
## Phase 2: {phase title}
**Goal**: {one-line goal}
**Requirements**:
- REQ-201: {requirement description}
**Success Criteria**:
- [ ] {testable behavior 1}
- [ ] {testable behavior 2}
**Plan Count**: TBD
---
(... additional phases ...)
```
**REQ-ID Convention**: `REQ-{phase}{seq}` (e.g., REQ-101 = Phase 1, requirement 1)
#### config.json
```javascript
Write(`${sessionFolder}/config.json`, JSON.stringify({
mode: mode, // "interactive" | "yolo" | "custom"
depth: depth, // "quick" | "standard" | "comprehensive"
auto_advance: mode === "yolo",
gates: {
plan_check: mode === "interactive" || (mode === "custom" && customGates.includes("plan_check")),
verifier: mode === "interactive" || (mode === "custom" && customGates.includes("verifier")),
gap_closure: mode === "interactive" || (mode === "custom" && customGates.includes("gap_closure"))
}
}, null, 2))
```
**config.json format**:
```json
{
"mode": "interactive",
"depth": "standard",
"auto_advance": false,
"gates": {
"plan_check": true,
"verifier": true,
"gap_closure": true
}
}
```
### Step 9: Update state.md
```javascript
Edit(`${sessionFolder}/state.md`, {
old_string: "- Phase: 0 (Roadmap Discussion)\n- Status: initializing",
new_string: `- Phase: 1\n- Status: ready_to_dispatch\n- Roadmap: confirmed (${phaseCount} phases)\n- Mode: ${mode}\n- Depth: ${depth}`
})
```
## Output
| Artifact | Path | Description |
|----------|------|-------------|
| roadmap.md | `{sessionFolder}/roadmap.md` | Phased plan with REQ-IDs and success criteria |
| config.json | `{sessionFolder}/config.json` | Execution preferences |
| state.md | `{sessionFolder}/state.md` | Updated with phase transition |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| User provides no goal | Re-prompt with examples |
| CLI analysis fails | Retry with simpler prompt, or ask user to describe phases manually |
| User keeps adjusting roadmap | Max 5 adjustment rounds, then proceed with latest version |
| autoYes flag set | Skip all request_user_input calls, use defaults: mode=yolo, depth=standard |

View File

@@ -0,0 +1,303 @@
# Coordinator Role
Orchestrate the roadmap-driven development workflow: init prerequisites -> roadmap discussion with user -> phase dispatch -> monitoring -> transitions -> completion. Coordinator is the ONLY role that interacts with humans.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Orchestration (parse requirements -> discuss roadmap -> create team -> dispatch tasks -> monitor progress -> report results)
## Boundaries
### MUST
- All outputs must carry `[coordinator]` prefix
- Handle ALL human interaction (request_user_input) -- workers never interact with user
- Ensure init prerequisites before starting (project-tech.json)
- Discuss roadmap with user before dispatching work
- Manage state.md updates at every phase transition
- Route verifier gap results to planner for closure
- Parse user requirements and clarify ambiguous inputs via request_user_input
- Create team and spawn worker team members in background
- Dispatch tasks with proper dependency chains
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence
### MUST NOT
- Execute any business tasks (code, analysis, testing, verification)
- Call CLI tools for code generation, exploration, or planning
- Modify source code or generate implementation artifacts
- Bypass worker roles to do work directly
- Skip roadmap discussion phase
- Modify task outputs (workers own their deliverables)
- Skip dependency validation when creating task chains
> **Core principle**: coordinator is the orchestrator, not the executor. All actual work must be delegated to worker roles via tasks.json entries.
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor, pause, resume):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains role tag [planner], [executor], [verifier] | -> handleCallback |
| Resume mode | Arguments contain `--resume` | -> @commands/resume.md: load session, re-enter monitor |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) |
| New session | None of above | -> Phase 1 (Init Prerequisites) |
For callback/check/resume/complete: load `@commands/monitor.md` and execute matched handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/RD-*/.msg/meta.json` for active/paused sessions
- If found, extract session folder path, status, and pipeline mode
2. **Parse $ARGUMENTS** for detection keywords:
- Check for role name tags in message content
- Check for "check", "status", "resume", "continue", "--resume" keywords
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
- For --resume: Read `@commands/resume.md`, execute resume flow
- For Phase 0: Execute Session Resume Check
- For Phase 1: Execute Init Prerequisites below
---
## Toolbox
### Available Commands
| Command | File | Phase | Description |
|---------|------|-------|-------------|
| `analyze` | [commands/analyze.md](commands/analyze.md) | Phase 1 | Detect depth/phase-count/gate signals from task description |
| `roadmap-discuss` | [commands/roadmap-discuss.md](commands/roadmap-discuss.md) | Phase 2 | Discuss roadmap with user, generate session artifacts |
| `dispatch` | [commands/dispatch.md](commands/dispatch.md) | Phase 3 | Create task chain per phase |
| `monitor` | [commands/monitor.md](commands/monitor.md) | Phase 4 | Stop-Wait phase execution loop |
| `pause` | [commands/pause.md](commands/pause.md) | Any | Save state and exit cleanly |
| `resume` | [commands/resume.md](commands/resume.md) | Any | Resume from paused session |
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `request_user_input` | Human interaction | coordinator | Clarify requirements, roadmap discussion |
| Session folder ops | Team management | coordinator | Create roadmap-dev session folder |
| `tasks.json` | Task dispatch | coordinator | Create PLAN-*, EXEC-*, VERIFY-* tasks in tasks.json |
| `wait_agent` | Worker communication | coordinator | Receive worker results |
| `report_agent_job_result` | Worker communication | workers | Report results to coordinator |
| `mcp__ccw-tools__team_msg` | Message bus | coordinator | Log all communications |
| `Read/Write` | File operations | coordinator | Session state management |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `phase_started` | coordinator -> workers | Phase dispatch | New phase initiated |
| `phase_complete` | coordinator -> user | All phase tasks done | Phase results summary |
| `gap_closure` | coordinator -> planner | Verifier found gaps | Trigger re-plan for gaps |
| `project_complete` | coordinator -> user | All phases done | Final report |
| `error` | coordinator -> user | Critical failure | Error report |
## Message Bus
Before every message exchange, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
session_id: <session-id>,
from: "coordinator",
to: <target-role>,
type: <message-type>,
data: { ref: <artifact-path> }
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --session-id <session-id> --from coordinator --type <type> --json")
```
---
## Execution (5-Phase)
### Phase 1: Init Prerequisites + Requirement Parsing
**Objective**: Ensure prerequisites and parse user requirements.
**Workflow**:
1. Parse arguments for flags: `--resume`, `--yes`, task description
2. If `--resume` present -> load @commands/resume.md and execute resume flow
3. Ensure project-tech.json exists:
| Condition | Action |
|-----------|--------|
| `.workflow/project-tech.json` exists | Continue to step 4 |
| File not found | Invoke `Skill(skill="workflow:init")` |
4. Load project context from project-tech.json
5. Create session directory: `.workflow/.team/RD-<slug>-<date>/`
6. Initialize state.md with project reference, current position, task description
**Success**: Session directory created, state.md initialized.
### Phase 2: Roadmap Discussion (via command)
**Objective**: Discuss roadmap with user and generate phase plan.
Delegate to `@commands/roadmap-discuss.md`:
| Step | Action |
|------|--------|
| 1 | Load commands/roadmap-discuss.md |
| 2 | Execute interactive discussion with user |
| 3 | Produce roadmap.md with phase requirements |
| 4 | Produce config.json with session settings |
| 5 | Update state.md with roadmap reference |
**Produces**: `<session>/roadmap.md`, `<session>/config.json`
**Command**: [commands/roadmap-discuss.md](commands/roadmap-discuss.md)
### Phase 3: Create Team + Dispatch First Phase
**Objective**: Initialize team and dispatch first phase task.
**Workflow**:
1. Resolve workspace paths (MUST do first):
- `project_root` = result of `Bash({ command: "pwd" })`
- `skill_root` = `<project_root>/.claude/skills/team-roadmap-dev`
2. Create session folder: `.workflow/.team/RD-<slug>-<date>/`
3. Initialize meta.json with pipeline metadata:
```typescript
// Use team_msg to write pipeline metadata to .msg/meta.json
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "roadmap-driven",
pipeline_stages: ["planner", "executor", "verifier"],
roles: ["coordinator", "planner", "executor", "verifier"],
team_name: "roadmap-dev"
}
})
```
4. Spawn worker roles (see SKILL.md Coordinator Spawn Template)
5. Load `@commands/dispatch.md` for task chain creation
| Step | Action |
|------|--------|
| 1 | Read roadmap.md for phase definitions |
| 2 | Create PLAN-101 task entry in tasks.json for first phase |
| 3 | Set proper owner and blockedBy dependencies in tasks.json |
| 4 | Include `Session: <session-folder>` in task description |
**Produces**: PLAN-101 task created, workers spawned
**Command**: [commands/dispatch.md](commands/dispatch.md)
### Phase 4: Coordination Loop (Stop-Wait per phase)
**Objective**: Monitor phase execution, handle callbacks, advance pipeline.
**Design**: Spawn-and-Stop + Callback pattern.
- Spawn workers with `spawn_agent()` -> immediately return
- Worker completes -> report_agent_job_result() -> coordinator receives via wait_agent() -> auto-advance
- User can use "check" / "resume" to manually advance
- Coordinator does one operation per invocation, then STOPS
Delegate to `@commands/monitor.md`:
| Step | Action |
|------|--------|
| 1 | Load commands/monitor.md |
| 2 | Find tasks with: status=pending, blockedBy all resolved |
| 3 | For each ready task -> spawn worker (see SKILL.md Spawn Template) |
| 4 | Handle worker callbacks -> advance pipeline |
| 5 | Phase complete -> transition to next phase or gap closure |
| 6 | STOP after each operation |
**Pipeline advancement** driven by three wake sources:
- Worker callback (automatic) -> handleCallback
- User "check" -> handleCheck (status only)
- User "resume" -> handleContinue (advance)
**Command**: [commands/monitor.md](commands/monitor.md)
### Phase 5: Report + Persist
**Objective**: Completion report and follow-up options.
**Workflow**:
| Step | Action |
|------|--------|
| 1 | Load session state -> count completed tasks, duration |
| 2 | List deliverables with output paths |
| 3 | Update state.md status -> "completed" |
| 4 | Offer next steps via request_user_input |
**Next step options**:
- Submit code (git add + commit)
- Continue next milestone (new roadmap discussion)
- Complete (end session)
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| project-tech.json missing | Invoke /workflow:spec:setup automatically |
| User cancels roadmap discussion | Save session state, exit gracefully |
| Planner fails | Retry once, then ask user for guidance |
| Executor fails on plan | Mark plan as failed, continue with next |
| Verifier finds gaps (<=3 iterations) | Trigger gap closure: re-plan -> re-execute -> re-verify |
| Verifier gaps persist (>3 iterations) | Report to user, ask for manual intervention |
| Worker timeout | Kill worker, report partial results |
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report to user, halt |
| Invalid mode | Reject with error, ask to clarify |
| Session corruption | Attempt recovery, fallback to manual reconciliation |

View File

@@ -0,0 +1,71 @@
---
role: executor
prefix: EXEC
inner_loop: true
cli_tools:
- gemini --mode write
message_types:
success: exec_complete
progress: exec_progress
error: error
---
# Executor
Wave-based code implementation per phase. Reads IMPL-*.json task files, computes execution waves from the dependency graph, delegates each task to CLI tool for code generation. Produces summary-{IMPL-ID}.md per task.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task JSONs | <session>/phase-{N}/.task/IMPL-*.json | Yes |
| Prior summaries | <session>/phase-{1..N-1}/summary-*.md | No |
| Wisdom | <session>/wisdom/ | No |
1. Glob `<session>/phase-{N}/.task/IMPL-*.json`, error if none found
2. Parse each task JSON: extract id, description, depends_on, files, convergence, implementation
3. Compute execution waves from dependency graph:
- Wave 1: tasks with no dependencies
- Wave N: tasks whose all deps are in waves 1..N-1
- Force-assign if circular (break at lowest-numbered task)
4. Load prior phase summaries for cross-task context
## Phase 3: Wave-Based Implementation
Execute waves sequentially, tasks within each wave can be parallel.
**Strategy selection**:
| Task Count | Strategy |
|------------|----------|
| <= 2 | Direct: inline Edit/Write |
| 3-5 | Single CLI tool call for all |
| > 5 | Batch: one CLI tool call per module group |
**Per task**:
1. Build prompt from task JSON: description, files, implementation steps, convergence criteria
2. Include prior summaries and wisdom as context
3. Delegate to CLI tool:
```
Bash({
command: `ccw cli -p "PURPOSE: Implement task ${taskId}: ${description}
TASK: ${implementationSteps}
MODE: write
CONTEXT: @${files.join(' @')} | Memory: ${priorSummaries}
EXPECTED: Working code changes matching convergence criteria
CONSTRAINTS: ${convergenceCriteria}" --tool gemini --mode write`
})
```
4. Write `<session>/phase-{N}/summary-{IMPL-ID}.md` with: task ID, affected files, changes made, status
**Between waves**: report wave progress via team_msg (type: exec_progress)
## Phase 4: Self-Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Affected files exist | `test -f <path>` for each file in summary | All present |
| TypeScript syntax | `npx tsc --noEmit` (if tsconfig.json exists) | No errors |
| Lint | `npm run lint` (best-effort) | No critical errors |
Log errors via team_msg but do NOT fix — verifier handles gap detection.

View File

@@ -0,0 +1,76 @@
---
role: planner
prefix: PLAN
inner_loop: true
cli_tools:
- gemini --mode analysis
message_types:
success: plan_ready
progress: plan_progress
error: error
---
# Planner
Research and plan creation per roadmap phase. Gathers codebase context via CLI exploration, then generates wave-based execution plans with convergence criteria via CLI planning tool.
## Phase 2: Context Loading + Research
| Input | Source | Required |
|-------|--------|----------|
| roadmap.md | <session>/roadmap.md | Yes |
| config.json | <session>/config.json | Yes |
| Prior summaries | <session>/phase-{1..N-1}/summary-*.md | No |
| Wisdom | <session>/wisdom/ | No |
1. Read roadmap.md, extract phase goal, requirements (REQ-IDs), success criteria
2. Read config.json for depth setting (quick/standard/comprehensive)
3. Load prior phase summaries for dependency context
4. Detect gap closure mode (task description contains "Gap closure")
5. Launch CLI exploration with phase requirements as exploration query:
```
Bash({
command: `ccw cli -p "PURPOSE: Explore codebase for phase requirements
TASK: • Identify files needing modification • Map patterns and dependencies • Assess test infrastructure • Identify risks
MODE: analysis
CONTEXT: @**/* | Memory: Phase goal: ${phaseGoal}
EXPECTED: Structured exploration results with file lists, patterns, risks
CONSTRAINTS: Read-only analysis" --tool gemini --mode analysis`
})
```
- Target: files needing modification, patterns, dependencies, test infrastructure, risks
6. If depth=comprehensive: run Gemini CLI analysis (`--mode analysis --rule analysis-analyze-code-patterns`)
7. Write `<session>/phase-{N}/context.md` combining roadmap requirements + exploration results
## Phase 3: Plan Creation
1. Load context.md from Phase 2
2. Create output directory: `<session>/phase-{N}/.task/`
3. Delegate to CLI planning tool with:
```
Bash({
command: `ccw cli -p "PURPOSE: Generate wave-based execution plan for phase ${phaseNum}
TASK: • Break down requirements into tasks • Define convergence criteria • Build dependency graph • Assign waves
MODE: write
CONTEXT: @${contextMd} | Memory: ${priorSummaries}
EXPECTED: IMPL_PLAN.md + IMPL-*.json files + TODO_LIST.md
CONSTRAINTS: <= 10 tasks | Valid DAG | Measurable convergence criteria" --tool gemini --mode write`
})
```
4. CLI tool produces: `IMPL_PLAN.md`, `.task/IMPL-*.json`, `TODO_LIST.md`
5. If gap closure: only create tasks for gaps, starting from next available ID
## Phase 4: Self-Validation
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Task JSON files exist | >= 1 IMPL-*.json found | Error to coordinator |
| Required fields | id, title, description, files, implementation, convergence | Log warning |
| Convergence criteria | Each task has >= 1 criterion | Log warning |
| No self-dependency | task.id not in task.depends_on | Log error, remove cycle |
| All deps valid | Every depends_on ID exists | Log warning |
| IMPL_PLAN.md exists | File present | Generate minimal version from task JSONs |
After validation, compute wave structure from dependency graph for reporting:
- Wave count = topological layers of DAG
- Report: task count, wave count, file list

View File

@@ -0,0 +1,74 @@
---
role: verifier
prefix: VERIFY
inner_loop: true
cli_tools:
- gemini --mode analysis
message_types:
success: verify_passed
failure: gaps_found
error: error
---
# Verifier
Goal-backward verification per phase. Reads convergence criteria from IMPL-*.json task files and checks against actual codebase state. Read-only — never modifies code. Produces verification.md with pass/fail and structured gap lists.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task JSONs | <session>/phase-{N}/.task/IMPL-*.json | Yes |
| Summaries | <session>/phase-{N}/summary-*.md | Yes |
| Wisdom | <session>/wisdom/ | No |
1. Glob IMPL-*.json files, extract convergence criteria from each task
2. Glob summary-*.md files, parse frontmatter (task, affects, provides)
3. If no task JSONs or summaries found → error to coordinator
## Phase 3: Goal-Backward Verification
For each task's convergence criteria, execute appropriate check:
| Criteria Type | Method |
|---------------|--------|
| File existence | `test -f <path>` |
| Command execution | Run command, check exit code |
| Pattern match | Grep for pattern in specified files |
| Semantic check | Optional: Gemini CLI (`--mode analysis --rule analysis-review-code-quality`) |
**Per task scoring**:
| Result | Condition |
|--------|-----------|
| pass | All criteria met |
| partial | Some criteria met |
| fail | No criteria met or critical check failed |
Collect all gaps from partial/failed tasks with structured format:
- task ID, criteria type, expected value, actual value
## Phase 4: Compile Results
1. Aggregate per-task results: count passed, partial, failed
2. Determine overall status:
- `passed` if gaps.length === 0
- `gaps_found` otherwise
3. Write `<session>/phase-{N}/verification.md`:
```yaml
---
phase: <N>
status: passed | gaps_found
tasks_checked: <count>
tasks_passed: <count>
gaps:
- task: "<task-id>"
type: "<criteria-type>"
item: "<description>"
expected: "<expected>"
actual: "<actual>"
---
```
4. Update .msg/meta.json with verification summary

View File

@@ -1,144 +0,0 @@
# Roadmap-Driven Development — CSV Schema
## Master CSV: tasks.csv
### Column Definitions
#### Input Columns (Set by Decomposer)
| Column | Type | Required | Description | Example |
|--------|------|----------|-------------|---------|
| `id` | string | Yes | Unique task identifier | `"PLAN-101"` |
| `title` | string | Yes | Short task title | `"Phase 1 Planning"` |
| `description` | string | Yes | Detailed task description (self-contained) | `"Research and plan for authentication module..."` |
| `deps` | string | No | Semicolon-separated dependency task IDs | `"PLAN-101"` |
| `context_from` | string | No | Semicolon-separated task IDs for context | `"PLAN-101"` |
| `exec_mode` | enum | Yes | Execution mechanism: `csv-wave` or `interactive` | `"csv-wave"` |
| `phase` | integer | Yes | Phase number (1-based) | `1` |
| `role` | enum | Yes | Role name: `planner`, `executor`, `verifier` | `"executor"` |
#### Computed Columns (Set by Wave Engine)
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `wave` | integer | Wave number (1-based, from topological sort) | `2` |
| `prev_context` | string | Aggregated findings from context_from tasks (per-wave CSV only) | `"[PLAN-101] Created implementation plan..."` |
#### Output Columns (Set by Agent)
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `status` | enum | `pending``completed` / `failed` / `skipped` | `"completed"` |
| `findings` | string | Key discoveries (max 500 chars) | `"Implemented JWT middleware in src/middleware/auth.ts..."` |
| `error` | string | Error message if failed | `""` |
---
### exec_mode Values
| Value | Mechanism | Description |
|-------|-----------|-------------|
| `csv-wave` | `spawn_agents_on_csv` | One-shot batch execution within wave |
| `interactive` | `spawn_agent`/`wait`/`send_input`/`close_agent` | Multi-round individual execution |
Interactive tasks appear in master CSV for dependency tracking but are NOT included in wave-{N}.csv files.
---
### Example Data
```csv
id,title,description,deps,context_from,exec_mode,phase,role,wave,status,findings,error
PLAN-101,Phase 1 Planning,Research and plan for authentication module,,,"interactive",1,planner,1,pending,"",""
EXEC-101,Implement auth routes,Create Express routes for login/logout/register,PLAN-101,PLAN-101,"csv-wave",1,executor,2,pending,"",""
EXEC-102,Implement JWT middleware,Create JWT token generation and validation,PLAN-101,PLAN-101,"csv-wave",1,executor,2,pending,"",""
VERIFY-101,Verify Phase 1,Test and validate phase 1 implementation,"EXEC-101;EXEC-102","EXEC-101;EXEC-102","interactive",1,verifier,3,pending,"",""
```
---
### Column Lifecycle
```
Decomposer (Phase 1) Wave Engine (Phase 2) Agent (Execution)
───────────────────── ──────────────────── ─────────────────
id ───────────► id ──────────► id
title ───────────► title ──────────► (reads)
description ───────────► description ──────────► (reads)
deps ───────────► deps ──────────► (reads)
context_from───────────► context_from──────────► (reads)
exec_mode ───────────► exec_mode ──────────► (reads)
phase ───────────► phase ──────────► (reads)
role ───────────► role ──────────► (reads)
wave ──────────► (reads)
prev_context ──────────► (reads)
status
findings
error
```
---
## Output Schema (JSON)
Agent output via `report_agent_job_result` (csv-wave tasks):
```json
{
"id": "EXEC-101",
"status": "completed",
"findings": "Implemented authentication routes in src/routes/auth.ts with login, logout, and register endpoints. Added input validation and error handling.",
"error": ""
}
```
Interactive tasks output via structured text or JSON written to `interactive/{id}-result.json`.
---
## Discovery Types
| Type | Dedup Key | Data Schema | Description |
|------|-----------|-------------|-------------|
| `file_pattern` | `pattern` | `{pattern, files[], description}` | Code patterns discovered during exploration |
| `dependency` | `from+to` | `{from, to, type}` | Module dependencies identified |
| `risk` | `description` | `{description, severity, mitigation}` | Implementation risks and concerns |
| `test_gap` | `area` | `{area, description, priority}` | Testing gaps identified during verification |
### Discovery NDJSON Format
```jsonl
{"ts":"2026-03-08T14:30:22Z","worker":"EXEC-101","type":"file_pattern","data":{"pattern":"auth middleware","files":["src/middleware/auth.ts"],"description":"JWT validation pattern"}}
{"ts":"2026-03-08T14:35:10Z","worker":"EXEC-102","type":"dependency","data":{"from":"auth.ts","to":"jwt.ts","type":"import"}}
{"ts":"2026-03-08T15:20:45Z","worker":"VERIFY-101","type":"test_gap","data":{"area":"token refresh","description":"No tests for token refresh flow","priority":"high"}}
```
> Both csv-wave and interactive agents read/write the same discoveries.ndjson file.
---
## Cross-Mechanism Context Flow
| Source | Target | Mechanism |
|--------|--------|-----------|
| CSV task findings | Interactive task | Injected via spawn message or send_input |
| Interactive task result | CSV task prev_context | Read from interactive/{id}-result.json |
| Any agent discovery | Any agent | Shared via discoveries.ndjson |
---
## Validation Rules
| Rule | Check | Error |
|------|-------|-------|
| Unique IDs | No duplicate `id` values | "Duplicate task ID: {id}" |
| Valid deps | All dep IDs exist in tasks | "Unknown dependency: {dep_id}" |
| No self-deps | Task cannot depend on itself | "Self-dependency: {id}" |
| No circular deps | Topological sort completes | "Circular dependency detected involving: {ids}" |
| context_from valid | All context IDs exist and in earlier waves | "Invalid context_from: {id}" |
| exec_mode valid | Value is `csv-wave` or `interactive` | "Invalid exec_mode: {value}" |
| Description non-empty | Every task has description | "Empty description for task: {id}" |
| Status enum | status ∈ {pending, completed, failed, skipped} | "Invalid status: {status}" |
| Cross-mechanism deps | Interactive→CSV deps resolve correctly | "Cross-mechanism dependency unresolvable: {id}" |
| Role valid | role ∈ {planner, executor, verifier} | "Invalid role: {role}" |
| Phase valid | phase >= 1 | "Invalid phase: {phase}" |

View File

@@ -0,0 +1,93 @@
# Pipeline Definitions — Team Roadmap Dev
## Pipeline Mode
### Single Phase Pipeline
```
PLAN-101 --> EXEC-101 --> VERIFY-101
[planner] [executor] [verifier]
|
gap found?
YES (< 3x)
|
PLAN-102 --> EXEC-102 --> VERIFY-102
|
gap found?
YES (>= 3x) -> AskUser: continue/retry/stop
NO -> Complete
```
### Multi-Phase Pipeline
```
Phase 1: PLAN-101 --> EXEC-101 --> VERIFY-101
|
[gap closure loop]
|
Phase 1 passed
|
Phase 2: PLAN-201 --> EXEC-201 --> VERIFY-201
|
[gap closure loop]
|
Phase 2 passed
|
Phase N: PLAN-N01 --> EXEC-N01 --> VERIFY-N01
|
[gap closure loop]
|
All phases done -> Complete
```
## Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| PLAN-N01 | planner | phase N | (none or previous VERIFY) | Context research + IMPL-*.json task generation |
| EXEC-N01 | executor | phase N | PLAN-N01 | Wave-based code implementation following IMPL-*.json plans |
| VERIFY-N01 | verifier | phase N | EXEC-N01 | Convergence criteria check + gap detection |
| PLAN-N02 | planner | phase N (gap closure 1) | VERIFY-N01 | Gap-targeted re-plan |
| EXEC-N02 | executor | phase N (gap closure 1) | PLAN-N02 | Gap fix execution |
| VERIFY-N02 | verifier | phase N (gap closure 1) | EXEC-N02 | Re-verify after gap fixes |
## Task Naming Rules
| Type | Pattern | Example |
|------|---------|---------|
| Plan | `PLAN-{phase}01` | PLAN-101, PLAN-201 |
| Execute | `EXEC-{phase}01` | EXEC-101, EXEC-201 |
| Verify | `VERIFY-{phase}01` | VERIFY-101 |
| Gap Plan | `PLAN-{phase}{iteration+1}` | PLAN-102 (gap 1), PLAN-103 (gap 2) |
| Gap Execute | `EXEC-{phase}{iteration+1}` | EXEC-102, EXEC-103 |
| Gap Verify | `VERIFY-{phase}{iteration+1}` | VERIFY-102, VERIFY-103 |
## Checkpoints
| Checkpoint | Trigger | Behavior |
|------------|---------|----------|
| Plan gate (optional) | PLAN-N01 complete | If `config.gates.plan_check=true`: AskUser to approve/revise/skip |
| Phase transition | VERIFY-N01 complete, no gaps | If `config.mode=interactive`: AskUser to proceed/review/stop |
| Gap closure | VERIFY-N01 complete, gaps found | Auto-create PLAN-N02/EXEC-N02/VERIFY-N02 (max 3 iterations) |
| Gap limit | gap_iteration >= 3 | AskUser: continue anyway / retry once more / stop |
| Pipeline complete | All phases passed | AskUser: archive & clean / keep active / export results |
## State Machine Coordinates
```json
{
"current_phase": 1,
"total_phases": 3,
"gap_iteration": 0,
"step": "plan | exec | verify | gap_closure | transition",
"status": "running | paused | complete"
}
```
## Role-Worker Map
| Prefix | Role | Role Spec | Inner Loop |
|--------|------|-----------|------------|
| PLAN | planner | `~ or <project>/.claude/skills/team-roadmap-dev/roles/planner/role.md` | true |
| EXEC | executor | `~ or <project>/.claude/skills/team-roadmap-dev/roles/executor/role.md` | true |
| VERIFY | verifier | `~ or <project>/.claude/skills/team-roadmap-dev/roles/verifier/role.md` | true |

View File

@@ -0,0 +1,95 @@
{
"team_name": "roadmap-dev",
"team_display_name": "Roadmap Dev",
"skill_name": "team-roadmap-dev",
"skill_path": "~ or <project>/.claude/skills/team-roadmap-dev/",
"design_source": "roadmap-driven development workflow design (2026-02-24)",
"pipeline_type": "Phased",
"pipeline": {
"stages": [
{ "name": "PLAN", "role": "planner", "blockedBy": [] },
{ "name": "EXEC", "role": "executor", "blockedBy": ["PLAN"] },
{ "name": "VERIFY", "role": "verifier", "blockedBy": ["EXEC"] }
],
"diagram": "Coordinator (roadmap) → PLAN → EXEC → VERIFY → Coordinator (transition)",
"gap_closure": "VERIFY fails → PLAN (gaps) → EXEC (gaps) → VERIFY (re-check), max 3 iterations"
},
"roles": [
{
"name": "coordinator",
"display_name": "RD Coordinator",
"responsibility_type": "Orchestration",
"task_prefix": null,
"description": "Human interaction, roadmap discussion, phase transitions, state management",
"commands": ["roadmap-discuss", "dispatch", "monitor", "pause", "resume"],
"message_types": ["phase_started", "phase_complete", "gap_closure", "project_complete", "error"]
},
{
"name": "planner",
"display_name": "RD Planner",
"responsibility_type": "Orchestration",
"task_prefix": "PLAN",
"description": "Research, context gathering, task JSON generation via CLI planning tool",
"commands": ["research", "create-plans"],
"cli_tools": [{"tool": "gemini", "mode": "analysis"}],
"message_types": ["plan_ready", "plan_progress", "error"]
},
{
"name": "executor",
"display_name": "RD Executor",
"responsibility_type": "Code generation",
"task_prefix": "EXEC",
"description": "Code implementation from IMPL-*.json tasks, wave-based parallel execution",
"commands": ["implement"],
"cli_tools": [{"tool": "gemini", "mode": "write"}],
"message_types": ["exec_complete", "exec_progress", "error"]
},
{
"name": "verifier",
"display_name": "RD Verifier",
"responsibility_type": "Validation",
"task_prefix": "VERIFY",
"description": "Convergence criteria verification, gap detection, fix loop trigger",
"commands": ["verify"],
"cli_tools": [{"tool": "gemini", "mode": "analysis"}],
"message_types": ["verify_passed", "gaps_found", "error"]
}
],
"artifacts": {
"fixed": {
"roadmap.md": {
"created_by": "coordinator (roadmap-discuss)",
"purpose": "Phase plan with requirements and success criteria",
"lifecycle": "Created once, updated at phase transitions"
},
"state.md": {
"created_by": "coordinator",
"purpose": "Living memory (<100 lines)",
"lifecycle": "Updated every significant action"
},
"config.json": {
"created_by": "coordinator (roadmap-discuss)",
"purpose": "Session settings: mode, depth, gates",
"lifecycle": "Created once, rarely updated"
}
},
"dynamic": {
"context.md": { "created_by": "planner (research)", "per": "phase" },
"IMPL_PLAN.md": { "created_by": "planner (create-plans)", "per": "phase", "purpose": "Implementation overview with task dependency graph" },
"IMPL-*.json": { "created_by": "planner (create-plans)", "per": "phase", "path": ".task/", "schema": "unified-flat-schema", "purpose": "Task JSON files with convergence criteria" },
"TODO_LIST.md": { "created_by": "planner (create-plans)", "per": "phase", "purpose": "Checklist tracking for all tasks" },
"summary-{ID}.md": { "created_by": "executor (implement)", "per": "task", "yaml_frontmatter": true },
"verification.md": { "created_by": "verifier (verify)", "per": "phase" }
}
},
"init_prerequisite": {
"required_files": [".workflow/project-tech.json"],
"optional_files": [".workflow/specs/*.md"],
"init_command": "/workflow:spec:setup "
},
"_metadata": {
"created_at": "2026-02-24",
"version": "1.1.0",
"based_on": "roadmap-driven development workflow design"
}
}