Add unit tests for various components and stores in the terminal dashboard

- Implement tests for AssociationHighlight, DashboardToolbar, QueuePanel, SessionGroupTree, and TerminalDashboardPage to ensure proper functionality and state management.
- Create tests for cliSessionStore, issueQueueIntegrationStore, queueExecutionStore, queueSchedulerStore, sessionManagerStore, and terminalGridStore to validate state resets and workspace scoping.
- Mock necessary dependencies and state management hooks to isolate tests and ensure accurate behavior.
This commit is contained in:
catlog22
2026-03-08 21:38:20 +08:00
parent 9aa07e8d01
commit 62d8aa3623
157 changed files with 36544 additions and 71 deletions

View File

@@ -0,0 +1,660 @@
---
name: team-arch-opt
description: Architecture optimization team skill. Analyzes codebase architecture, designs refactoring plans, implements changes, validates improvements, and reviews code quality via CSV wave pipeline with interactive review-fix cycles.
argument-hint: "[-y|--yes] [-c|--concurrency N] [--continue] \"architecture optimization task description\""
allowed-tools: spawn_agents_on_csv, spawn_agent, wait, send_input, close_agent, Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm task decomposition, skip interactive validation, use defaults.
# Team Architecture Optimization
## Usage
```bash
$team-arch-opt "Refactor the auth module to reduce coupling and eliminate circular dependencies"
$team-arch-opt -c 4 "Analyze and fix God Classes across the service layer"
$team-arch-opt -y "Remove dead code and clean up barrel exports in src/utils"
$team-arch-opt --continue "tao-refactor-auth-20260308"
```
**Flags**:
- `-y, --yes`: Skip all confirmations (auto mode)
- `-c, --concurrency N`: Max concurrent agents within each wave (default: 3)
- `--continue`: Resume existing session
**Output Directory**: `.workflow/.csv-wave/{session-id}/`
**Core Output**: `tasks.csv` (master state) + `results.csv` (final) + `discoveries.ndjson` (shared exploration) + `context.md` (human-readable report)
---
## Overview
Orchestrate multi-agent architecture optimization: analyze codebase structure, design refactoring plan, implement changes, validate improvements, review code quality. The pipeline has five domain roles (analyzer, designer, refactorer, validator, reviewer) mapped to CSV wave stages with an interactive review-fix cycle.
**Execution Model**: Hybrid -- CSV wave pipeline (primary) + individual agent spawn (secondary)
```
+-------------------------------------------------------------------+
| TEAM ARCHITECTURE OPTIMIZATION WORKFLOW |
+-------------------------------------------------------------------+
| |
| Phase 0: Pre-Wave Interactive (Requirement Clarification) |
| +- Parse user task description |
| +- Detect scope: targeted module vs full architecture |
| +- Clarify ambiguous requirements (AskUserQuestion) |
| +- Output: refined requirements for decomposition |
| |
| Phase 1: Requirement -> CSV + Classification |
| +- Identify architecture issues to target |
| +- Build 5-stage pipeline (analyze->design->refactor->validate |
| | +review) |
| +- Classify tasks: csv-wave | interactive (exec_mode) |
| +- Compute dependency waves (topological sort) |
| +- Generate tasks.csv with wave + exec_mode columns |
| +- User validates task breakdown (skip if -y) |
| |
| Phase 2: Wave Execution Engine (Extended) |
| +- For each wave (1..N): |
| | +- Execute pre-wave interactive tasks (if any) |
| | +- Build wave CSV (filter csv-wave tasks for this wave) |
| | +- Inject previous findings into prev_context column |
| | +- spawn_agents_on_csv(wave CSV) |
| | +- Execute post-wave interactive tasks (if any) |
| | +- Merge all results into master tasks.csv |
| | +- Check: any failed? -> skip dependents |
| +- discoveries.ndjson shared across all modes (append-only) |
| +- Review-fix cycle: max 3 iterations per branch |
| |
| Phase 3: Post-Wave Interactive (Completion Action) |
| +- Pipeline completion report with improvement metrics |
| +- Interactive completion choice (Archive/Keep/Export) |
| +- Final aggregation / report |
| |
| Phase 4: Results Aggregation |
| +- Export final results.csv |
| +- Generate context.md with all findings |
| +- Display summary: completed/failed/skipped per wave |
| +- Offer: view results | retry failed | done |
| |
+-------------------------------------------------------------------+
```
---
## Pipeline Definition
```
Stage 1 Stage 2 Stage 3 Stage 4
ANALYZE-001 --> DESIGN-001 --> REFACTOR-001 --> VALIDATE-001
[analyzer] [designer] [refactorer] [validator]
^ |
+<-- FIX-001 ----+
| REVIEW-001
+<--------> [reviewer]
(max 3 iterations)
```
---
## Task Classification Rules
Each task is classified by `exec_mode`:
| exec_mode | Mechanism | Criteria |
|-----------|-----------|----------|
| `csv-wave` | `spawn_agents_on_csv` | One-shot, structured I/O, no multi-round interaction |
| `interactive` | `spawn_agent`/`wait`/`send_input`/`close_agent` | Multi-round, revision cycles, user checkpoints |
**Classification Decision**:
| Task Property | Classification |
|---------------|---------------|
| Architecture analysis (single-pass scan) | `csv-wave` |
| Refactoring plan design (single-pass) | `csv-wave` |
| Code refactoring implementation | `csv-wave` |
| Validation (build, test, metrics) | `csv-wave` |
| Code review (single-pass) | `csv-wave` |
| Review-fix cycle (iterative revision) | `interactive` |
| User checkpoint (plan approval) | `interactive` |
| Discussion round (DISCUSS-REFACTOR, DISCUSS-REVIEW) | `interactive` |
---
## CSV Schema
### tasks.csv (Master State)
```csv
id,title,description,role,issue_type,priority,target_files,deps,context_from,exec_mode,wave,status,findings,verdict,artifacts_produced,error
"ANALYZE-001","Analyze architecture","Analyze codebase architecture to identify structural issues: cycles, coupling, cohesion, God Classes, dead code, API bloat. Produce baseline metrics and ranked report.","analyzer","","","","","","csv-wave","1","pending","","","",""
"DESIGN-001","Design refactoring plan","Analyze architecture report to design prioritized refactoring plan with strategies, expected improvements, and risk assessments.","designer","","","","ANALYZE-001","ANALYZE-001","csv-wave","2","pending","","","",""
"REFACTOR-001","Implement refactorings","Implement architecture refactoring changes following design plan in priority order (P0 first).","refactorer","","","","DESIGN-001","DESIGN-001","csv-wave","3","pending","","","",""
"VALIDATE-001","Validate changes","Validate refactoring: build checks, test suite, dependency metrics, API compatibility.","validator","","","","REFACTOR-001","REFACTOR-001","csv-wave","4","pending","","PASS","",""
"REVIEW-001","Review refactoring code","Review refactoring changes for correctness, patterns, completeness, migration safety, best practices.","reviewer","","","","REFACTOR-001","REFACTOR-001","csv-wave","4","pending","","APPROVE","",""
```
**Columns**:
| Column | Phase | Description |
|--------|-------|-------------|
| `id` | Input | Unique task identifier (PREFIX-NNN format) |
| `title` | Input | Short task title |
| `description` | Input | Detailed task description (self-contained) |
| `role` | Input | Worker role: analyzer, designer, refactorer, validator, reviewer |
| `issue_type` | Input | Architecture issue category: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT |
| `priority` | Input | P0 (Critical), P1 (High), P2 (Medium), P3 (Low) |
| `target_files` | Input | Semicolon-separated file paths to focus on |
| `deps` | Input | Semicolon-separated dependency task IDs |
| `context_from` | Input | Semicolon-separated task IDs whose findings this task needs |
| `exec_mode` | Input | `csv-wave` or `interactive` |
| `wave` | Computed | Wave number (computed by topological sort, 1-based) |
| `status` | Output | `pending` -> `completed` / `failed` / `skipped` |
| `findings` | Output | Key discoveries or implementation notes (max 500 chars) |
| `verdict` | Output | Validation/review verdict: PASS, WARN, FAIL, APPROVE, REVISE, REJECT |
| `artifacts_produced` | Output | Semicolon-separated paths of produced artifacts |
| `error` | Output | Error message if failed (empty if success) |
### Per-Wave CSV (Temporary)
Each wave generates a temporary `wave-{N}.csv` with extra `prev_context` column (csv-wave tasks only).
---
## Agent Registry (Interactive Agents)
| Agent | Role File | Pattern | Responsibility | Position |
|-------|-----------|---------|----------------|----------|
| Plan Reviewer | agents/plan-reviewer.md | 2.3 (send_input cycle) | Review architecture report or refactoring plan at user checkpoint | pre-wave |
| Fix Cycle Handler | agents/fix-cycle-handler.md | 2.3 (send_input cycle) | Manage review-fix iteration cycle (max 3 rounds) | post-wave |
| Completion Handler | agents/completion-handler.md | 2.3 (send_input cycle) | Handle pipeline completion action (Archive/Keep/Export) | standalone |
> **COMPACT PROTECTION**: Agent files are execution documents. When context compression occurs, **you MUST immediately `Read` the corresponding agent.md** to reload.
---
## Output Artifacts
| File | Purpose | Lifecycle |
|------|---------|-----------|
| `tasks.csv` | Master state -- all tasks with status/findings | Updated after each wave |
| `wave-{N}.csv` | Per-wave input (temporary, csv-wave tasks only) | Created before wave, deleted after |
| `results.csv` | Final export of all task results | Created in Phase 4 |
| `discoveries.ndjson` | Shared exploration board (all agents, both modes) | Append-only, carries across waves |
| `context.md` | Human-readable execution report | Created in Phase 4 |
| `task-analysis.json` | Phase 1 output: scope, issues, pipeline config | Created in Phase 1 |
| `artifacts/architecture-baseline.json` | Analyzer: pre-refactoring metrics | Created by analyzer |
| `artifacts/architecture-report.md` | Analyzer: ranked structural issue findings | Created by analyzer |
| `artifacts/refactoring-plan.md` | Designer: prioritized refactoring plan | Created by designer |
| `artifacts/validation-results.json` | Validator: post-refactoring validation | Created by validator |
| `artifacts/review-report.md` | Reviewer: code review findings | Created by reviewer |
| `interactive/{id}-result.json` | Results from interactive tasks | Created per interactive task |
---
## Session Structure
```
.workflow/.csv-wave/{session-id}/
+-- tasks.csv # Master state (all tasks, both modes)
+-- results.csv # Final results export
+-- discoveries.ndjson # Shared discovery board (all agents)
+-- context.md # Human-readable report
+-- task-analysis.json # Phase 1 analysis output
+-- wave-{N}.csv # Temporary per-wave input (csv-wave only)
+-- artifacts/
| +-- architecture-baseline.json # Analyzer output
| +-- architecture-report.md # Analyzer output
| +-- refactoring-plan.md # Designer output
| +-- validation-results.json # Validator output
| +-- review-report.md # Reviewer output
+-- interactive/ # Interactive task artifacts
| +-- {id}-result.json
+-- wisdom/
+-- patterns.md # Discovered patterns and conventions
```
---
## Implementation
### Session Initialization
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
const AUTO_YES = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const continueMode = $ARGUMENTS.includes('--continue')
const concurrencyMatch = $ARGUMENTS.match(/(?:--concurrency|-c)\s+(\d+)/)
const maxConcurrency = concurrencyMatch ? parseInt(concurrencyMatch[1]) : 3
const requirement = $ARGUMENTS
.replace(/--yes|-y|--continue|--concurrency\s+\d+|-c\s+\d+/g, '')
.trim()
const slug = requirement.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 40)
const dateStr = getUtc8ISOString().substring(0, 10).replace(/-/g, '')
const sessionId = `tao-${slug}-${dateStr}`
const sessionFolder = `.workflow/.csv-wave/${sessionId}`
Bash(`mkdir -p ${sessionFolder}/artifacts ${sessionFolder}/interactive ${sessionFolder}/wisdom`)
// Initialize discoveries.ndjson
Write(`${sessionFolder}/discoveries.ndjson`, '')
// Initialize wisdom
Write(`${sessionFolder}/wisdom/patterns.md`, '# Patterns & Conventions\n')
```
---
### Phase 0: Pre-Wave Interactive (Requirement Clarification)
**Objective**: Parse user task, detect architecture scope, clarify ambiguities, prepare for decomposition.
**Workflow**:
1. **Parse user task description** from $ARGUMENTS
2. **Check for existing sessions** (continue mode):
- Scan `.workflow/.csv-wave/tao-*/tasks.csv` for sessions with pending tasks
- If `--continue`: resume the specified or most recent session, skip to Phase 2
- If active session found: ask user whether to resume or start new
3. **Identify architecture optimization target**:
| Signal | Target |
|--------|--------|
| Specific file/module mentioned | Scoped refactoring |
| "coupling", "dependency", "structure", generic | Full architecture analysis |
| Specific issue (cycles, God Class, duplication) | Targeted issue resolution |
4. **Clarify if ambiguous** (skip if AUTO_YES):
```javascript
AskUserQuestion({
questions: [{
question: "Please confirm the architecture optimization scope:",
header: "Architecture Scope",
multiSelect: false,
options: [
{ label: "Proceed as described", description: "Scope is clear" },
{ label: "Narrow scope", description: "Specify modules/files to focus on" },
{ label: "Add constraints", description: "Exclude areas, set priorities" }
]
}]
})
```
5. **Output**: Refined requirement string for Phase 1
**Success Criteria**:
- Refined requirements available for Phase 1 decomposition
- Existing session detected and handled if applicable
---
### Phase 1: Requirement -> CSV + Classification
**Objective**: Decompose architecture optimization task into the 5-stage pipeline tasks, assign waves, generate tasks.csv.
**Decomposition Rules**:
1. **Stage mapping** -- architecture optimization always follows this pipeline:
| Stage | Role | Task Prefix | Wave | Description |
|-------|------|-------------|------|-------------|
| 1 | analyzer | ANALYZE | 1 | Scan codebase, identify structural issues, produce baseline metrics |
| 2 | designer | DESIGN | 2 | Design refactoring plan from architecture report |
| 3 | refactorer | REFACTOR | 3 | Implement refactorings per plan priority |
| 4a | validator | VALIDATE | 4 | Validate build, tests, metrics, API compatibility |
| 4b | reviewer | REVIEW | 4 | Review refactoring code for correctness and patterns |
2. **Single-pipeline decomposition**: Generate one task per stage with sequential dependencies:
- ANALYZE-001 (wave 1, no deps)
- DESIGN-001 (wave 2, deps: ANALYZE-001)
- REFACTOR-001 (wave 3, deps: DESIGN-001)
- VALIDATE-001 (wave 4, deps: REFACTOR-001)
- REVIEW-001 (wave 4, deps: REFACTOR-001)
3. **Description enrichment**: Each task description must be self-contained with:
- Clear goal statement
- Input artifacts to read
- Output artifacts to produce
- Success criteria
- Session folder path
**Classification Rules**:
| Task Property | exec_mode |
|---------------|-----------|
| ANALYZE, DESIGN, REFACTOR, VALIDATE, REVIEW (initial pass) | `csv-wave` |
| FIX tasks (review-fix cycle) | `interactive` (handled by fix-cycle-handler agent) |
**Wave Computation**: Kahn's BFS topological sort with depth tracking (csv-wave tasks only).
**User Validation**: Display task breakdown with wave + exec_mode assignment (skip if AUTO_YES).
**Success Criteria**:
- tasks.csv created with valid schema, wave, and exec_mode assignments
- task-analysis.json written with scope and pipeline config
- No circular dependencies
- User approved (or AUTO_YES)
---
### Phase 2: Wave Execution Engine (Extended)
**Objective**: Execute tasks wave-by-wave with hybrid mechanism support and cross-wave context propagation.
```javascript
const masterCsv = Read(`${sessionFolder}/tasks.csv`)
let tasks = parseCsv(masterCsv)
const maxWave = Math.max(...tasks.map(t => t.wave))
for (let wave = 1; wave <= maxWave; wave++) {
console.log(`\nWave ${wave}/${maxWave}`)
// 1. Separate tasks by exec_mode
const waveTasks = tasks.filter(t => t.wave === wave && t.status === 'pending')
const csvTasks = waveTasks.filter(t => t.exec_mode === 'csv-wave')
const interactiveTasks = waveTasks.filter(t => t.exec_mode === 'interactive')
// 2. Check dependencies -- skip tasks whose deps failed
for (const task of waveTasks) {
const depIds = (task.deps || '').split(';').filter(Boolean)
const depStatuses = depIds.map(id => tasks.find(t => t.id === id)?.status)
if (depStatuses.some(s => s === 'failed' || s === 'skipped')) {
task.status = 'skipped'
task.error = `Dependency failed: ${depIds.filter((id, i) =>
['failed','skipped'].includes(depStatuses[i])).join(', ')}`
}
}
// 3. Execute pre-wave interactive tasks (if any)
for (const task of interactiveTasks.filter(t => t.status === 'pending')) {
// Determine agent file based on task type
const agentFile = task.id.startsWith('FIX') ? 'agents/fix-cycle-handler.md' : 'agents/plan-reviewer.md'
Read(agentFile)
const agent = spawn_agent({
message: `## TASK ASSIGNMENT\n\n### MANDATORY FIRST STEPS\n1. Read: ${agentFile}\n2. Read: ${sessionFolder}/discoveries.ndjson\n3. Read: .workflow/project-tech.json (if exists)\n\n---\n\nGoal: ${task.description}\nScope: ${task.title}\nSession: ${sessionFolder}\n\n### Previous Context\n${buildPrevContext(task, tasks)}`
})
const result = wait({ ids: [agent], timeout_ms: 600000 })
if (result.timed_out) {
send_input({ id: agent, message: "Please finalize and output current findings." })
wait({ ids: [agent], timeout_ms: 120000 })
}
Write(`${sessionFolder}/interactive/${task.id}-result.json`, JSON.stringify({
task_id: task.id, status: "completed", findings: parseFindings(result),
timestamp: getUtc8ISOString()
}))
close_agent({ id: agent })
task.status = 'completed'
task.findings = parseFindings(result)
}
// 4. Build prev_context for csv-wave tasks
const pendingCsvTasks = csvTasks.filter(t => t.status === 'pending')
for (const task of pendingCsvTasks) {
task.prev_context = buildPrevContext(task, tasks)
}
if (pendingCsvTasks.length > 0) {
// 5. Write wave CSV
Write(`${sessionFolder}/wave-${wave}.csv`, toCsv(pendingCsvTasks))
// 6. Determine instruction -- read from instructions/agent-instruction.md
Read('instructions/agent-instruction.md')
// 7. Execute wave via spawn_agents_on_csv
spawn_agents_on_csv({
csv_path: `${sessionFolder}/wave-${wave}.csv`,
id_column: "id",
instruction: archOptInstruction, // from instructions/agent-instruction.md
max_concurrency: maxConcurrency,
max_runtime_seconds: 900,
output_csv_path: `${sessionFolder}/wave-${wave}-results.csv`,
output_schema: {
type: "object",
properties: {
id: { type: "string" },
status: { type: "string", enum: ["completed", "failed"] },
findings: { type: "string" },
verdict: { type: "string" },
artifacts_produced: { type: "string" },
error: { type: "string" }
}
}
})
// 8. Merge results into master CSV
const results = parseCsv(Read(`${sessionFolder}/wave-${wave}-results.csv`))
for (const r of results) {
const t = tasks.find(t => t.id === r.id)
if (t) Object.assign(t, r)
}
}
// 9. Update master CSV
Write(`${sessionFolder}/tasks.csv`, toCsv(tasks))
// 10. Cleanup temp files
Bash(`rm -f ${sessionFolder}/wave-${wave}.csv ${sessionFolder}/wave-${wave}-results.csv`)
// 11. Post-wave: check for review-fix cycle
const validateTask = tasks.find(t => t.id.startsWith('VALIDATE') && t.wave === wave)
const reviewTask = tasks.find(t => t.id.startsWith('REVIEW') && t.wave === wave)
if ((validateTask?.verdict === 'FAIL' || reviewTask?.verdict === 'REVISE' || reviewTask?.verdict === 'REJECT')) {
const fixCycleCount = tasks.filter(t => t.id.startsWith('FIX')).length
if (fixCycleCount < 3) {
// Create FIX task, add to tasks, re-run refactor -> validate+review cycle
const fixId = `FIX-${String(fixCycleCount + 1).padStart(3, '0')}`
const feedback = [validateTask?.error, reviewTask?.findings].filter(Boolean).join('\n')
tasks.push({
id: fixId, title: `Fix issues from review/validation cycle ${fixCycleCount + 1}`,
description: `Fix issues found:\n${feedback}`,
role: 'refactorer', issue_type: '', priority: 'P0', target_files: '',
deps: '', context_from: '', exec_mode: 'interactive',
wave: wave + 1, status: 'pending', findings: '', verdict: '',
artifacts_produced: '', error: ''
})
}
}
// 12. Display wave summary
const completed = waveTasks.filter(t => t.status === 'completed').length
const failed = waveTasks.filter(t => t.status === 'failed').length
const skipped = waveTasks.filter(t => t.status === 'skipped').length
console.log(`Wave ${wave} Complete: ${completed} completed, ${failed} failed, ${skipped} skipped`)
}
```
**Success Criteria**:
- All waves executed in order
- Both csv-wave and interactive tasks handled per wave
- Each wave's results merged into master CSV before next wave starts
- Dependent tasks skipped when predecessor failed
- Review-fix cycle handled with max 3 iterations
- discoveries.ndjson accumulated across all waves and mechanisms
---
### Phase 3: Post-Wave Interactive (Completion Action)
**Objective**: Pipeline completion report with architecture improvement metrics and interactive completion choice.
```javascript
// 1. Generate pipeline summary
const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
const completed = tasks.filter(t => t.status === 'completed')
const failed = tasks.filter(t => t.status === 'failed')
// 2. Load improvement metrics from validation results
let improvements = ''
try {
const validation = JSON.parse(Read(`${sessionFolder}/artifacts/validation-results.json`))
improvements = `Architecture Improvements:\n${validation.dimensions.map(d =>
` ${d.name}: ${d.baseline} -> ${d.current} (${d.improvement})`).join('\n')}`
} catch {}
console.log(`
============================================
ARCHITECTURE OPTIMIZATION COMPLETE
Deliverables:
- Architecture Baseline: artifacts/architecture-baseline.json
- Architecture Report: artifacts/architecture-report.md
- Refactoring Plan: artifacts/refactoring-plan.md
- Validation Results: artifacts/validation-results.json
- Review Report: artifacts/review-report.md
${improvements}
Pipeline: ${completed.length}/${tasks.length} tasks
Session: ${sessionFolder}
============================================
`)
// 3. Completion action
if (!AUTO_YES) {
AskUserQuestion({
questions: [{
question: "Architecture optimization complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, output final summary" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Retry Failed", description: "Re-run failed tasks" }
]
}]
})
}
```
**Success Criteria**:
- Post-wave interactive processing complete
- User informed of results and improvement metrics
---
### Phase 4: Results Aggregation
**Objective**: Generate final results and human-readable report.
```javascript
// 1. Export results.csv
Bash(`cp ${sessionFolder}/tasks.csv ${sessionFolder}/results.csv`)
// 2. Generate context.md
const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
let contextMd = `# Architecture Optimization Report\n\n`
contextMd += `**Session**: ${sessionId}\n`
contextMd += `**Date**: ${getUtc8ISOString().substring(0, 10)}\n\n`
contextMd += `## Summary\n`
contextMd += `| Status | Count |\n|--------|-------|\n`
contextMd += `| Completed | ${tasks.filter(t => t.status === 'completed').length} |\n`
contextMd += `| Failed | ${tasks.filter(t => t.status === 'failed').length} |\n`
contextMd += `| Skipped | ${tasks.filter(t => t.status === 'skipped').length} |\n\n`
contextMd += `## Deliverables\n\n`
contextMd += `| Artifact | Path |\n|----------|------|\n`
contextMd += `| Architecture Baseline | artifacts/architecture-baseline.json |\n`
contextMd += `| Architecture Report | artifacts/architecture-report.md |\n`
contextMd += `| Refactoring Plan | artifacts/refactoring-plan.md |\n`
contextMd += `| Validation Results | artifacts/validation-results.json |\n`
contextMd += `| Review Report | artifacts/review-report.md |\n\n`
const maxWave = Math.max(...tasks.map(t => t.wave))
contextMd += `## Wave Execution\n\n`
for (let w = 1; w <= maxWave; w++) {
const waveTasks = tasks.filter(t => t.wave === w)
contextMd += `### Wave ${w}\n\n`
for (const t of waveTasks) {
const icon = t.status === 'completed' ? '[DONE]' : t.status === 'failed' ? '[FAIL]' : '[SKIP]'
contextMd += `${icon} **${t.title}** [${t.role}] ${t.verdict ? `(${t.verdict})` : ''} ${t.findings || ''}\n\n`
}
}
Write(`${sessionFolder}/context.md`, contextMd)
console.log(`Results exported to: ${sessionFolder}/results.csv`)
console.log(`Report generated at: ${sessionFolder}/context.md`)
```
**Success Criteria**:
- results.csv exported (all tasks, both modes)
- context.md generated with deliverables list
- Summary displayed to user
---
## Shared Discovery Board Protocol
All agents (csv-wave and interactive) share a single `discoveries.ndjson` file for cross-task knowledge exchange.
**Format**: One JSON object per line (NDJSON):
```jsonl
{"ts":"2026-03-08T10:00:00Z","worker":"ANALYZE-001","type":"cycle_found","data":{"modules":["auth","user"],"depth":2,"description":"Circular dependency between auth and user modules"}}
{"ts":"2026-03-08T10:05:00Z","worker":"REFACTOR-001","type":"file_modified","data":{"file":"src/auth/index.ts","change":"Extracted interface to break cycle","lines_added":15}}
```
**Discovery Types**:
| Type | Data Schema | Description |
|------|-------------|-------------|
| `cycle_found` | `{modules, depth, description}` | Circular dependency detected |
| `god_class_found` | `{file, loc, methods, description}` | God Class/Module identified |
| `coupling_issue` | `{module, fan_in, fan_out, description}` | High coupling detected |
| `dead_code_found` | `{file, type, description}` | Dead code or dead export found |
| `file_modified` | `{file, change, lines_added}` | File change recorded |
| `pattern_found` | `{pattern_name, location, description}` | Code pattern identified |
| `metric_measured` | `{metric, value, unit, module}` | Architecture metric measured |
| `artifact_produced` | `{name, path, producer, type}` | Deliverable created |
**Protocol**:
1. Agents MUST read discoveries.ndjson at start of execution
2. Agents MUST append relevant discoveries during execution
3. Agents MUST NOT modify or delete existing entries
4. Deduplication by `{type, data.file}` or `{type, data.modules}` key
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Circular dependency in tasks | Detect in wave computation, abort with error message |
| CSV agent timeout | Mark as failed in results, continue with wave |
| CSV agent failed | Mark as failed, skip dependent tasks in later waves |
| Interactive agent timeout | Urge convergence via send_input, then close if still timed out |
| Interactive agent failed | Mark as failed, skip dependents |
| All agents in wave failed | Log error, offer retry or abort |
| CSV parse error | Validate CSV format before execution, show line number |
| discoveries.ndjson corrupt | Ignore malformed lines, continue with valid entries |
| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues |
| Validation fails on build | Create FIX task with compilation error details |
| Architecture baseline unavailable | Fall back to static analysis estimates |
| Continue mode: no session found | List available sessions, prompt user to select |
---
## Core Rules
1. **Start Immediately**: First action is session initialization, then Phase 0/1
2. **Wave Order is Sacred**: Never execute wave N before wave N-1 completes and results are merged
3. **CSV is Source of Truth**: Master tasks.csv holds all state (both csv-wave and interactive)
4. **CSV First**: Default to csv-wave for tasks; only use interactive when interaction pattern requires it
5. **Context Propagation**: prev_context built from master CSV, not from memory
6. **Discovery Board is Append-Only**: Never clear, modify, or recreate discoveries.ndjson -- both mechanisms share it
7. **Skip on Failure**: If a dependency failed, skip the dependent task (regardless of mechanism)
8. **Max 3 Fix Cycles**: Review-fix cycle capped at 3 iterations; escalate to user after
9. **Cleanup Temp Files**: Remove wave-{N}.csv after results are merged
10. **DO NOT STOP**: Continuous execution until all waves complete or all remaining tasks are skipped

View File

@@ -0,0 +1,138 @@
# Completion Handler Agent
Handle pipeline completion action for architecture optimization: present results summary, offer Archive/Keep/Export options, execute chosen action.
## Identity
- **Type**: `interactive`
- **Responsibility**: Pipeline completion and session lifecycle management
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Present complete pipeline summary with improvement metrics
- Offer completion action choices
- Execute chosen action (archive, keep, export)
- Produce structured output
### MUST NOT
- Skip presenting results summary
- Execute destructive actions without confirmation
- Modify source code
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `Read` | builtin | Load result artifacts |
| `Write` | builtin | Write export files |
| `Bash` | builtin | Archive/cleanup operations |
| `AskUserQuestion` | builtin | Present completion choices |
---
## Execution
### Phase 1: Results Collection
**Objective**: Gather all pipeline results for summary.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| tasks.csv | Yes | Master task state |
| Architecture baseline | Yes | Pre-refactoring metrics |
| Validation results | Yes | Post-refactoring metrics |
| Review report | Yes | Code review findings |
**Steps**:
1. Read tasks.csv -- count completed/failed/skipped
2. Read architecture-baseline.json -- extract before metrics
3. Read validation-results.json -- extract after metrics, compute improvements
4. Read review-report.md -- extract final verdict
**Output**: Compiled results summary
---
### Phase 2: Present and Choose
**Objective**: Display results and get user's completion choice.
**Steps**:
1. Display pipeline summary with improvement metrics
2. Present completion action:
```javascript
AskUserQuestion({
questions: [{
question: "Architecture optimization complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, output final summary" },
{ label: "Keep Active", description: "Keep session for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location" }
]
}]
})
```
**Output**: User's choice
---
### Phase 3: Execute Action
**Objective**: Execute the chosen completion action.
| Choice | Action |
|--------|--------|
| Archive & Clean | Copy results.csv and context.md to archive, mark session completed |
| Keep Active | Mark session as paused, leave all artifacts in place |
| Export Results | Copy key deliverables to user-specified location |
---
## Structured Output Template
```
## Pipeline Summary
- Tasks: X completed, Y failed, Z skipped
- Duration: estimated from timestamps
## Architecture Improvements
- Metric 1: before -> after (improvement %)
- Metric 2: before -> after (improvement %)
## Deliverables
- Architecture Report: path
- Refactoring Plan: path
- Validation Results: path
- Review Report: path
## Action Taken
- Choice: Archive & Clean / Keep Active / Export Results
- Status: completed
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Result artifacts missing | Report partial summary with available data |
| Archive operation fails | Default to Keep Active |
| Export path invalid | Ask user for valid path |
| Timeout approaching | Default to Keep Active |

