mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-03-26 19:56:37 +08:00
feat: migrate all codex team skills from spawn_agents_on_csv to spawn_agent + wait_agent architecture
- Delete 21 old team skill directories using CSV-wave pipeline pattern (~100+ files) - Delete old team-lifecycle (v3) and team-planex-v2 - Create generic team-worker.toml and team-supervisor.toml (replacing tlv4-specific TOMLs) - Convert 19 team skills from Claude Code format (Agent/SendMessage/TaskCreate) to Codex format (spawn_agent/wait_agent/tasks.json/request_user_input) - Update team-lifecycle-v4 to use generic agent types (team_worker/team_supervisor) - Convert all coordinator role files: dispatch.md, monitor.md, role.md - Convert all worker role files: remove run_in_background, fix Bash syntax - Convert all specs/pipelines.md references - Final state: 20 team skills, 217 .md files, zero Claude Code API residuals Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,698 +1,151 @@
|
||||
---
|
||||
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, request_user_input
|
||||
description: Unified team skill for architecture optimization. Uses team-worker agent architecture with role directories for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team arch-opt".
|
||||
allowed-tools: spawn_agent(*), wait_agent(*), send_input(*), close_agent(*), report_agent_job_result(*), request_user_input(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Auto-confirm task decomposition, skip interactive validation, use defaults.
|
||||
|
||||
# Team Architecture Optimization
|
||||
|
||||
## Usage
|
||||
Orchestrate multi-agent architecture optimization: analyze codebase -> design refactoring plan -> implement changes -> validate improvements -> review code quality.
|
||||
|
||||
```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)
|
||||
## Architecture
|
||||
|
||||
```
|
||||
+-------------------------------------------------------------------+
|
||||
| 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 (request_user_input) |
|
||||
| +- 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 |
|
||||
| |
|
||||
+-------------------------------------------------------------------+
|
||||
Skill(skill="team-arch-opt", args="task description")
|
||||
|
|
||||
SKILL.md (this file) = Router
|
||||
|
|
||||
+--------------+--------------+
|
||||
| |
|
||||
no --role flag --role <name>
|
||||
| |
|
||||
Coordinator Worker
|
||||
roles/coordinator/role.md roles/<name>/role.md
|
||||
|
|
||||
+-- analyze -> dispatch -> spawn workers -> STOP
|
||||
|
|
||||
+-------+-------+-------+-------+
|
||||
v v v v v
|
||||
[analyzer][designer][refactorer][validator][reviewer]
|
||||
```
|
||||
|
||||
---
|
||||
## Role Registry
|
||||
|
||||
## Pipeline Definition
|
||||
| Role | Path | Prefix | Inner Loop |
|
||||
|------|------|--------|------------|
|
||||
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — |
|
||||
| analyzer | [roles/analyzer/role.md](roles/analyzer/role.md) | ANALYZE-* | false |
|
||||
| designer | [roles/designer/role.md](roles/designer/role.md) | DESIGN-* | false |
|
||||
| refactorer | [roles/refactorer/role.md](roles/refactorer/role.md) | REFACTOR-*, FIX-* | true |
|
||||
| validator | [roles/validator/role.md](roles/validator/role.md) | VALIDATE-* | false |
|
||||
| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REVIEW-*, QUALITY-* | false |
|
||||
|
||||
## Role Router
|
||||
|
||||
Parse `$ARGUMENTS`:
|
||||
- Has `--role <name>` -> Read `roles/<name>/role.md`, execute Phase 2-4
|
||||
- No `--role` -> `roles/coordinator/role.md`, execute entry router
|
||||
|
||||
## Shared Constants
|
||||
|
||||
- **Session prefix**: `TAO`
|
||||
- **Session path**: `.workflow/.team/TAO-<slug>-<date>/`
|
||||
- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications)
|
||||
- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)`
|
||||
|
||||
## Worker Spawn Template
|
||||
|
||||
Coordinator spawns workers using this template:
|
||||
|
||||
```
|
||||
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)
|
||||
spawn_agent({
|
||||
agent_type: "team_worker",
|
||||
items: [
|
||||
{ type: "text", text: `## Role Assignment
|
||||
role: <role>
|
||||
role_spec: <skill_root>/roles/<role>/role.md
|
||||
session: <session-folder>
|
||||
session_id: <session-id>
|
||||
requirement: <task-description>
|
||||
inner_loop: <true|false>
|
||||
|
||||
Read role_spec file (<skill_root>/roles/<role>/role.md) to load Phase 2-4 domain instructions.` },
|
||||
|
||||
{ type: "text", text: `## Task Context
|
||||
task_id: <task-id>
|
||||
title: <task-title>
|
||||
description: <task-description>
|
||||
pipeline_phase: <pipeline-phase>` },
|
||||
|
||||
{ type: "text", text: `## Upstream Context
|
||||
<prev_context>` }
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
After spawning, use `wait_agent({ ids: [...], timeout_ms: 900000 })` to collect results, then `close_agent({ id })` each worker.
|
||||
|
||||
## Task Classification Rules
|
||||
**Inner Loop roles** (refactorer): Set `inner_loop: true`.
|
||||
**Single-task roles** (analyzer, designer, validator, reviewer): Set `inner_loop: false`.
|
||||
|
||||
Each task is classified by `exec_mode`:
|
||||
## User Commands
|
||||
|
||||
| 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 |
|
||||
| Command | Action |
|
||||
|---------|--------|
|
||||
| `check` / `status` | View execution status graph (branch-grouped), no advancement |
|
||||
| `resume` / `continue` | Check worker states, advance next step |
|
||||
| `revise <TASK-ID> [feedback]` | Revise specific task + cascade downstream |
|
||||
| `feedback <text>` | Analyze feedback impact, create targeted revision chain |
|
||||
| `recheck` | Re-run quality check |
|
||||
| `improve [dimension]` | Auto-improve weakest dimension |
|
||||
|
||||
**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
|
||||
## Session Directory
|
||||
|
||||
```
|
||||
.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
|
||||
.workflow/.team/TAO-<slug>-<date>/
|
||||
├── session.json # Session metadata + status + parallel_mode
|
||||
├── task-analysis.json # Coordinator analyze output
|
||||
├── artifacts/
|
||||
│ ├── architecture-baseline.json # Analyzer: pre-refactoring metrics
|
||||
│ ├── architecture-report.md # Analyzer: ranked structural issue findings
|
||||
│ ├── refactoring-plan.md # Designer: prioritized refactoring plan
|
||||
│ ├── validation-results.json # Validator: post-refactoring validation
|
||||
│ ├── review-report.md # Reviewer: code review findings
|
||||
│ ├── aggregate-results.json # Fan-out/independent: aggregated results
|
||||
│ ├── branches/ # Fan-out mode branch artifacts
|
||||
│ │ └── B{NN}/
|
||||
│ │ ├── refactoring-detail.md
|
||||
│ │ ├── validation-results.json
|
||||
│ │ └── review-report.md
|
||||
│ └── pipelines/ # Independent mode pipeline artifacts
|
||||
│ └── {P}/
|
||||
│ └── ...
|
||||
├── explorations/
|
||||
│ ├── cache-index.json # Shared explore cache
|
||||
│ └── <hash>.md
|
||||
├── wisdom/
|
||||
│ └── patterns.md # Discovered patterns and conventions
|
||||
├── discussions/
|
||||
│ ├── DISCUSS-REFACTOR.md
|
||||
│ └── DISCUSS-REVIEW.md
|
||||
└── .msg/
|
||||
├── messages.jsonl # Message bus log
|
||||
└── meta.json # Session state + cross-role state
|
||||
```
|
||||
|
||||
---
|
||||
## Specs Reference
|
||||
|
||||
## 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
|
||||
request_user_input({
|
||||
questions: [{
|
||||
question: "Please confirm the architecture optimization scope.",
|
||||
header: "Scope",
|
||||
id: "arch_scope",
|
||||
options: [
|
||||
{ label: "Proceed (Recommended)", description: "Scope is clear, start analysis" },
|
||||
{ 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) {
|
||||
request_user_input({
|
||||
questions: [{
|
||||
question: "Architecture optimization complete. Choose next action.",
|
||||
header: "Done",
|
||||
id: "completion",
|
||||
options: [
|
||||
{ label: "Archive (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
|
||||
|
||||
---
|
||||
- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions, task registry, parallel modes
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Coordinator Role Constraints (Main Agent)
|
||||
|
||||
**CRITICAL**: The coordinator (main agent executing this skill) is responsible for **orchestration only**, NOT implementation.
|
||||
|
||||
15. **Coordinator Does NOT Execute Code**: The main agent MUST NOT write, modify, or implement any code directly. All implementation work is delegated to spawned team agents. The coordinator only:
|
||||
- Spawns agents with task assignments
|
||||
- Waits for agent callbacks
|
||||
- Merges results and coordinates workflow
|
||||
- Manages workflow transitions between phases
|
||||
|
||||
16. **Patient Waiting is Mandatory**: Agent execution takes significant time (typically 10-30 minutes per phase, sometimes longer). The coordinator MUST:
|
||||
- Wait patiently for `wait()` calls to complete
|
||||
- NOT skip workflow steps due to perceived delays
|
||||
- NOT assume agents have failed just because they're taking time
|
||||
- Trust the timeout mechanisms defined in the skill
|
||||
|
||||
17. **Use send_input for Clarification**: When agents need guidance or appear stuck, the coordinator MUST:
|
||||
- Use `send_input()` to ask questions or provide clarification
|
||||
- NOT skip the agent or move to next phase prematurely
|
||||
- Give agents opportunity to respond before escalating
|
||||
- Example: `send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })`
|
||||
|
||||
18. **No Workflow Shortcuts**: The coordinator MUST NOT:
|
||||
- Skip phases or stages defined in the workflow
|
||||
- Bypass required approval or review steps
|
||||
- Execute dependent tasks before prerequisites complete
|
||||
- Assume task completion without explicit agent callback
|
||||
- Make up or fabricate agent results
|
||||
|
||||
19. **Respect Long-Running Processes**: This is a complex multi-agent workflow that requires patience:
|
||||
- Total execution time may range from 30-90 minutes or longer
|
||||
- Each phase may take 10-30 minutes depending on complexity
|
||||
- The coordinator must remain active and attentive throughout the entire process
|
||||
- Do not terminate or skip steps due to time concerns
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Unknown command | Error with available command list |
|
||||
| Role not found | Error with role registry |
|
||||
| CLI tool fails | Worker fallback to direct implementation |
|
||||
| Fast-advance conflict | Coordinator reconciles on next callback |
|
||||
| Completion action fails | Default to Keep Active |
|
||||
| consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline |
|
||||
| Branch fix cycle >= 3 | Escalate only that branch to user, others continue |
|
||||
| max_branches exceeded | Coordinator truncates to top N at CP-2.5 |
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
# 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 |
|
||||
| `request_user_input` | 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
|
||||
request_user_input({
|
||||
questions: [{
|
||||
question: "Architecture optimization complete. What would you like to do?",
|
||||
header: "Completion",
|
||||
id: "completion_action",
|
||||
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 |
|
||||
@@ -1,146 +0,0 @@
|
||||
# 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 |
|
||||
@@ -1,150 +0,0 @@
|
||||
# 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 |
|
||||
@@ -1,114 +0,0 @@
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS
|
||||
1. Read shared discoveries: {session_folder}/discoveries.ndjson (if exists, skip if not)
|
||||
2. Read project context: .workflow/project-tech.json (if exists)
|
||||
3. Read task schema: ~ or <project>/.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": ""
|
||||
}
|
||||
78
.codex/skills/team-arch-opt/roles/analyzer/role.md
Normal file
78
.codex/skills/team-arch-opt/roles/analyzer/role.md
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
role: analyzer
|
||||
prefix: ANALYZE
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Analyzer
|
||||
|
||||
Analyze codebase architecture to identify structural issues: dependency cycles, coupling/cohesion problems, layering violations, God Classes, code duplication, dead code, and API surface bloat. Produce quantified baseline metrics and a ranked architecture report.
|
||||
|
||||
## Phase 2: Context & Environment Detection
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Task description | From task subject/description | Yes |
|
||||
| Session path | Extracted from task description | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | No |
|
||||
|
||||
1. Extract session path and target scope from task description
|
||||
2. Detect project type by scanning for framework markers:
|
||||
|
||||
| Signal File | Project Type | Analysis Focus |
|
||||
|-------------|-------------|----------------|
|
||||
| package.json + React/Vue/Angular | Frontend | Component tree, prop drilling, state management, barrel exports |
|
||||
| package.json + Express/Fastify/NestJS | Backend Node | Service layer boundaries, middleware chains, DB access patterns |
|
||||
| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | Module boundaries, trait/interface usage, dependency injection |
|
||||
| Mixed framework markers | Full-stack / Monorepo | Cross-package dependencies, shared types, API contracts |
|
||||
| CLI entry / bin/ directory | CLI Tool | Command structure, plugin architecture, configuration layering |
|
||||
| No detection | Generic | All architecture dimensions |
|
||||
|
||||
3. Use `explore` CLI tool to map module structure, dependency graph, and layer boundaries within target scope
|
||||
4. Detect available analysis tools (linters, dependency analyzers, build tools)
|
||||
|
||||
## Phase 3: Architecture Analysis
|
||||
|
||||
Execute analysis based on detected project type:
|
||||
|
||||
**Dependency analysis**:
|
||||
- Build import/require graph across modules
|
||||
- Detect circular dependencies (direct and transitive cycles)
|
||||
- Identify layering violations (e.g., UI importing from data layer, utils importing from domain)
|
||||
- Calculate fan-in/fan-out per module (high fan-out = fragile hub, high fan-in = tightly coupled)
|
||||
|
||||
**Structural analysis**:
|
||||
- Identify God Classes / God Modules (> 500 LOC, > 10 public methods, too many responsibilities)
|
||||
- Calculate coupling metrics (afferent/efferent coupling per module)
|
||||
- Calculate cohesion metrics (LCOM -- Lack of Cohesion of Methods)
|
||||
- Detect code duplication (repeated logic blocks, copy-paste patterns)
|
||||
- Identify missing abstractions (repeated conditionals, switch-on-type patterns)
|
||||
|
||||
**API surface analysis**:
|
||||
- Count exported symbols per module (export bloat detection)
|
||||
- Identify dead exports (exported but never imported elsewhere)
|
||||
- Detect dead code (unreachable functions, unused variables, orphan files)
|
||||
- Check for pattern inconsistencies (mixed naming conventions, inconsistent error handling)
|
||||
|
||||
**All project types**:
|
||||
- Collect quantified architecture baseline metrics (dependency count, cycle count, coupling scores, LOC distribution)
|
||||
- Rank top 3-7 architecture issues by severity (Critical / High / Medium)
|
||||
- Record evidence: file paths, line numbers, measured values
|
||||
|
||||
## Phase 4: Report Generation
|
||||
|
||||
1. Write architecture baseline to `<session>/artifacts/architecture-baseline.json`:
|
||||
- Module count, dependency count, cycle count, average coupling, average cohesion
|
||||
- God Class candidates with LOC and method count
|
||||
- Dead code file count, dead export count
|
||||
- Timestamp and project type details
|
||||
|
||||
2. Write architecture report to `<session>/artifacts/architecture-report.md`:
|
||||
- Ranked list of architecture issues with severity, location (file:line or module), measured impact
|
||||
- Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT
|
||||
- Evidence summary per issue
|
||||
- Detected project type and analysis methods used
|
||||
|
||||
3. Update `<session>/wisdom/.msg/meta.json` under `analyzer` namespace:
|
||||
- Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back
|
||||
@@ -0,0 +1,57 @@
|
||||
# Analyze Task
|
||||
|
||||
Parse user task -> detect architecture capabilities -> build dependency graph -> design roles.
|
||||
|
||||
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
|
||||
|
||||
## Signal Detection
|
||||
|
||||
| Keywords | Capability | Prefix |
|
||||
|----------|------------|--------|
|
||||
| analyze, scan, audit, map, identify | analyzer | ANALYZE |
|
||||
| design, plan, strategy, refactoring-plan | designer | DESIGN |
|
||||
| refactor, implement, fix, apply | refactorer | REFACTOR |
|
||||
| validate, build, test, verify, compile | validator | VALIDATE |
|
||||
| review, audit-code, quality, check-code | reviewer | REVIEW |
|
||||
|
||||
## Dependency Graph
|
||||
|
||||
Natural ordering tiers:
|
||||
- Tier 0: analyzer (knowledge gathering -- no dependencies)
|
||||
- Tier 1: designer (requires analyzer output)
|
||||
- Tier 2: refactorer (requires designer output)
|
||||
- Tier 3: validator, reviewer (validation requires refactored artifacts, can run in parallel)
|
||||
|
||||
## Complexity Scoring
|
||||
|
||||
| Factor | Points |
|
||||
|--------|--------|
|
||||
| Per capability | +1 |
|
||||
| Cross-domain refactoring | +2 |
|
||||
| Parallel branches requested | +1 per branch |
|
||||
| Serial depth > 3 | +1 |
|
||||
| Multiple targets (independent mode) | +2 |
|
||||
|
||||
Results: 1-3 Low, 4-6 Medium, 7+ High
|
||||
|
||||
## Role Minimization
|
||||
|
||||
- Cap at 5 roles
|
||||
- Merge overlapping capabilities
|
||||
- Absorb trivial single-step roles
|
||||
|
||||
## Output
|
||||
|
||||
Write <session>/task-analysis.json:
|
||||
```json
|
||||
{
|
||||
"task_description": "<original>",
|
||||
"pipeline_type": "<single|fan-out|independent|auto>",
|
||||
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }],
|
||||
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } },
|
||||
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
|
||||
"complexity": { "score": 0, "level": "Low|Medium|High" },
|
||||
"parallel_mode": "<auto|single|fan-out|independent>",
|
||||
"max_branches": 5
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,287 @@
|
||||
# Command: Dispatch
|
||||
|
||||
Create the architecture optimization task chain with correct dependencies and structured task descriptions. Supports single, fan-out, independent, and auto parallel modes.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| User requirement | From coordinator Phase 1 | Yes |
|
||||
| Session folder | From coordinator Phase 2 | Yes |
|
||||
| Pipeline definition | From SKILL.md Pipeline Definitions | Yes |
|
||||
| Parallel mode | From tasks.json `parallel_mode` | Yes |
|
||||
| Max branches | From tasks.json `max_branches` | Yes |
|
||||
| Independent targets | From tasks.json `independent_targets` (independent mode only) | Conditional |
|
||||
|
||||
1. Load user requirement and refactoring scope from tasks.json
|
||||
2. Load pipeline stage definitions from SKILL.md Task Metadata Registry
|
||||
3. Read `parallel_mode` and `max_branches` from tasks.json
|
||||
4. For `independent` mode: read `independent_targets` array from tasks.json
|
||||
|
||||
## Phase 3: Task Chain Creation (Mode-Branched)
|
||||
|
||||
### Task Entry Template
|
||||
|
||||
Every task in tasks.json `tasks` object uses structured format:
|
||||
|
||||
```json
|
||||
{
|
||||
"<TASK-ID>": {
|
||||
"title": "<concise title>",
|
||||
"description": "PURPOSE: <what this task achieves> | Success: <measurable completion criteria>\nTASK:\n - <step 1: specific action>\n - <step 2: specific action>\n - <step 3: specific action>\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: <branch-id or 'none'>\n - Upstream artifacts: <artifact-1>, <artifact-2>\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <deliverable path> + <quality criteria>\nCONSTRAINTS: <scope limits, focus areas>\n---\nInnerLoop: <true|false>\nBranchId: <B01|A|none>",
|
||||
"role": "<role-name>",
|
||||
"prefix": "<PREFIX>",
|
||||
"deps": ["<upstream-task-id>"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Mode Router
|
||||
|
||||
| Mode | Action |
|
||||
|------|--------|
|
||||
| `single` | Create 5 tasks (ANALYZE -> DESIGN -> REFACTOR -> VALIDATE + REVIEW) -- unchanged from linear pipeline |
|
||||
| `auto` | Create ANALYZE-001 + DESIGN-001 only. **Defer branch creation to CP-2.5** after design completes |
|
||||
| `fan-out` | Create ANALYZE-001 + DESIGN-001 only. **Defer branch creation to CP-2.5** after design completes |
|
||||
| `independent` | Create M complete pipelines immediately (one per target) |
|
||||
|
||||
---
|
||||
|
||||
### Single Mode Task Chain
|
||||
|
||||
Create tasks in dependency order (backward compatible, unchanged):
|
||||
|
||||
**ANALYZE-001** (analyzer, Stage 1):
|
||||
```json
|
||||
{
|
||||
"ANALYZE-001": {
|
||||
"title": "Analyze codebase architecture",
|
||||
"description": "PURPOSE: Analyze codebase architecture to identify structural issues | Success: Baseline metrics captured, top 3-7 issues ranked by severity\nTASK:\n - Detect project type and available analysis tools\n - Execute analysis across relevant dimensions (dependencies, coupling, cohesion, layering, duplication, dead code)\n - Collect baseline metrics and rank architecture issues by severity\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/architecture-baseline.json + <session>/artifacts/architecture-report.md | Quantified metrics with evidence\nCONSTRAINTS: Focus on <refactoring-scope> | Analyze before any changes\n---\nInnerLoop: false",
|
||||
"role": "analyzer",
|
||||
"prefix": "ANALYZE",
|
||||
"deps": [],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**DESIGN-001** (designer, Stage 2):
|
||||
```json
|
||||
{
|
||||
"DESIGN-001": {
|
||||
"title": "Design prioritized refactoring plan",
|
||||
"description": "PURPOSE: Design prioritized refactoring plan from architecture analysis | Success: Actionable plan with measurable success criteria per refactoring\nTASK:\n - Analyze architecture report and baseline metrics\n - Select refactoring strategies per issue type\n - Prioritize by impact/effort ratio, define success criteria\n - Each refactoring MUST have a unique REFACTOR-ID (REFACTOR-001, REFACTOR-002, ...) with non-overlapping target files\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: architecture-baseline.json, architecture-report.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/refactoring-plan.md | Priority-ordered with structural improvement targets, discrete REFACTOR-IDs\nCONSTRAINTS: Focus on highest-impact refactorings | Risk assessment required | Non-overlapping file targets per REFACTOR-ID\n---\nInnerLoop: false",
|
||||
"role": "designer",
|
||||
"prefix": "DESIGN",
|
||||
"deps": ["ANALYZE-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**REFACTOR-001** (refactorer, Stage 3):
|
||||
```json
|
||||
{
|
||||
"REFACTOR-001": {
|
||||
"title": "Implement refactoring changes per design plan",
|
||||
"description": "PURPOSE: Implement refactoring changes per design plan | Success: All planned refactorings applied, code compiles, existing tests pass\nTASK:\n - Load refactoring plan and identify target files\n - Apply refactorings in priority order (P0 first)\n - Update all import references for moved/renamed modules\n - Validate changes compile and pass existing tests\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: refactoring-plan.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: Modified source files + validation passing | Refactorings applied without regressions\nCONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions\n---\nInnerLoop: true",
|
||||
"role": "refactorer",
|
||||
"prefix": "REFACTOR",
|
||||
"deps": ["DESIGN-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**VALIDATE-001** (validator, Stage 4 - parallel):
|
||||
```json
|
||||
{
|
||||
"VALIDATE-001": {
|
||||
"title": "Validate refactoring results against baseline",
|
||||
"description": "PURPOSE: Validate refactoring results against baseline | Success: Build passes, tests pass, no metric regressions, API compatible\nTASK:\n - Load architecture baseline and plan success criteria\n - Run build validation (compilation, type checking)\n - Run test validation (existing test suite)\n - Compare dependency metrics against baseline\n - Verify API compatibility (no dangling references)\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: architecture-baseline.json, refactoring-plan.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/validation-results.json | Per-dimension validation with verdicts\nCONSTRAINTS: Must compare against baseline | Flag any regressions or broken imports\n---\nInnerLoop: false",
|
||||
"role": "validator",
|
||||
"prefix": "VALIDATE",
|
||||
"deps": ["REFACTOR-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**REVIEW-001** (reviewer, Stage 4 - parallel):
|
||||
```json
|
||||
{
|
||||
"REVIEW-001": {
|
||||
"title": "Review refactoring code for correctness and quality",
|
||||
"description": "PURPOSE: Review refactoring code for correctness, pattern consistency, and migration safety | Success: All dimensions reviewed, verdict issued\nTASK:\n - Load modified files and refactoring plan\n - Review across 5 dimensions: correctness, pattern consistency, completeness, migration safety, best practices\n - Issue verdict: APPROVE, REVISE, or REJECT with actionable feedback\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: refactoring-plan.md, validation-results.json (if available)\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity\nCONSTRAINTS: Focus on refactoring changes only | Provide specific file:line references\n---\nInnerLoop: false",
|
||||
"role": "reviewer",
|
||||
"prefix": "REVIEW",
|
||||
"deps": ["REFACTOR-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Auto / Fan-out Mode Task Chain (Deferred Branching)
|
||||
|
||||
For `auto` and `fan-out` modes, create only shared stages now. Branch tasks are created at **CP-2.5** after DESIGN-001 completes.
|
||||
|
||||
Create ANALYZE-001 and DESIGN-001 with same templates as single mode above.
|
||||
|
||||
**Do NOT create REFACTOR/VALIDATE/REVIEW tasks yet.** They are created by the CP-2.5 Branch Creation subroutine in monitor.md.
|
||||
|
||||
---
|
||||
|
||||
### Independent Mode Task Chain
|
||||
|
||||
For `independent` mode, create M complete pipelines -- one per target in `independent_targets` array.
|
||||
|
||||
Pipeline prefix chars: `A, B, C, D, E, F, G, H, I, J` (from config `pipeline_prefix_chars`).
|
||||
|
||||
For each target index `i` (0-based), with prefix char `P = pipeline_prefix_chars[i]`:
|
||||
|
||||
```javascript
|
||||
// Create session subdirectory for this pipeline
|
||||
Bash("mkdir -p <session>/artifacts/pipelines/<P>")
|
||||
|
||||
// Add pipeline tasks to tasks.json:
|
||||
state.tasks["ANALYZE-<P>01"] = { title: "...", role: "analyzer", prefix: "ANALYZE", deps: [], ... }
|
||||
state.tasks["DESIGN-<P>01"] = { title: "...", role: "designer", prefix: "DESIGN", deps: ["ANALYZE-<P>01"], ... }
|
||||
state.tasks["REFACTOR-<P>01"] = { title: "...", role: "refactorer", prefix: "REFACTOR", deps: ["DESIGN-<P>01"], ... }
|
||||
state.tasks["VALIDATE-<P>01"] = { title: "...", role: "validator", prefix: "VALIDATE", deps: ["REFACTOR-<P>01"], ... }
|
||||
state.tasks["REVIEW-<P>01"] = { title: "...", role: "reviewer", prefix: "REVIEW", deps: ["REFACTOR-<P>01"], ... }
|
||||
```
|
||||
|
||||
Task descriptions follow same template as single mode, with additions:
|
||||
- `Pipeline: <P>` in CONTEXT
|
||||
- Artifact paths use `<session>/artifacts/pipelines/<P>/` instead of `<session>/artifacts/`
|
||||
- Meta.json namespace uses `<role>.<P>` (e.g., `analyzer.A`, `refactorer.B`)
|
||||
- Each pipeline's scope is its specific target from `independent_targets[i]`
|
||||
|
||||
Example for pipeline A with target "refactor auth module":
|
||||
```json
|
||||
{
|
||||
"ANALYZE-A01": {
|
||||
"title": "Analyze auth module architecture",
|
||||
"description": "PURPOSE: Analyze auth module architecture | Success: Auth module structural issues identified\nTASK:\n - Detect project type and available analysis tools\n - Execute architecture analysis focused on auth module\n - Collect baseline metrics and rank auth module issues\nCONTEXT:\n - Session: <session-folder>\n - Scope: refactor auth module\n - Pipeline: A\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: analyzer.A)\nEXPECTED: <session>/artifacts/pipelines/A/architecture-baseline.json + architecture-report.md\nCONSTRAINTS: Focus on auth module scope\n---\nInnerLoop: false\nPipelineId: A",
|
||||
"role": "analyzer",
|
||||
"prefix": "ANALYZE",
|
||||
"deps": [],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CP-2.5: Branch Creation Subroutine
|
||||
|
||||
**Triggered by**: monitor.md handleSpawnNext when DESIGN-001 completes in `auto` or `fan-out` mode.
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. Read `<session>/artifacts/refactoring-plan.md` to count REFACTOR-IDs
|
||||
2. Read `.msg/meta.json` -> `designer.refactoring_count`
|
||||
3. **Auto mode decision**:
|
||||
|
||||
| Refactoring Count | Decision |
|
||||
|-------------------|----------|
|
||||
| count <= 2 | Switch to `single` mode -- add REFACTOR-001, VALIDATE-001, REVIEW-001 to tasks.json (standard single pipeline) |
|
||||
| count >= 3 | Switch to `fan-out` mode -- add branch tasks below |
|
||||
|
||||
4. Update tasks.json with resolved `parallel_mode` (auto -> single or fan-out)
|
||||
|
||||
5. **Fan-out branch creation** (when count >= 3 or forced fan-out):
|
||||
- Truncate to `max_branches` if `refactoring_count > max_branches` (keep top N by priority)
|
||||
- For each refactoring `i` (1-indexed), branch ID = `B{NN}` where NN = zero-padded i:
|
||||
|
||||
```javascript
|
||||
// Create branch artifact directory
|
||||
Bash("mkdir -p <session>/artifacts/branches/B{NN}")
|
||||
|
||||
// Extract single REFACTOR detail to branch
|
||||
Write("<session>/artifacts/branches/B{NN}/refactoring-detail.md",
|
||||
extracted REFACTOR-{NNN} block from refactoring-plan.md)
|
||||
```
|
||||
|
||||
6. Add branch tasks to tasks.json for each branch B{NN}:
|
||||
|
||||
```json
|
||||
{
|
||||
"REFACTOR-B{NN}": {
|
||||
"title": "Implement refactoring REFACTOR-{NNN}",
|
||||
"description": "PURPOSE: Implement refactoring REFACTOR-{NNN} | Success: Single refactoring applied, compiles, tests pass\nTASK:\n - Load refactoring detail from branches/B{NN}/refactoring-detail.md\n - Apply this single refactoring to target files\n - Update all import references for moved/renamed modules\n - Validate changes compile and pass existing tests\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: refactorer.B{NN})\nEXPECTED: Modified source files for REFACTOR-{NNN} only\nCONSTRAINTS: Only implement this branch's refactoring | Do not touch files outside REFACTOR-{NNN} scope\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "refactorer",
|
||||
"prefix": "REFACTOR",
|
||||
"deps": ["DESIGN-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
},
|
||||
"VALIDATE-B{NN}": {
|
||||
"title": "Validate branch B{NN} refactoring",
|
||||
"description": "PURPOSE: Validate branch B{NN} refactoring | Success: REFACTOR-{NNN} passes build, tests, and metric checks\nTASK:\n - Load architecture baseline and REFACTOR-{NNN} success criteria\n - Validate build, tests, dependency metrics, and API compatibility\n - Compare against baseline, check for regressions\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: validator.B{NN})\nEXPECTED: <session>/artifacts/branches/B{NN}/validation-results.json\nCONSTRAINTS: Only validate this branch's changes\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "validator",
|
||||
"prefix": "VALIDATE",
|
||||
"deps": ["REFACTOR-B{NN}"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
},
|
||||
"REVIEW-B{NN}": {
|
||||
"title": "Review branch B{NN} refactoring code",
|
||||
"description": "PURPOSE: Review branch B{NN} refactoring code | Success: Code quality verified for REFACTOR-{NNN}\nTASK:\n - Load modified files from refactorer.B{NN} namespace in .msg/meta.json\n - Review across 5 dimensions for this branch's changes only\n - Issue verdict: APPROVE, REVISE, or REJECT\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: reviewer.B{NN})\nEXPECTED: <session>/artifacts/branches/B{NN}/review-report.md\nCONSTRAINTS: Only review this branch's changes\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "reviewer",
|
||||
"prefix": "REVIEW",
|
||||
"deps": ["REFACTOR-B{NN}"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
7. Update tasks.json:
|
||||
- `branches`: array of branch IDs (["B01", "B02", ...])
|
||||
- `fix_cycles`: object keyed by branch ID, all initialized to 0
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
Verify task chain integrity:
|
||||
|
||||
| Check | Method | Expected |
|
||||
|-------|--------|----------|
|
||||
| Task count correct | tasks.json task count | single: 5, auto/fan-out: 2 (pre-CP-2.5), independent: 5*M |
|
||||
| Dependencies correct | Trace dependency graph | Acyclic, correct deps |
|
||||
| No circular dependencies | Trace dependency graph | Acyclic |
|
||||
| Task IDs use correct prefixes | Pattern check | Match naming rules per mode |
|
||||
| Structured descriptions complete | Each has PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS | All present |
|
||||
| Branch/Pipeline IDs consistent | Cross-check with tasks.json | Match |
|
||||
|
||||
### Naming Rules Summary
|
||||
|
||||
| Mode | Stage 3 | Stage 4 | Fix |
|
||||
|------|---------|---------|-----|
|
||||
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001, FIX-002 |
|
||||
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1, FIX-B01-2 |
|
||||
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1, FIX-A01-2 |
|
||||
|
||||
If validation fails, fix the specific task and re-validate.
|
||||
@@ -0,0 +1,204 @@
|
||||
# Monitor Pipeline
|
||||
|
||||
Synchronous pipeline coordination using spawn_agent + wait_agent.
|
||||
|
||||
## Constants
|
||||
|
||||
- WORKER_AGENT: team_worker
|
||||
- ONE_STEP_PER_INVOCATION: false (synchronous wait loop)
|
||||
- FAST_ADVANCE_AWARE: true
|
||||
|
||||
## Handler Router
|
||||
|
||||
| Source | Handler |
|
||||
|--------|---------|
|
||||
| Message contains branch tag [refactorer-B01], etc. | handleSpawnNext (branch-aware) |
|
||||
| Message contains pipeline tag [analyzer-A], etc. | handleSpawnNext (pipeline-aware) |
|
||||
| "consensus_blocked" | handleConsensus |
|
||||
| "capability_gap" | handleAdapt |
|
||||
| "check" or "status" | handleCheck |
|
||||
| "resume" or "continue" | handleResume |
|
||||
| All tasks completed | handleComplete |
|
||||
| Default | handleSpawnNext |
|
||||
|
||||
## handleCheck
|
||||
|
||||
Read-only status report from tasks.json, then STOP.
|
||||
|
||||
1. Read tasks.json
|
||||
2. Count tasks by status (pending, in_progress, completed, failed)
|
||||
|
||||
Output (single mode):
|
||||
```
|
||||
[coordinator] Pipeline Status
|
||||
[coordinator] Progress: <done>/<total> (<pct>%)
|
||||
[coordinator] Active agents: <list from active_agents>
|
||||
[coordinator] Ready: <pending tasks with resolved deps>
|
||||
[coordinator] Commands: 'resume' to advance | 'check' to refresh
|
||||
```
|
||||
|
||||
Fan-out mode adds per-branch grouping. Independent mode adds per-pipeline grouping.
|
||||
|
||||
## handleResume
|
||||
|
||||
1. Read tasks.json, check active_agents
|
||||
2. No active agents -> handleSpawnNext
|
||||
3. Has active agents -> check each status
|
||||
4. Proceed to handleSpawnNext
|
||||
|
||||
## handleSpawnNext
|
||||
|
||||
Find ready tasks, spawn workers, wait for completion, process results.
|
||||
|
||||
1. Read tasks.json
|
||||
2. Collect: completedTasks, inProgressTasks, readyTasks (pending + all deps completed)
|
||||
3. No ready + nothing in progress -> handleComplete
|
||||
4. No ready + work in progress -> report waiting, STOP
|
||||
5. Has ready -> for each:
|
||||
a. Check if inner loop role with active worker -> skip (worker picks up)
|
||||
b. Update task status in tasks.json -> in_progress
|
||||
c. team_msg log -> task_unblocked
|
||||
d. **CP-2.5 check** (auto/fan-out mode only):
|
||||
- If completed task is DESIGN-001 AND parallel_mode is `auto` or `fan-out`:
|
||||
- Execute CP-2.5 Branch Creation from dispatch.md
|
||||
- After branch creation, re-collect readyTasks (spawns all REFACTOR-B* in parallel)
|
||||
|
||||
### Spawn Workers
|
||||
|
||||
For each ready task:
|
||||
|
||||
```javascript
|
||||
// 1) Update status in tasks.json
|
||||
state.tasks[taskId].status = 'in_progress'
|
||||
|
||||
// 2) Spawn worker
|
||||
const agentId = spawn_agent({
|
||||
agent_type: "team_worker",
|
||||
items: [
|
||||
{ type: "text", text: `## Role Assignment
|
||||
role: ${task.role}
|
||||
role_spec: ${skillRoot}/roles/${task.role}/role.md
|
||||
session: ${sessionFolder}
|
||||
session_id: ${sessionId}
|
||||
team_name: arch-opt
|
||||
requirement: ${task.description}
|
||||
inner_loop: ${task.role === 'refactorer'}` },
|
||||
|
||||
{ type: "text", text: `Read role_spec file (${skillRoot}/roles/${task.role}/role.md) to load Phase 2-4 domain instructions.
|
||||
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` },
|
||||
|
||||
{ type: "text", text: `## Task Context
|
||||
task_id: ${taskId}
|
||||
title: ${task.title}
|
||||
description: ${task.description}` },
|
||||
|
||||
{ type: "text", text: `## Upstream Context\n${prevContext}` }
|
||||
]
|
||||
})
|
||||
|
||||
// 3) Track agent
|
||||
state.active_agents[taskId] = { agentId, role: task.role, started_at: now }
|
||||
```
|
||||
|
||||
6. Parallel spawn rules by mode:
|
||||
|
||||
| Mode | Scenario | Spawn Behavior |
|
||||
|------|----------|---------------|
|
||||
| Single | Stage 4 ready | Spawn VALIDATE-001 + REVIEW-001 in parallel |
|
||||
| Fan-out (CP-2.5 done) | All REFACTOR-B* unblocked | Spawn ALL REFACTOR-B* in parallel |
|
||||
| Fan-out (REFACTOR-B{NN} done) | VALIDATE + REVIEW ready | Spawn both for that branch in parallel |
|
||||
| Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel |
|
||||
|
||||
### Wait and Process Results
|
||||
|
||||
After spawning all ready tasks:
|
||||
|
||||
```javascript
|
||||
// 4) Batch wait for all spawned workers
|
||||
const agentIds = Object.values(state.active_agents).map(a => a.agentId)
|
||||
wait_agent({ ids: agentIds, timeout_ms: 900000 })
|
||||
|
||||
// 5) Collect results
|
||||
for (const [taskId, agent] of Object.entries(state.active_agents)) {
|
||||
state.tasks[taskId].status = 'completed'
|
||||
close_agent({ id: agent.agentId })
|
||||
delete state.active_agents[taskId]
|
||||
}
|
||||
```
|
||||
|
||||
### Persist and Loop
|
||||
|
||||
After processing all results:
|
||||
1. Write updated tasks.json
|
||||
2. Check stage checkpoints (CP-1, CP-2, CP-2.5, CP-3)
|
||||
3. Check if more tasks are now ready (deps newly resolved)
|
||||
4. If yes -> loop back to step 1 of handleSpawnNext
|
||||
5. If no more ready and all done -> handleComplete
|
||||
6. If no more ready but some still blocked -> report status, STOP
|
||||
|
||||
## Review-Fix Cycle (CP-3)
|
||||
|
||||
**Per-branch/pipeline scoping**: Each branch/pipeline has its own independent fix cycle.
|
||||
|
||||
When both VALIDATE-* and REVIEW-* are completed for a branch/pipeline:
|
||||
|
||||
1. Read validation verdict from scoped meta.json namespace
|
||||
2. Read review verdict from scoped meta.json namespace
|
||||
|
||||
| Validate Verdict | Review Verdict | Action |
|
||||
|-----------------|----------------|--------|
|
||||
| PASS | APPROVE | -> handleComplete check |
|
||||
| PASS | REVISE | Create FIX task in tasks.json with review feedback |
|
||||
| FAIL | APPROVE | Create FIX task in tasks.json with validation feedback |
|
||||
| FAIL | REVISE/REJECT | Create FIX task in tasks.json with combined feedback |
|
||||
| Any | REJECT | Create FIX task in tasks.json + flag for designer re-evaluation |
|
||||
|
||||
Fix cycle tracking per branch in tasks.json `fix_cycles`:
|
||||
- < 3: Add FIX task to tasks.json, increment cycle count
|
||||
- >= 3: Escalate THIS branch to user. Other branches continue
|
||||
|
||||
## handleComplete
|
||||
|
||||
Pipeline done. Generate report and completion action.
|
||||
|
||||
Completion check by mode:
|
||||
| Mode | Completion Condition |
|
||||
|------|---------------------|
|
||||
| Single | All 5 tasks (+ any FIX/retry tasks) completed |
|
||||
| Fan-out | ALL branches have VALIDATE + REVIEW completed (or escalated), shared stages done |
|
||||
| Independent | ALL pipelines have VALIDATE + REVIEW completed (or escalated) |
|
||||
|
||||
1. For fan-out/independent: aggregate per-branch/pipeline results to `<session>/artifacts/aggregate-results.json`
|
||||
2. If any tasks not completed, return to handleSpawnNext
|
||||
3. If all completed -> transition to coordinator Phase 5
|
||||
4. Execute completion action per tasks.json completion_action:
|
||||
- interactive -> request_user_input (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean (rm -rf session folder)
|
||||
- auto_keep -> Keep Active (status=paused)
|
||||
|
||||
## handleConsensus
|
||||
|
||||
Handle consensus_blocked signals from discuss rounds.
|
||||
|
||||
| Severity | Action |
|
||||
|----------|--------|
|
||||
| HIGH | Pause pipeline (or branch), notify user with findings summary |
|
||||
| MEDIUM | Add revision task to tasks.json for the blocked role (scoped to branch if applicable) |
|
||||
| LOW | Log finding, continue pipeline |
|
||||
|
||||
## handleAdapt
|
||||
|
||||
Capability gap reported mid-pipeline.
|
||||
|
||||
1. Parse gap description
|
||||
2. Check if existing role covers it -> redirect
|
||||
3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/
|
||||
4. Add new task to tasks.json, spawn worker via spawn_agent + wait_agent
|
||||
5. Role count >= 5 -> merge or pause
|
||||
|
||||
## Fast-Advance Reconciliation
|
||||
|
||||
On every coordinator wake:
|
||||
1. Read team_msg entries with type="fast_advance"
|
||||
2. Sync active_agents with spawned successors
|
||||
3. No duplicate spawns
|
||||
162
.codex/skills/team-arch-opt/roles/coordinator/role.md
Normal file
162
.codex/skills/team-arch-opt/roles/coordinator/role.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Coordinator
|
||||
|
||||
Orchestrate team-arch-opt: analyze -> dispatch -> spawn -> monitor -> report.
|
||||
|
||||
## Identity
|
||||
- Name: coordinator | Tag: [coordinator]
|
||||
- Responsibility: Analyze task -> Create session -> Dispatch tasks -> Monitor progress -> Report results
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Spawn workers via `spawn_agent({ agent_type: "team_worker" })` and wait via `wait_agent`
|
||||
- Follow Command Execution Protocol for dispatch and monitor commands
|
||||
- Respect pipeline stage dependencies (deps)
|
||||
- Handle review-fix cycles with max 3 iterations
|
||||
- Execute completion action in Phase 5
|
||||
|
||||
### MUST NOT
|
||||
- Implement domain logic (analyzing, refactoring, reviewing) -- workers handle this
|
||||
- Spawn workers without creating tasks first
|
||||
- Skip checkpoints when configured
|
||||
- Force-advance pipeline past failed review/validation
|
||||
- Modify source code directly -- delegate to refactorer worker
|
||||
|
||||
## Command Execution Protocol
|
||||
|
||||
When coordinator needs to execute a specific phase:
|
||||
1. Read `commands/<command>.md`
|
||||
2. Follow the workflow defined in the command
|
||||
3. Commands are inline execution guides, NOT separate agents
|
||||
4. Execute synchronously, complete before proceeding
|
||||
|
||||
## Entry Router
|
||||
|
||||
| Detection | Condition | Handler |
|
||||
|-----------|-----------|---------|
|
||||
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
|
||||
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
|
||||
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
|
||||
| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) |
|
||||
| Interrupted session | Active session in .workflow/.team/TAO-* | -> Phase 0 |
|
||||
| New session | None of above | -> Phase 1 |
|
||||
|
||||
For check/resume/adapt/complete: load @commands/monitor.md, execute handler, STOP.
|
||||
|
||||
## Phase 0: Session Resume Check
|
||||
|
||||
1. Scan `.workflow/.team/TAO-*/tasks.json` for active/paused sessions
|
||||
2. No sessions -> Phase 1
|
||||
3. Single session -> reconcile:
|
||||
a. Read tasks.json, reset in_progress -> pending
|
||||
b. Rebuild active_agents map
|
||||
c. Kick first ready task via handleSpawnNext
|
||||
4. Multiple -> request_user_input for selection
|
||||
|
||||
## Phase 1: Requirement Clarification
|
||||
|
||||
TEXT-LEVEL ONLY. No source code reading.
|
||||
|
||||
1. Parse task description from $ARGUMENTS
|
||||
2. Parse parallel mode flags:
|
||||
|
||||
| Flag | Value | Default |
|
||||
|------|-------|---------|
|
||||
| `--parallel-mode` | `single`, `fan-out`, `independent`, `auto` | `auto` |
|
||||
| `--max-branches` | integer 1-10 | 5 |
|
||||
|
||||
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 |
|
||||
| Multiple quoted targets (independent mode) | Per-target scoped refactoring |
|
||||
|
||||
4. If target is unclear, request_user_input for scope clarification
|
||||
5. Record requirement with scope, target issues, parallel_mode, max_branches
|
||||
|
||||
## Phase 2: Create Session + Initialize
|
||||
|
||||
1. Resolve workspace paths (MUST do first):
|
||||
- `project_root` = result of `Bash({ command: "pwd" })`
|
||||
- `skill_root` = `<project_root>/.codex/skills/team-arch-opt`
|
||||
2. Generate session ID: `TAO-<slug>-<date>`
|
||||
3. Create session folder structure:
|
||||
```bash
|
||||
mkdir -p .workflow/.team/${SESSION_ID}/{artifacts,artifacts/branches,artifacts/pipelines,wisdom,wisdom/.msg}
|
||||
```
|
||||
4. Initialize meta.json via team_msg state_update:
|
||||
```
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log", session_id: "<id>", from: "coordinator",
|
||||
type: "state_update", summary: "Session initialized",
|
||||
data: { pipeline_mode: "<mode>", pipeline_stages: ["analyzer","designer","refactorer","validator","reviewer"], team_name: "arch-opt" }
|
||||
})
|
||||
```
|
||||
5. Write initial tasks.json:
|
||||
```json
|
||||
{
|
||||
"session_id": "<id>",
|
||||
"pipeline": "<parallel_mode>",
|
||||
"requirement": "<original requirement>",
|
||||
"created_at": "<ISO timestamp>",
|
||||
"parallel_mode": "<single|fan-out|independent|auto>",
|
||||
"max_branches": 5,
|
||||
"branches": [],
|
||||
"independent_targets": [],
|
||||
"fix_cycles": {},
|
||||
"completed_waves": [],
|
||||
"active_agents": {},
|
||||
"tasks": {}
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 3: Create Task Chain
|
||||
|
||||
Delegate to @commands/dispatch.md:
|
||||
1. Read dependency graph and parallel mode from tasks.json
|
||||
2. Topological sort tasks
|
||||
3. Write tasks to tasks.json with deps arrays
|
||||
4. Update tasks.json metadata (total count)
|
||||
|
||||
## Phase 4: Spawn-and-Wait
|
||||
|
||||
Delegate to @commands/monitor.md#handleSpawnNext:
|
||||
1. Find ready tasks (pending + deps resolved)
|
||||
2. Spawn team_worker agents via spawn_agent
|
||||
3. Wait for completion via wait_agent
|
||||
4. Process results, advance pipeline
|
||||
5. Repeat until all waves complete or pipeline blocked
|
||||
|
||||
## Phase 5: Report + Completion Action
|
||||
|
||||
1. Load session state -> count completed tasks, calculate duration
|
||||
2. List deliverables:
|
||||
|
||||
| Deliverable | Path |
|
||||
|-------------|------|
|
||||
| Architecture Baseline | <session>/artifacts/architecture-baseline.json |
|
||||
| Architecture Report | <session>/artifacts/architecture-report.md |
|
||||
| Refactoring Plan | <session>/artifacts/refactoring-plan.md |
|
||||
| Validation Results | <session>/artifacts/validation-results.json |
|
||||
| Review Report | <session>/artifacts/review-report.md |
|
||||
|
||||
3. Include discussion summaries if discuss rounds were used
|
||||
4. Output pipeline summary: task count, duration, improvement metrics
|
||||
|
||||
5. Execute completion action per tasks.json completion_action:
|
||||
- interactive -> request_user_input (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean (rm -rf session folder)
|
||||
- auto_keep -> Keep Active (status=paused)
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| Task too vague | request_user_input for clarification |
|
||||
| Session corruption | Attempt recovery, fallback to manual |
|
||||
| Worker crash | Reset task to pending in tasks.json, respawn via spawn_agent |
|
||||
| Dependency cycle | Detect in analysis, halt |
|
||||
| Role limit exceeded | Merge overlapping roles |
|
||||
115
.codex/skills/team-arch-opt/roles/designer/role.md
Normal file
115
.codex/skills/team-arch-opt/roles/designer/role.md
Normal file
@@ -0,0 +1,115 @@
|
||||
---
|
||||
role: designer
|
||||
prefix: DESIGN
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Refactoring Designer
|
||||
|
||||
Analyze architecture reports and baseline metrics to design a prioritized refactoring plan with concrete strategies, expected structural improvements, and risk assessments.
|
||||
|
||||
## Phase 2: Analysis Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Architecture report | <session>/artifacts/architecture-report.md | Yes |
|
||||
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
| Wisdom files | <session>/wisdom/patterns.md | No |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. Read architecture report -- extract ranked issue list with severities and categories
|
||||
3. Read architecture baseline -- extract current structural metrics
|
||||
4. Load .msg/meta.json for analyzer findings (project_type, scope)
|
||||
5. Assess overall refactoring complexity:
|
||||
|
||||
| Issue Count | Severity Mix | Complexity |
|
||||
|-------------|-------------|------------|
|
||||
| 1-2 | All Medium | Low |
|
||||
| 2-3 | Mix of High/Medium | Medium |
|
||||
| 3+ or any Critical | Any Critical present | High |
|
||||
|
||||
## Phase 3: Strategy Formulation
|
||||
|
||||
For each architecture issue, select refactoring approach by type:
|
||||
|
||||
| Issue Type | Strategies | Risk Level |
|
||||
|------------|-----------|------------|
|
||||
| Circular dependency | Interface extraction, dependency inversion, mediator pattern | High |
|
||||
| God Class/Module | SRP decomposition, extract class/module, delegate pattern | High |
|
||||
| Layering violation | Move to correct layer, introduce Facade, add anti-corruption layer | Medium |
|
||||
| Code duplication | Extract shared utility/base class, template method pattern | Low |
|
||||
| High coupling | Introduce interface/abstraction, dependency injection, event-driven | Medium |
|
||||
| API bloat / dead exports | Privatize internals, re-export only public API, barrel file cleanup | Low |
|
||||
| Dead code | Safe removal with reference verification | Low |
|
||||
| Missing abstraction | Extract interface/type, introduce strategy/factory pattern | Medium |
|
||||
|
||||
Prioritize refactorings by impact/effort ratio:
|
||||
|
||||
| Priority | Criteria |
|
||||
|----------|----------|
|
||||
| P0 (Critical) | High impact + Low effort -- quick wins (dead code removal, simple moves) |
|
||||
| P1 (High) | High impact + Medium effort (cycle breaking, layer fixes) |
|
||||
| P2 (Medium) | Medium impact + Low effort (duplication extraction) |
|
||||
| P3 (Low) | Low impact or High effort -- defer (large God Class decomposition) |
|
||||
|
||||
If complexity is High, invoke `discuss` CLI tool (DISCUSS-REFACTOR round) to evaluate trade-offs between competing strategies before finalizing the plan.
|
||||
|
||||
Define measurable success criteria per refactoring (target metric improvement or structural change).
|
||||
|
||||
## Phase 4: Plan Output
|
||||
|
||||
1. Write refactoring plan to `<session>/artifacts/refactoring-plan.md`:
|
||||
|
||||
Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block:
|
||||
|
||||
```markdown
|
||||
### REFACTOR-001: <title>
|
||||
- Priority: P0
|
||||
- Target issue: <issue from report>
|
||||
- Issue type: <CYCLE|COUPLING|GOD_CLASS|DUPLICATION|LAYER_VIOLATION|DEAD_CODE|API_BLOAT>
|
||||
- Target files: <file-list>
|
||||
- Strategy: <selected approach>
|
||||
- Expected improvement: <metric> by <description>
|
||||
- Risk level: <Low/Medium/High>
|
||||
- Success criteria: <specific structural change to verify>
|
||||
- Implementation guidance:
|
||||
1. <step 1>
|
||||
2. <step 2>
|
||||
3. <step 3>
|
||||
|
||||
### REFACTOR-002: <title>
|
||||
...
|
||||
```
|
||||
|
||||
Requirements:
|
||||
- Each REFACTOR-ID is sequentially numbered (REFACTOR-001, REFACTOR-002, ...)
|
||||
- Each refactoring must be **non-overlapping** in target files (no two REFACTOR-IDs modify the same file unless explicitly noted with conflict resolution)
|
||||
- Implementation guidance must be self-contained -- a branch refactorer should be able to work from a single REFACTOR block without reading others
|
||||
|
||||
2. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace:
|
||||
- Read existing -> merge -> write back:
|
||||
```json
|
||||
{
|
||||
"designer": {
|
||||
"complexity": "<Low|Medium|High>",
|
||||
"refactoring_count": 4,
|
||||
"priorities": ["P0", "P0", "P1", "P2"],
|
||||
"discuss_used": false,
|
||||
"refactorings": [
|
||||
{
|
||||
"id": "REFACTOR-001",
|
||||
"title": "<title>",
|
||||
"issue_type": "<CYCLE|COUPLING|...>",
|
||||
"priority": "P0",
|
||||
"target_files": ["src/a.ts", "src/b.ts"],
|
||||
"expected_improvement": "<metric> by <description>",
|
||||
"success_criteria": "<threshold>"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. If DISCUSS-REFACTOR was triggered, record discussion summary in `<session>/discussions/DISCUSS-REFACTOR.md`
|
||||
102
.codex/skills/team-arch-opt/roles/refactorer/role.md
Normal file
102
.codex/skills/team-arch-opt/roles/refactorer/role.md
Normal file
@@ -0,0 +1,102 @@
|
||||
---
|
||||
role: refactorer
|
||||
prefix: REFACTOR
|
||||
inner_loop: true
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Code Refactorer
|
||||
|
||||
Implement architecture refactoring changes following the design plan. For FIX tasks, apply targeted corrections based on review/validation feedback.
|
||||
|
||||
## Modes
|
||||
|
||||
| Mode | Task Prefix | Trigger | Focus |
|
||||
|------|-------------|---------|-------|
|
||||
| Refactor | REFACTOR | Design plan ready | Apply refactorings per plan priority |
|
||||
| Fix | FIX | Review/validation feedback | Targeted fixes for identified issues |
|
||||
|
||||
## Phase 2: Plan & Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Refactoring plan | <session>/artifacts/refactoring-plan.md | Yes (REFACTOR, no branch) |
|
||||
| Branch refactoring detail | <session>/artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) |
|
||||
| Pipeline refactoring plan | <session>/artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) |
|
||||
| Review/validation feedback | From task description | Yes (FIX) |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
| Wisdom files | <session>/wisdom/patterns.md | No |
|
||||
| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) |
|
||||
|
||||
1. Extract session path and task mode (REFACTOR or FIX) from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- load single refactoring detail |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- load pipeline-scoped plan |
|
||||
| Neither present | - | Single mode -- load full refactoring plan |
|
||||
|
||||
3. **Load refactoring context by mode**:
|
||||
- **Single mode (no branch)**: Read `<session>/artifacts/refactoring-plan.md` -- extract ALL priority-ordered changes
|
||||
- **Fan-out branch**: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- extract ONLY this branch's refactoring (single REFACTOR-ID)
|
||||
- **Independent pipeline**: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` -- extract this pipeline's plan
|
||||
|
||||
4. For FIX: parse review/validation feedback for specific issues to address
|
||||
5. Use `explore` CLI tool to load implementation context for target files
|
||||
6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks
|
||||
|
||||
**Meta.json namespace**:
|
||||
- Single: write to `refactorer` namespace
|
||||
- Fan-out: write to `refactorer.B{NN}` namespace
|
||||
- Independent: write to `refactorer.{P}` namespace
|
||||
|
||||
## Phase 3: Code Implementation
|
||||
|
||||
Implementation backend selection:
|
||||
|
||||
| Backend | Condition | Method |
|
||||
|---------|-----------|--------|
|
||||
| CLI | Multi-file refactoring with clear plan | ccw cli --tool gemini --mode write |
|
||||
| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools |
|
||||
|
||||
For REFACTOR tasks:
|
||||
- **Single mode**: Apply refactorings in plan priority order (P0 first, then P1, etc.)
|
||||
- **Fan-out branch**: Apply ONLY this branch's single refactoring (from refactoring-detail.md)
|
||||
- **Independent pipeline**: Apply this pipeline's refactorings in priority order
|
||||
- Follow implementation guidance from plan (target files, patterns)
|
||||
- **Preserve existing behavior -- refactoring must not change functionality**
|
||||
- **Update ALL import references** when moving/renaming modules
|
||||
- **Update ALL test files** that reference moved/renamed symbols
|
||||
|
||||
For FIX tasks:
|
||||
- Read specific issues from review/validation feedback
|
||||
- Apply targeted corrections to flagged code locations
|
||||
- Verify the fix addresses the exact concern raised
|
||||
|
||||
General rules:
|
||||
- Make minimal, focused changes per refactoring
|
||||
- Add comments only where refactoring logic is non-obvious
|
||||
- Preserve existing code style and conventions
|
||||
- Verify no dangling imports after module moves
|
||||
|
||||
## Phase 4: Self-Validation
|
||||
|
||||
| Check | Method | Pass Criteria |
|
||||
|-------|--------|---------------|
|
||||
| Syntax | IDE diagnostics or build check | No new errors |
|
||||
| File integrity | Verify all planned files exist and are modified | All present |
|
||||
| Import integrity | Verify no broken imports after moves | All imports resolve |
|
||||
| Acceptance | Match refactoring plan success criteria | All structural changes applied |
|
||||
| No regression | Run existing tests if available | No new failures |
|
||||
|
||||
If validation fails, attempt auto-fix (max 2 attempts) before reporting error.
|
||||
|
||||
Append to context_accumulator for next REFACTOR/FIX task (single/inner-loop mode only):
|
||||
- Files modified, refactorings applied, validation results
|
||||
- Any discovered patterns or caveats for subsequent iterations
|
||||
|
||||
**Branch output paths**:
|
||||
- Single: write artifacts to `<session>/artifacts/`
|
||||
- Fan-out: write artifacts to `<session>/artifacts/branches/B{NN}/`
|
||||
- Independent: write artifacts to `<session>/artifacts/pipelines/{P}/`
|
||||
111
.codex/skills/team-arch-opt/roles/reviewer/role.md
Normal file
111
.codex/skills/team-arch-opt/roles/reviewer/role.md
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
role: reviewer
|
||||
prefix: REVIEW
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Reviewer
|
||||
|
||||
Review refactoring code changes for correctness, pattern consistency, completeness, migration safety, and adherence to best practices. Provide structured verdicts with actionable feedback.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Refactoring code changes | From REFACTOR task artifacts / git diff | Yes |
|
||||
| Refactoring plan / detail | Varies by mode (see below) | Yes |
|
||||
| Validation results | Varies by mode (see below) | No |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- review only this branch's changes |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- review pipeline-scoped changes |
|
||||
| Neither present | - | Single mode -- review all refactoring changes |
|
||||
|
||||
3. **Load refactoring context by mode**:
|
||||
- Single: Read `<session>/artifacts/refactoring-plan.md`
|
||||
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md`
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
|
||||
|
||||
4. Load .msg/meta.json for scoped refactorer namespace:
|
||||
- Single: `refactorer` namespace
|
||||
- Fan-out: `refactorer.B{NN}` namespace
|
||||
- Independent: `refactorer.{P}` namespace
|
||||
|
||||
5. Identify changed files from refactorer context -- read ONLY files modified by this branch/pipeline
|
||||
6. If validation results available, read from scoped path:
|
||||
- Single: `<session>/artifacts/validation-results.json`
|
||||
- Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json`
|
||||
- Independent: `<session>/artifacts/pipelines/{P}/validation-results.json`
|
||||
|
||||
## Phase 3: Multi-Dimension Review
|
||||
|
||||
Analyze refactoring changes across five dimensions:
|
||||
|
||||
| Dimension | Focus | Severity |
|
||||
|-----------|-------|----------|
|
||||
| Correctness | No behavior changes, all references updated, no dangling imports | Critical |
|
||||
| Pattern consistency | Follows existing patterns, naming consistent, language-idiomatic | High |
|
||||
| Completeness | All related code updated (imports, tests, config, documentation) | High |
|
||||
| Migration safety | No dangling references, backward compatible, public API preserved | Critical |
|
||||
| Best practices | Clean Architecture / SOLID principles, appropriate abstraction level | Medium |
|
||||
|
||||
Per-dimension review process:
|
||||
- Scan modified files for patterns matching each dimension
|
||||
- Record findings with severity (Critical / High / Medium / Low)
|
||||
- Include specific file:line references and suggested fixes
|
||||
|
||||
**Correctness checks**:
|
||||
- Verify moved code preserves original behavior (no logic changes mixed with structural changes)
|
||||
- Check all import/require statements updated to new paths
|
||||
- Verify no orphaned files left behind after moves
|
||||
|
||||
**Pattern consistency checks**:
|
||||
- New module names follow existing naming conventions
|
||||
- Extracted interfaces/classes use consistent patterns with existing codebase
|
||||
- File organization matches project conventions (e.g., index files, barrel exports)
|
||||
|
||||
**Completeness checks**:
|
||||
- All test files updated for moved/renamed modules
|
||||
- Configuration files updated if needed (e.g., path aliases, build configs)
|
||||
- Type definitions updated for extracted interfaces
|
||||
|
||||
**Migration safety checks**:
|
||||
- Public API surface unchanged (same exports available to consumers)
|
||||
- No circular dependencies introduced by the refactoring
|
||||
- Re-exports in place if module paths changed for backward compatibility
|
||||
|
||||
**Best practices checks**:
|
||||
- Extracted modules have clear single responsibility
|
||||
- Dependency direction follows layer conventions (dependencies flow inward)
|
||||
- Appropriate abstraction level (not over-engineered, not under-abstracted)
|
||||
|
||||
If any Critical findings detected, invoke `discuss` CLI tool (DISCUSS-REVIEW round) to validate the assessment before issuing verdict.
|
||||
|
||||
## Phase 4: Verdict & Feedback
|
||||
|
||||
Classify overall verdict based on findings:
|
||||
|
||||
| Verdict | Condition | Action |
|
||||
|---------|-----------|--------|
|
||||
| APPROVE | No Critical or High findings | Send review_complete |
|
||||
| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback |
|
||||
| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for designer escalation |
|
||||
|
||||
1. Write review report to scoped output path:
|
||||
- Single: `<session>/artifacts/review-report.md`
|
||||
- Fan-out: `<session>/artifacts/branches/B{NN}/review-report.md`
|
||||
- Independent: `<session>/artifacts/pipelines/{P}/review-report.md`
|
||||
- Content: Per-dimension findings with severity, file:line, description; Overall verdict with rationale; Specific fix instructions for REVISE/REJECT verdicts
|
||||
|
||||
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
|
||||
- Single: merge `{ "reviewer": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
- Fan-out: merge `{ "reviewer.B{NN}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
- Independent: merge `{ "reviewer.{P}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
|
||||
3. If DISCUSS-REVIEW was triggered, record discussion summary in `<session>/discussions/DISCUSS-REVIEW.md` (or `DISCUSS-REVIEW-B{NN}.md` for branch-scoped discussions)
|
||||
115
.codex/skills/team-arch-opt/roles/validator/role.md
Normal file
115
.codex/skills/team-arch-opt/roles/validator/role.md
Normal file
@@ -0,0 +1,115 @@
|
||||
---
|
||||
role: validator
|
||||
prefix: VALIDATE
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Validator
|
||||
|
||||
Validate refactoring changes by running build checks, test suites, dependency metric comparisons, and API compatibility verification. Ensure refactoring improves architecture without breaking functionality.
|
||||
|
||||
## Phase 2: Environment & Baseline Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes |
|
||||
| Refactoring plan / detail | Varies by mode (see below) | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- validate only this branch's changes |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- use pipeline-scoped baseline |
|
||||
| Neither present | - | Single mode -- full validation |
|
||||
|
||||
3. **Load architecture baseline**:
|
||||
- Single / Fan-out: Read `<session>/artifacts/architecture-baseline.json` (shared baseline)
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/architecture-baseline.json`
|
||||
|
||||
4. **Load refactoring context**:
|
||||
- Single: Read `<session>/artifacts/refactoring-plan.md` -- all success criteria
|
||||
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
|
||||
|
||||
5. Load .msg/meta.json for project type and refactoring scope
|
||||
6. Detect available validation tools from project:
|
||||
|
||||
| Signal | Validation Tool | Method |
|
||||
|--------|----------------|--------|
|
||||
| package.json + tsc | TypeScript compiler | Type-check entire project |
|
||||
| package.json + vitest/jest | Test runner | Run existing test suite |
|
||||
| package.json + eslint | Linter | Run lint checks for import/export issues |
|
||||
| Cargo.toml | Rust compiler | cargo check + cargo test |
|
||||
| go.mod | Go tools | go build + go test |
|
||||
| Makefile with test target | Custom tests | make test |
|
||||
| No tooling detected | Manual validation | File existence + import grep checks |
|
||||
|
||||
7. Get changed files scope from .msg/meta.json:
|
||||
- Single: `refactorer` namespace
|
||||
- Fan-out: `refactorer.B{NN}` namespace
|
||||
- Independent: `refactorer.{P}` namespace
|
||||
|
||||
## Phase 3: Validation Execution
|
||||
|
||||
Run validations across four dimensions:
|
||||
|
||||
**Build validation**:
|
||||
- Compile/type-check the project -- zero new errors allowed
|
||||
- Verify all moved/renamed files are correctly referenced
|
||||
- Check for missing imports or unresolved modules
|
||||
|
||||
**Test validation**:
|
||||
- Run existing test suite -- all previously passing tests must still pass
|
||||
- Identify any tests that need updating due to module moves (update, don't skip)
|
||||
- Check for test file imports that reference old paths
|
||||
|
||||
**Dependency metric validation**:
|
||||
- Recalculate architecture metrics post-refactoring
|
||||
- Compare coupling scores against baseline (must improve or stay neutral)
|
||||
- Verify no new circular dependencies introduced
|
||||
- Check cohesion metrics for affected modules
|
||||
|
||||
**API compatibility validation**:
|
||||
- Verify public API signatures are preserved (exported function/class/type names)
|
||||
- Check for dangling references (imports pointing to removed/moved files)
|
||||
- Verify no new dead exports introduced by the refactoring
|
||||
- Check that re-exports maintain backward compatibility where needed
|
||||
|
||||
**Branch-scoped validation** (fan-out mode):
|
||||
- Only validate metrics relevant to this branch's refactoring (from refactoring-detail.md)
|
||||
- Still check for regressions across all metrics (not just branch-specific ones)
|
||||
|
||||
## Phase 4: Result Analysis
|
||||
|
||||
Compare against baseline and plan criteria:
|
||||
|
||||
| Metric | Threshold | Verdict |
|
||||
|--------|-----------|---------|
|
||||
| Build passes | Zero compilation errors | PASS |
|
||||
| All tests pass | No new test failures | PASS |
|
||||
| Coupling improved or neutral | No metric degradation > 5% | PASS |
|
||||
| No new cycles introduced | Cycle count <= baseline | PASS |
|
||||
| All plan success criteria met | Every criterion satisfied | PASS |
|
||||
| Partial improvement | Some metrics improved, none degraded | WARN |
|
||||
| Build fails | Compilation errors detected | FAIL -> fix_required |
|
||||
| Test failures | Previously passing tests now fail | FAIL -> fix_required |
|
||||
| New cycles introduced | Cycle count > baseline | FAIL -> fix_required |
|
||||
| Dangling references | Unresolved imports detected | FAIL -> fix_required |
|
||||
|
||||
1. Write validation results to output path:
|
||||
- Single: `<session>/artifacts/validation-results.json`
|
||||
- Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json`
|
||||
- Independent: `<session>/artifacts/pipelines/{P}/validation-results.json`
|
||||
- Content: Per-dimension: name, baseline value, current value, improvement/regression, verdict; Overall verdict: PASS / WARN / FAIL; Failure details (if any)
|
||||
|
||||
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
|
||||
- Single: merge `{ "validator": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
- Fan-out: merge `{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
- Independent: merge `{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
|
||||
3. If verdict is FAIL, include detailed feedback in message for FIX task creation:
|
||||
- Which validations failed, specific errors, suggested investigation areas
|
||||
@@ -1,174 +0,0 @@
|
||||
# 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}" |
|
||||
102
.codex/skills/team-arch-opt/specs/pipelines.md
Normal file
102
.codex/skills/team-arch-opt/specs/pipelines.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Pipeline Definitions — team-arch-opt
|
||||
|
||||
## Available Pipelines
|
||||
|
||||
### Single Mode (Linear)
|
||||
|
||||
```
|
||||
ANALYZE-001 → DESIGN-001 → REFACTOR-001 → VALIDATE-001 + REVIEW-001
|
||||
[analyzer] [designer] [refactorer] [validator] [reviewer]
|
||||
^ |
|
||||
+<-- FIX-001 ----+
|
||||
(max 3 iterations)
|
||||
```
|
||||
|
||||
### Fan-out Mode (Shared Stages + Parallel Branches)
|
||||
|
||||
```
|
||||
ANALYZE-001 → DESIGN-001 --+→ REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
|
||||
[analyzer] [designer] | [refactorer] [validator] [reviewer]
|
||||
+→ REFACTOR-B02 → VALIDATE-B02 + REVIEW-B02
|
||||
+→ REFACTOR-B0N → VALIDATE-B0N + REVIEW-B0N
|
||||
|
|
||||
AGGREGATE → Phase 5
|
||||
```
|
||||
|
||||
Branch tasks created at CP-2.5 after DESIGN-001 completes.
|
||||
|
||||
### Independent Mode (M Complete Pipelines)
|
||||
|
||||
```
|
||||
Pipeline A: ANALYZE-A01 → DESIGN-A01 → REFACTOR-A01 → VALIDATE-A01 + REVIEW-A01
|
||||
Pipeline B: ANALYZE-B01 → DESIGN-B01 → REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
|
||||
... |
|
||||
AGGREGATE → Phase 5
|
||||
```
|
||||
|
||||
### Auto Mode
|
||||
|
||||
Auto-detects based on refactoring count at CP-2.5:
|
||||
- count <= 2 → switch to single mode
|
||||
- count >= 3 → switch to fan-out mode
|
||||
|
||||
## Task Metadata Registry
|
||||
|
||||
### Single Mode
|
||||
|
||||
| Task ID | Role | Phase | Dependencies | Description |
|
||||
|---------|------|-------|-------------|-------------|
|
||||
| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues |
|
||||
| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report |
|
||||
| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings |
|
||||
| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility |
|
||||
| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness |
|
||||
| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation |
|
||||
|
||||
### Fan-out Mode (Branch Tasks at CP-2.5)
|
||||
|
||||
| Task ID | Role | Phase | Dependencies | Description |
|
||||
|---------|------|-------|-------------|-------------|
|
||||
| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture |
|
||||
| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs |
|
||||
| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only |
|
||||
| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} |
|
||||
| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} |
|
||||
| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} |
|
||||
|
||||
### Independent Mode
|
||||
|
||||
| Task ID | Role | Phase | Dependencies | Description |
|
||||
|---------|------|-------|-------------|-------------|
|
||||
| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target |
|
||||
| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} |
|
||||
| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings |
|
||||
| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} |
|
||||
| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} |
|
||||
|
||||
## Checkpoints
|
||||
|
||||
| Checkpoint | Trigger | Location | Behavior |
|
||||
|------------|---------|----------|----------|
|
||||
| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope |
|
||||
| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities |
|
||||
| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks, spawn all REFACTOR-B* in parallel |
|
||||
| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) |
|
||||
| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action |
|
||||
|
||||
## Task Naming Rules
|
||||
|
||||
| Mode | Stage 3 | Stage 4 | Fix | Retry |
|
||||
|------|---------|---------|-----|-------|
|
||||
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 |
|
||||
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 |
|
||||
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 |
|
||||
|
||||
## Parallel Mode Invocation
|
||||
|
||||
```bash
|
||||
Skill(skill="team-arch-opt", args="<task-description>") # auto mode
|
||||
Skill(skill="team-arch-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out
|
||||
Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent
|
||||
Skill(skill="team-arch-opt", args="--max-branches=3 <task-description>") # limit branches
|
||||
```
|
||||
263
.codex/skills/team-arch-opt/specs/team-config.json
Normal file
263
.codex/skills/team-arch-opt/specs/team-config.json
Normal file
@@ -0,0 +1,263 @@
|
||||
{
|
||||
"version": "5.0.0",
|
||||
"team_name": "arch-opt",
|
||||
"team_display_name": "Architecture Optimization",
|
||||
"skill_name": "team-arch-opt",
|
||||
"skill_path": "~ or <project>/.claude/skills/team-arch-opt/",
|
||||
"pipeline_type": "Linear with Review-Fix Cycle (Parallel-Capable)",
|
||||
"completion_action": "interactive",
|
||||
"has_inline_discuss": true,
|
||||
"has_shared_explore": true,
|
||||
"has_checkpoint_feedback": true,
|
||||
"has_session_resume": true,
|
||||
|
||||
"roles": [
|
||||
{
|
||||
"name": "coordinator",
|
||||
"type": "orchestrator",
|
||||
"description": "Orchestrates architecture optimization pipeline, manages task chains, handles review-fix cycles",
|
||||
"spec_path": "roles/coordinator/role.md",
|
||||
"tools": ["Task", "TaskCreate", "TaskList", "TaskGet", "TaskUpdate", "TeamCreate", "TeamDelete", "SendMessage", "AskUserQuestion", "Read", "Write", "Bash", "Glob", "Grep"]
|
||||
},
|
||||
{
|
||||
"name": "analyzer",
|
||||
"type": "orchestration",
|
||||
"description": "Analyzes architecture: dependency graphs, coupling/cohesion, layering violations, God Classes, dead code",
|
||||
"role_spec": "roles/analyzer/role.md",
|
||||
"inner_loop": false,
|
||||
"frontmatter": {
|
||||
"prefix": "ANALYZE",
|
||||
"inner_loop": false,
|
||||
"additional_prefixes": [],
|
||||
"discuss_rounds": [],
|
||||
"cli_tools": ["explore"],
|
||||
"message_types": {
|
||||
"success": "analyze_complete",
|
||||
"error": "error"
|
||||
}
|
||||
},
|
||||
"weight": 1,
|
||||
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
|
||||
},
|
||||
{
|
||||
"name": "designer",
|
||||
"type": "orchestration",
|
||||
"description": "Designs refactoring strategies from architecture analysis, produces prioritized refactoring plan with discrete REFACTOR-IDs",
|
||||
"role_spec": "roles/designer/role.md",
|
||||
"inner_loop": false,
|
||||
"frontmatter": {
|
||||
"prefix": "DESIGN",
|
||||
"inner_loop": false,
|
||||
"additional_prefixes": [],
|
||||
"discuss_rounds": ["DISCUSS-REFACTOR"],
|
||||
"cli_tools": ["discuss"],
|
||||
"message_types": {
|
||||
"success": "design_complete",
|
||||
"error": "error"
|
||||
}
|
||||
},
|
||||
"weight": 2,
|
||||
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
|
||||
},
|
||||
{
|
||||
"name": "refactorer",
|
||||
"type": "code_generation",
|
||||
"description": "Implements architecture refactoring changes following the design plan",
|
||||
"role_spec": "roles/refactorer/role.md",
|
||||
"inner_loop": true,
|
||||
"frontmatter": {
|
||||
"prefix": "REFACTOR",
|
||||
"inner_loop": true,
|
||||
"additional_prefixes": ["FIX"],
|
||||
"discuss_rounds": [],
|
||||
"cli_tools": ["explore"],
|
||||
"message_types": {
|
||||
"success": "refactor_complete",
|
||||
"error": "error",
|
||||
"fix": "fix_required"
|
||||
}
|
||||
},
|
||||
"weight": 3,
|
||||
"tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
|
||||
},
|
||||
{
|
||||
"name": "validator",
|
||||
"type": "validation",
|
||||
"description": "Validates refactoring: build checks, test suites, dependency metrics, API compatibility",
|
||||
"role_spec": "roles/validator/role.md",
|
||||
"inner_loop": false,
|
||||
"frontmatter": {
|
||||
"prefix": "VALIDATE",
|
||||
"inner_loop": false,
|
||||
"additional_prefixes": [],
|
||||
"discuss_rounds": [],
|
||||
"cli_tools": [],
|
||||
"message_types": {
|
||||
"success": "validate_complete",
|
||||
"error": "error",
|
||||
"fix": "fix_required"
|
||||
}
|
||||
},
|
||||
"weight": 4,
|
||||
"tools": ["Read", "Bash", "Glob", "Grep", "Task"]
|
||||
},
|
||||
{
|
||||
"name": "reviewer",
|
||||
"type": "read_only_analysis",
|
||||
"description": "Reviews refactoring code for correctness, pattern consistency, completeness, migration safety, and best practices",
|
||||
"role_spec": "roles/reviewer/role.md",
|
||||
"inner_loop": false,
|
||||
"frontmatter": {
|
||||
"prefix": "REVIEW",
|
||||
"inner_loop": false,
|
||||
"additional_prefixes": ["QUALITY"],
|
||||
"discuss_rounds": ["DISCUSS-REVIEW"],
|
||||
"cli_tools": ["discuss"],
|
||||
"message_types": {
|
||||
"success": "review_complete",
|
||||
"error": "error",
|
||||
"fix": "fix_required"
|
||||
}
|
||||
},
|
||||
"weight": 4,
|
||||
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
|
||||
}
|
||||
],
|
||||
|
||||
"parallel_config": {
|
||||
"modes": ["single", "fan-out", "independent", "auto"],
|
||||
"default_mode": "auto",
|
||||
"max_branches": 5,
|
||||
"auto_mode_rules": {
|
||||
"single": "refactoring_count <= 2",
|
||||
"fan-out": "refactoring_count >= 3"
|
||||
}
|
||||
},
|
||||
|
||||
"pipeline": {
|
||||
"stages": [
|
||||
{
|
||||
"stage": 1,
|
||||
"name": "Architecture Analysis",
|
||||
"roles": ["analyzer"],
|
||||
"blockedBy": [],
|
||||
"fast_advance": true
|
||||
},
|
||||
{
|
||||
"stage": 2,
|
||||
"name": "Refactoring Design",
|
||||
"roles": ["designer"],
|
||||
"blockedBy": ["ANALYZE"],
|
||||
"fast_advance": true
|
||||
},
|
||||
{
|
||||
"stage": 3,
|
||||
"name": "Code Refactoring",
|
||||
"roles": ["refactorer"],
|
||||
"blockedBy": ["DESIGN"],
|
||||
"fast_advance": false
|
||||
},
|
||||
{
|
||||
"stage": 4,
|
||||
"name": "Validate & Review",
|
||||
"roles": ["validator", "reviewer"],
|
||||
"blockedBy": ["REFACTOR"],
|
||||
"fast_advance": false,
|
||||
"parallel": true,
|
||||
"review_fix_cycle": {
|
||||
"trigger": "REVIEW or VALIDATE finds issues",
|
||||
"target_stage": 3,
|
||||
"max_iterations": 3
|
||||
}
|
||||
}
|
||||
],
|
||||
"parallel_pipelines": {
|
||||
"fan-out": {
|
||||
"shared_stages": [1, 2],
|
||||
"branch_stages": [3, 4],
|
||||
"branch_prefix": "B",
|
||||
"review_fix_cycle": {
|
||||
"scope": "per_branch",
|
||||
"max_iterations": 3
|
||||
}
|
||||
},
|
||||
"independent": {
|
||||
"pipeline_prefix_chars": "ABCDEFGHIJ",
|
||||
"review_fix_cycle": {
|
||||
"scope": "per_pipeline",
|
||||
"max_iterations": 3
|
||||
}
|
||||
}
|
||||
},
|
||||
"diagram": "See pipeline-diagram section"
|
||||
},
|
||||
|
||||
"cli_tools": [
|
||||
{
|
||||
"name": "explore",
|
||||
"implementation": "ccw cli with analysis mode",
|
||||
"callable_by": ["analyzer", "refactorer"],
|
||||
"purpose": "Shared codebase exploration for architecture-critical structures, dependency graphs, and module boundaries",
|
||||
"has_cache": true,
|
||||
"cache_domain": "explorations"
|
||||
},
|
||||
{
|
||||
"name": "discuss",
|
||||
"implementation": "ccw cli with analysis mode",
|
||||
"callable_by": ["designer", "reviewer"],
|
||||
"purpose": "Multi-perspective discussion for refactoring approaches and review findings",
|
||||
"has_cache": false
|
||||
}
|
||||
],
|
||||
|
||||
"shared_resources": [
|
||||
{
|
||||
"name": "Architecture Baseline",
|
||||
"path": "<session>/artifacts/architecture-baseline.json",
|
||||
"usage": "Pre-refactoring architecture metrics for comparison",
|
||||
"scope": "shared (fan-out) / per-pipeline (independent)"
|
||||
},
|
||||
{
|
||||
"name": "Architecture Report",
|
||||
"path": "<session>/artifacts/architecture-report.md",
|
||||
"usage": "Analyzer output consumed by designer",
|
||||
"scope": "shared (fan-out) / per-pipeline (independent)"
|
||||
},
|
||||
{
|
||||
"name": "Refactoring Plan",
|
||||
"path": "<session>/artifacts/refactoring-plan.md",
|
||||
"usage": "Designer output consumed by refactorer",
|
||||
"scope": "shared (fan-out) / per-pipeline (independent)"
|
||||
},
|
||||
{
|
||||
"name": "Validation Results",
|
||||
"path": "<session>/artifacts/validation-results.json",
|
||||
"usage": "Validator output consumed by reviewer",
|
||||
"scope": "per-branch (fan-out) / per-pipeline (independent)"
|
||||
}
|
||||
],
|
||||
|
||||
"shared_memory_namespacing": {
|
||||
"single": {
|
||||
"analyzer": "analyzer",
|
||||
"designer": "designer",
|
||||
"refactorer": "refactorer",
|
||||
"validator": "validator",
|
||||
"reviewer": "reviewer"
|
||||
},
|
||||
"fan-out": {
|
||||
"analyzer": "analyzer",
|
||||
"designer": "designer",
|
||||
"refactorer": "refactorer.B{NN}",
|
||||
"validator": "validator.B{NN}",
|
||||
"reviewer": "reviewer.B{NN}"
|
||||
},
|
||||
"independent": {
|
||||
"analyzer": "analyzer.{P}",
|
||||
"designer": "designer.{P}",
|
||||
"refactorer": "refactorer.{P}",
|
||||
"validator": "validator.{P}",
|
||||
"reviewer": "reviewer.{P}"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user