
Parallel Dev Cycle
- 71 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Manage parallel development cycles and multiple concurrent workstreams
About
Manages multiple parallel development cycles and concurrent workstreams. Teams use this to coordinate different parts of a system being built simultaneously and detect conflicts early.
- Parallel workflows
- Concurrent tasks
- Cycle management
Parallel Dev Cycle by the numbers
- 71 all-time installs (skills.sh)
- Ranked #1,491 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill parallel-dev-cycleAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 71 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Manage parallel development cycles and multiple concurrent workstreams
Files
Parallel Dev Cycle
Multi-agent parallel development cycle using Codex subagent pattern with four specialized workers: 1. Requirements Analysis & Extension (RA) - Requirement analysis and self-enhancement 2. Exploration & Planning (EP) - Codebase exploration and implementation planning 3. Code Development (CD) - Code development with debug strategy support 4. Validation & Archival Summary (VAS) - Validation and archival summary
Orchestration logic (phase management, state updates, feedback coordination) runs inline in the main flow — no separate orchestrator agent is spawned. Only 4 worker agents are allocated.
Each agent maintains one main document (e.g., requirements.md, plan.json, implementation.md) that is completely rewritten per iteration, plus auxiliary logs (changes.log, debug-log.ndjson) that are append-only.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ User Input (Task) │
└────────────────────────────┬────────────────────────────────┘
│
v
┌──────────────────────────────┐
│ Main Flow (Inline Orchestration) │
│ Phase 1 → 2 → 3 → 4 │
└──────────────────────────────┘
│
┌────────────────────┼────────────────────┐
│ │ │
v v v
┌────────┐ ┌────────┐ ┌────────┐
│ RA │ │ EP │ │ CD │
│Agent │ │Agent │ │Agent │
└────────┘ └────────┘ └────────┘
│ │ │
└────────────────────┼────────────────────┘
│
v
┌────────┐
│ VAS │
│ Agent │
└────────┘
│
v
┌──────────────────────────────┐
│ Summary Report │
│ & Markdown Docs │
└──────────────────────────────┘Key Design Principles
1. Main Document + Auxiliary Logs: Each agent maintains one main document (rewritten per iteration) and auxiliary logs (append-only) 2. Version-Based Overwrite: Main documents completely rewritten per version; logs append-only 3. Automatic Archival: Old main document versions automatically archived to history/ directory 4. Complete Audit Trail: Changes.log (NDJSON) preserves all change history 5. Parallel Coordination: Four agents launched simultaneously; coordination via shared state and inline main flow 6. File References: Use short file paths instead of content passing 7. Self-Enhancement: RA agent proactively extends requirements based on context 8. Shared Discovery Board: All agents share exploration findings via discoveries.ndjson — read on start, write as you discover, eliminating redundant codebase exploration
Arguments
| Arg | Required | Description |
|---|---|---|
| TASK | One of TASK or --cycle-id | Task description (for new cycle, mutually exclusive with --cycle-id) |
| --cycle-id | One of TASK or --cycle-id | Existing cycle ID to continue (from API or previous session) |
| --extend | No | Extension description (only valid with --cycle-id) |
| --auto | No | Auto-cycle mode (run all phases sequentially without user confirmation) |
| --parallel | No | Number of parallel agents (default: 4, max: 4) |
Auto Mode
When --auto: Run all phases sequentially without user confirmation between iterations. Use recommended defaults for all decisions. Automatically continue iteration loop until tests pass or max iterations reached.
Prep Package Integration
When prep-package.json exists at {projectRoot}/.workflow/.cycle/prep-package.json, Phase 1 consumes it to:
- Use refined task description instead of raw TASK
- Apply auto-iteration config (convergence criteria, phase gates)
- Inject per-iteration agent focus directives (0→1 vs 1→100)
Prep packages are generated by the interactive prompt /prompts:prep-cycle. See phases/00-prep-checklist.md for schema.
Execution Flow
Input Parsing:
└─ Parse arguments (TASK | --cycle-id + --extend)
└─ Convert to structured context (cycleId, state, progressDir)
└─ Initialize progress tracking: functions.update_plan([...phases])
Phase 1: Session Initialization
└─ Ref: phases/01-session-init.md
├─ Create new cycle OR resume existing cycle
├─ Initialize state file and directory structure
└─ Output: cycleId, state, progressDir
Phase 2: Agent Execution (Parallel)
└─ Ref: phases/02-agent-execution.md
├─ Tasks attached: Spawn RA → Spawn EP → Spawn CD → Spawn VAS → Wait all
├─ Spawn RA, EP, CD, VAS agents in parallel
├─ Wait for all agents with timeout handling
└─ Output: agentOutputs (4 agent results)
Phase 3: Result Aggregation & Iteration
└─ Ref: phases/03-result-aggregation.md
├─ Parse PHASE_RESULT from each agent
├─ Detect issues (test failures, blockers)
├─ Decision: Issues found AND iteration < max?
│ ├─ Yes → Send feedback via followup_task, loop back to Phase 2
│ └─ No → Proceed to Phase 4
└─ Output: parsedResults, iteration status
Phase 4: Completion & Summary
└─ Ref: phases/04-completion-summary.md
├─ Generate unified summary report
├─ Update final state
├─ Sync session state: $session-sync -y "Dev cycle complete: {iterations} iterations"
├─ Close all agents
└─ Output: final cycle report with continuation instructionsPhase Reference Documents (read on-demand when phase executes):
| Phase | Document | Purpose |
|---|---|---|
| 1 | phases/01-session-init.md | Session creation/resume and state initialization |
| 2 | phases/02-agent-execution.md | Parallel agent spawning and execution |
| 3 | phases/03-result-aggregation.md | Result parsing, feedback generation, iteration handling |
| 4 | phases/04-completion-summary.md | Final summary generation and cleanup |
Data Flow
User Input (TASK | --cycle-id + --extend)
↓
[Parse Arguments]
↓ cycleId, state, progressDir
Phase 1: Session Initialization
↓ cycleId, state, progressDir (initialized/resumed)
Phase 2: Agent Execution
├─ All agents read coordination/discoveries.ndjson on start
├─ Each agent explores → writes new discoveries to board
├─ Later-finishing agents benefit from earlier agents' findings
↓ agentOutputs {ra, ep, cd, vas} + shared discoveries.ndjson
Phase 3: Result Aggregation
↓ parsedResults, hasIssues, iteration count
↓ [Loop back to Phase 2 if issues and iteration < max]
↓ (discoveries.ndjson carries over across iterations)
Phase 4: Completion & Summary
↓ finalState, summaryReport
Return: cycle_id, iterations, final_stateSession Structure
{projectRoot}/.workflow/.cycle/
├── {cycleId}.json # Master state file
├── {cycleId}.progress/
├── ra/
│ ├── requirements.md # Current version (complete rewrite)
│ ├── changes.log # NDJSON complete history (append-only)
│ └── history/ # Archived snapshots
├── ep/
│ ├── exploration.md # Codebase exploration report
│ ├── architecture.md # Architecture design
│ ├── plan.json # Structured task list (current version)
│ ├── changes.log # NDJSON complete history
│ └── history/
├── cd/
│ ├── implementation.md # Current version
│ ├── debug-log.ndjson # Debug hypothesis tracking
│ ├── changes.log # NDJSON complete history
│ └── history/
├── vas/
│ ├── summary.md # Current version
│ ├── changes.log # NDJSON complete history
│ └── history/
└── coordination/
├── discoveries.ndjson # Shared discovery board (all agents append)
├── timeline.md # Execution timeline
└── decisions.log # Decision logState Management
Master state file: {projectRoot}/.workflow/.cycle/{cycleId}.json
{
"cycle_id": "cycle-v1-20260122T100000-abc123",
"title": "Task title",
"description": "Full task description",
"status": "created | running | paused | completed | failed",
"created_at": "ISO8601", "updated_at": "ISO8601",
"max_iterations": 5, "current_iteration": 0,
"agents": {
"ra": { "status": "idle | running | completed | failed", "output_files": [] },
"ep": { "status": "idle", "output_files": [] },
"cd": { "status": "idle", "output_files": [] },
"vas": { "status": "idle", "output_files": [] }
},
"current_phase": "init | ra | ep | cd | vas | aggregation | complete",
"completed_phases": [],
"requirements": null, "plan": null, "changes": [], "test_results": null,
"coordination": { "feedback_log": [], "blockers": [] }
}Recovery: If state corrupted, rebuild from .progress/ markdown files and changes.log.
Progress Tracking
Initialization (MANDATORY)
// Initialize progress tracking after input parsing
functions.update_plan([
{ id: "phase-1", title: "Phase 1: Session Initialization", status: "in_progress" },
{ id: "phase-2", title: "Phase 2: Agent Execution", status: "pending" },
{ id: "phase-3", title: "Phase 3: Result Aggregation", status: "pending" },
{ id: "phase-4", title: "Phase 4: Completion & Summary", status: "pending" }
])Phase Transitions
// After Phase 1 completes
functions.update_plan([
{ id: "phase-1", status: "completed" },
{ id: "phase-2", status: "in_progress" }
])
// After Phase 2 completes
functions.update_plan([
{ id: "phase-2", status: "completed" },
{ id: "phase-3", status: "in_progress" }
])
// After Phase 3 — iterate or complete
// If iterating back to Phase 2:
functions.update_plan([
{ id: "phase-3", status: "completed" },
{ id: "phase-2", title: "Phase 2: Agent Execution (Iteration N)", status: "in_progress" }
])
// If proceeding to Phase 4:
functions.update_plan([
{ id: "phase-3", status: "completed" },
{ id: "phase-4", status: "in_progress" }
])
// After Phase 4 completes
functions.update_plan([{ id: "phase-4", status: "completed" }])Versioning
- 1.0.0: Initial cycle → 1.x.0: Each iteration (minor bump)
- Each iteration: archive old → complete rewrite → append changes.log
Archive: copy requirements.md → history/requirements-v1.0.0.md
Rewrite: overwrite requirements.md with v1.1.0 (complete new content)
Append: changes.log ← {"timestamp","version":"1.1.0","action":"update","description":"..."}| Agent Output | Rewrite (per iteration) | Append-only |
|---|---|---|
| RA | requirements.md | changes.log |
| EP | exploration.md, architecture.md, plan.json | changes.log |
| CD | implementation.md, issues.md | changes.log, debug-log.ndjson |
| VAS | summary.md, test-results.json | changes.log |
Coordination Protocol
Execution Order: RA → EP → CD → VAS (dependency chain, all spawned in parallel but block on dependencies)
Shared Discovery Board
All agents share a real-time discovery board at coordination/discoveries.ndjson. Each agent reads it on start and appends findings during work. This eliminates redundant codebase exploration.
Lifecycle:
- Created by the first agent to write a discovery (file may not exist initially)
- Carries over across iterations — never cleared or recreated
- Agents use Bash
echo '...' >> discoveries.ndjsonto append entries
Format: NDJSON, each line is a self-contained JSON with required top-level fields ts, agent, type, data:
{"ts":"2026-01-22T10:00:00+08:00","agent":"ra","type":"tech_stack","data":{"language":"TypeScript","framework":"Express","test":"Jest","build":"tsup"}}Discovery Types:
| type | Dedup Key | Writers | Readers | Required data Fields |
|---|---|---|---|---|
tech_stack | singleton | RA | EP, CD, VAS | language, framework, test, build |
project_config | data.path | RA | EP, CD | path, key_deps[], scripts{} |
existing_feature | data.name | RA, EP | CD | name, files[], summary |
architecture | singleton | EP | CD, VAS | pattern, layers[], entry |
code_pattern | data.name | EP, CD | CD, VAS | name, description, example_file |
integration_point | data.file | EP | CD | file, description, exports[] |
similar_impl | data.feature | EP | CD | feature, files[], relevance |
code_convention | singleton | CD | VAS | naming, imports, formatting |
utility | data.name | CD | VAS | name, file, usage |
test_command | singleton | CD, VAS | VAS, CD | unit, integration(opt), coverage(opt) |
test_baseline | singleton | VAS | CD | total, passing, coverage_pct, framework, config |
test_pattern | singleton | VAS | CD | style, naming, fixtures |
blocker | data.issue | any | all | issue, severity, impact |
Protocol Rules: 1. Read board before own exploration → skip covered areas (if file doesn't exist, skip) 2. Write discoveries immediately via Bash echo >> → don't batch 3. Deduplicate — check existing entries; skip if same type + dedup key value already exists 4. Append-only — never modify or delete existing lines
Agent → Main Flow Communication
PHASE_RESULT:
- phase: ra | ep | cd | vas
- status: success | failed | partial
- files_written: [list]
- summary: one-line summary
- issues: []Main Flow → Agent Communication
Feedback via followup_task (file refs + issue summary, never full content):
## FEEDBACK FROM [Source]
[Issue summary with file:line references]
## Reference
- File: .progress/vas/test-results.json (v1.0.0)
## Actions Required
1. [Specific fix]Rules: Only main flow writes state file. Agents read state, write to own .progress/{agent}/ directory only.
Core Rules
1. Start Immediately: First action is functions.update_plan initialization, then Phase 1 execution 2. Progressive Phase Loading: Read phase docs ONLY when that phase is about to execute 3. Parse Every Output: Extract PHASE_RESULT data from each agent for next phase 4. Auto-Continue: After each phase, execute next pending phase automatically 5. Track Progress: Update functions.update_plan at each phase transition 6. Single Writer: Only main flow writes to master state file; agents report via PHASE_RESULT 7. File References: Pass file paths between agents, not content 8. DO NOT STOP: Continuous execution until all phases complete or max iterations reached
Error Handling
| Error Type | Recovery |
|---|---|
| Agent timeout | followup_task requesting convergence, then retry |
| State corrupted | Rebuild from progress markdown files and changes.log |
| Agent failed | Re-spawn agent with previous context |
| Conflicting results | Main flow sends reconciliation request |
| Missing files | RA/EP agents identify and request clarification |
| Max iterations reached | Generate summary with remaining issues documented |
Coordinator Checklist (Main Flow)
Before Each Phase
- [ ] Read phase reference document
- [ ] Check current state for dependencies
- [ ] Update
functions.update_planwith phase status
After Each Phase
- [ ] Parse agent outputs (PHASE_RESULT)
- [ ] Update master state file
- [ ] Update
functions.update_planphase completion - [ ] Determine next action (continue / iterate / complete)
Reference Documents
| Document | Purpose |
|---|---|
| roles/ | Agent role definitions (RA, EP, CD, VAS) |
Usage
# Start new cycle
/parallel-dev-cycle TASK="Implement real-time notifications"
# Continue cycle
/parallel-dev-cycle --cycle-id=cycle-v1-20260122-abc123
# Iteration with extension
/parallel-dev-cycle --cycle-id=cycle-v1-20260122-abc123 --extend="Also add email notifications"
# Auto mode
/parallel-dev-cycle --auto TASK="Add OAuth authentication"Prep Package Schema & Integration Spec
Schema definition for prep-package.json and integration points with the parallel-dev-cycle skill.
File Location
{projectRoot}/.workflow/.cycle/prep-package.jsonGenerated by: /prompts:prep-cycle (interactive prompt) Consumed by: Phase 1 (Session Initialization)
JSON Schema
{
"version": "1.0.0",
"generated_at": "ISO8601",
"prep_status": "ready | needs_refinement | blocked",
"environment": {
"project_root": "/path/to/project",
"prerequisites": {
"required_passed": true,
"recommended_passed": true,
"warnings": ["string"]
},
"tech_stack": "string (e.g. Express.js + TypeORM + PostgreSQL)",
"test_framework": "string (e.g. jest, vitest, pytest)",
"has_project_tech": true,
"has_project_guidelines": true
},
"task": {
"original": "raw user input",
"refined": "enhanced task description with all 5 dimensions",
"quality_score": 8,
"dimensions": {
"objective": { "score": 2, "value": "..." },
"success_criteria": { "score": 2, "value": "..." },
"scope": { "score": 2, "value": "..." },
"constraints": { "score": 1, "value": "..." },
"context": { "score": 1, "value": "..." }
},
"source_refs": [
{
"path": "docs/prd.md",
"type": "local_file | url | auto_detected",
"status": "verified | linked | not_found",
"preview": "first ~20 lines (local_file only)"
}
]
},
"auto_iteration": {
"enabled": true,
"no_confirmation": true,
"max_iterations": 5,
"timeout_per_iteration_ms": 1800000,
"convergence": {
"test_pass_rate": 90,
"coverage": 80,
"max_critical_bugs": 0,
"max_open_issues": 3
},
"phase_gates": {
"zero_to_one": {
"iterations": [1, 2],
"exit_criteria": {
"code_compiles": true,
"core_test_passes": true,
"min_requirements_implemented": 1
}
},
"one_to_hundred": {
"iterations": [3, 4, 5],
"exit_criteria": {
"test_pass_rate": 90,
"coverage": 80,
"critical_bugs": 0
}
}
},
"agent_focus": {
"zero_to_one": {
"ra": "core_requirements_only",
"ep": "minimal_viable_architecture",
"cd": "happy_path_first",
"vas": "smoke_tests_only"
},
"one_to_hundred": {
"ra": "full_requirements_with_nfr",
"ep": "refined_architecture_with_risks",
"cd": "complete_implementation_with_error_handling",
"vas": "full_test_suite_with_coverage"
}
}
}
}Phase 1 Integration (Consume & Check)
Phase 1 对 prep-package.json 执行 6 项验证,全部通过才加载,任一失败回退默认行为:
| # | 检查项 | 条件 | 失败处理 |
|---|---|---|---|
| 1 | prep_status | === "ready" | 跳过 prep |
| 2 | project_root | 与当前 projectRoot 一致 | 跳过 prep(防错误项目) |
| 3 | quality_score | >= 6 | 跳过 prep(任务质量不达标) |
| 4 | 时效性 | generated_at 在 24h 以内 | 跳过 prep(可能过期) |
| 5 | 必需字段 | task.refined, convergence, phase_gates, agent_focus 全部存在 | 跳过 prep |
| 6 | 收敛值合法 | test_pass_rate/coverage 为 0-100 的数字 | 跳过 prep |
// In 01-session-init.md, Step 1.1:
const prepPath = `${projectRoot}/.workflow/.cycle/prep-package.json`
if (fs.existsSync(prepPath)) {
const raw = JSON.parse(Read(prepPath))
const checks = validatePrepPackage(raw, projectRoot)
if (checks.valid) {
prepPackage = raw
task = prepPackage.task.refined
// Inject into state:
state.convergence = prepPackage.auto_iteration.convergence
state.phase_gates = prepPackage.auto_iteration.phase_gates
state.agent_focus = prepPackage.auto_iteration.agent_focus
state.max_iterations = prepPackage.auto_iteration.max_iterations
} else {
console.warn('Prep package validation failed, using defaults')
// prepPackage remains null → no convergence/phase_gates/agent_focus
}
}Phase 2 Integration (Agent Focus Directives)
// Before spawning each agent, append focus directive:
function getAgentFocusDirective(agentName, state) {
if (!state.phase_gates) return ""
const iteration = state.current_iteration
const isZeroToOne = state.phase_gates.zero_to_one.iterations.includes(iteration)
const focus = isZeroToOne
? state.agent_focus.zero_to_one[agentName]
: state.agent_focus.one_to_hundred[agentName]
const directives = {
core_requirements_only: "Focus ONLY on core functional requirements. Skip NFRs and edge cases.",
minimal_viable_architecture: "Design the simplest working architecture. Skip optimization.",
happy_path_first: "Implement ONLY the happy path. Skip error handling and edge cases.",
smoke_tests_only: "Run smoke tests only. Skip coverage analysis and exhaustive validation.",
full_requirements_with_nfr: "Complete requirements including NFRs, edge cases, security.",
refined_architecture_with_risks: "Refine architecture with risk mitigation and scalability.",
complete_implementation_with_error_handling: "Complete all tasks with error handling and validation.",
full_test_suite_with_coverage: "Full test suite with coverage report and quality audit."
}
return `\n## FOCUS DIRECTIVE (${isZeroToOne ? '0→1' : '1→100'})\n${directives[focus] || ''}\n`
}Phase 3 Integration (Convergence Evaluation)
// In 03-result-aggregation.md, Step 3.4:
function evaluateConvergence(parsedResults, state) {
if (!state.phase_gates) {
// No prep package: use default issue detection
return { converged: !parsedResults.vas.issues?.length, phase: "default" }
}
const iteration = state.current_iteration
const isZeroToOne = state.phase_gates.zero_to_one.iterations.includes(iteration)
if (isZeroToOne) {
return {
converged: parsedResults.cd.status !== 'failed'
&& (parsedResults.vas.test_pass_rate > 0 || parsedResults.cd.tests_passing),
phase: "0→1"
}
}
const conv = state.convergence
return {
converged: (parsedResults.vas.test_pass_rate || 0) >= conv.test_pass_rate
&& (parsedResults.vas.coverage || 0) >= conv.coverage
&& (parsedResults.vas.critical_issues || 0) <= conv.max_critical_bugs,
phase: "1→100"
}
}Phase 1: Session Initialization
Create or resume a development cycle, initialize state file and directory structure.
Objective
- Parse user arguments (TASK, --cycle-id, --extend, --auto, --parallel)
- Create new cycle with unique ID OR resume existing cycle
- Initialize directory structure for all agents
- Create master state file
- Output: cycleId, state, progressDir
Execution
Step 1.1: Parse Arguments & Load Prep Package
const { cycleId: existingCycleId, task, mode = 'interactive', extension } = options
// Validate mutual exclusivity
if (!existingCycleId && !task) {
console.error('Either --cycle-id or task description is required')
return { status: 'error', message: 'Missing cycleId or task' }
}
// ── Prep Package: Detect → Validate → Consume ──
let prepPackage = null
const prepPath = `${projectRoot}/.workflow/.cycle/prep-package.json`
if (fs.existsSync(prepPath)) {
const raw = JSON.parse(Read(prepPath))
const checks = validatePrepPackage(raw, projectRoot)
if (checks.valid) {
prepPackage = raw
task = prepPackage.task.refined
console.log(`✓ Prep package loaded: score=${prepPackage.task.quality_score}/10, auto=${prepPackage.auto_iteration.enabled}`)
console.log(` Checks passed: ${checks.passed.join(', ')}`)
} else {
console.warn(`⚠ Prep package found but failed validation:`)
checks.failures.forEach(f => console.warn(` ✗ ${f}`))
console.warn(` → Falling back to default behavior (prep-package ignored)`)
prepPackage = null
}
}
/**
* Validate prep-package.json integrity before consumption.
* Returns { valid: bool, passed: string[], failures: string[] }
*/
function validatePrepPackage(prep, projectRoot) {
const passed = []
const failures = []
// Check 1: prep_status must be "ready"
if (prep.prep_status === 'ready') {
passed.push('status=ready')
} else {
failures.push(`prep_status is "${prep.prep_status}", expected "ready"`)
}
// Check 2: project_root must match current project
if (prep.environment?.project_root === projectRoot) {
passed.push('project_root match')
} else {
failures.push(`project_root mismatch: prep="${prep.environment?.project_root}", current="${projectRoot}"`)
}
// Check 3: quality_score must be >= 6
if ((prep.task?.quality_score || 0) >= 6) {
passed.push(`quality=${prep.task.quality_score}/10`)
} else {
failures.push(`quality_score ${prep.task?.quality_score || 0} < 6 minimum`)
}
// Check 4: generated_at must be within 24 hours
const generatedAt = new Date(prep.generated_at)
const hoursSince = (Date.now() - generatedAt.getTime()) / (1000 * 60 * 60)
if (hoursSince <= 24) {
passed.push(`age=${Math.round(hoursSince)}h`)
} else {
failures.push(`prep-package is ${Math.round(hoursSince)}h old (max 24h), may be stale`)
}
// Check 5: required fields exist
const requiredFields = [
'task.refined',
'auto_iteration.convergence.test_pass_rate',
'auto_iteration.convergence.coverage',
'auto_iteration.phase_gates.zero_to_one',
'auto_iteration.phase_gates.one_to_hundred',
'auto_iteration.agent_focus.zero_to_one',
'auto_iteration.agent_focus.one_to_hundred'
]
const missing = requiredFields.filter(path => {
const val = path.split('.').reduce((obj, key) => obj?.[key], prep)
return val === undefined || val === null
})
if (missing.length === 0) {
passed.push('fields complete')
} else {
failures.push(`missing fields: ${missing.join(', ')}`)
}
// Check 6: convergence values are valid numbers
const conv = prep.auto_iteration?.convergence
if (conv && typeof conv.test_pass_rate === 'number' && typeof conv.coverage === 'number'
&& conv.test_pass_rate > 0 && conv.test_pass_rate <= 100
&& conv.coverage > 0 && conv.coverage <= 100) {
passed.push(`convergence valid (test≥${conv.test_pass_rate}%, cov≥${conv.coverage}%)`)
} else {
failures.push(`convergence values invalid: test_pass_rate=${conv?.test_pass_rate}, coverage=${conv?.coverage}`)
}
return {
valid: failures.length === 0,
passed,
failures
}
}Step 1.2: Utility Functions
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
function readCycleState(cycleId) {
const stateFile = `${projectRoot}/.workflow/.cycle/${cycleId}.json`
if (!fs.existsSync(stateFile)) {
return null
}
return JSON.parse(Read(stateFile))
}Step 1.3: New Cycle Creation
When TASK is provided (no --cycle-id):
// Generate unique cycle ID
const timestamp = getUtc8ISOString().replace(/[-:]/g, '').split('.')[0]
const random = Math.random().toString(36).substring(2, 10)
const cycleId = `cycle-v1-${timestamp}-${random}`
console.log(`Creating new cycle: ${cycleId}`)Create Directory Structure
mkdir -p ${projectRoot}/.workflow/.cycle/${cycleId}.progress/{ra,ep,cd,vas,coordination}
mkdir -p ${projectRoot}/.workflow/.cycle/${cycleId}.progress/ra/history
mkdir -p ${projectRoot}/.workflow/.cycle/${cycleId}.progress/ep/history
mkdir -p ${projectRoot}/.workflow/.cycle/${cycleId}.progress/cd/history
mkdir -p ${projectRoot}/.workflow/.cycle/${cycleId}.progress/vas/historyInitialize State File
function createCycleState(cycleId, taskDescription) {
const stateFile = `${projectRoot}/.workflow/.cycle/${cycleId}.json`
const now = getUtc8ISOString()
const state = {
// Metadata
cycle_id: cycleId,
title: taskDescription.substring(0, 100),
description: taskDescription,
max_iterations: prepPackage?.auto_iteration?.max_iterations || 5,
status: 'running',
created_at: now,
updated_at: now,
// Agent tracking
agents: {
ra: { status: 'idle', output_files: [] },
ep: { status: 'idle', output_files: [] },
cd: { status: 'idle', output_files: [] },
vas: { status: 'idle', output_files: [] }
},
// Phase tracking
current_phase: 'init',
completed_phases: [],
current_iteration: 0,
// Shared context (populated by agents)
requirements: null,
exploration: null,
plan: null,
changes: [],
test_results: null,
// Prep package integration (from /prompts:prep-cycle)
convergence: prepPackage?.auto_iteration?.convergence || null,
phase_gates: prepPackage?.auto_iteration?.phase_gates || null,
agent_focus: prepPackage?.auto_iteration?.agent_focus || null,
source_refs: prepPackage?.task?.source_refs || null
}
Write(stateFile, JSON.stringify(state, null, 2))
return state
}Step 1.4: Resume Existing Cycle
When --cycle-id is provided:
const cycleId = existingCycleId
const state = readCycleState(cycleId)
if (!state) {
console.error(`Cycle not found: ${cycleId}`)
return { status: 'error', message: 'Cycle not found' }
}
console.log(`Resuming cycle: ${cycleId}`)
// Apply extension if provided
if (extension) {
console.log(`Extension: ${extension}`)
state.description += `\n\n--- ITERATION ${state.current_iteration + 1} ---\n${extension}`
}Step 1.5: Control Signal Check
Before proceeding, verify cycle status allows continuation:
function checkControlSignals(cycleId) {
const state = readCycleState(cycleId)
switch (state?.status) {
case 'paused':
return { continue: false, action: 'pause_exit' }
case 'failed':
return { continue: false, action: 'stop_exit' }
case 'running':
return { continue: true, action: 'continue' }
default:
return { continue: false, action: 'stop_exit' }
}
}Output
- Variable:
cycleId- Unique cycle identifier - Variable:
state- Initialized or resumed cycle state object - Variable:
progressDir-${projectRoot}/.workflow/.cycle/${cycleId}.progress - TodoWrite: Mark Phase 1 completed, Phase 2 in_progress
Next Phase
Return to main flow, then auto-continue to Phase 2: Agent Execution.
Phase 2: Agent Execution (Parallel)
Spawn four specialized agents in parallel and wait for all to complete with timeout handling.
Objective
- Spawn RA, EP, CD, VAS agents simultaneously using Codex subagent pattern
- Pass cycle context, role references, and discovery protocol to each agent
- Wait for all agents with configurable timeout
- Handle timeout with convergence request
- Output: agentOutputs from all 4 agents
Shared Discovery Board
All agents share a discovery board at {progressDir}/coordination/discoveries.ndjson. Each agent reads it on start and writes discoveries during execution. This eliminates redundant codebase exploration across agents.
Agent reads board → skips covered areas → explores unknowns → writes new findings → other agents benefit
Discovery Protocol Snippet (injected into every agent prompt)
## SHARED DISCOVERY PROTOCOL
Board: ${progressDir}/coordination/discoveries.ndjson
**On Start**: Read board (if exists; if not, skip — you'll be the first writer).
Skip exploration for areas already covered.
**During Work**: Append discoveries as NDJSON entries via Bash `echo '...' >> discoveries.ndjson`.
**Format**: {"ts":"<ISO8601>","agent":"<role>","type":"<type>","data":{<required fields>}}
**Cross-iteration**: Board persists across iterations. Never clear it.
**You Write** (dedup key in parentheses):
- `<type>` (<dedup key>) → required data: <field1>, <field2>, ...
**You Read**: <comma-separated list of types from other agents>
**Rules**: Read before explore. Write via `echo >>`. Dedup by type+key. Append-only.Agent Role References
Each agent reads its detailed role definition at execution time:
| Agent | Role File | Main Output |
|---|---|---|
| RA | roles/requirements-analyst.md | requirements.md |
| EP | roles/exploration-planner.md | exploration.md, architecture.md, plan.json |
| CD | roles/code-developer.md | implementation.md |
| VAS | roles/validation-archivist.md | summary.md |
Execution
Step 2.1: Spawn RA Agent (Requirements Analyst)
function spawnRAAgent(cycleId, state, progressDir) {
// Build source references section from prep-package
const sourceRefsSection = (state.source_refs && state.source_refs.length > 0)
? `## REQUIREMENT SOURCE DOCUMENTS
Read these original requirement documents BEFORE analyzing the task:
${state.source_refs
.filter(r => r.status === 'verified' || r.status === 'linked')
.map((r, i) => {
if (r.type === 'local_file' || r.type === 'auto_detected') {
return `${i + 1}. **Read**: ${r.path} (${r.type})`
} else if (r.type === 'url') {
return `${i + 1}. **Reference URL**: ${r.path} (fetch if accessible)`
}
return ''
}).join('\n')}
Use these documents as the primary source of truth for requirements analysis.
Cross-reference the task description against these documents for completeness.
`
: ''
// Build focus directive from prep-package
const focusDirective = getAgentFocusDirective('ra', state)
return spawn_agent({
agent_type: "requirements_analyst",
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. Read: ${projectRoot}/.workflow/project-tech.json (if exists)
3. Read: ${projectRoot}/.workflow/specs/*.md (if exists)
4. Read: ${projectRoot}/.workflow/.cycle/${cycleId}.progress/coordination/feedback.md (if exists)
---
## SHARED DISCOVERY PROTOCOL
Board: ${progressDir}/coordination/discoveries.ndjson
**On Start**: Read board (if exists; if not, skip — you'll be the first writer). Skip exploration for areas already covered.
**During Work**: Append discoveries as NDJSON entries via Bash \`echo '...' >> discoveries.ndjson\`.
**Format**: {"ts":"<ISO8601>","agent":"ra","type":"<type>","data":{<see required fields>}}
**Cross-iteration**: Board persists across iterations. Never clear it.
**You Write** (dedup key in parentheses):
- \`tech_stack\` (singleton) → required data: language, framework, test, build
- \`project_config\` (data.path) → required data: path, key_deps[], scripts{}
- \`existing_feature\` (data.name) → required data: name, files[], summary
**You Read**: architecture, similar_impl, test_baseline, blocker
**Rules**: Read before explore. Write via \`echo >> \`. Dedup by type+key. Append-only.
---
${sourceRefsSection}
## CYCLE CONTEXT
- **Cycle ID**: ${cycleId}
- **Progress Dir**: ${progressDir}/ra/
- **Current Iteration**: ${state.current_iteration}
- **Task Description**: ${state.description}
## CURRENT REQUIREMENTS STATE
${state.requirements ? JSON.stringify(state.requirements, null, 2) : 'No previous requirements'}
## YOUR ROLE
Requirements Analyst - Analyze and refine requirements throughout the cycle.
## RESPONSIBILITIES
1. Analyze initial task description
2. Generate comprehensive requirements specification
3. Identify edge cases and implicit requirements
4. Track requirement changes across iterations
5. Maintain requirements.md and changes.log
6. **Share discoveries** to coordination/discoveries.ndjson
${focusDirective}
## DELIVERABLES
Write files to ${progressDir}/ra/:
- requirements.md: Full requirements specification
- edge-cases.md: Edge case analysis
- changes.log: NDJSON format change tracking
## OUTPUT FORMAT
\`\`\`
PHASE_RESULT:
- phase: ra
- status: success | failed
- files_written: [list]
- summary: one-line summary
- issues: []
\`\`\`
`
})
}Step 2.2: Spawn EP Agent (Exploration & Planning)
function spawnEPAgent(cycleId, state, progressDir) {
return spawn_agent({
agent_type: "exploration_planner",
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. Read: ${projectRoot}/.workflow/project-tech.json
3. Read: ${projectRoot}/.workflow/specs/*.md
4. Read: ${progressDir}/ra/requirements.md
---
## SHARED DISCOVERY PROTOCOL
Board: ${progressDir}/coordination/discoveries.ndjson
**On Start**: Read board (if exists; if not, skip — you'll be the first writer). Skip exploration for areas already covered.
**During Work**: Append discoveries as NDJSON entries via Bash \`echo '...' >> discoveries.ndjson\`.
**Format**: {"ts":"<ISO8601>","agent":"ep","type":"<type>","data":{<see required fields>}}
**Cross-iteration**: Board persists across iterations. Never clear it.
**You Write** (dedup key in parentheses):
- \`architecture\` (singleton) → required data: pattern, layers[], entry
- \`code_pattern\` (data.name) → required data: name, description, example_file
- \`integration_point\` (data.file) → required data: file, description, exports[]
- \`similar_impl\` (data.feature) → required data: feature, files[], relevance
**You Read**: tech_stack, project_config, existing_feature, test_command, test_baseline
**Rules**: Read before explore. Write via \`echo >> \`. Dedup by type+key. Append-only.
---
## CYCLE CONTEXT
- **Cycle ID**: ${cycleId}
- **Progress Dir**: ${progressDir}/ep/
- **Requirements**: See requirements.md
- **Current Plan**: ${state.plan ? 'Existing' : 'None - first iteration'}
## YOUR ROLE
Exploration & Planning Agent - Explore architecture and generate implementation plan.
## RESPONSIBILITIES
1. Explore codebase architecture
2. Map integration points
3. Design implementation approach
4. Generate plan.json with task breakdown
5. Update or iterate on existing plan
6. **Share discoveries** to coordination/discoveries.ndjson
## DELIVERABLES
Write files to ${progressDir}/ep/:
- exploration.md: Codebase exploration findings
- architecture.md: Architecture design
- plan.json: Implementation plan (structured)
## OUTPUT FORMAT
\`\`\`
PHASE_RESULT:
- phase: ep
- status: success | failed
- files_written: [list]
- summary: one-line summary
- plan_version: X.Y.Z
\`\`\`
`
})
}Step 2.3: Spawn CD Agent (Code Developer)
function spawnCDAgent(cycleId, state, progressDir) {
return spawn_agent({
agent_type: "code_developer",
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. Read: ${progressDir}/ep/plan.json
3. Read: ${progressDir}/ra/requirements.md
---
## SHARED DISCOVERY PROTOCOL
Board: ${progressDir}/coordination/discoveries.ndjson
**On Start**: Read board (if exists; if not, skip — you'll be the first writer). Skip exploration for areas already covered.
**During Work**: Append discoveries as NDJSON entries via Bash \`echo '...' >> discoveries.ndjson\`.
**Format**: {"ts":"<ISO8601>","agent":"cd","type":"<type>","data":{<see required fields>}}
**Cross-iteration**: Board persists across iterations. Never clear it.
**You Write** (dedup key in parentheses):
- \`code_convention\` (singleton) → required data: naming, imports, formatting
- \`utility\` (data.name) → required data: name, file, usage
- \`test_command\` (singleton) → required data: unit, integration(opt), coverage(opt)
- \`blocker\` (data.issue) → required data: issue, severity, impact
**You Read**: tech_stack, architecture, code_pattern, integration_point, similar_impl, test_baseline, test_command
**Rules**: Read before explore. Write via \`echo >> \`. Dedup by type+key. Append-only.
---
## CYCLE CONTEXT
- **Cycle ID**: ${cycleId}
- **Progress Dir**: ${progressDir}/cd/
- **Plan Version**: ${state.plan?.version || 'N/A'}
- **Previous Changes**: ${state.changes?.length || 0} files
## YOUR ROLE
Code Developer - Implement features based on plan and requirements.
## RESPONSIBILITIES
1. Implement features from plan
2. Track code changes
3. Handle integration issues
4. Maintain code quality
5. Report implementation progress and issues
6. **Share discoveries** to coordination/discoveries.ndjson
## DELIVERABLES
Write files to ${progressDir}/cd/:
- implementation.md: Implementation progress and decisions
- changes.log: NDJSON format, each line: {file, action, timestamp}
- issues.md: Development issues and blockers
## OUTPUT FORMAT
\`\`\`
PHASE_RESULT:
- phase: cd
- status: success | failed | partial
- files_changed: [count]
- summary: one-line summary
- blockers: []
\`\`\`
`
})
}Step 2.4: Spawn VAS Agent (Validation & Archival)
function spawnVASAgent(cycleId, state, progressDir) {
return spawn_agent({
agent_type: "validation_archivist",
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. Read: ${progressDir}/cd/changes.log
---
## SHARED DISCOVERY PROTOCOL
Board: ${progressDir}/coordination/discoveries.ndjson
**On Start**: Read board (if exists; if not, skip — you'll be the first writer). Skip exploration for areas already covered.
**During Work**: Append discoveries as NDJSON entries via Bash \`echo '...' >> discoveries.ndjson\`.
**Format**: {"ts":"<ISO8601>","agent":"vas","type":"<type>","data":{<see required fields>}}
**Cross-iteration**: Board persists across iterations. Never clear it.
**You Write** (dedup key in parentheses):
- \`test_baseline\` (singleton) → required data: total, passing, coverage_pct, framework, config
- \`test_pattern\` (singleton) → required data: style, naming, fixtures
- \`test_command\` (singleton) → required data: unit, e2e(opt), coverage(opt)
- \`blocker\` (data.issue) → required data: issue, severity, impact
**You Read**: tech_stack, architecture, code_pattern, code_convention, test_command, utility, integration_point
**Rules**: Read before explore. Write via \`echo >> \`. Dedup by type+key. Append-only.
---
## CYCLE CONTEXT
- **Cycle ID**: ${cycleId}
- **Progress Dir**: ${progressDir}/vas/
- **Changes Count**: ${state.changes?.length || 0}
- **Iteration**: ${state.current_iteration}
## YOUR ROLE
Validation & Archival Specialist - Validate quality and create documentation.
## RESPONSIBILITIES
1. Run tests on implemented features
2. Generate coverage reports
3. Create archival documentation
4. Summarize cycle results
5. Generate version history
6. **Share discoveries** to coordination/discoveries.ndjson
## DELIVERABLES
Write files to ${progressDir}/vas/:
- validation.md: Test validation results
- test-results.json: Detailed test results
- coverage.md: Coverage report
- summary.md: Cycle summary and recommendations
## OUTPUT FORMAT
\`\`\`
PHASE_RESULT:
- phase: vas
- status: success | failed
- test_pass_rate: X%
- coverage: X%
- issues: []
\`\`\`
`
})
}Step 2.5: Launch All Agents & Wait
// Spawn all 4 agents in parallel
console.log('Spawning agents...')
const agents = {
ra: spawnRAAgent(cycleId, state, progressDir),
ep: spawnEPAgent(cycleId, state, progressDir),
cd: spawnCDAgent(cycleId, state, progressDir),
vas: spawnVASAgent(cycleId, state, progressDir)
}
// Wait for all agents to complete
console.log('Waiting for all agents...')
const results = wait_agent({
timeout_ms: 1800000 // 30 minutes
})Step 2.6: Timeout Handling
if (results.timed_out) {
console.log('Some agents timed out, requesting status...')
Object.entries(agents).forEach(([name, id]) => {
if (!results.status[id].completed) {
followup_task({ target: id, message: "STATUS_CHECK: Report current progress, findings so far, and estimated remaining work." })
}
})
const statusResults = wait_agent({ timeout_ms: 180000 }) // 3 min
if (statusResults.timed_out) {
Object.entries(agents).forEach(([name, id]) => {
if (!statusResults.status[id].completed) {
followup_task({ target: id, message: "FINALIZE: Output all current findings immediately. Time limit reached.", interrupt: true })
}
})
const forcedResults = wait_agent({ timeout_ms: 180000 }) // 3 min
if (forcedResults.timed_out) {
Object.entries(agents).forEach(([name, id]) => {
if (!forcedResults.status[id].completed) {
close_agent({ target: id })
}
})
}
}
}Output
- Variable:
agents- Map of agent names to agent IDs - Variable:
results- Wait results with completion status for each agent - Variable:
agentOutputs- Collected outputs from all 4 agents - TodoWrite: Mark Phase 2 completed, Phase 3 in_progress
Next Phase
Return to main flow, then auto-continue to Phase 3: Result Aggregation & Iteration.
Phase 3: Result Aggregation & Iteration
Parse agent outputs, detect issues, generate feedback, and manage the iteration loop.
Objective
- Parse PHASE_RESULT from each agent's output
- Aggregate results into unified state
- Detect issues (test failures, blockers)
- Generate targeted feedback for affected agents
- Manage iteration loop (continue or proceed to completion)
- Output: parsedResults, iteration decision
Execution
Step 3.1: Collect Agent Outputs
// Collect outputs from all 4 agents
const agentOutputs = {
ra: results.status[agents.ra].completed,
ep: results.status[agents.ep].completed,
cd: results.status[agents.cd].completed,
vas: results.status[agents.vas].completed
}Step 3.2: Parse PHASE_RESULT
Each agent outputs a structured PHASE_RESULT block. Parse it to extract status and data:
function parseAgentOutputs(agentOutputs) {
const results = {
ra: parseOutput(agentOutputs.ra, 'ra'),
ep: parseOutput(agentOutputs.ep, 'ep'),
cd: parseOutput(agentOutputs.cd, 'cd'),
vas: parseOutput(agentOutputs.vas, 'vas')
}
return results
}
function parseOutput(output, agent) {
const result = {
agent: agent,
status: 'unknown',
data: {}
}
// Parse PHASE_RESULT block
const match = output.match(/PHASE_RESULT:\s*([\s\S]*?)(?:\n\n|$)/)
if (match) {
const lines = match[1].split('\n')
for (const line of lines) {
const m = line.match(/^-\s*(\w+):\s*(.+)$/)
if (m) {
result[m[1]] = m[2].trim()
}
}
}
return result
}Step 3.3: Update State with Results
// Update agent states
state.agents.ra.status = 'completed'
state.agents.ep.status = 'completed'
state.agents.cd.status = 'completed'
state.agents.vas.status = 'completed'
// Update shared context from parsed results
state.requirements = parsedResults.ra.requirements
state.exploration = parsedResults.ep.exploration
state.plan = parsedResults.ep.plan
state.changes = parsedResults.cd.changes
state.test_results = parsedResults.vas.test_results
state.completed_phases.push(...['ra', 'ep', 'cd', 'vas'])
state.updated_at = getUtc8ISOString()
// Persist state
Write(`${projectRoot}/.workflow/.cycle/${cycleId}.json`, JSON.stringify(state, null, 2))Step 3.4: Issue Detection
const hasIssues = parsedResults.vas.test_results?.passed === false ||
parsedResults.cd.issues?.length > 0
if (hasIssues && iteration < maxIterations) {
console.log('Issues detected, preparing for next iteration...')
// → Proceed to Step 3.5 (Feedback Generation)
} else if (!hasIssues) {
console.log('All phases completed successfully')
// → Proceed to Phase 4
} else if (iteration >= maxIterations) {
console.log(`Reached maximum iterations (${maxIterations})`)
// → Proceed to Phase 4 with issues documented
}Step 3.5: Feedback Generation
Generate targeted feedback based on issue type:
function generateFeedback(parsedResults) {
const feedback = {}
// Check VAS results → feedback to CD
if (parsedResults.vas.test_pass_rate < 100) {
feedback.cd = `
## FEEDBACK FROM VALIDATION
Test pass rate: ${parsedResults.vas.test_pass_rate}%
## ISSUES TO FIX
${parsedResults.vas.data.issues || 'See test-results.json for details'}
## NEXT STEP
Fix failing tests and update implementation.md with resolution.
`
}
// Check CD blockers → feedback to RA
if (parsedResults.cd.blockers?.length > 0) {
feedback.ra = `
## FEEDBACK FROM DEVELOPMENT
Blockers encountered:
${parsedResults.cd.blockers.map(b => `- ${b}`).join('\n')}
## NEXT STEP
Clarify requirements or identify alternative approaches.
Update requirements.md if needed.
`
}
return feedback
}Step 3.6: Send Feedback via followup_task
const feedback = generateFeedback(parsedResults)
// Send feedback to relevant agents
if (feedback.ra) {
followup_task({
target: agents.ra,
message: feedback.ra
})
}
if (feedback.cd) {
followup_task({
target: agents.cd,
message: feedback.cd
})
}
// Wait for agents to process feedback and update
const updatedResults = wait_agent({
timeout_ms: 1800000 // 30 minutes for fixes
})
console.log('Agents updated, continuing...')Step 3.7: Iteration Loop Decision
// After feedback processing, decide next action:
//
// Option A: Issues remain AND iteration < max
// → Loop back to Phase 2 (re-spawn or continue agents)
//
// Option B: No issues remaining
// → Proceed to Phase 4 (Completion)
//
// Option C: Max iterations reached
// → Proceed to Phase 4 with issues documented
if (hasIssues && iteration < maxIterations) {
// Continue iteration loop
iteration++
state.current_iteration = iteration
// → Back to Phase 2
} else {
// Exit loop → Phase 4
continueLoop = false
}Iteration Flow Diagram
Phase 2: Agent Execution
↓
Phase 3: Result Aggregation
↓
┌─ Issues detected?
│ ├─ No → Phase 4 (Complete)
│ └─ Yes
│ ├─ iteration < max?
│ │ ├─ Yes → Generate feedback → followup_task → Wait → Back to Phase 2
│ │ └─ No → Phase 4 (Complete with issues)Output
- Variable:
parsedResults- Parsed results from all 4 agents - Variable:
hasIssues- Boolean indicating if issues were found - Variable:
continueLoop- Boolean indicating if iteration should continue - TodoWrite: Mark Phase 3 completed, Phase 4 in_progress (or loop)
Next Phase
If iteration continues: Return to Phase 2. If iteration completes: Return to main flow, then auto-continue to Phase 4: Completion & Summary.
Phase 4: Completion & Summary
Generate unified summary report, update final state, close all agents, and provide continuation instructions.
Objective
- Generate comprehensive cycle summary report
- Update master state file with final status
- Close all agent sessions
- Provide continuation instructions for future iterations
- Output: final cycle report
Execution
Step 4.1: Generate Final Summary
function generateFinalSummary(cycleId, state) {
const summaryFile = `${projectRoot}/.workflow/.cycle/${cycleId}.progress/coordination/summary.md`
const summary = `# Cycle Summary - ${cycleId}
## Metadata
- Cycle ID: ${cycleId}
- Started: ${state.created_at}
- Completed: ${state.completed_at}
- Iterations: ${state.current_iteration}
- Status: ${state.status}
## Phase Results
- Requirements Analysis: ✓ Completed
- Exploration & Planning: ✓ Completed
- Code Development: ✓ Completed
- Validation & Archival: ✓ Completed
## Key Deliverables
- Requirements: ${state.requirements ? '✓' : '✗'}
- Architecture Plan: ${state.plan ? '✓' : '✗'}
- Code Changes: ${state.changes?.length || 0} files
- Test Results: ${state.test_results?.pass_rate || '0'}% passing
## Generated Files
- ${projectRoot}/.workflow/.cycle/${cycleId}.progress/ra/requirements.md
- ${projectRoot}/.workflow/.cycle/${cycleId}.progress/ep/plan.json
- ${projectRoot}/.workflow/.cycle/${cycleId}.progress/cd/changes.log
- ${projectRoot}/.workflow/.cycle/${cycleId}.progress/vas/summary.md
## Continuation Instructions
To extend this cycle:
\`\`\`bash
/parallel-dev-cycle --cycle-id=${cycleId} --extend="New requirement or feedback"
\`\`\`
This will spawn agents for iteration ${state.current_iteration + 1}.
`
Write(summaryFile, summary)
}Step 4.2: Update Final State
state.status = 'completed'
state.completed_at = getUtc8ISOString()
Write(`${projectRoot}/.workflow/.cycle/${cycleId}.json`, JSON.stringify(state, null, 2))Step 4.3: Close All Agents
Object.values(agents).forEach(id => {
try {
close_agent({ target: id })
} catch (e) {
console.warn(`Failed to close agent ${id}`)
}
})Step 4.4: Return Result
console.log('\n=== Parallel Dev Cycle Finished ===')
return {
status: 'completed',
cycle_id: cycleId,
iterations: iteration,
final_state: state
}Output
- File:
{projectRoot}/.workflow/.cycle/{cycleId}.progress/coordination/summary.md - File:
{projectRoot}/.workflow/.cycle/{cycleId}.json(final state) - TodoWrite: Mark Phase 4 completed (all tasks done)
Completion
Parallel Dev Cycle has completed. The cycle report is at {projectRoot}/.workflow/.cycle/{cycleId}.progress/coordination/summary.md.
To continue iterating:
/parallel-dev-cycle --cycle-id={cycleId} --extend="Additional requirements or feedback"Code Developer Agent (CD)
Role Definition
The Code Developer is responsible for implementing features according to the plan and requirements. This agent handles all code changes, tracks modifications, and reports issues.
Core Responsibilities
1. Implement Features
- Write code following project conventions
- Follow the implementation plan
- Ensure code quality
- Track progress
2. Handle Integration
- Integrate with existing systems
- Maintain compatibility
- Update related components
- Handle data migrations
3. Track Changes
- Document all file modifications
- Log changes in NDJSON format
- Track which iteration introduced which changes
- Update changes.log
4. Report Issues
- Document development blockers
- Identify missing requirements
- Flag integration conflicts
- Report unforeseen challenges
Key Reminders
ALWAYS:
- Follow existing code style and patterns
- Test code before submitting
- Document code changes clearly
- Track blockers and issues
- Append to changes.log, never overwrite
- Reference requirements in code comments
- Use meaningful commit messages in implementation notes
NEVER:
- Ignore linting or code quality warnings
- Make assumptions about unclear requirements
- Skip testing critical functionality
- Modify unrelated code
- Leave TODO comments without context
- Implement features not in the plan
Shared Discovery Protocol
CD agent participates in the Shared Discovery Board (coordination/discoveries.ndjson). This append-only NDJSON file enables all agents to share exploration findings in real-time, eliminating redundant codebase exploration.
Board Location & Lifecycle
- Path:
{progressDir}/coordination/discoveries.ndjson - First access: If file does not exist, skip reading — you may be the first writer. Create it on first write.
- Cross-iteration: Board carries over across iterations. Do NOT clear or recreate it. New iterations append to existing entries.
Physical Write Method
Append one NDJSON line using Bash:
echo '{"ts":"2026-01-22T11:00:00+08:00","agent":"cd","type":"code_convention","data":{"naming":"camelCase functions, PascalCase classes","imports":"absolute paths via @/ alias","formatting":"prettier with default config"}}' >> {progressDir}/coordination/discoveries.ndjsonCD Reads (from other agents)
| type | Dedup Key | Use |
|---|---|---|
tech_stack | (singleton) | Know language/framework without detection — skip project scanning |
architecture | (singleton) | Understand system layout (layers, entry point) before coding |
code_pattern | data.name | Follow existing conventions (error handling, validation, etc.) immediately |
integration_point | data.file | Know exactly which files to modify and what interfaces to match |
similar_impl | data.feature | Read reference implementations for consistency |
test_baseline | (singleton) | Know current test count/coverage before making changes |
test_command | (singleton) | Run tests directly without figuring out commands |
CD Writes (for other agents)
| type | Dedup Key | Required data Fields | When |
|---|---|---|---|
code_convention | (singleton — only 1 entry) | naming, imports, formatting | After observing naming/import/formatting patterns |
utility | data.name | name, file, usage | After finding each reusable helper function |
test_command | (singleton — only 1 entry) | unit, integration(optional), coverage(optional) | After discovering test scripts |
blocker | data.issue | issue, severity (high\ | medium\ |
Discovery Entry Format
Each line is a self-contained JSON object with exactly these top-level fields:
{"ts":"<ISO8601>","agent":"cd","type":"<type>","data":{<required fields per type>}}Protocol Rules
1. Read board first — before own exploration, read discoveries.ndjson (if exists) and skip already-covered areas 2. Write as you discover — append new findings immediately via Bash echo >>, don't batch 3. Deduplicate — check existing entries before writing; skip if same type + dedup key value already exists 4. Never modify existing lines — append-only, no edits, no deletions
---
Execution Process
Phase 1: Planning & Setup
1. Read Context
- Plan from exploration-planner.md
- Requirements from requirements-analyst.md
- Project tech stack and guidelines
2. Read Discovery Board
- Read
{progressDir}/coordination/discoveries.ndjson(if exists) - Parse entries by type — note what's already discovered
- If
tech_stack/architectureexist → skip project structure exploration - If
code_pattern/code_conventionexist → adopt conventions directly - If
integration_pointexist → know target files without searching - If
similar_implexist → read reference files for consistency - If
test_commandexist → use known commands for testing
3. Understand Project Structure (skip areas covered by board)
- Review similar existing implementations
- Understand coding conventions
- Check for relevant utilities/libraries
- Write discoveries: append
code_convention,utilityentries for new findings
4. Prepare Environment
- Create feature branch (if using git)
- Set up development environment
- Prepare test environment
Phase 2: Implementation
For each task in the plan:
1. Read Task Details
- Task description and success criteria
- Dependencies (ensure they're completed)
- Integration points
2. Implement Feature
- Write code in target files
- Follow project conventions
- Add code comments
- Reference requirements
3. Track Changes
- Log each file modification to changes.log
- Format:
{timestamp, iteration, file, action, description} - Include reason for change
4. Test Implementation
- Run unit tests
- Verify integration
- Test error cases
- Check performance
- If tests fail: Initiate Debug Workflow (see Debug Workflow section)
5. Report Progress
- Update implementation.md
- Log any issues or blockers
- Note decisions made
Debug Workflow
When tests fail during implementation, the CD agent MUST initiate the hypothesis-driven debug workflow. This workflow systematically identifies and resolves bugs through structured hypothesis testing.
Debug Triggers
| Trigger | Condition | Action |
|---|---|---|
| Test Failure | Automated tests fail during implementation | Start debug workflow |
| Integration Conflict | Blockers logged in issues.md | Start debug workflow |
| VAS Feedback | Main flow provides validation failure feedback | Start debug workflow |
Debug Workflow Phases
1. Isolate Failure
- Pinpoint the specific test or condition that is failing
- Extract exact error message and stack trace
- Identify the failing component/function
2. Formulate Hypothesis
- Generate a specific, testable hypothesis about the root cause
- Example: "Error is caused by null value passed from function X"
- Log hypothesis in
debug-log.ndjson - Prioritize hypotheses based on: error messages > recent changes > dependency relationships > edge cases
3. Design Experiment
- Determine minimal change to test hypothesis
- Options: add logging, create minimal unit test, inspect variable, add breakpoint
- Document experiment design
4. Execute & Observe
- Apply the change and run the test
- Capture inputs, actions taken, and observed outcomes
- Log structured results in
debug-log.ndjson
5. Analyze & Conclude
- Compare outcome to hypothesis
- If confirmed: Proceed to implement fix (Phase 6)
- If refuted: Log finding and formulate new hypothesis (return to Phase 2)
- If inconclusive: Refine experiment and repeat
6. Implement Fix
- Once root cause confirmed, implement necessary code changes
- Document fix rationale in implementation.md
- Log fix in changes.log
7. Verify Fix
- Run all relevant tests to ensure fix is effective
- Verify no regressions introduced
- Mark issue as resolved in issues.md
Debug Log Format (NDJSON)
File: {projectRoot}/.workflow/.cycle/{cycleId}.progress/cd/debug-log.ndjson
Schema:
{
"timestamp": "2026-01-23T10:00:00+08:00",
"iteration": 1,
"issue_id": "BUG-001",
"file": "src/auth/oauth.ts",
"hypothesis": "OAuth token refresh fails due to expired refresh_token not handled",
"action": "Added logging to capture refresh_token expiry",
"observation": "Refresh token is expired but code doesn't check expiry before use",
"outcome": "confirmed"
}Outcome values: confirmed | refuted | inconclusive
Hypothesis Priority Order
1. Direct Error Messages/Stack Traces: Most reliable starting point 2. Recent Changes: Check changes.log for recent modifications 3. Dependency Relationships: Analyze relationships between failing component and its dependencies 4. Edge Cases: Review edge-cases.md for documented edge cases
Output
Debug workflow generates an additional file:
- debug-log.ndjson: NDJSON log of all hypothesis-test cycles
Phase 3: Output
Generate files in {projectRoot}/.workflow/.cycle/{cycleId}.progress/cd/:
implementation.md:
# Implementation Progress - Version X.Y.Z
## Summary
Overview of what was implemented in this iteration.
## Completed Tasks
- ✓ TASK-001: Setup OAuth configuration
- ✓ TASK-002: Update User model
- ✓ TASK-003: Implement OAuth strategy
- ⏳ TASK-004: Create authentication endpoints (in progress)
## Key Implementation Decisions
1. Used passport-oauth2 for OAuth handling
- Rationale: Mature, well-maintained library
- Alternative considered: Manual OAuth implementation
- Chosen: passport-oauth2 (community support)
2. Stored OAuth tokens in database
- Rationale: Needed for refresh tokens
- Alternative: Client-side storage
- Chosen: Database (security)
## Code Structure
- src/config/oauth.ts - OAuth configuration
- src/strategies/oauth-google.ts - Google strategy implementation
- src/routes/auth.ts - Authentication endpoints
- src/models/User.ts - Updated User model
## Testing Status
- Unit tests: 15/15 passing
- Integration tests: 8/10 passing
- Failing: OAuth refresh token edge cases
## Next Steps
- Fix OAuth refresh token handling
- Complete integration tests
- Code review and mergechanges.log (NDJSON):
{"timestamp":"2026-01-22T10:30:00+08:00","iteration":1,"file":"src/config/oauth.ts","action":"create","task":"TASK-001","description":"Created OAuth configuration","lines_added":45,"lines_removed":0}
{"timestamp":"2026-01-22T10:45:00+08:00","iteration":1,"file":"src/models/User.ts","action":"modify","task":"TASK-002","description":"Added oauth_id and oauth_provider fields","lines_added":8,"lines_removed":0}
{"timestamp":"2026-01-22T11:15:00+08:00","iteration":1,"file":"src/strategies/oauth-google.ts","action":"create","task":"TASK-003","description":"Implemented Google OAuth strategy","lines_added":120,"lines_removed":0}issues.md:
# Development Issues - Version X.Y.Z
## Open Issues
### Issue 1: OAuth Token Refresh
- Severity: High
- Description: Refresh token logic doesn't handle expired refresh tokens
- Blocker: No, can implement fallback
- Suggested Solution: Redirect to re-authentication
### Issue 2: Database Migration
- Severity: Medium
- Description: Migration doesn't handle existing users
- Blocker: No, can use default values
- Suggested Solution: Set oauth_id = null for existing users
## Resolved Issues
- ✓ OAuth callback URL validation (fixed in commit abc123)
- ✓ CORS issues with OAuth provider (updated headers)
## Questions for RA
- Q1: Should OAuth be optional or required for login?
- Current: Optional (can still use password)
- Impact: Affects user flow designOutput Format
PHASE_RESULT:
- phase: cd
- status: success | failed | partial
- files_written: [implementation.md, changes.log, debug-log.ndjson (if debug executed), issues.md]
- summary: N tasks completed, M files modified, X blockers identified
- tasks_completed: N
- files_modified: M
- tests_passing: X/Y
- debug_cycles: Z (if debug executed)
- blockers: []
- issues: [list of open issues]Interaction with Other Agents
Receives From:
- EP (Exploration Planner): "Here's the implementation plan"
- Used to guide development
- RA (Requirements Analyst): "Requirement FR-X means..."
- Used for clarification
- Main Flow: "Fix these issues in next iteration"
- Used for priority setting
Sends To:
- VAS (Validator): "Here are code changes, ready for testing"
- Used for test generation
- RA (Requirements Analyst): "FR-X is unclear, need clarification"
- Used for requirement updates
- Main Flow: "Found blocker X, need help"
- Used for decision making
Code Quality Standards
Minimum Standards:
- Follow project linting rules
- Include error handling for all external calls
- Add comments for non-obvious code
- Reference requirements in code
- Test all happy and unhappy paths
Expected Commits Include:
- Why: Reason for change
- What: What was changed
- Testing: How was it tested
- Related: Link to requirement/task
Best Practices
1. Incremental Implementation: Complete one task fully before starting next 2. Early Testing: Test as you implement, not after 3. Clear Documentation: Document implementation decisions 4. Communication: Report blockers immediately 5. Code Review Readiness: Keep commits atomic and well-described 6. Track Progress: Update implementation.md regularly
Exploration & Planning Agent (EP)
Role Definition
The Exploration & Planning Agent is responsible for understanding the codebase architecture, identifying integration points, and generating detailed implementation plans. This agent bridges between requirements and development.
Core Responsibilities
1. Explore Codebase
- Map existing architecture
- Identify relevant modules
- Find similar implementations
- Locate integration points
2. Analyze Dependencies
- Track external dependencies
- Identify internal dependencies
- Map data flow
- Document integration interfaces
3. Design Implementation Plan
- Break down into actionable tasks
- Estimate effort levels
- Identify critical paths
- Plan task dependencies
4. Generate Architecture Design
- Component diagrams
- Integration points
- Data model considerations
- Potential risks and mitigations
Key Reminders
ALWAYS:
- Generate plan.json with structured format
- Version both exploration.md and plan.json
- Include effort estimates for each task
- Document identified risks
- Map task dependencies accurately
- Provide clear integration guidelines
NEVER:
- Plan implementation details (leave for CD agent)
- Create tasks that are too large (break into subtasks)
- Ignore existing code patterns
- Skip dependency analysis
- Forget to document risks
Shared Discovery Protocol
EP agent participates in the Shared Discovery Board (coordination/discoveries.ndjson). This append-only NDJSON file enables all agents to share exploration findings in real-time, eliminating redundant codebase exploration.
Board Location & Lifecycle
- Path:
{progressDir}/coordination/discoveries.ndjson - First access: If file does not exist, skip reading — you may be the first writer. Create it on first write.
- Cross-iteration: Board carries over across iterations. Do NOT clear or recreate it. New iterations append to existing entries.
Physical Write Method
Append one NDJSON line using Bash:
echo '{"ts":"2026-01-22T10:30:00+08:00","agent":"ep","type":"architecture","data":{"pattern":"layered","layers":["routes","services","models"],"entry":"src/index.ts"}}' >> {progressDir}/coordination/discoveries.ndjsonEP Reads (from other agents)
| type | Dedup Key | Use |
|---|---|---|
tech_stack | (singleton) | Skip tech stack detection, jump directly to architecture analysis |
project_config | data.path | Know dependencies and scripts without re-scanning config files |
existing_feature | data.name | Understand existing functionality as exploration starting points |
test_command | (singleton) | Know how to verify architectural assumptions |
test_baseline | (singleton) | Calibrate plan effort estimates based on current test coverage and pass rate |
EP Writes (for other agents)
| type | Dedup Key | Required data Fields | When |
|---|---|---|---|
architecture | (singleton — only 1 entry) | pattern, layers[], entry | After mapping overall system structure |
code_pattern | data.name | name, description, example_file | After identifying each coding convention |
integration_point | data.file | file, description, exports[] | After locating each integration target |
similar_impl | data.feature | feature, files[], relevance (high\ | medium\ |
Discovery Entry Format
Each line is a self-contained JSON object with exactly these top-level fields:
{"ts":"<ISO8601>","agent":"ep","type":"<type>","data":{<required fields per type>}}Protocol Rules
1. Read board first — before own exploration, read discoveries.ndjson (if exists) and skip already-covered areas 2. Write as you discover — append new findings immediately via Bash echo >>, don't batch 3. Deduplicate — check existing entries before writing; skip if same type + dedup key value already exists 4. Never modify existing lines — append-only, no edits, no deletions
---
Execution Process
Phase 1: Codebase Exploration
1. Read Context
- Cycle state
- Requirements from RA
- Project tech stack and guidelines
2. Read Discovery Board
- Read
{progressDir}/coordination/discoveries.ndjson(if exists) - Parse entries by type — note what's already discovered
- If
tech_stackexists → skip tech stack scanning, use shared data - If
project_configexists → skip package.json/tsconfig reading - If
existing_featureentries exist → use as exploration starting points
3. Explore Architecture (skip areas covered by board)
- Identify existing patterns and conventions
- Find similar feature implementations
- Map module boundaries
- Document current architecture
- Write discoveries: append
architecture,code_pattern,integration_point,similar_implentries to board
4. Analyze Integration Points
- Where will new code integrate?
- What interfaces need to match?
- What data models exist?
- What dependencies exist?
- Write discoveries: append
integration_pointentries for each finding
5. Generate Exploration Report
- Write
exploration.mddocumenting findings - Include architecture overview
- Document identified patterns
- List integration points and risks
Phase 2: Planning
1. Re-read Discovery Board
- Check for newly appeared entries since Phase 1 (other agents may have written)
- If
test_baselineexists → calibrate effort estimates based on current coverage/pass rate - If
blockerentries exist → factor into risk assessment and task dependencies
2. Decompose Requirements
- Convert each requirement to one or more tasks
- Identify logical grouping
- Determine task sequencing
2. Estimate Effort
- Small (< 1 hour)
- Medium (1-4 hours)
- Large (> 4 hours)
3. Map Dependencies
- Task A depends on Task B
- Identify critical path
- Plan parallel opportunities
4. Generate Plan.json
- Structured task list
- Dependencies between tasks
- Effort estimates
- Integration guidelines
Phase 3: Output
Generate files in {projectRoot}/.workflow/.cycle/{cycleId}.progress/ep/:
exploration.md:
# Codebase Exploration - Version X.Y.Z
## Architecture Overview
Current system architecture and how new code fits in.
## Existing Patterns
- Authentication: Uses JWT with middleware
- Database: PostgreSQL with TypeORM
- API: Express.js with REST conventions
- ...
## Integration Points for [Feature]
- File: src/middleware/auth.ts
- Add new OAuth strategies here
- Extend AuthProvider interface
- Update token generation logic
- File: src/models/User.ts
- Add oauth_id field
- Migrate existing users
- Update constraints
## Identified Risks
- Risk 1: OAuth token refresh complexity
- Mitigation: Use library like passport-oauth2
- Risk 2: Database migration impact
- Mitigation: Rolling deployment strategyarchitecture.md:
# Architecture Design - Version X.Y.Z
## Component Diagram
[Describe relationships between components]
## Data Model Changes
- User table: Add oauth_id, oauth_provider fields
- Sessions table: Update token structure
- ...
## API Endpoints
- POST /auth/oauth/google - Initiate OAuth
- GET /auth/oauth/callback - Handle callback
- ...
## Integration Flow
1. User clicks "Login with Google"
2. Client redirects to /auth/oauth/google
3. Server initiates Google OAuth flow
4. ... (complete flow)plan.json:
{
"version": "1.0.0",
"total_tasks": 8,
"estimated_duration": "Medium",
"tasks": [
{
"id": "TASK-001",
"title": "Setup OAuth configuration",
"description": "Create OAuth app credentials and config",
"effort": "small",
"estimated_hours": 1,
"depends_on": [],
"files": ["src/config/oauth.ts"],
"success_criteria": "Config loads without errors"
},
{
"id": "TASK-002",
"title": "Update User model",
"description": "Add oauth_id and oauth_provider fields",
"effort": "medium",
"estimated_hours": 2,
"depends_on": ["TASK-001"],
"files": ["src/models/User.ts", "migrations/*"],
"success_criteria": "Migration runs successfully"
},
{
"id": "TASK-003",
"title": "Implement OAuth strategy",
"description": "Add Google OAuth strategy",
"effort": "large",
"estimated_hours": 4,
"depends_on": ["TASK-001"],
"files": ["src/strategies/oauth-google.ts"],
"success_criteria": "OAuth flow works end-to-end"
},
{
"id": "TASK-004",
"title": "Create authentication endpoints",
"description": "POST /auth/oauth/google, GET /auth/oauth/callback",
"effort": "medium",
"estimated_hours": 3,
"depends_on": ["TASK-003"],
"files": ["src/routes/auth.ts"],
"success_criteria": "Endpoints respond correctly"
},
{
"id": "TASK-005",
"title": "Add tests for OAuth flow",
"description": "Unit and integration tests",
"effort": "large",
"estimated_hours": 4,
"depends_on": ["TASK-004"],
"files": ["tests/auth-oauth.test.ts"],
"success_criteria": "All tests passing"
},
{
"id": "TASK-006",
"title": "Update frontend login",
"description": "Add OAuth button to login page",
"effort": "small",
"estimated_hours": 1,
"depends_on": [],
"files": ["frontend/components/Login.tsx"],
"success_criteria": "Button appears and works"
},
{
"id": "TASK-007",
"title": "Documentation",
"description": "Update API docs and setup guide",
"effort": "medium",
"estimated_hours": 2,
"depends_on": ["TASK-005"],
"files": ["docs/auth.md", "docs/setup.md"],
"success_criteria": "Docs are complete and clear"
}
],
"critical_path": ["TASK-001", "TASK-003", "TASK-004", "TASK-005"],
"parallel_opportunities": [
["TASK-002", "TASK-003"],
["TASK-005", "TASK-006"]
]
}Output Format
PHASE_RESULT:
- phase: ep
- status: success | failed | partial
- files_written: [exploration.md, architecture.md, plan.json]
- summary: Architecture explored, X tasks planned, version X.Y.Z
- plan_version: X.Y.Z
- task_count: N
- critical_path_length: N
- issues: []Interaction with Other Agents
Receives From:
- RA (Requirements Analyst): "Definitive requirements, version X.Y.Z"
- Used to structure plan
- Main Flow: "Continue planning with iteration X"
- Used to update plan for extensions
Sends To:
- CD (Developer): "Here's the implementation plan"
- Used for feature implementation
- VAS (Validator): "Here's what will be implemented"
- Used for test strategy generation
Best Practices
1. Understand Existing Patterns: Follow codebase conventions 2. Realistic Estimates: Include buffer for unknowns 3. Clear Dependencies: Document why tasks depend on each other 4. Risk Identification: Don't ignore potential issues 5. Integration Guidelines: Make integration obvious for CD 6. Versioning: Update version when requirements change
Requirements Analyst Agent (RA)
Role Definition
The Requirements Analyst maintains a single file (requirements.md) containing all requirements, edge cases, and constraints. Each iteration completely rewrites the file with new version.
Core Responsibilities
1. Analyze Task Description
- Parse initial task or extension
- Decompose into functional requirements
- Identify implicit requirements
- Clarify ambiguous statements
2. Identify Edge Cases
- Scenario planning
- Boundary condition analysis
- Error handling requirements
- Performance constraints
3. Maintain Single Document
- Write complete
requirements.mdeach iteration - Include version header with previous summary
- Document all FR, NFR, edge cases in one file
- Auto-archive old version to
history/
4. Track All Changes
- Append to
changes.log(NDJSON) for audit trail - Never delete historical data
- Version-based change tracking
Key Reminders
ALWAYS:
- Complete rewrite of
requirements.mdeach iteration - Archive previous version to
history/requirements-v{version}.md - Include version header (current + previous summary)
- Append all changes to
changes.log(NDJSON) - Timestamp all actions with ISO8601 format
NEVER:
- Maintain incremental history in main document
- Delete previous versions manually (auto-archived)
- Forget to increment version number
- Skip documenting edge cases
Shared Discovery Protocol
RA agent participates in the Shared Discovery Board (coordination/discoveries.ndjson). This append-only NDJSON file enables all agents to share exploration findings in real-time, eliminating redundant codebase exploration.
Board Location & Lifecycle
- Path:
{progressDir}/coordination/discoveries.ndjson - First access: If file does not exist, skip reading — you are the first writer. Create it on first write.
- Cross-iteration: Board carries over across iterations. Do NOT clear or recreate it. New iterations append to existing entries.
Physical Write Method
Append one NDJSON line using Bash:
echo '{"ts":"2026-01-22T10:00:00+08:00","agent":"ra","type":"tech_stack","data":{"language":"TypeScript","framework":"Express","test":"Jest","build":"tsup"}}' >> {progressDir}/coordination/discoveries.ndjsonRA Reads (from other agents)
| type | Dedup Key | Use |
|---|---|---|
architecture | (singleton) | Understand system structure for requirements scoping |
similar_impl | data.feature | Identify existing features to avoid duplicate requirements |
test_baseline | (singleton) | Calibrate NFR targets (coverage, pass rate) based on current state |
blocker | data.issue | Incorporate known constraints into requirements |
RA Writes (for other agents)
| type | Dedup Key | Required data Fields | When |
|---|---|---|---|
tech_stack | (singleton — only 1 entry) | language, framework, test, build | After reading package.json / project config |
project_config | data.path | path, key_deps[], scripts{} | After scanning each project config file |
existing_feature | data.name | name, files[], summary | After identifying each existing capability |
Discovery Entry Format
Each line is a self-contained JSON object with exactly these top-level fields:
{"ts":"<ISO8601>","agent":"ra","type":"<type>","data":{<required fields per type>}}Protocol Rules
1. Read board first — before own exploration, read discoveries.ndjson (if exists) and skip already-covered areas 2. Write as you discover — append new findings immediately via Bash echo >>, don't batch 3. Deduplicate — check existing entries before writing; skip if same type + dedup key value already exists 4. Never modify existing lines — append-only, no edits, no deletions
---
Execution Process
Phase 1: Initial Analysis (v1.0.0)
1. Read Context
- Cycle state from
{projectRoot}/.workflow/.cycle/{cycleId}.json - Task description from state
- Project tech stack and guidelines
2. Read Discovery Board
- Read
{progressDir}/coordination/discoveries.ndjson(if exists) - Parse entries by type — note what's already discovered
- If
tech_stackexists → skip tech stack detection - If
existing_featureentries exist → incorporate into requirements baseline
3. Analyze Explicit Requirements
- Functional requirements from user task
- Non-functional requirements (explicit)
- Constraints and assumptions
- Edge cases
4. Write Discoveries
- Append
tech_stackentry if not already on board (from package.json, tsconfig, etc.) - Append
project_configentry with key deps and scripts - Append
existing_featureentries for each existing capability found during analysis
5. Proactive Enhancement (Self-Enhancement Phase)
- Execute enhancement strategies based on triggers
- Scan codebase for implied requirements
- Read Discovery Board again — check for
architecture,integration_point,blockerfrom EP/CD/VAS (may have appeared since step 2) - Analyze peer agent outputs (EP, CD, VAS from previous iteration)
- Suggest associated features and NFR scaffolding
6. Consolidate & Finalize
- Merge explicit requirements with proactively generated ones
- Mark enhanced items with "(ENHANCED v1.0.0 by RA)"
- Add optional "## Proactive Enhancements" section with justification
6. Generate Single File
- Write
requirements.mdv1.0.0 - Include all sections in one document
- Add version header
- Create initial
changes.logentry
Phase 2: Iteration (v1.1.0, v1.2.0, ...)
1. Archive Old Version
- Read current
requirements.md(v1.0.0) - Copy to
history/requirements-v1.0.0.md - Extract version and summary
2. Analyze Extension
- Read user feedback/extension
- Identify new requirements
- Update edge cases
- Maintain constraints
3. Rewrite Complete File
- Completely overwrite
requirements.md - New version: v1.1.0
- Include "Previous Version" summary in header
- Mark new items with "(NEW v1.1.0)"
- Update history summary table
4. Append to Changes.log
{"timestamp":"2026-01-23T10:00:00+08:00","version":"1.1.0","agent":"ra","action":"update","change":"Added MFA requirement","iteration":2}Phase 3: Output
Generate/update two files in {projectRoot}/.workflow/.cycle/{cycleId}.progress/ra/:
requirements.md (COMPLETE REWRITE):
# Requirements Specification - v1.1.0
## Document Status
| Field | Value |
|-------|-------|
| **Version** | 1.1.0 |
| **Previous Version** | 1.0.0 (Initial OAuth requirements) |
| **This Version** | Added Google OAuth support |
| **Iteration** | 2 |
| **Updated** | 2026-01-23T10:00:00+08:00 |
---
## Functional Requirements
### FR-001: OAuth Authentication
User can authenticate via OAuth providers.
**Status**: Implemented (v1.0.0), Enhanced (v1.1.0)
**Providers**: Google (NEW v1.1.0)
**Priority**: High
---
### FR-002: User Profile Creation
System creates user profile on first login.
**Status**: Defined (v1.0.0)
**Priority**: Medium
---
## Non-Functional Requirements
### NFR-001: Performance
Response time < 500ms for all OAuth flows.
**Status**: Not tested
---
### NFR-002: Scalability
Support 1000 concurrent users.
**Status**: Not tested
---
## Edge Cases
### EC-001: OAuth Timeout
**Scenario**: Provider doesn't respond in 5 seconds
**Expected**: Display error, offer retry
**Test Strategy**: Mock provider timeout
**Status**: Defined (v1.0.0)
---
### EC-002: Invalid OAuth Credentials (NEW v1.1.0)
**Scenario**: User provides invalid credentials
**Expected**: Clear error message, redirect to login
**Test Strategy**: Mock invalid credentials
**Status**: New in v1.1.0
---
## Constraints
- Must use existing JWT session management
- No new database servers
- Compatible with existing User table
---
## Assumptions
- OAuth providers are available 99.9% of time
- Users have modern browsers supporting redirects
---
## Success Criteria
- [ ] All functional requirements implemented
- [ ] All NFRs validated
- [ ] Test coverage > 80%
- [ ] Production deployment successful
---
## History Summary
| Version | Date | Summary |
|---------|------|---------|
| 1.0.0 | 2026-01-22 | Initial OAuth requirements |
| 1.1.0 | 2026-01-23 | + Google OAuth support (current) |
**Detailed History**: See `history/` directory and `changes.log`changes.log (APPEND ONLY):
{"timestamp":"2026-01-22T10:00:00+08:00","version":"1.0.0","agent":"ra","action":"create","change":"Initial requirements","iteration":1}
{"timestamp":"2026-01-23T10:00:00+08:00","version":"1.1.0","agent":"ra","action":"update","change":"Added Google OAuth support","iteration":2}Output Format
PHASE_RESULT:
- phase: ra
- status: success | failed
- version: 1.1.0
- files_written: [requirements.md, changes.log]
- archived: [history/requirements-v1.0.0.md]
- summary: Requirements updated to v1.1.0, added Google OAuth support
- requirements_count: 2
- edge_cases_count: 2
- new_items: ["FR-001 enhancement", "EC-002"]Version Management
Version Numbering
- 1.0.0: Initial cycle
- 1.x.0: Each new iteration (minor bump)
- 2.0.0: Complete rewrite (rare, major changes)
Archival Process
// Before writing new version
if (previousVersionExists) {
const oldFile = 'requirements.md'
const archiveFile = `history/requirements-v${previousVersion}.md`
Copy(oldFile, archiveFile) // Auto-archive
console.log(`Archived v${previousVersion}`)
}
// Write complete new version
Write('requirements.md', newContent) // COMPLETE OVERWRITE
// Append to audit log
appendNDJSON('changes.log', {
timestamp: now,
version: newVersion,
agent: 'ra',
action: 'update',
change: changeSummary,
iteration: currentIteration
})Interaction with Other Agents
Sends To
- EP (Explorer): "Requirements ready, see requirements.md v1.1.0"
- File reference, not full content
- CD (Developer): "Requirement FR-X clarified in v1.1.1"
- Version-specific reference
Receives From
- CD (Developer): "FR-002 is unclear, need clarification"
- Response: Update requirements.md, bump version
- User: "Add new requirement FR-003"
- Response: Rewrite requirements.md with FR-003
Best Practices
1. Single Source of Truth: One file contains everything 2. Complete Rewrites: Don't maintain incremental diffs 3. Clear Versioning: Header always shows version 4. Automatic Archival: Old versions safely stored 5. Audit Trail: Changes.log tracks every modification 6. Readability First: File should be clear and concise 7. Version Markers: Mark new items with "(NEW v1.x.0)" 8. Proactive Enhancement: Always apply self-enhancement phase
Self-Enhancement Mechanism
The RA agent proactively extends requirements based on context analysis.
Enhancement Triggers
| Trigger | Condition | Action |
|---|---|---|
| Initial Analysis | First iteration (v1.0.0) | Expand vague or high-level requests |
| Implicit Context | Key config files detected (package.json, Dockerfile, CI config) | Infer NFRs and constraints |
| Cross-Agent Feedback | Previous iteration has exploration.identified_risks, cd.blockers, or vas.test_results.failed_tests | Cover uncovered requirements |
Enhancement Strategies
1. Codebase Analysis
- Scan key project files (package.json, Dockerfile, CI/CD configs)
- Infer technological constraints and dependencies
- Identify operational requirements
- Example: Detecting
storybookdependency → suggest component-driven UI process
2. Peer Output Mining
- Analyze EP agent's
exploration.architecture_summary - Review CD agent's blockers and issues
- Examine VAS agent's
test_results.failed_tests - Formalize insights as new requirements
3. Common Feature Association
- Based on functional requirements, suggest associated features
- Example: "build user login" → suggest "password reset", "MFA"
- Mark as enhancement candidates for user confirmation
4. NFR Scaffolding
- For each major functional requirement, add standard NFRs
- Categories: Performance, Security, Scalability, Accessibility
- Set initial values as "TBD" to ensure consideration
Output Format for Enhanced Requirements
Enhanced requirements are integrated directly into requirements.md:
## Functional Requirements
### FR-001: OAuth Authentication
User can authenticate via OAuth providers.
**Status**: Defined (v1.0.0)
**Priority**: High
### FR-002: Password Reset (ENHANCED v1.0.0 by RA)
Users can reset their password via email link.
**Status**: Enhanced (auto-suggested)
**Priority**: Medium
**Trigger**: Common Feature Association (FR-001 → password reset)
---
## Proactive Enhancements
This section documents auto-generated requirements by the RA agent.
| ID | Trigger | Strategy | Justification |
|----|---------|----------|---------------|
| FR-002 | FR-001 requires login | Common Feature Association | Standard auth feature set |
| NFR-003 | package.json has `jest` | Codebase Analysis | Test framework implies testability NFR |Integration Notes
- Self-enhancement is internal to RA agent - no main flow changes needed
- Read-only access to codebase and cycle state required
- Enhanced requirements are transparently marked for user review
- User can accept, modify, or reject enhanced requirements in next iteration
Validation & Archival Agent (VAS)
Role Definition
The Validation & Archival Agent is responsible for verifying implementation quality, running tests, generating coverage reports, and creating comprehensive archival documentation for the entire cycle.
Core Responsibilities
1. Test Execution
- Run unit tests
- Run integration tests
- Generate coverage reports
- Track test results
2. Quality Validation
- Verify against requirements
- Check for edge case handling
- Validate performance
- Assess security posture
3. Documentation Generation
- Create comprehensive summary
- Document test results
- Generate coverage reports
- Create archival records
4. Iteration Feedback
- Identify failing tests
- Report coverage gaps
- Suggest fixes for failures
- Flag regression risks
Key Reminders
ALWAYS:
- Run complete test suite before validating
- Generate coverage reports with breakdowns
- Document all test results in JSON format
- Version all documents and reports
- Track which tests failed and why
- Generate actionable recommendations
- Maintain comprehensive archival records
NEVER:
- Skip tests to meet deadlines
- Ignore coverage gaps
- Delete test results or logs
- Mark tests as passing without verification
- Forget to document breaking changes
- Skip regression testing
Shared Discovery Protocol
VAS agent participates in the Shared Discovery Board (coordination/discoveries.ndjson). This append-only NDJSON file enables all agents to share exploration findings in real-time, eliminating redundant codebase exploration.
Board Location & Lifecycle
- Path:
{progressDir}/coordination/discoveries.ndjson - First access: If file does not exist, skip reading — you may be the first writer. Create it on first write.
- Cross-iteration: Board carries over across iterations. Do NOT clear or recreate it. New iterations append to existing entries.
Physical Write Method
Append one NDJSON line using Bash:
echo '{"ts":"2026-01-22T12:00:00+08:00","agent":"vas","type":"test_baseline","data":{"total":120,"passing":118,"coverage_pct":82,"framework":"jest","config":"jest.config.ts"}}' >> {progressDir}/coordination/discoveries.ndjsonVAS Reads (from other agents)
| type | Dedup Key | Use |
|---|---|---|
tech_stack | (singleton) | Know test framework without detection — skip scanning |
architecture | (singleton) | Understand system layout for validation strategy planning |
code_pattern | data.name | Know patterns to validate code against |
code_convention | (singleton) | Verify code follows naming/import conventions |
test_command | (singleton) | Run tests directly without figuring out commands |
utility | data.name | Know available validation/assertion helpers |
integration_point | data.file | Focus integration tests on known integration points |
VAS Writes (for other agents)
| type | Dedup Key | Required data Fields | When |
|---|---|---|---|
test_baseline | (singleton — only 1 entry, overwrite by appending newer) | total, passing, coverage_pct, framework, config | After running initial test suite |
test_pattern | (singleton — only 1 entry) | style, naming, fixtures | After observing test file organization |
test_command | (singleton — only 1 entry) | unit, e2e(optional), coverage(optional) | After discovering test scripts (if CD hasn't written it already) |
blocker | data.issue | issue, severity (high\ | medium\ |
Discovery Entry Format
Each line is a self-contained JSON object with exactly these top-level fields:
{"ts":"<ISO8601>","agent":"vas","type":"<type>","data":{<required fields per type>}}Protocol Rules
1. Read board first — before own exploration, read discoveries.ndjson (if exists) and skip already-covered areas 2. Write as you discover — append new findings immediately via Bash echo >>, don't batch 3. Deduplicate — check existing entries before writing; skip if same type + dedup key value already exists 4. Never modify existing lines — append-only, no edits, no deletions
---
Execution Process
Phase 1: Test Execution
1. Read Context
- Code changes from CD agent
- Requirements from RA agent
- Project tech stack and guidelines
2. Read Discovery Board
- Read
{progressDir}/coordination/discoveries.ndjson(if exists) - Parse entries by type — note what's already discovered
- If
tech_stackexists → skip test framework detection - If
test_commandexists → use known commands directly - If
architectureexists → plan validation strategy around known structure - If
code_patternexists → validate code follows known patterns - If
integration_pointexists → focus integration tests on these points
3. Prepare Test Environment
- Set up test databases (clean state)
- Configure test fixtures
- Initialize test data
4. Run Test Suites (use test_command from board if available)
- Execute unit tests
- Execute integration tests
- Execute end-to-end tests
- Run security tests if applicable
- Write discoveries: append
test_baselinewith initial results
5. Collect Results
- Test pass/fail status
- Execution time
- Error messages and stack traces
- Coverage metrics
- Write discoveries: append
test_patternif test organization discovered
Phase 2: Analysis & Validation
1. Analyze Test Results
- Calculate pass rate
- Identify failing tests
- Categorize failures (bug vs flaky)
- Track coverage
2. Verify Against Requirements
- Check FR coverage (all implemented?)
- Check NFR validation (performance OK?)
- Check edge case handling
3. Generate Reports
- Coverage analysis by module
- Test result summary
- Recommendations for fixes
- Risk assessment
Phase 3: Archival Documentation
1. Create Summary
- What was implemented
- Quality metrics
- Known issues
- Recommendations
2. Archive Results
- Store test results
- Store coverage data
- Store execution logs
- Store decision records
Phase 4: Output
Generate files in {projectRoot}/.workflow/.cycle/{cycleId}.progress/vas/:
validation.md:
# Validation Report - Version X.Y.Z
## Executive Summary
- Iteration: 1 of 1
- Status: PASSED with warnings
- Pass Rate: 92% (46/50 tests)
- Coverage: 87% (target: 80%)
- Issues: 1 critical, 2 medium
## Test Execution Summary
- Total Tests: 50
- Passed: 46
- Failed: 3
- Skipped: 1
- Duration: 2m 34s
### By Category
- Unit Tests: 25/25 passed
- Integration Tests: 18/20 passed (2 flaky)
- End-to-End: 3/5 passed (2 timeout issues)
## Coverage Report
- Overall: 87%
- src/strategies/oauth-google.ts: 95%
- src/routes/auth.ts: 82%
- src/config/oauth.ts: 100%
## Test Failures
### FAILED: OAuth token refresh with expired refresh token
- File: tests/oauth-refresh.test.ts
- Error: "Refresh token invalid"
- Root Cause: Edge case not handled in strategy
- Fix Required: Update strategy to handle invalid tokens
- Severity: Medium
### FAILED: Concurrent login attempts
- File: tests/concurrent-login.test.ts
- Error: "Race condition in session creation"
- Root Cause: Concurrent writes to user session
- Fix Required: Add mutex/lock for session writes
- Severity: Critical
## Requirements Coverage
- ✓ FR-001: User OAuth login (PASSED)
- ✓ FR-002: Multiple providers (PASSED - only Google tested)
- ⚠ FR-003: Token refresh (PARTIAL - edge cases failing)
- ✓ NFR-001: Response time < 500ms (PASSED)
- ✓ NFR-002: Handle 100 concurrent users (PASSED)
## Recommendations
1. Fix critical race condition before production
2. Improve OAuth refresh token handling
3. Add tests for multi-provider scenarios
4. Performance test with higher concurrency levels
## Issues Requiring Attention
- [ ] Fix race condition (CRITICAL)
- [ ] Handle expired refresh tokens (MEDIUM)
- [ ] Test with GitHub provider (MEDIUM)test-results.json:
{
"version": "1.0.0",
"timestamp": "2026-01-22T12:00:00+08:00",
"iteration": 1,
"summary": {
"total": 50,
"passed": 46,
"failed": 3,
"skipped": 1,
"duration_ms": 154000
},
"by_suite": [
{
"suite": "OAuth Strategy",
"tests": 15,
"passed": 14,
"failed": 1,
"tests": [
{
"name": "Google OAuth - successful login",
"status": "passed",
"duration_ms": 245
},
{
"name": "Google OAuth - invalid credentials",
"status": "passed",
"duration_ms": 198
},
{
"name": "Google OAuth - token refresh with expired token",
"status": "failed",
"duration_ms": 523,
"error": "Refresh token invalid",
"stack": "at Strategy.refresh (src/strategies/oauth-google.ts:45)"
}
]
}
],
"coverage": {
"lines": 87,
"statements": 89,
"functions": 85,
"branches": 78,
"by_file": [
{
"file": "src/strategies/oauth-google.ts",
"coverage": 95
},
{
"file": "src/routes/auth.ts",
"coverage": 82
}
]
}
}coverage.md:
# Coverage Report - Version X.Y.Z
## Overall Coverage: 87%
**Target: 80% ✓ PASSED**
## Breakdown by Module
| Module | Lines | Functions | Branches | Status |
|--------|-------|-----------|----------|--------|
| OAuth Strategy | 95% | 93% | 88% | ✓ Excellent |
| Auth Routes | 82% | 85% | 75% | ⚠ Acceptable |
| OAuth Config | 100% | 100% | 100% | ✓ Perfect |
| User Model | 78% | 80% | 70% | ⚠ Needs work |
## Uncovered Scenarios
- Error recovery in edge cases
- Multi-provider error handling
- Token revocation flow
- Concurrent request handling
## Recommendations for Improvement
1. Add tests for provider errors
2. Test token revocation edge cases
3. Add concurrency tests
4. Improve error path coveragesummary.md:
# Cycle Completion Summary - Version X.Y.Z
## Cycle Overview
- Cycle ID: cycle-v1-20260122-abc123
- Task: Implement OAuth authentication
- Duration: 2 hours 30 minutes
- Iterations: 1
## Deliverables
- ✓ Requirements specification (3 pages)
- ✓ Implementation plan (8 tasks)
- ✓ Code implementation (1,200 lines)
- ✓ Test suite (50 tests, 92% passing)
- ✓ Documentation (complete)
## Quality Metrics
| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Test Pass Rate | 92% | 90% | ✓ |
| Code Coverage | 87% | 80% | ✓ |
| Performance | 245ms avg | 500ms | ✓ |
| Requirements Met | 3/3 | 100% | ✓ |
## Known Issues
1. **CRITICAL**: Race condition in session writes
- Impact: Potential data loss under load
- Status: Requires fix before production
2. **MEDIUM**: Refresh token edge case
- Impact: Users may need to re-authenticate
- Status: Can be fixed in next iteration
## Recommended Next Steps
1. Fix critical race condition
2. Add GitHub provider support
3. Performance testing under high load
4. Security audit of OAuth flow
## Files Modified
- src/config/oauth.ts (new)
- src/strategies/oauth-google.ts (new)
- src/routes/auth.ts (modified: +50 lines)
- src/models/User.ts (modified: +8 lines)
- migrations/* (new: user schema update)
- tests/* (new: 50 test cases)
## Approval Status
- Code Review: Pending
- Requirements Met: YES
- Tests Passing: 46/50 (92%)
- **READY FOR**: Code review and fixes
## Sign-Off
- Validation Agent: VAS-001
- Timestamp: 2026-01-22T12:00:00+08:00Output Format
PHASE_RESULT:
- phase: vas
- status: success | failed | partial
- files_written: [validation.md, test-results.json, coverage.md, summary.md]
- summary: Tests executed, X% pass rate, Y% coverage, Z issues found
- test_pass_rate: X%
- coverage: Y%
- failed_tests: [list]
- critical_issues: N
- ready_for_production: true | falseInteraction with Other Agents
Receives From:
- CD (Code Developer): "Here are code changes, ready for testing"
- Used for generating test strategy
- RA (Requirements Analyst): "Here are success criteria"
- Used for validation checks
Sends To:
- CD (Developer): "These tests are failing, needs fixes"
- Used for prioritizing work
- Main Flow: "Quality report and recommendations"
- Used for final sign-off
Quality Standards
Minimum Pass Criteria:
- 90% test pass rate
- 80% code coverage
- All critical requirements implemented
- No critical bugs
Production Readiness Criteria:
- 95%+ test pass rate
- 85%+ code coverage
- Security review completed
- Performance benchmarks met
Best Practices
1. Clean Test Environment: Run tests in isolated environment 2. Consistent Metrics: Use same tools and metrics across iterations 3. Comprehensive Reporting: Document all findings clearly 4. Actionable Feedback: Provide specific fix recommendations 5. Archive Everything: Keep complete records for future reference 6. Version Control: Track report versions for audit trail