View File

@@ -0,0 +1,146 @@
# Fix Cycle Handler Agent
Manage the review-fix iteration cycle for architecture refactoring. Reads validation/review feedback, applies targeted fixes, re-validates, up to 3 iterations.
## Identity
- **Type**: `interactive`
- **Responsibility**: Iterative fix-verify cycle for refactoring issues
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Read validation results and review report to understand failures
- Apply targeted fixes addressing specific feedback items
- Re-validate after each fix attempt
- Track iteration count (max 3)
- Produce structured output with fix summary
### MUST NOT
- Skip reading feedback before attempting fixes
- Apply broad changes unrelated to feedback
- Exceed 3 fix iterations
- Modify code outside the scope of reported issues
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `Read` | builtin | Load feedback artifacts and source files |
| `Edit` | builtin | Apply targeted code fixes |
| `Write` | builtin | Write updated artifacts |
| `Bash` | builtin | Run build/test validation |
| `Grep` | builtin | Search for patterns |
| `Glob` | builtin | Find files |
---
## Execution
### Phase 1: Feedback Loading
**Objective**: Load and parse validation/review feedback.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Validation results | Yes (if validation failed) | From artifacts/validation-results.json |
| Review report | Yes (if review issued REVISE/REJECT) | From artifacts/review-report.md |
| Refactoring plan | Yes | Original plan for reference |
| Discoveries | No | Shared findings |
**Steps**:
1. Read validation-results.json -- identify failed dimensions (build, test, metrics, API)
2. Read review-report.md -- identify Critical/High findings with file:line references
3. Categorize issues by type and priority
**Output**: Prioritized list of issues to fix
---
### Phase 2: Fix Implementation (Iterative)
**Objective**: Apply fixes and re-validate, up to 3 rounds.
**Steps**:
For each iteration (1..3):
1. **Apply fixes**:
- Address highest-severity issues first
- Make minimal, targeted changes at reported file:line locations
- Update imports if structural changes are needed
- Preserve existing behavior
2. **Self-validate**:
- Run build check (no new compilation errors)
- Run test suite (no new test failures)
- Verify fix addresses the specific concern raised
3. **Check convergence**:
| Validation Result | Action |
|-------------------|--------|
| All checks pass | Exit loop, report success |
| Some checks still fail, iteration < 3 | Continue to next iteration |
| Still failing at iteration 3 | Report remaining issues for escalation |
**Output**: Fix results per iteration
---
### Phase 3: Result Reporting
**Objective**: Produce final fix cycle summary.
**Steps**:
1. Update validation-results.json with post-fix metrics
2. Append fix discoveries to discoveries.ndjson
3. Report final status
---
## Structured Output Template
```
## Summary
- Fix cycle completed: N iterations, M issues resolved, K remaining
## Iterations
### Iteration 1
- Fixed: [list of fixes applied with file:line]
- Validation: [pass/fail per dimension]
### Iteration 2 (if needed)
- Fixed: [list of fixes]
- Validation: [pass/fail]
## Final Status
- verdict: PASS | PARTIAL | ESCALATE
- Remaining issues (if any): [list]
## Artifacts Updated
- artifacts/validation-results.json (updated metrics)
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Fix introduces new errors | Revert fix, try alternative approach |
| Cannot reproduce reported issue | Log as resolved-by-environment, continue |
| Fix scope exceeds current files | Report scope expansion needed, escalate |
| Timeout approaching | Output partial results with iteration count |
| 3 iterations exhausted | Report remaining issues for user escalation |

View File

@@ -0,0 +1,150 @@
# Plan Reviewer Agent
Review architecture report or refactoring plan at user checkpoints, providing interactive approval or revision requests.
## Identity
- **Type**: `interactive`
- **Responsibility**: Review and approve/revise plans before execution proceeds
## Boundaries
### MUST
- Load role definition via MANDATORY FIRST STEPS pattern
- Read the architecture report or refactoring plan being reviewed
- Produce structured output with clear APPROVE/REVISE verdict
- Include specific file:line references in findings
### MUST NOT
- Skip the MANDATORY FIRST STEPS role loading
- Modify source code directly
- Produce unstructured output
- Approve without actually reading the plan
---
## Toolbox
### Available Tools
| Tool | Type | Purpose |
|------|------|---------|
| `Read` | builtin | Load plan artifacts and project files |
| `Grep` | builtin | Search for patterns in codebase |
| `Glob` | builtin | Find files by pattern |
| `Bash` | builtin | Run build/test commands |
### Tool Usage Patterns
**Read Pattern**: Load context files before review
```
Read("{session_folder}/artifacts/architecture-report.md")
Read("{session_folder}/artifacts/refactoring-plan.md")
Read("{session_folder}/discoveries.ndjson")
```
---
## Execution
### Phase 1: Context Loading
**Objective**: Load the plan or report to review.
**Input**:
| Source | Required | Description |
|--------|----------|-------------|
| Architecture report | Yes (if reviewing analysis) | Ranked issue list from analyzer |
| Refactoring plan | Yes (if reviewing design) | Prioritized plan from designer |
| Discoveries | No | Shared findings from prior stages |
**Steps**:
1. Read the artifact being reviewed from session artifacts folder
2. Read discoveries.ndjson for additional context
3. Identify which checkpoint this review corresponds to (CP-1 for analysis, CP-2 for design)
**Output**: Loaded plan context for review
---
### Phase 2: Plan Review
**Objective**: Evaluate plan quality, completeness, and feasibility.
**Steps**:
1. **For architecture report review (CP-1)**:
- Verify all issue categories are covered (cycles, coupling, cohesion, God Classes, dead code, API bloat)
- Check that severity rankings are justified with evidence
- Validate baseline metrics are quantified and reproducible
- Check scope coverage matches original requirement
2. **For refactoring plan review (CP-2)**:
- Verify each refactoring has unique REFACTOR-ID and self-contained detail
- Check priority assignments follow impact/effort matrix
- Validate target files are non-overlapping between refactorings
- Verify success criteria are measurable
- Check that implementation guidance is actionable
- Assess risk levels and mitigation strategies
3. **Issue classification**:
| Finding Severity | Condition | Impact |
|------------------|-----------|--------|
| Critical | Missing key analysis area or infeasible plan | REVISE required |
| High | Unclear criteria or overlapping targets | REVISE recommended |
| Medium | Minor gaps in coverage or detail | Note for improvement |
| Low | Style or formatting issues | Informational |
**Output**: Review findings with severity classifications
---
### Phase 3: Verdict
**Objective**: Issue APPROVE or REVISE verdict.
| Verdict | Condition | Action |
|---------|-----------|--------|
| APPROVE | No Critical or High findings | Plan is ready for next stage |
| REVISE | Has Critical or High findings | Return specific feedback for revision |
**Output**: Verdict with detailed feedback
---
## Structured Output Template
```
## Summary
- One-sentence verdict: APPROVE or REVISE with rationale
## Findings
- Finding 1: [severity] description with artifact reference
- Finding 2: [severity] description with specific section reference
## Verdict
- APPROVE: Plan is ready for execution
OR
- REVISE: Specific items requiring revision
1. Issue description + suggested fix
2. Issue description + suggested fix
## Recommendations
- Optional improvement suggestions (non-blocking)
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Artifact file not found | Report in findings, request re-generation |
| Plan structure invalid | Report as Critical finding, REVISE verdict |
| Scope mismatch | Report in findings, note for coordinator |
| Timeout approaching | Output current findings with "PARTIAL" status |

View File

@@ -0,0 +1,114 @@
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS
1. Read shared discoveries: {session_folder}/discoveries.ndjson (if exists, skip if not)
2. Read project context: .workflow/project-tech.json (if exists)
3. Read task schema: .codex/skills/team-arch-opt/schemas/tasks-schema.md
---
## Your Task
**Task ID**: {id}
**Title**: {title}
**Description**: {description}
**Role**: {role}
**Issue Type**: {issue_type}
**Priority**: {priority}
**Target Files**: {target_files}
### Previous Tasks' Findings (Context)
{prev_context}
---
## Execution Protocol
1. **Read discoveries**: Load {session_folder}/discoveries.ndjson for shared exploration findings
2. **Use context**: Apply previous tasks' findings from prev_context above
3. **Execute by role**:
**If role = analyzer**:
- Scan codebase for architecture issues within target scope
- Build import/require graph, detect circular dependencies
- Identify God Classes (>500 LOC, >10 public methods)
- Calculate coupling (fan-in/fan-out) and cohesion metrics
- Detect dead code, dead exports, layering violations
- Collect quantified baseline metrics
- Rank top 3-7 issues by severity (Critical/High/Medium)
- Write `{session_folder}/artifacts/architecture-baseline.json` (metrics)
- Write `{session_folder}/artifacts/architecture-report.md` (ranked issues)
**If role = designer**:
- Read architecture report and baseline from {session_folder}/artifacts/
- For each issue, select refactoring strategy by type:
- CYCLE: interface extraction, dependency inversion, mediator
- GOD_CLASS: SRP decomposition, extract class/module
- COUPLING: introduce interface/abstraction, DI, events
- DUPLICATION: extract shared utility/base class
- LAYER_VIOLATION: move to correct layer, add facade
- DEAD_CODE: safe removal with reference verification
- API_BLOAT: privatize internals, barrel file cleanup
- Prioritize by impact/effort: P0 (high impact+low effort) to P3 (low impact or high effort)
- Assign unique REFACTOR-IDs (REFACTOR-001, 002, ...) with non-overlapping file targets
- Write `{session_folder}/artifacts/refactoring-plan.md`
**If role = refactorer**:
- Read refactoring plan from {session_folder}/artifacts/refactoring-plan.md
- Apply refactorings in priority order (P0 first)
- Preserve existing behavior -- refactoring must not change functionality
- Update ALL import references when moving/renaming modules
- Update ALL test files referencing moved/renamed symbols
- Verify no dangling imports after module moves
**If role = validator**:
- Read baseline from {session_folder}/artifacts/architecture-baseline.json
- Read plan from {session_folder}/artifacts/refactoring-plan.md
- Build validation: compile/type-check, zero new errors
- Test validation: run test suite, no new failures
- Metric validation: coupling improved or neutral, no new cycles
- API validation: public signatures preserved, no dangling references
- Write `{session_folder}/artifacts/validation-results.json`
- Set verdict: PASS / WARN / FAIL
**If role = reviewer**:
- Read plan from {session_folder}/artifacts/refactoring-plan.md
- Review changed files across 5 dimensions:
- Correctness: no behavior changes, all references updated
- Pattern consistency: follows existing conventions
- Completeness: imports, tests, configs all updated
- Migration safety: no dangling refs, backward compatible
- Best practices: SOLID, appropriate abstraction
- Write `{session_folder}/artifacts/review-report.md`
- Set verdict: APPROVE / REVISE / REJECT
4. **Share discoveries**: Append exploration findings to shared board:
```bash
echo '{"ts":"<ISO8601>","worker":"{id}","type":"<type>","data":{...}}' >> {session_folder}/discoveries.ndjson
```
5. **Report result**: Return JSON via report_agent_job_result
### Discovery Types to Share
- `cycle_found`: `{modules, depth, description}` -- Circular dependency detected
- `god_class_found`: `{file, loc, methods, description}` -- God Class identified
- `coupling_issue`: `{module, fan_in, fan_out, description}` -- High coupling
- `dead_code_found`: `{file, type, description}` -- Dead code found
- `layer_violation`: `{from, to, description}` -- Layering violation
- `file_modified`: `{file, change, lines_added}` -- File change recorded
- `pattern_found`: `{pattern_name, location, description}` -- Pattern identified
- `metric_measured`: `{metric, value, unit, module}` -- Metric measured
- `artifact_produced`: `{name, path, producer, type}` -- Deliverable created
---
## Output (report_agent_job_result)
Return JSON:
{
"id": "{id}",
"status": "completed" | "failed",
"findings": "Key discoveries and implementation notes (max 500 chars)",
"verdict": "PASS|WARN|FAIL|APPROVE|REVISE|REJECT or empty",
"artifacts_produced": "semicolon-separated artifact paths",
"error": ""
}

View File

@@ -0,0 +1,174 @@
# Team Architecture Optimization -- CSV Schema
## Master CSV: tasks.csv
### Column Definitions
#### Input Columns (Set by Decomposer)
| Column | Type | Required | Description | Example |
|--------|------|----------|-------------|---------|
| `id` | string | Yes | Unique task identifier (PREFIX-NNN) | `"ANALYZE-001"` |
| `title` | string | Yes | Short task title | `"Analyze architecture"` |
| `description` | string | Yes | Detailed task description (self-contained) with goal, inputs, outputs, success criteria | `"Analyze codebase architecture..."` |
| `role` | enum | Yes | Worker role: `analyzer`, `designer`, `refactorer`, `validator`, `reviewer` | `"analyzer"` |
| `issue_type` | string | No | Architecture issue category: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT | `"CYCLE"` |
| `priority` | enum | No | P0 (Critical), P1 (High), P2 (Medium), P3 (Low) | `"P0"` |
| `target_files` | string | No | Semicolon-separated file paths to focus on | `"src/auth/index.ts;src/user/index.ts"` |
| `deps` | string | No | Semicolon-separated dependency task IDs | `"ANALYZE-001"` |
| `context_from` | string | No | Semicolon-separated task IDs for context | `"ANALYZE-001"` |
| `exec_mode` | enum | Yes | Execution mechanism: `csv-wave` or `interactive` | `"csv-wave"` |
#### Computed Columns (Set by Wave Engine)
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `wave` | integer | Wave number (1-based, from topological sort) | `2` |
| `prev_context` | string | Aggregated findings from context_from tasks (per-wave CSV only) | `"[ANALYZE-001] Found 5 architecture issues..."` |
#### Output Columns (Set by Agent)
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `status` | enum | `pending` -> `completed` / `failed` / `skipped` | `"completed"` |
| `findings` | string | Key discoveries (max 500 chars) | `"Found 3 circular deps, 2 God Classes..."` |
| `verdict` | string | Validation/review verdict: PASS, WARN, FAIL, APPROVE, REVISE, REJECT | `"PASS"` |
| `artifacts_produced` | string | Semicolon-separated paths of produced artifacts | `"artifacts/architecture-report.md"` |
| `error` | string | Error message if failed | `""` |
---
### exec_mode Values
| Value | Mechanism | Description |
|-------|-----------|-------------|
| `csv-wave` | `spawn_agents_on_csv` | One-shot batch execution within wave |
| `interactive` | `spawn_agent`/`wait`/`send_input`/`close_agent` | Multi-round individual execution |
Interactive tasks appear in master CSV for dependency tracking but are NOT included in wave-{N}.csv files.
---
### Role Prefix Mapping
| Role | Prefix | Stage | Responsibility |
|------|--------|-------|----------------|
| analyzer | ANALYZE | 1 | Architecture analysis, baseline metrics, issue identification |
| designer | DESIGN | 2 | Refactoring plan design, strategy selection, prioritization |
| refactorer | REFACTOR / FIX | 3 | Code implementation, refactoring application, targeted fixes |
| validator | VALIDATE | 4 | Build checks, test suite, metric validation, API compatibility |
| reviewer | REVIEW | 4 | Code review for correctness, patterns, completeness, safety |
---
### Example Data
```csv
id,title,description,role,issue_type,priority,target_files,deps,context_from,exec_mode,wave,status,findings,verdict,artifacts_produced,error
"ANALYZE-001","Analyze architecture","PURPOSE: Analyze codebase architecture to identify structural issues\nTASK:\n- Build import graph, detect circular deps\n- Identify God Classes (>500 LOC, >10 methods)\n- Calculate coupling/cohesion metrics\n- Detect dead code and dead exports\nINPUT: Codebase under target scope\nOUTPUT: artifacts/architecture-baseline.json + artifacts/architecture-report.md\nSUCCESS: Ranked issue list with severity, baseline metrics collected\nSESSION: .workflow/.csv-wave/tao-example-20260308","analyzer","","","","","","csv-wave","1","pending","","","",""
"DESIGN-001","Design refactoring plan","PURPOSE: Design prioritized refactoring plan from architecture report\nTASK:\n- For each issue, select refactoring strategy\n- Prioritize by impact/effort ratio (P0-P3)\n- Define measurable success criteria per refactoring\n- Assign unique REFACTOR-IDs with non-overlapping file targets\nINPUT: artifacts/architecture-report.md + artifacts/architecture-baseline.json\nOUTPUT: artifacts/refactoring-plan.md\nSUCCESS: Prioritized plan with self-contained REFACTOR blocks\nSESSION: .workflow/.csv-wave/tao-example-20260308","designer","","","","ANALYZE-001","ANALYZE-001","csv-wave","2","pending","","","",""
"REFACTOR-001","Implement refactorings","PURPOSE: Implement architecture refactoring changes per plan\nTASK:\n- Apply refactorings in priority order (P0 first)\n- Update all import references when moving/renaming\n- Update all test files referencing moved symbols\n- Preserve existing behavior\nINPUT: artifacts/refactoring-plan.md\nOUTPUT: Modified source files\nSUCCESS: All planned structural changes applied, no dangling imports\nSESSION: .workflow/.csv-wave/tao-example-20260308","refactorer","","","","DESIGN-001","DESIGN-001","csv-wave","3","pending","","","",""
"VALIDATE-001","Validate refactoring","PURPOSE: Validate refactoring improves architecture without breaking functionality\nTASK:\n- Build check: zero new compilation errors\n- Test suite: all previously passing tests still pass\n- Metrics: coupling improved or neutral, no new cycles\n- API: public signatures preserved\nINPUT: artifacts/architecture-baseline.json + artifacts/refactoring-plan.md\nOUTPUT: artifacts/validation-results.json\nSUCCESS: All dimensions PASS\nSESSION: .workflow/.csv-wave/tao-example-20260308","validator","","","","REFACTOR-001","REFACTOR-001","csv-wave","4","pending","","","",""
"REVIEW-001","Review refactoring code","PURPOSE: Review refactoring changes for correctness and quality\nTASK:\n- Correctness: no behavior changes, all references updated\n- Pattern consistency: follows existing conventions\n- Completeness: imports, tests, configs all updated\n- Migration safety: no dangling refs, backward compatible\n- Best practices: SOLID principles, appropriate abstraction\nINPUT: artifacts/refactoring-plan.md + changed files\nOUTPUT: artifacts/review-report.md\nSUCCESS: APPROVE verdict (no Critical/High findings)\nSESSION: .workflow/.csv-wave/tao-example-20260308","reviewer","","","","REFACTOR-001","REFACTOR-001","csv-wave","4","pending","","","",""
```
---
### Column Lifecycle
```
Decomposer (Phase 1) Wave Engine (Phase 2) Agent (Execution)
--------------------- -------------------- -----------------
id ----------> id ----------> id
title ----------> title ----------> (reads)
description ----------> description ----------> (reads)
role ----------> role ----------> (reads)
issue_type ----------> issue_type ----------> (reads)
priority ----------> priority ----------> (reads)
target_files----------> target_files----------> (reads)
deps ----------> deps ----------> (reads)
context_from----------> context_from----------> (reads)
exec_mode ----------> exec_mode ----------> (reads)
wave ----------> (reads)
prev_context ----------> (reads)
status
findings
verdict
artifacts_produced
error
```
---
## Output Schema (JSON)
Agent output via `report_agent_job_result` (csv-wave tasks):
```json
{
"id": "ANALYZE-001",
"status": "completed",
"findings": "Found 5 architecture issues: 2 circular deps (auth<->user, service<->repo), 1 God Class (UserManager 850 LOC), 1 dead code cluster (src/legacy/), 1 API bloat (utils/ exports 45 symbols, 12 unused).",
"verdict": "",
"artifacts_produced": "artifacts/architecture-baseline.json;artifacts/architecture-report.md",
"error": ""
}
```
Interactive tasks output via structured text or JSON written to `interactive/{id}-result.json`.
---
## Discovery Types
| Type | Dedup Key | Data Schema | Description |
|------|-----------|-------------|-------------|
| `cycle_found` | `data.modules` (sorted) | `{modules, depth, description}` | Circular dependency detected |
| `god_class_found` | `data.file` | `{file, loc, methods, description}` | God Class/Module identified |
| `coupling_issue` | `data.module` | `{module, fan_in, fan_out, description}` | High coupling detected |
| `dead_code_found` | `data.file+data.type` | `{file, type, description}` | Dead code or dead export |
| `layer_violation` | `data.from+data.to` | `{from, to, description}` | Layering violation detected |
| `file_modified` | `data.file` | `{file, change, lines_added}` | File change recorded |
| `pattern_found` | `data.pattern_name+data.location` | `{pattern_name, location, description}` | Code pattern identified |
| `metric_measured` | `data.metric+data.module` | `{metric, value, unit, module}` | Architecture metric measured |
| `artifact_produced` | `data.path` | `{name, path, producer, type}` | Deliverable created |
### Discovery NDJSON Format
```jsonl
{"ts":"2026-03-08T10:00:00Z","worker":"ANALYZE-001","type":"cycle_found","data":{"modules":["auth","user"],"depth":2,"description":"Circular dependency: auth imports user, user imports auth"}}
{"ts":"2026-03-08T10:01:00Z","worker":"ANALYZE-001","type":"god_class_found","data":{"file":"src/services/UserManager.ts","loc":850,"methods":15,"description":"UserManager handles auth, profile, permissions, notifications"}}
{"ts":"2026-03-08T10:05:00Z","worker":"ANALYZE-001","type":"metric_measured","data":{"metric":"coupling_score","value":0.72,"unit":"normalized","module":"src/auth/"}}
{"ts":"2026-03-08T10:20:00Z","worker":"REFACTOR-001","type":"file_modified","data":{"file":"src/auth/index.ts","change":"Extracted IAuthService interface to break cycle","lines_added":25}}
{"ts":"2026-03-08T10:25:00Z","worker":"REFACTOR-001","type":"artifact_produced","data":{"name":"refactoring-summary","path":"artifacts/refactoring-plan.md","producer":"designer","type":"markdown"}}
```
> Both csv-wave and interactive agents read/write the same discoveries.ndjson file.
---
## Cross-Mechanism Context Flow
| Source | Target | Mechanism |
|--------|--------|-----------|
| CSV task findings | Interactive task | Injected via spawn message or send_input |
| Interactive task result | CSV task prev_context | Read from interactive/{id}-result.json |
| Any agent discovery | Any agent | Shared via discoveries.ndjson |
---
## Validation Rules
| Rule | Check | Error |
|------|-------|-------|
| Unique IDs | No duplicate `id` values | "Duplicate task ID: {id}" |
| Valid deps | All dep IDs exist in tasks | "Unknown dependency: {dep_id}" |
| No self-deps | Task cannot depend on itself | "Self-dependency: {id}" |
| No circular deps | Topological sort completes | "Circular dependency detected involving: {ids}" |
| context_from valid | All context IDs exist and in earlier waves | "Invalid context_from: {id}" |
| exec_mode valid | Value is `csv-wave` or `interactive` | "Invalid exec_mode: {value}" |
| Description non-empty | Every task has description | "Empty description for task: {id}" |
| Status enum | status in {pending, completed, failed, skipped} | "Invalid status: {status}" |
| Role valid | role in {analyzer, designer, refactorer, validator, reviewer} | "Invalid role: {role}" |
| Verdict enum | verdict in {PASS, WARN, FAIL, APPROVE, REVISE, REJECT, ""} | "Invalid verdict: {verdict}" |
| Cross-mechanism deps | Interactive to CSV deps resolve correctly | "Cross-mechanism dependency unresolvable: {id}" |