Add quality gates, role library, and templates for team lifecycle v3

- Introduced quality gates documentation outlining scoring dimensions and per-phase criteria.
- Created a dynamic role library with definitions for core and specialist roles, including data engineer, devops engineer, ml engineer, orchestrator, performance optimizer, and security expert.
- Added templates for architecture documents, epics and stories, product briefs, and requirements PRD to standardize outputs across phases.
This commit is contained in:
catlog22
2026-03-05 10:20:42 +08:00
parent bbdd1840de
commit bf057a927b
65 changed files with 5023 additions and 50 deletions

View File

@@ -130,7 +130,7 @@ For callback/check/resume/adapt/complete: load `commands/monitor.md` and execute
- Dependency graph: build DAG of work streams
- Complexity scoring: count capabilities, cross-domain factor, parallel tracks
- Role minimization: merge overlapping, absorb trivial, cap at 5
- **Role-spec metadata**: Generate frontmatter fields (prefix, inner_loop, subagents, message_types)
- **Role-spec metadata**: Generate frontmatter fields (prefix, inner_loop, additional_members, message_types)
4. **Output**: Write `<session>/task-analysis.json`
@@ -185,10 +185,10 @@ Regardless of complexity score or role count, coordinator MUST:
5. **Read `specs/role-spec-template.md`** for Behavioral Traits + Reference Patterns
6. **For each role in task-analysis.json#roles**:
- Fill YAML frontmatter: role, prefix, inner_loop, subagents, message_types
- Fill YAML frontmatter: role, prefix, inner_loop, additional_members, message_types
- **Compose Phase 2-4 content** (NOT copy from template):
- Phase 2: Derive input sources and context loading steps from **task description + upstream dependencies**
- Phase 3: Describe **execution goal** (WHAT to achieve) from task description — do NOT prescribe specific subagent or tool
- Phase 3: Describe **execution goal** (WHAT to achieve) from task description — do NOT prescribe specific CLI tool or approach
- Phase 4: Combine **Behavioral Traits** (from template) + **output_type** (from task analysis) to compose verification steps
- Reference Patterns may guide phase structure, but task description determines specific content
- Write generated role-spec to `<session>/role-specs/<role-name>.md`

View File

@@ -1,7 +1,6 @@
---
prefix: ANALYZE
inner_loop: false
additional_members: []
message_types:
success: analyze_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: ARCH
inner_loop: false
additional_members: []
message_types:
success: arch_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: DEV
inner_loop: true
additional_members: []
message_types:
success: dev_complete
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: QA
inner_loop: false
additional_members: []
message_types:
success: qa_passed
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: EXPLORE
inner_loop: false
additional_members: []
message_types:
success: context_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: MARSHAL
inner_loop: false
additional_members: []
message_types:
success: queue_ready
conflict: conflict_found

View File

@@ -2,7 +2,6 @@
prefix: SOLVE
inner_loop: false
additional_prefixes: [SOLVE-fix]
additional_members: []
message_types:
success: solution_ready
multi: multi_solution

View File

@@ -0,0 +1,46 @@
# Changelog
## v2.1 - Architecture Fix (2026-03-05)
### Fixed
- **Critical**: Removed subagent calls from worker role-specs
- Workers now correctly use CLI tools instead of attempting Agent() spawn
- Removed subagents directory (workers cannot use it)
- Updated SKILL.md to clarify architectural constraints
### Changed
- Multi-perspective critique: Now uses parallel CLI calls
- Codebase exploration: Now uses `ccw cli --tool gemini`
- Document generation: Now uses `ccw cli --tool gemini --mode write`
### Impact
- No functional change for users
- Implementation now architecturally correct
- Workers will no longer fail with "Unknown skill: Agent"
### Files Modified
- `SKILL.md`: Replaced "Subagent Registry" with "CLI Tool Usage in Workers"
- `role-specs/analyst.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls
- `role-specs/writer.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls
- `role-specs/reviewer.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls
- `role-specs/planner.md`: Updated complexity routing table to reference CLI exploration
- `role-specs/architect.md`: Removed `subagents: [explore]`
- `subagents/`: Directory removed
### Technical Details
**Why Workers Cannot Spawn Subagents**:
When a worker attempts `Agent()`, it fails with "Unknown skill: Agent". Only the Coordinator (main conversation context) can spawn agents.
**Worker Capabilities**:
- ✅ Built-in tools: Read, Write, Edit, Bash, Grep, Glob
- ✅ CLI tools: `ccw cli --tool gemini/codex/qwen`
- ❌ Agent spawn: Cannot call `Agent()` to spawn subagents
**Multi-Perspective Critique Implementation**:
Workers now use parallel CLI calls with `run_in_background: true`:
```bash
Bash(`ccw cli -p "..." --tool gemini --mode analysis`, { run_in_background: true })
Bash(`ccw cli -p "..." --tool codex --mode analysis`, { run_in_background: true })
Bash(`ccw cli -p "..." --tool claude --mode analysis`, { run_in_background: true })
```

View File

@@ -0,0 +1,295 @@
---
name: team-lifecycle-v2
description: Optimized team skill for full lifecycle. Reduced discuss (6→3), progressive spec refinement preserved. team-worker agent architecture. Triggers on "team lifecycle v2".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Lifecycle v2
Optimized lifecycle: specification → implementation → testing → review. Built on **team-worker agent architecture**. Key optimization: discuss rounds reduced from 6 to 3 (direction, requirements, final gate).
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-lifecycle-v2") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (inline)
Phase 0-5 orchestration
|
+----+-----+-------+-------+-------+-------+
v v v v v v v
[team-worker agents, each loaded with a role-spec]
analyst writer planner executor tester reviewer
^ ^
on-demand by coordinator
+---------+ +--------+
|architect| |fe-dev |
+---------+ +--------+
+--------+
| fe-qa |
+--------+
Subagent (callable by analyst, writer, reviewer):
[discuss-subagent] - multi-perspective critique (3 rounds)
```
## Role Router
Coordinator-only. Workers spawned as `team-worker` agents.
### Role Registry
| Role | Spec | Task Prefix | Type | Inner Loop |
|------|------|-------------|------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - |
| analyst | [role-specs/analyst.md](role-specs/analyst.md) | RESEARCH-* | pipeline | false |
| writer | [role-specs/writer.md](role-specs/writer.md) | DRAFT-* | pipeline | true |
| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true |
| executor | [role-specs/executor.md](role-specs/executor.md) | IMPL-* | pipeline | true |
| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | pipeline | false |
| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* + QUALITY-* + IMPROVE-* | pipeline | false |
| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | consulting | false |
| fe-developer | [role-specs/fe-developer.md](role-specs/fe-developer.md) | DEV-FE-* | frontend | false |
| fe-qa | [role-specs/fe-qa.md](role-specs/fe-qa.md) | QA-FE-* | frontend | false |
### CLI Tool Usage in Workers
**⚠️ ARCHITECTURAL CONSTRAINT**: Workers CANNOT call Agent() to spawn subagents.
Workers must use CLI tools for complex analysis.
| Capability | CLI Command | Used By |
|------------|-------------|---------|
| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel calls) | analyst, writer, reviewer |
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner |
| Document generation | `ccw cli --tool gemini --mode write` | writer |
### Coordinator-Only Utilities
If Coordinator needs utility members for team-level orchestration, it can spawn them.
Workers cannot spawn utility members.
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md`.
### Orchestration Mode
**Invocation**: `Skill(skill="team-lifecycle-v2", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1-3: clarify -> TeamCreate -> create task chain
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances
-> Loop until pipeline complete -> Phase 5 report
```
**User Commands**:
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream |
| `feedback <text>` | Analyze feedback, create targeted revision |
| `recheck` | Re-run QUALITY-001 quality check |
| `improve [dimension]` | Auto-improve weakest dimension |
---
## Coordinator Spawn Template
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-lifecycle-v2/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
---
## Pipeline Definitions
### Spec-only (6 tasks, 3 discuss)
```
RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3)
```
Note: DRAFT-001, DRAFT-003, DRAFT-004 use self-validation only (no discuss).
### Impl-only (4 tasks)
```
PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001
```
### Full-lifecycle (10 tasks)
```
[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001
```
### Frontend Pipelines
```
FE-only: PLAN-001 -> DEV-FE-001 -> QA-FE-001
(GC loop: max 2 rounds)
Fullstack: PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
Full + FE: [Spec pipeline] -> PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001
```
### Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
```
Beat Cycle
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check pipeline |
+- handleSpawnNext -+
| find ready tasks |
| spawn workers ---+--> [team-worker] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor?
| --> spawn team-worker B directly
| --> log fast_advance to message bus
+- complex case? --> SendMessage to coordinator
======================================================================
```
### Checkpoints
| Trigger | Position | Behavior |
|---------|----------|----------|
| Spec->Impl transition | QUALITY-001 completed | Display checkpoint, pause for user |
| GC loop max | QA-FE max 2 rounds | Stop iteration, report |
| Pipeline stall | No ready + no running | Report to user |
**Checkpoint Output Template** (QUALITY-001):
```
[coordinator] ══════════════════════════════════════════
[coordinator] SPEC PHASE COMPLETE
[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%)
[coordinator]
[coordinator] Dimension Scores:
[coordinator] Completeness: <bar> <n>%
[coordinator] Consistency: <bar> <n>%
[coordinator] Traceability: <bar> <n>%
[coordinator] Depth: <bar> <n>%
[coordinator] Coverage: <bar> <n>%
[coordinator]
[coordinator] Available Actions:
[coordinator] resume -> Proceed to implementation
[coordinator] improve -> Auto-improve weakest dimension
[coordinator] revise <TASK-ID> -> Revise specific document
[coordinator] recheck -> Re-run quality check
[coordinator] feedback <text> -> Inject feedback
[coordinator] ══════════════════════════════════════════
```
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Discuss |
|---------|------|-------|-------------|---------|
| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 |
| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate |
| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 |
| DRAFT-003 | writer | spec | DRAFT-002 | self-validate |
| DRAFT-004 | writer | spec | DRAFT-003 | self-validate |
| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 |
| PLAN-001 | planner | impl | (none or QUALITY-001) | - |
| IMPL-001 | executor | impl | PLAN-001 | - |
| TEST-001 | tester | impl | IMPL-001 | - |
| REVIEW-001 | reviewer | impl | IMPL-001 | - |
| DEV-FE-001 | fe-developer | impl | PLAN-001 | - |
| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - |
---
## Session Directory
```
.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json
+-- spec/
| +-- spec-config.json
| +-- discovery-context.json
| +-- product-brief.md
| +-- requirements/
| +-- architecture/
| +-- epics/
| +-- readiness-report.md
+-- discussions/
+-- plan/
| +-- plan.json
| +-- .task/TASK-*.json
+-- explorations/
+-- .msg/
+-- shared-memory.json
```
## Session Resume
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion
3. Audit TaskList -> reconcile session state
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team, spawn needed workers only
6. Kick first executable task
## Shared Resources
| Resource | Path | Usage |
|----------|------|-------|
| Document Standards | [specs/document-standards.md](specs/document-standards.md) | YAML frontmatter, naming, structure |
| Quality Gates | [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gates |
| Team Config | [specs/team-config.json](specs/team-config.json) | Role registry, pipeline definitions |
| Product Brief Template | [templates/product-brief.md](templates/product-brief.md) | DRAFT-001 |
| Requirements Template | [templates/requirements-prd.md](templates/requirements-prd.md) | DRAFT-002 |
| Architecture Template | [templates/architecture-doc.md](templates/architecture-doc.md) | DRAFT-003 |
| Epics Template | [templates/epics-template.md](templates/epics-template.md) | DRAFT-004 |
| Discuss Subagent | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | 3-round discuss protocol |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown command | Error with available command list |
| Role spec file not found | Error with expected path |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Worker proceeds without discuss, logs warning |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |

View File

@@ -0,0 +1,107 @@
---
role: analyst
prefix: RESEARCH
inner_loop: false
discuss_rounds: [DISCUSS-001]
message_types:
success: research_ready
progress: research_progress
error: error
---
# Analyst — Phase 2-4
## Phase 2: Seed Analysis
**Objective**: Extract structured seed information from the topic.
1. Extract session folder from task description (`Session: <path>`)
2. Parse topic from task description
3. If topic starts with `@` or ends with `.md`/`.txt` → Read referenced file
4. Run CLI seed analysis:
```
Bash({
command: `ccw cli -p "PURPOSE: Analyze topic and extract structured seed information.
TASK: * Extract problem statement * Identify target users * Determine domain context
* List constraints * Identify 3-5 exploration dimensions * Assess complexity
TOPIC: <topic-content>
MODE: analysis
EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[], complexity_assessment" --tool gemini --mode analysis`,
run_in_background: false
})
```
5. Parse seed analysis JSON
## Phase 3: Codebase Exploration (conditional)
**Objective**: Gather codebase context if project detected.
| Condition | Action |
|-----------|--------|
| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore |
| No project files | Skip (codebase_context = null) |
**When project detected**: Use CLI exploration.
```
Bash({
command: `ccw cli -p "PURPOSE: Explore codebase for context to inform spec generation
TASK: • Identify tech stack • Map architecture patterns • Document conventions • List integration points
MODE: analysis
CONTEXT: @**/*
EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[]" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`,
run_in_background: false
})
```
## Phase 4: Context Packaging + Discuss
### 4a: Context Packaging
**spec-config.json**`<session>/spec/spec-config.json`
**discovery-context.json**`<session>/spec/discovery-context.json`
**design-intelligence.json**`<session>/analysis/design-intelligence.json` (UI mode only)
### 4b: Inline Discuss (DISCUSS-001)
**Multi-perspective critique via parallel CLI calls**:
```bash
# Product perspective
Bash(`ccw cli -p "PURPOSE: Review discovery context from product perspective
CONTEXT: @<session>/spec/discovery-context.json
EXPECTED: Rating (1-5) + concerns + recommendations
CONSTRAINTS: Focus on market fit, user value, scope clarity" --tool gemini --mode analysis`, { run_in_background: true })
# Risk perspective
Bash(`ccw cli -p "PURPOSE: Review discovery context from risk perspective
CONTEXT: @<session>/spec/discovery-context.json
EXPECTED: Rating (1-5) + risks + mitigation strategies
CONSTRAINTS: Focus on technical risks, dependencies, unknowns" --tool codex --mode analysis`, { run_in_background: true })
# Coverage perspective
Bash(`ccw cli -p "PURPOSE: Review discovery context from coverage perspective
CONTEXT: @<session>/spec/discovery-context.json
EXPECTED: Rating (1-5) + gaps + missing dimensions
CONSTRAINTS: Focus on completeness, edge cases, requirements coverage" --tool claude --mode analysis`, { run_in_background: true })
```
Wait for all results, aggregate ratings and feedback, determine consensus verdict:
- **HIGH**: Any rating <= 2 → User pause required
- **MEDIUM**: All ratings 3-4 → Proceed with caution
- **LOW**: All ratings >= 4 → Proceed
Handle verdict per consensus protocol.
**Report**: complexity, codebase presence, problem statement, dimensions, discuss verdict, output paths.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI failure | Fallback to direct Claude analysis |
| Codebase detection failed | Continue as new project |
| Topic too vague | Report with clarification questions |
| CLI critique fails | Proceed without critique, log warning |

View File

@@ -3,7 +3,6 @@ role: architect
prefix: ARCH
inner_loop: false
discuss_rounds: []
subagents: [explore]
message_types:
success: arch_ready
concern: arch_concern

View File

@@ -27,8 +27,8 @@ If `<session-folder>/spec/` exists → load requirements/_index.md, architecture
| Complexity | Criteria | Strategy |
|------------|----------|----------|
| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only |
| Medium | 200-500 chars or moderate scope | 2-3 angle explore subagent |
| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle explore subagent |
| Medium | 200-500 chars or moderate scope | 2-3 angle CLI exploration |
| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle CLI exploration |
For each angle, use CLI exploration (cache-aware — check cache-index.json before each call):

View File

@@ -0,0 +1,122 @@
---
role: reviewer
prefix: REVIEW
additional_prefixes: [QUALITY, IMPROVE]
inner_loop: false
discuss_rounds: [DISCUSS-003]
message_types:
success_review: review_result
success_quality: quality_result
fix: fix_required
error: error
---
# Reviewer — Phase 2-4
## Phase 2: Mode Detection
| Task Prefix | Mode | Dimensions | Discuss |
|-------------|------|-----------|---------|
| REVIEW-* | Code Review | quality, security, architecture, requirements | None |
| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage | DISCUSS-003 |
| IMPROVE-* | Spec Quality (recheck) | Same as QUALITY | DISCUSS-003 |
## Phase 3: Review Execution
### Code Review (REVIEW-*)
**Inputs**: Plan file, git diff, modified files, test results
**4 dimensions**:
| Dimension | Critical Issues |
|-----------|----------------|
| Quality | Empty catch, any in public APIs, @ts-ignore, console.log |
| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML |
| Architecture | Circular deps, parent imports >2 levels, files >500 lines |
| Requirements | Missing core functionality, incomplete acceptance criteria |
### Spec Quality (QUALITY-* / IMPROVE-*)
**Inputs**: All spec docs in session folder, quality gate config
**5 dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Completeness | 25% | All sections present with substance |
| Consistency | 20% | Terminology, format, references |
| Traceability | 25% | Goals -> Reqs -> Arch -> Stories chain |
| Depth | 20% | AC testable, ADRs justified, stories estimable |
| Coverage | 10% | Original requirements mapped |
**Quality gate**:
| Gate | Criteria |
|------|----------|
| PASS | Score >= 80% AND coverage >= 70% |
| REVIEW | Score 60-79% OR coverage 50-69% |
| FAIL | Score < 60% OR coverage < 50% |
**Artifacts**: readiness-report.md + spec-summary.md
## Phase 4: Verdict + Discuss
### Code Review Verdict
| Verdict | Criteria |
|---------|----------|
| BLOCK | Critical issues present |
| CONDITIONAL | High/medium only |
| APPROVE | Low or none |
### Spec Quality Discuss (DISCUSS-003)
After generating readiness-report.md, perform multi-perspective critique via parallel CLI calls:
```bash
# Product perspective
Bash(`ccw cli -p "PURPOSE: Review spec readiness from product perspective
CONTEXT: @<session>/spec/readiness-report.md
EXPECTED: Rating (1-5) + product concerns + recommendations
CONSTRAINTS: Focus on market alignment, user value, business viability" --tool gemini --mode analysis`, { run_in_background: true })
# Technical perspective
Bash(`ccw cli -p "PURPOSE: Review spec readiness from technical perspective
CONTEXT: @<session>/spec/readiness-report.md
EXPECTED: Rating (1-5) + technical risks + feasibility assessment
CONSTRAINTS: Focus on architecture soundness, tech debt, implementation complexity" --tool codex --mode analysis`, { run_in_background: true })
# Quality perspective
Bash(`ccw cli -p "PURPOSE: Review spec readiness from quality perspective
CONTEXT: @<session>/spec/readiness-report.md
EXPECTED: Rating (1-5) + quality gaps + improvement areas
CONSTRAINTS: Focus on completeness, testability, consistency" --tool claude --mode analysis`, { run_in_background: true })
# Risk perspective
Bash(`ccw cli -p "PURPOSE: Review spec readiness from risk perspective
CONTEXT: @<session>/spec/readiness-report.md
EXPECTED: Rating (1-5) + risk factors + mitigation strategies
CONSTRAINTS: Focus on dependencies, unknowns, timeline risks" --tool gemini --mode analysis`, { run_in_background: true })
# Coverage perspective
Bash(`ccw cli -p "PURPOSE: Review spec readiness from coverage perspective
CONTEXT: @<session>/spec/readiness-report.md
EXPECTED: Rating (1-5) + coverage gaps + missing requirements
CONSTRAINTS: Focus on edge cases, non-functional requirements, traceability" --tool codex --mode analysis`, { run_in_background: true })
```
Wait for all results, aggregate ratings and feedback, determine consensus verdict per protocol.
> **Note**: DISCUSS-003 HIGH always triggers user pause (final sign-off gate).
**Report**: mode, verdict/gate, dimension scores, discuss verdict (QUALITY only), output paths.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Missing context | Request from coordinator |
| Invalid mode | Abort with error |
| Analysis failure | Retry, then fallback |
| CLI critique fails | Proceed without critique, log warning |

View File

@@ -0,0 +1,117 @@
---
role: writer
prefix: DRAFT
inner_loop: true
discuss_rounds: [DISCUSS-002]
message_types:
success: draft_ready
revision: draft_revision
error: error
---
# Writer — Phase 2-4
## Phase 2: Context Loading
**Objective**: Load all required inputs for document generation.
### Document type routing
| Task Subject Contains | Doc Type | Template | Validation |
|----------------------|----------|----------|------------|
| Product Brief | product-brief | templates/product-brief.md | self-validate |
| Requirements / PRD | requirements | templates/requirements-prd.md | DISCUSS-002 |
| Architecture | architecture | templates/architecture-doc.md | self-validate |
| Epics | epics | templates/epics-template.md | self-validate |
### Progressive dependency loading
| Doc Type | Requires |
|----------|----------|
| product-brief | discovery-context.json |
| requirements | + product-brief.md |
| architecture | + requirements/_index.md |
| epics | + architecture/_index.md |
**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to generation.
| Input | Source | Required |
|-------|--------|----------|
| Document standards | `../../specs/document-standards.md` | Yes |
| Template | From routing table | Yes |
| Spec config | `<session>/spec/spec-config.json` | Yes |
| Discovery context | `<session>/spec/discovery-context.json` | Yes |
| Discussion feedback | `<session>/discussions/<discuss-file>` | If exists |
| Prior decisions | context_accumulator (in-memory) | If prior tasks |
## Phase 3: Document Generation
**Objective**: Generate document using CLI tool.
```
Bash({
command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template and standards
TASK: • Load template • Apply spec config and discovery context • Integrate prior feedback • Generate all sections
MODE: write
CONTEXT: @<session>/spec/*.json @<template-path> | Memory: Prior decisions: <accumulator summary>
EXPECTED: Document at <output-path> with: YAML frontmatter, all sections, cross-references
CONSTRAINTS: Follow document-standards.md" --tool gemini --mode write --rule development-implement-feature --cd <session>`,
run_in_background: false
})
```
## Phase 4: Validation
### 4a: Self-Validation (all doc types)
| Check | What to Verify |
|-------|---------------|
| has_frontmatter | Starts with YAML frontmatter |
| sections_complete | All template sections present |
| cross_references | session_id included |
| progressive_consistency | References to upstream docs are valid |
### 4b: Validation Routing
| Doc Type | Validation Method |
|----------|------------------|
| product-brief | Self-validation only → report |
| requirements (PRD) | Self-validation + **DISCUSS-002** |
| architecture | Self-validation only → report |
| epics | Self-validation only → report |
**DISCUSS-002** (PRD only) - Multi-perspective critique via parallel CLI calls:
```bash
# Quality perspective
Bash(`ccw cli -p "PURPOSE: Review requirements document from quality perspective
CONTEXT: @<session>/spec/requirements/_index.md
EXPECTED: Rating (1-5) + quality issues + improvement suggestions
CONSTRAINTS: Focus on completeness, testability, consistency" --tool gemini --mode analysis`, { run_in_background: true })
# Product perspective
Bash(`ccw cli -p "PURPOSE: Review requirements document from product perspective
CONTEXT: @<session>/spec/requirements/_index.md
EXPECTED: Rating (1-5) + product concerns + alignment feedback
CONSTRAINTS: Focus on user value, market fit, scope clarity" --tool codex --mode analysis`, { run_in_background: true })
# Coverage perspective
Bash(`ccw cli -p "PURPOSE: Review requirements document from coverage perspective
CONTEXT: @<session>/spec/requirements/_index.md
EXPECTED: Rating (1-5) + coverage gaps + missing requirements
CONSTRAINTS: Focus on edge cases, non-functional requirements, traceability" --tool claude --mode analysis`, { run_in_background: true })
```
Wait for all results, aggregate ratings and feedback, determine consensus verdict per protocol.
**Report**: doc type, validation status, discuss verdict (PRD only), output path.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI failure | Retry once with alternative tool. Still fails → log, continue next |
| CLI critique fails | Skip critique, log warning |
| Cumulative 3 task failures | SendMessage to coordinator, STOP |
| Prior doc not found | Notify coordinator, request prerequisite |
| Discussion contradicts prior docs | Note conflict, flag for coordinator |

View File

@@ -0,0 +1,134 @@
# Command: dispatch
Create task chains based on execution mode. v2: 3 discuss points instead of 6.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Mode | Phase 1 requirements | Yes |
| Session folder | Phase 2 session init | Yes |
| Scope | User requirements | Yes |
## Phase 3: Task Chain Creation
### Spec Pipeline (6 tasks, 3 discuss)
| # | Subject | Owner | BlockedBy | Description | Validation |
|---|---------|-------|-----------|-------------|------------|
| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 |
| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | self-validate |
| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-002 |
| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | self-validate |
| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | self-validate |
| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-003 |
### Impl Pipeline (4 tasks)
| # | Subject | Owner | BlockedBy | Description |
|---|---------|-------|-----------|-------------|
| 1 | PLAN-001 | planner | (none) | Multi-angle exploration and planning |
| 2 | IMPL-001 | executor | PLAN-001 | Code implementation |
| 3 | TEST-001 | tester | IMPL-001 | Test-fix cycles |
| 4 | REVIEW-001 | reviewer | IMPL-001 | 4-dimension code review |
### FE Pipeline (3 tasks)
| # | Subject | Owner | BlockedBy | Description |
|---|---------|-------|-----------|-------------|
| 1 | PLAN-001 | planner | (none) | Planning (frontend focus) |
| 2 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation |
| 3 | QA-FE-001 | fe-qa | DEV-FE-001 | 5-dimension frontend QA |
### Fullstack Pipeline (6 tasks)
| # | Subject | Owner | BlockedBy | Description |
|---|---------|-------|-----------|-------------|
| 1 | PLAN-001 | planner | (none) | Fullstack planning |
| 2 | IMPL-001 | executor | PLAN-001 | Backend implementation |
| 3 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation |
| 4 | TEST-001 | tester | IMPL-001 | Backend test-fix |
| 5 | QA-FE-001 | fe-qa | DEV-FE-001 | Frontend QA |
| 6 | REVIEW-001 | reviewer | TEST-001, QA-FE-001 | Full code review |
### Composite Modes
| Mode | Construction | PLAN-001 BlockedBy |
|------|-------------|-------------------|
| full-lifecycle | Spec (6) + Impl (4) | QUALITY-001 |
| full-lifecycle-fe | Spec (6) + Fullstack (6) | QUALITY-001 |
### Task Description Template
```
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what> | Success: <criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Scope: <scope>
- Upstream: <artifacts>
EXPECTED: <deliverable> + <quality>
CONSTRAINTS: <scope limits>
---
Validation: <DISCUSS-NNN or self-validate>
InnerLoop: <true|false>",
addBlockedBy: [<deps>]
})
```
### Revision Task Template
```
TaskCreate({
subject: "<ORIGINAL-ID>-R1",
owner: "<same-role>",
description: "PURPOSE: Revision of <ORIGINAL-ID> | Success: Address feedback
TASK:
- Review original + feedback
- Apply fixes
- Validate
CONTEXT:
- Session: <session-folder>
- Original: <artifact-path>
- Feedback: <text>
EXPECTED: Updated artifact + summary
---
Validation: <same-as-original>
InnerLoop: <true|false>",
blockedBy: [<predecessor-R1 if cascaded>]
})
```
**Cascade Rules**:
| Revised Task | Downstream |
|-------------|-----------|
| RESEARCH-001 | DRAFT-001~004-R1, QUALITY-001-R1 |
| DRAFT-001 | DRAFT-002~004-R1, QUALITY-001-R1 |
| DRAFT-002 | DRAFT-003~004-R1, QUALITY-001-R1 |
| DRAFT-003 | DRAFT-004-R1, QUALITY-001-R1 |
| DRAFT-004 | QUALITY-001-R1 |
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Task count | Matches mode total |
| Dependencies | Every blockedBy references existing task |
| Owner | Each task owner matches Role Registry |
| Session ref | Every task contains `Session:` |
| Validation field | Spec tasks have Validation field |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown mode | Reject with supported modes |
| Missing spec for impl-only | Error, suggest spec-only |
| TaskCreate fails | Log error, report |
| Duplicate task | Skip, log warning |

View File

@@ -0,0 +1,134 @@
# Command: monitor
Event-driven pipeline coordination. v2: 3 discuss points, simplified consensus handling.
## Constants
| Constant | Value |
|----------|-------|
| SPAWN_MODE | background |
| ONE_STEP_PER_INVOCATION | true |
| FAST_ADVANCE_AWARE | true |
| WORKER_AGENT | team-worker |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | team-session.json | Yes |
| Task list | TaskList() | Yes |
| Active workers | session.active_workers[] | Yes |
## Phase 3: Handler Routing
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | `[<role-name>]` from worker | handleCallback |
| 2 | "check" or "status" | handleCheck |
| 3 | "resume" / "continue" | handleResume |
| 4 | None (initial spawn) | handleSpawnNext |
| 5 | "revise" + task ID | handleRevise |
| 6 | "feedback" + text | handleFeedback |
| 7 | "recheck" | handleRecheck |
| 8 | "improve" | handleImprove |
---
### handleCallback
```
Receive callback from [<role>]
+- Progress update? -> Update session -> STOP
+- Task completed? -> remove from active_workers -> update session
| +- Handle checkpoints (QUALITY-001)
| +- -> handleSpawnNext
+- No matching worker -> scan all active -> handleSpawnNext or STOP
```
Fast-advance reconciliation: read team_msg fast_advance entries, sync active_workers.
### handleCheck
Read-only status report, no advancement.
```
[coordinator] Pipeline Status (v2)
[coordinator] Mode: <mode> | Progress: <completed>/<total> (<percent>%)
[coordinator] Discuss: <completed-discuss>/<total-discuss> rounds
[coordinator] Execution Graph:
Spec Phase:
[<icon> RESEARCH-001(+D1)] -> [<icon> DRAFT-001] -> [<icon> DRAFT-002(+D2)] -> [<icon> DRAFT-003] -> [<icon> DRAFT-004] -> [<icon> QUALITY-001(+D3)]
Impl Phase:
[<icon> PLAN-001] -> [<icon> IMPL-001] -> [<icon> TEST-001] + [<icon> REVIEW-001]
done=completed >>>=running o=pending
```
Then STOP.
### handleResume
```
Load active_workers
+- No active -> handleSpawnNext
+- Has active -> check each:
+- completed -> mark done
+- in_progress -> still running
+- other -> reset to pending
After: some completed -> handleSpawnNext; all running -> STOP
```
### handleSpawnNext
```
Collect task states from TaskList()
+- readySubjects: pending + all blockedBy completed
+- NONE + work in progress -> STOP
+- NONE + nothing running -> PIPELINE_COMPLETE -> Phase 5
+- HAS ready -> for each:
+- Inner Loop role AND already active? -> SKIP
+- Spawn team-worker (see SKILL.md Spawn Template)
+- Add to active_workers
Update session -> STOP
```
### handleRevise / handleFeedback / handleRecheck / handleImprove
Same as v1 (see dispatch.md for templates). Changes:
- Revision tasks use v2 Validation field ("self-validate" or "DISCUSS-NNN")
---
### Consensus-Blocked Handling (v2 simplified)
Only 3 discuss points to handle:
```
handleCallback receives consensus_blocked:
+- DISCUSS-003 (QUALITY) + HIGH -> PAUSE for user (final gate)
+- Any discuss + HIGH -> Create REVISION task (max 1 per task)
+- MEDIUM -> proceed with warning, log to wisdom/issues.md
+- LOW -> proceed normally
```
### Fast-Advance State Sync
On every coordinator wake:
1. Read team_msg fast_advance entries
2. Sync active_workers with spawned successors
### Worker Failure Handling
1. Reset task -> pending
2. Log via team_msg (type: error)
3. Report to user
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session not found | Error, suggest re-init |
| Unknown role callback | Log, scan for completions |
| Pipeline stall | Check missing tasks, report |
| Fast-advance orphan | Reset to pending, re-spawn |

View File

@@ -0,0 +1,139 @@
# Coordinator Role
Orchestrate team-lifecycle-v2: team creation, task dispatching, progress monitoring, session state. Uses **team-worker agent** for all worker spawns.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report
## Boundaries
### MUST
- Parse user requirements and clarify via AskUserQuestion
- Create team and spawn workers using **team-worker** agent type
- Dispatch tasks with proper dependency chains
- Monitor progress via callbacks and route messages
- Maintain session state (team-session.json)
### MUST NOT
- Execute spec/impl/research work directly
- Modify task outputs
- Skip dependency validation
---
## Entry Router
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag | -> handleCallback |
| Status check | "check" or "status" | -> handleCheck |
| Manual resume | "resume" or "continue" | -> handleResume |
| Interrupted session | Active/paused session in `.workflow/.team/TLS-*` | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume: load `commands/monitor.md`, execute handler, STOP.
---
## Phase 0: Session Resume Check
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused
2. No sessions -> Phase 1
3. Single session -> resume (reconciliation)
4. Multiple -> AskUserQuestion
**Session Reconciliation**:
1. Audit TaskList, reconcile with session state
2. Reset in_progress -> pending (interrupted tasks)
3. Rebuild team if disbanded
4. Create missing tasks with correct blockedBy
5. Kick first executable -> Phase 4
---
## Phase 1: Requirement Clarification
1. Parse arguments for mode, scope, focus
2. Ask missing parameters via AskUserQuestion:
- Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe
- Scope: project description
3. Frontend auto-detection (keyword + package.json scanning)
4. Store requirements
---
## Phase 2: Create Team + Initialize Session
1. Generate session ID: `TLS-<slug>-<date>`
2. Create session folder: `.workflow/.team/<session-id>/`
3. TeamCreate
4. Initialize directories (spec/, discussions/, plan/, explorations/)
5. Write team-session.json
6. Initialize meta.json via team_msg state_update:
```
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<mode>",
pipeline_stages: [<role-list>],
roles: [<all-roles>],
team_name: "lifecycle-v2"
}
})
```
---
## Phase 3: Create Task Chain
Delegate to `commands/dispatch.md`:
1. Read Task Metadata Registry for task definitions
2. Create tasks via TaskCreate with correct blockedBy
3. Include `Session: <session-folder>` in every task
4. Mark discuss rounds (DISCUSS-001, DISCUSS-002, DISCUSS-003) or "self-validate"
---
## Phase 4: Spawn-and-Stop
1. Load `commands/monitor.md`
2. Find ready tasks (pending + blockedBy resolved)
3. Spawn team-worker for each ready task
4. Output summary
5. STOP
### Checkpoint Gate (QUALITY-001)
When QUALITY-001 completes:
1. Read readiness-report.md
2. Parse quality gate and dimension scores
3. Output Checkpoint Template (see SKILL.md)
4. Pause for user command
---
## Phase 5: Report + Next Steps
1. Count completed tasks, duration
2. List deliverables
3. Update session status -> "completed"
4. Offer next steps: exit / view / extend / generate plan
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report, halt |
| Invalid mode | Reject, ask to clarify |
| Session corruption | Attempt recovery |

View File

@@ -0,0 +1,169 @@
{
"team_name": "team-lifecycle-v2",
"team_display_name": "Team Lifecycle v2",
"description": "Optimized team-worker agent architecture: discuss reduced 6→3, progressive refinement preserved",
"version": "6.0.0",
"architecture": "team-worker agent + role-specs",
"role_structure": "role-specs/{name}.md (Phase 2-4 only)",
"worker_agent": "team-worker",
"roles": {
"coordinator": {
"task_prefix": null,
"responsibility": "Pipeline orchestration, requirement clarification, task chain creation",
"message_types": ["plan_approved", "plan_revision", "task_unblocked", "fix_required", "error", "shutdown"]
},
"analyst": {
"task_prefix": "RESEARCH",
"role_spec": "role-specs/analyst.md",
"responsibility": "Seed analysis, codebase exploration, context gathering + discuss",
"inline_discuss": "DISCUSS-001",
"inner_loop": false,
"message_types": ["research_ready", "research_progress", "error"]
},
"writer": {
"task_prefix": "DRAFT",
"role_spec": "role-specs/writer.md",
"responsibility": "Product Brief / PRD / Architecture / Epics generation. Discuss at PRD only, self-validate others",
"inner_loop": true,
"inline_discuss": ["DISCUSS-002"],
"message_types": ["draft_ready", "draft_revision", "error"]
},
"planner": {
"task_prefix": "PLAN",
"role_spec": "role-specs/planner.md",
"responsibility": "Multi-angle exploration and structured implementation planning",
"inner_loop": true,
"message_types": ["plan_ready", "plan_revision", "error"]
},
"executor": {
"task_prefix": "IMPL",
"role_spec": "role-specs/executor.md",
"responsibility": "Code implementation following approved plans",
"inner_loop": true,
"message_types": ["impl_complete", "impl_progress", "error"]
},
"tester": {
"task_prefix": "TEST",
"role_spec": "role-specs/tester.md",
"responsibility": "Adaptive test-fix cycles, progressive testing",
"inner_loop": false,
"message_types": ["test_result", "fix_required", "error"]
},
"reviewer": {
"task_prefix": "REVIEW",
"additional_prefixes": ["QUALITY", "IMPROVE"],
"role_spec": "role-specs/reviewer.md",
"responsibility": "Code review (REVIEW-*) + Spec quality (QUALITY-*) + Improvement (IMPROVE-*) + final discuss",
"inline_discuss": "DISCUSS-003",
"inner_loop": false,
"message_types": ["review_result", "quality_result", "quality_recheck", "fix_required", "error"]
},
"architect": {
"task_prefix": "ARCH",
"role_spec": "role-specs/architect.md",
"responsibility": "Architecture assessment, tech feasibility. Consulting role",
"role_type": "consulting",
"inner_loop": false,
"message_types": ["arch_ready", "arch_concern", "error"]
},
"fe-developer": {
"task_prefix": "DEV-FE",
"role_spec": "role-specs/fe-developer.md",
"responsibility": "Frontend implementation",
"role_type": "frontend-pipeline",
"inner_loop": false,
"message_types": ["dev_fe_complete", "dev_fe_progress", "error"]
},
"fe-qa": {
"task_prefix": "QA-FE",
"role_spec": "role-specs/fe-qa.md",
"responsibility": "5-dimension frontend review, GC loop",
"role_type": "frontend-pipeline",
"inner_loop": false,
"message_types": ["qa_fe_passed", "qa_fe_result", "fix_required", "error"]
}
},
"subagents": {
"discuss": {
"spec": "subagents/discuss-subagent.md",
"type": "cli-discuss-agent",
"callable_by": ["analyst", "writer", "reviewer"],
"purpose": "Multi-perspective critique (3 rounds: direction, requirements, final gate)"
}
},
"checkpoint_commands": {
"revise": {
"handler": "handleRevise",
"pattern": "revise <TASK-ID> [feedback]",
"cascade": true
},
"feedback": {
"handler": "handleFeedback",
"pattern": "feedback <text>",
"cascade": true
},
"recheck": {
"handler": "handleRecheck",
"pattern": "recheck",
"cascade": false
},
"improve": {
"handler": "handleImprove",
"pattern": "improve [dimension]",
"cascade": false
}
},
"pipelines": {
"spec-only": {
"description": "Spec pipeline: research(+D1) -> brief -> prd(+D2) -> arch -> epics -> quality(+D3)",
"task_chain": ["RESEARCH-001", "DRAFT-001", "DRAFT-002", "DRAFT-003", "DRAFT-004", "QUALITY-001"],
"discuss_points": ["RESEARCH-001", "DRAFT-002", "QUALITY-001"],
"beats": 6
},
"impl-only": {
"description": "Implementation pipeline: plan -> implement -> test + review",
"task_chain": ["PLAN-001", "IMPL-001", "TEST-001", "REVIEW-001"],
"beats": 3
},
"full-lifecycle": {
"description": "Full lifecycle: spec + impl (PLAN blockedBy QUALITY)",
"task_chain": "spec-only + impl-only (PLAN-001 blockedBy QUALITY-001)",
"beats": 9
},
"fe-only": {
"description": "Frontend-only: plan -> dev -> qa",
"task_chain": ["PLAN-001", "DEV-FE-001", "QA-FE-001"],
"gc_loop": { "max_rounds": 2, "convergence": "score >= 8 && critical === 0" }
},
"fullstack": {
"description": "Fullstack: plan -> backend + frontend parallel -> test + qa -> review",
"task_chain": ["PLAN-001", "IMPL-001||DEV-FE-001", "TEST-001||QA-FE-001", "REVIEW-001"]
},
"full-lifecycle-fe": {
"description": "Full lifecycle with frontend",
"task_chain": "spec-only + fullstack (PLAN-001 blockedBy QUALITY-001)"
}
},
"frontend_detection": {
"keywords": ["component", "page", "UI", "frontend", "CSS", "HTML", "React", "Vue", "Tailwind", "Svelte", "Next.js"],
"routing_rules": {
"frontend_only": "All tasks match frontend keywords",
"fullstack": "Mix of frontend and backend tasks",
"backend_only": "No frontend keywords (default impl-only)"
}
},
"session_dirs": {
"base": ".workflow/.team/TLS-{slug}-{YYYY-MM-DD}/",
"spec": "spec/",
"discussions": "discussions/",
"plan": "plan/",
"explorations": "explorations/",
"messages": ".msg/"
}
}

View File

@@ -0,0 +1,432 @@
---
name: team-lifecycle-v3
description: Enhanced lifecycle with parallel execution, conditional routing, dynamic role injection, and task priority scheduling. Built on team-worker agent architecture with artifact contracts and automatic discovery.
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Lifecycle v3
Enhanced lifecycle: specification → implementation → testing → review with parallel execution, conditional routing, and dynamic specialist role injection. Built on **team-worker agent architecture** with **artifact contracts** and **automatic discovery**.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-lifecycle-v3") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (inline)
Phase 0-5 orchestration
+ Dynamic role injection
+ Priority scheduling
+ Artifact registry
|
+----+-----+-------+-------+-------+-------+-------+
v v v v v v v v
[team-worker agents, each loaded with a role-spec]
Core Pipeline (9 roles from v2):
analyst writer planner executor tester reviewer
architect fe-developer fe-qa
Specialist Roles (6 new roles, injected on-demand):
orchestrator security-expert performance-optimizer
data-engineer devops-engineer ml-engineer
Utility Members (3):
[explorer] [discussant] [doc-generator]
```
## Role Router
Coordinator-only. Workers spawned as `team-worker` agents.
### Role Registry
| Role | Spec | Task Prefix | Type | Inner Loop | Injection |
|------|------|-------------|------|------------|-----------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | Always |
| analyst | [role-specs/analyst.md](role-specs/analyst.md) | RESEARCH-* | pipeline | false | Always |
| writer | [role-specs/writer.md](role-specs/writer.md) | DRAFT-* | pipeline | true | Always |
| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true | Always |
| executor | [role-specs/executor.md](role-specs/executor.md) | IMPL-* | pipeline | true | Always |
| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | pipeline | false | Always |
| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* + QUALITY-* + IMPROVE-* | pipeline | false | Always |
| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | consulting | false | High complexity |
| fe-developer | [role-specs/fe-developer.md](role-specs/fe-developer.md) | DEV-FE-* | frontend | false | Frontend tasks |
| fe-qa | [role-specs/fe-qa.md](role-specs/fe-qa.md) | QA-FE-* | frontend | false | Frontend tasks |
| **orchestrator** | [role-specs/orchestrator.md](role-specs/orchestrator.md) | ORCH-* | specialist | false | **Multi-module** |
| **security-expert** | [role-specs/security-expert.md](role-specs/security-expert.md) | SECURITY-* | specialist | false | **security keywords** |
| **performance-optimizer** | [role-specs/performance-optimizer.md](role-specs/performance-optimizer.md) | PERF-* | specialist | false | **performance keywords** |
| **data-engineer** | [role-specs/data-engineer.md](role-specs/data-engineer.md) | DATA-* | specialist | false | **data keywords** |
| **devops-engineer** | [role-specs/devops-engineer.md](role-specs/devops-engineer.md) | DEVOPS-* | specialist | false | **devops keywords** |
| **ml-engineer** | [role-specs/ml-engineer.md](role-specs/ml-engineer.md) | ML-* | specialist | false | **ML keywords** |
### CLI Tool Usage in Workers
Workers use CLI tools for complex analysis:
| Capability | CLI Command | Used By |
|------------|-------------|---------|
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect |
| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer |
| Document generation | `ccw cli --tool gemini --mode write` | writer |
### Coordinator-Only Utility Members
Coordinator can spawn utility members for team-level orchestration:
| Utility Member | Purpose | When |
|----------------|---------|------|
| explorer | Parallel multi-angle exploration | High complexity analysis |
| discussant | Aggregate multi-CLI critique | Critical decision points |
### Dynamic Role Injection
Coordinator analyzes task description and plan complexity to inject specialist roles at runtime:
| Trigger | Injected Role | Injection Point |
|---------|---------------|-----------------|
| Keywords: security, vulnerability, OWASP | security-expert | After PLAN-001 |
| Keywords: performance, optimization, bottleneck | performance-optimizer | After IMPL-* |
| Keywords: data, pipeline, ETL, schema | data-engineer | Parallel with IMPL-* |
| Keywords: devops, CI/CD, deployment, docker | devops-engineer | After IMPL-* |
| Keywords: ML, model, training, inference | ml-engineer | Parallel with IMPL-* |
| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* |
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md`.
### Orchestration Mode
**Invocation**: `Skill(skill="team-lifecycle-v3", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1-3: clarify -> TeamCreate -> analyze complexity -> inject roles -> create task chain
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances
-> Loop until pipeline complete -> Phase 5 report + completion action
```
**User Commands**:
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream |
| `feedback <text>` | Analyze feedback, create targeted revision |
| `recheck` | Re-run QUALITY-001 quality check |
| `improve [dimension]` | Auto-improve weakest dimension |
---
## Coordinator Spawn Template
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-lifecycle-v3/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
priority: <P0|P1|P2>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
---
## Pipeline Definitions
### Spec-only (6 tasks, 3 discuss)
```
RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3)
```
### Impl-only (4 tasks)
```
PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001
```
### Full-lifecycle (10 tasks, v2 compatible)
```
[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001
```
### Enhanced Parallel Pipeline (v3 NEW)
```
RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3)
|
v
PLAN-001 (complexity assessment)
|
+---------------+---------------+
| | |
Low: IMPL-001 Med: ORCH-001 High: ARCH-001
| -> IMPL-* -> ORCH-001
| -> IMPL-*
v
IMPL-001 || DEV-FE-001 (parallel, P0)
|
v
TEST-001 || QA-FE-001 (parallel, P1)
|
v
REVIEW-001 (P1)
```
### Conditional Routing (v3 NEW)
PLAN-001 assesses complexity and routes accordingly:
| Complexity | Route | Roles |
|------------|-------|-------|
| Low (1-2 modules, shallow deps) | Direct IMPL | executor |
| Medium (3-4 modules, moderate deps) | Orchestrated IMPL | orchestrator -> executor (parallel) |
| High (5+ modules, deep deps) | Architecture + Orchestrated IMPL | architect -> orchestrator -> executor (parallel) |
### Dynamic Injection Example (v3 NEW)
Task description: "Implement user authentication with OAuth2, add security audit, optimize login performance"
Injected roles:
- security-expert (keyword: security, audit)
- performance-optimizer (keyword: optimize, performance)
Pipeline becomes:
```
PLAN-001 -> IMPL-001 || SECURITY-001 || PERF-001 -> TEST-001 -> REVIEW-001
```
### Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
```
Beat Cycle (v3 Enhanced)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check artifacts | <- v3: artifact validation
| update registry | <- v3: artifact registry
+- handleSpawnNext -+
| find ready tasks |
| priority sort | <- v3: P0/P1/P2 scheduling
| inject roles | <- v3: dynamic injection
| spawn workers ---+--> [team-worker] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor?
| --> spawn team-worker B directly
| --> log fast_advance to message bus
+- complex case? --> SendMessage to coordinator
======================================================================
```
### Checkpoints
| Trigger | Position | Behavior |
|---------|----------|----------|
| Spec->Impl transition | QUALITY-001 completed | Display checkpoint, pause for user |
| Complexity routing | PLAN-001 completed | Display routing decision, continue |
| Parallel merge | All parallel tasks complete | Validate integration, continue |
| GC loop max | QA-FE max 2 rounds | Stop iteration, report |
| Pipeline stall | No ready + no running | Report to user |
**Checkpoint Output Template** (QUALITY-001):
```
[coordinator] ══════════════════════════════════════════
[coordinator] SPEC PHASE COMPLETE
[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%)
[coordinator]
[coordinator] Dimension Scores:
[coordinator] Completeness: <bar> <n>%
[coordinator] Consistency: <bar> <n>%
[coordinator] Traceability: <bar> <n>%
[coordinator] Depth: <bar> <n>%
[coordinator] Coverage: <bar> <n>%
[coordinator]
[coordinator] Available Actions:
[coordinator] resume -> Proceed to implementation
[coordinator] improve -> Auto-improve weakest dimension
[coordinator] revise <TASK-ID> -> Revise specific document
[coordinator] recheck -> Re-run quality check
[coordinator] feedback <text> -> Inject feedback
[coordinator] ══════════════════════════════════════════
```
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Discuss | Priority |
|---------|------|-------|-------------|---------|----------|
| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | P0 |
| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate | P0 |
| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 | P0 |
| DRAFT-003 | writer | spec | DRAFT-002 | self-validate | P0 |
| DRAFT-004 | writer | spec | DRAFT-003 | self-validate | P0 |
| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 | P0 |
| PLAN-001 | planner | impl | (none or QUALITY-001) | - | P0 |
| ARCH-001 | architect | impl | PLAN-001 | - | P0 (if High complexity) |
| ORCH-001 | orchestrator | impl | PLAN-001 or ARCH-001 | - | P0 (if Med/High complexity) |
| IMPL-001 | executor | impl | PLAN-001 or ORCH-001 | - | P0 |
| DEV-FE-001 | fe-developer | impl | PLAN-001 or ORCH-001 | - | P0 (parallel with IMPL-001) |
| TEST-001 | tester | impl | IMPL-001 | - | P1 |
| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | P1 (parallel with TEST-001) |
| REVIEW-001 | reviewer | impl | IMPL-001 | - | P1 |
| SECURITY-001 | security-expert | impl | IMPL-001 | - | P0 (if injected) |
| PERF-001 | performance-optimizer | impl | IMPL-001 | - | P1 (if injected) |
| DATA-001 | data-engineer | impl | PLAN-001 | - | P0 (if injected, parallel) |
| DEVOPS-001 | devops-engineer | impl | IMPL-001 | - | P1 (if injected) |
| ML-001 | ml-engineer | impl | PLAN-001 | - | P0 (if injected, parallel) |
---
## v3 Artifact Contract
All workers generate `artifact-manifest.json` alongside deliverables for validation gating and automatic discovery.
### Manifest Schema
```json
{
"artifact_id": "string",
"creator_role": "string",
"artifact_type": "string",
"version": "string",
"path": "string",
"dependencies": ["string"],
"validation_status": "pending|passed|failed",
"validation_summary": "string",
"metadata": {
"created_at": "ISO8601 timestamp",
"task_id": "string",
"priority": "P0|P1|P2"
}
}
```
### Validation Gating
Coordinator checks `validation_status` before spawning downstream workers:
| Status | Action |
|--------|--------|
| `passed` | Spawn next worker |
| `failed` | Block spawn, trigger fix loop |
| `pending` | Wait or prompt manual validation |
### Artifact Registry
Coordinator maintains in-memory artifact registry for automatic discovery:
```json
{
"artifacts": {
"<artifact-id>": {
"manifest": { ... },
"discovered_at": "timestamp",
"consumed_by": ["<role-name>"]
}
}
}
```
Workers read `context-artifacts.json` in Phase 2 to discover upstream artifacts automatically.
---
## Session Directory
```
.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json
+-- artifact-registry.json <- v3 NEW
+-- spec/
| +-- spec-config.json
| +-- discovery-context.json
| +-- product-brief.md
| +-- requirements/
| +-- architecture/
| +-- epics/
| +-- readiness-report.md
+-- discussions/
+-- plan/
| +-- plan.json
| +-- .task/TASK-*.json
+-- explorations/
+-- artifacts/ <- v3 NEW: artifact manifests
| +-- artifact-manifest-*.json
+-- .msg/
+-- shared-memory.json
```
## Session Resume
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion
3. Audit TaskList -> reconcile session state
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team, spawn needed workers only
6. Restore artifact registry from session
7. Kick first executable task
## Shared Resources
| Resource | Path | Usage |
|----------|------|-------|
| Document Standards | [specs/document-standards.md](specs/document-standards.md) | YAML frontmatter, naming, structure |
| Quality Gates | [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gates |
| Team Config | [specs/team-config.json](specs/team-config.json) | Role registry, pipeline definitions |
| Artifact Contract | [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) | Artifact manifest schema |
| Role Library | [specs/role-library/](specs/role-library/) | Dynamic role definitions |
| Product Brief Template | [templates/product-brief.md](templates/product-brief.md) | DRAFT-001 |
| Requirements Template | [templates/requirements-prd.md](templates/requirements-prd.md) | DRAFT-002 |
| Architecture Template | [templates/architecture-doc.md](templates/architecture-doc.md) | DRAFT-003 |
| Epics Template | [templates/epics-template.md](templates/epics-template.md) | DRAFT-004 |
| Discuss Subagent | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | 3-round discuss protocol |
| Explorer Subagent | [subagents/explorer-subagent.md](subagents/explorer-subagent.md) | Shared exploration with cache |
| Doc Generator Subagent | [subagents/doc-generator-subagent.md](subagents/doc-generator-subagent.md) | Template-based doc generation |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown command | Error with available command list |
| Role spec file not found | Error with expected path |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Worker proceeds without discuss, logs warning |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| Artifact validation fails | Block downstream, trigger fix loop |
| Dynamic role injection fails | Log warning, continue with core roles |
| Priority conflict | P0 > P1 > P2, FIFO within same priority |
| Parallel merge timeout | Report stall, prompt user intervention |

View File

@@ -0,0 +1,108 @@
---
role: analyst
prefix: RESEARCH
inner_loop: false
discuss_rounds: [DISCUSS-001]
input_artifact_types: []
message_types:
success: research_ready
progress: research_progress
error: error
---
# Analyst — Phase 2-4
## Phase 2: Seed Analysis
**Objective**: Extract structured seed information from the topic.
1. Read upstream artifacts from `context-artifacts.json` (if exists)
2. Extract session folder from task description (`Session: <path>`)
3. Parse topic from task description
4. If topic starts with `@` or ends with `.md`/`.txt` → Read referenced file
5. Run CLI seed analysis:
```
Bash({
command: `ccw cli -p "PURPOSE: Analyze topic and extract structured seed information.
TASK: * Extract problem statement * Identify target users * Determine domain context
* List constraints * Identify 3-5 exploration dimensions * Assess complexity
TOPIC: <topic-content>
MODE: analysis
EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[], complexity_assessment" --tool gemini --mode analysis`,
run_in_background: false
})
```
6. Parse seed analysis JSON
## Phase 3: Codebase Exploration (conditional)
**Objective**: Gather codebase context if project detected.
| Condition | Action |
|-----------|--------|
| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore |
| No project files | Skip (codebase_context = null) |
**When project detected**: Use CLI exploration.
```
Bash({
command: `ccw cli -p "PURPOSE: Explore codebase for context to inform spec generation
TASK: • Identify tech stack • Map architecture patterns • Document conventions • List integration points
MODE: analysis
CONTEXT: @**/*
EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[]" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`,
run_in_background: false
})
```
## Phase 4: Context Packaging + Discuss
### 4a: Context Packaging
**spec-config.json**`<session>/spec/spec-config.json`
**discovery-context.json**`<session>/spec/discovery-context.json`
**design-intelligence.json**`<session>/analysis/design-intelligence.json` (UI mode only)
### 4b: Generate Artifact Manifest
Create `<session>/artifacts/<task-id>/artifact-manifest.json`:
```json
{
"artifact_id": "uuid-...",
"creator_role": "analyst",
"artifact_type": "spec",
"version": "1.0.0",
"path": "./spec/discovery-context.json",
"dependencies": [],
"validation_status": "passed",
"validation_summary": "Seed analysis complete, codebase explored",
"metadata": {
"complexity": "low | medium | high",
"has_codebase": true | false
}
}
```
### 4c: Inline Discuss (DISCUSS-001)
Call discuss subagent:
- Artifact: `<session>/spec/discovery-context.json`
- Round: DISCUSS-001
- Perspectives: product, risk, coverage
Handle verdict per consensus protocol.
**Report**: complexity, codebase presence, problem statement, dimensions, discuss verdict, output paths.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI failure | Fallback to direct Claude analysis |
| Codebase detection failed | Continue as new project |
| Topic too vague | Report with clarification questions |
| Discuss subagent fails | Proceed without discuss, log warning |

View File

@@ -0,0 +1,76 @@
---
role: architect
prefix: ARCH
inner_loop: false
discuss_rounds: []
input_artifact_types: []
message_types:
success: arch_ready
concern: arch_concern
error: error
---
# Architect — Phase 2-4
## Consultation Modes
| Task Pattern | Mode | Focus |
|-------------|------|-------|
| ARCH-SPEC-* | spec-review | Review architecture docs |
| ARCH-PLAN-* | plan-review | Review plan soundness |
| ARCH-CODE-* | code-review | Assess code change impact |
| ARCH-CONSULT-* | consult | Answer architecture questions |
| ARCH-FEASIBILITY-* | feasibility | Technical feasibility |
## Phase 2: Context Loading
**Common**: session folder, wisdom, project-tech.json, explorations
**Mode-specific**:
| Mode | Additional Context |
|------|-------------------|
| spec-review | architecture/_index.md, ADR-*.md |
| plan-review | plan/plan.json |
| code-review | git diff, changed files |
| consult | Question from task description |
| feasibility | Requirements + codebase |
## Phase 3: Assessment
Analyze using mode-specific criteria. Output: mode, verdict (APPROVE/CONCERN/BLOCK), dimensions[], concerns[], recommendations[].
For complex questions → Gemini CLI with architecture review rule:
```
Bash({
command: `ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture`,
run_in_background: true
})
```
## Phase 4: Report
Output to `<session-folder>/architecture/arch-<slug>.json`. Contribute decisions to wisdom/decisions.md.
**Frontend project outputs** (when frontend tech stack detected):
- `<session-folder>/architecture/design-tokens.json` — color, spacing, typography, shadow tokens
- `<session-folder>/architecture/component-specs/*.md` — per-component design spec
**Report**: mode, verdict, concern count, recommendations, output path(s).
### Coordinator Integration
| Timing | Task |
|--------|------|
| After DRAFT-003 | ARCH-SPEC-001: architecture doc review |
| After PLAN-001 | ARCH-PLAN-001: plan architecture review |
| On-demand | ARCH-CONSULT-001: architecture consultation |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Docs not found | Assess from available context |
| CLI timeout | Partial assessment |
| Insufficient context | Request explorer via coordinator |

View File

@@ -0,0 +1,67 @@
---
role: executor
prefix: IMPL
inner_loop: true
discuss_rounds: []
input_artifact_types: []
message_types:
success: impl_complete
progress: impl_progress
error: error
---
# Executor — Phase 2-4
## Phase 2: Task & Plan Loading
**Objective**: Load plan and determine execution strategy.
1. Load plan.json and .task/TASK-*.json from `<session-folder>/plan/`
**Backend selection** (priority order):
| Priority | Source | Method |
|----------|--------|--------|
| 1 | Task metadata | task.metadata.executor field |
| 2 | Plan default | "Execution Backend:" in plan |
| 3 | Auto-select | Simple (< 200 chars, no refactor) → agent; Complex → codex |
**Code review selection**:
| Priority | Source | Method |
|----------|--------|--------|
| 1 | Task metadata | task.metadata.code_review field |
| 2 | Plan default | "Code Review:" in plan |
| 3 | Auto-select | Critical keywords (auth, security, payment) → enabled |
## Phase 3: Code Implementation
**Objective**: Execute implementation across batches.
**Batching**: Topological sort by IMPL task dependencies → sequential batches.
| Backend | Invocation | Use Case |
|---------|-----------|----------|
| gemini | `ccw cli --tool gemini --mode write` (foreground) | Simple, direct edits |
| codex | `ccw cli --tool codex --mode write` (foreground) | Complex, architecture |
| qwen | `ccw cli --tool qwen --mode write` (foreground) | Alternative backend |
## Phase 4: Self-Validation
| Step | Method | Pass Criteria |
|------|--------|--------------|
| Syntax check | `tsc --noEmit` (30s) | Exit code 0 |
| Acceptance criteria | Match criteria keywords vs implementation | All addressed |
| Test detection | Find .test.ts/.spec.ts for modified files | Tests identified |
| Code review (optional) | gemini analysis or codex review | No blocking issues |
**Report**: task ID, status, files modified, validation results, backend used.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Syntax errors | Retry with error context (max 3) |
| Missing dependencies | Request from coordinator |
| Backend unavailable | Fallback to alternative tool |
| Circular dependencies | Abort, report graph |

View File

@@ -0,0 +1,79 @@
---
role: fe-developer
prefix: DEV-FE
inner_loop: false
discuss_rounds: []
input_artifact_types: []
message_types:
success: dev_fe_complete
progress: dev_fe_progress
error: error
---
# FE Developer — Phase 2-4
## Phase 2: Context Loading
**Inputs to load**:
- Plan: `<session-folder>/plan/plan.json`
- Design tokens: `<session-folder>/architecture/design-tokens.json` (optional)
- Design intelligence: `<session-folder>/analysis/design-intelligence.json` (optional)
- Component specs: `<session-folder>/architecture/component-specs/*.md` (optional)
- Shared memory, wisdom
**Tech stack detection**:
| Signal | Framework | Styling |
|--------|-----------|---------|
| react/react-dom in deps | react | - |
| vue in deps | vue | - |
| next in deps | nextjs | - |
| tailwindcss in deps | - | tailwind |
| @shadcn/ui in deps | - | shadcn |
## Phase 3: Frontend Implementation
**Step 1**: Generate design token CSS (if tokens available)
- Convert design-tokens.json → CSS custom properties (`:root { --color-*, --space-*, --text-* }`)
- Include dark mode overrides via `@media (prefers-color-scheme: dark)`
- Write to `src/styles/tokens.css`
**Step 2**: Implement components
| Task Size | Strategy |
|-----------|----------|
| Simple (<= 3 files, single component) | `ccw cli --tool gemini --mode write` (foreground) |
| Complex (system, multi-component) | `ccw cli --tool codex --mode write` (foreground) |
**Coding standards** (include in agent/CLI prompt):
- Use design token CSS variables, never hardcode colors/spacing
- Interactive elements: cursor: pointer
- Transitions: 150-300ms
- Text contrast: minimum 4.5:1
- Include focus-visible styles
- Support prefers-reduced-motion
- Responsive: mobile-first
- No emoji as functional icons
## Phase 4: Self-Validation
| Check | What |
|-------|------|
| hardcoded-color | No #hex outside tokens.css |
| cursor-pointer | Interactive elements have cursor: pointer |
| focus-styles | Interactive elements have focus styles |
| responsive | Has responsive breakpoints |
| reduced-motion | Animations respect prefers-reduced-motion |
| emoji-icon | No emoji as functional icons |
Contribute to wisdom/conventions.md. Update shared-memory.json with component inventory.
**Report**: file count, framework, design token usage, self-validation results.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Design tokens not found | Use project defaults |
| Tech stack undetected | Default HTML + CSS |
| CLI failure | Retry with alternative tool |

View File

@@ -0,0 +1,79 @@
---
role: fe-qa
prefix: QA-FE
inner_loop: false
discuss_rounds: []
input_artifact_types: []
message_types:
success: qa_fe_passed
result: qa_fe_result
fix: fix_required
error: error
---
# FE QA — Phase 2-4
## Review Dimensions
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Code Quality | 25% | TypeScript types, component structure, error handling |
| Accessibility | 25% | Semantic HTML, ARIA, keyboard nav, contrast, focus-visible |
| Design Compliance | 20% | Token usage, no hardcoded colors, no emoji icons |
| UX Best Practices | 15% | Loading/error/empty states, cursor-pointer, responsive |
| Pre-Delivery | 15% | No console.log, dark mode, i18n readiness |
## Phase 2: Context Loading
**Inputs**: design tokens, design intelligence, shared memory, previous QA results (for GC round tracking), changed frontend files via git diff.
Determine GC round from previous QA results count. Max 2 rounds.
## Phase 3: 5-Dimension Review
For each changed frontend file, check against all 5 dimensions. Score each dimension 0-10, deducting for issues found.
**Scoring deductions**:
| Severity | Deduction |
|----------|-----------|
| High | -2 to -3 |
| Medium | -1 to -1.5 |
| Low | -0.5 |
**Overall score** = weighted sum of dimension scores.
**Verdict routing**:
| Condition | Verdict |
|-----------|---------|
| Score >= 8 AND no critical issues | PASS |
| GC round >= max AND score >= 6 | PASS_WITH_WARNINGS |
| GC round >= max AND score < 6 | FAIL |
| Otherwise | NEEDS_FIX |
## Phase 4: Report
Write audit to `<session-folder>/qa/audit-fe-<task>-r<round>.json`. Update wisdom and shared memory.
**Report**: round, verdict, overall score, dimension scores, critical issues with Do/Don't format, action required (if NEEDS_FIX).
### Generator-Critic Loop
Orchestrated by coordinator:
```
Round 1: DEV-FE-001 → QA-FE-001
if NEEDS_FIX → coordinator creates DEV-FE-002 + QA-FE-002
Round 2: DEV-FE-002 → QA-FE-002
if still NEEDS_FIX → PASS_WITH_WARNINGS or FAIL (max 2)
```
**Convergence**: score >= 8 AND critical_count = 0
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No changed files | Report empty, score N/A |
| Design tokens not found | Skip design compliance, adjust weights |
| Max GC rounds exceeded | Force verdict |

View File

@@ -0,0 +1,145 @@
---
prefix: ORCH
inner_loop: false
message_types:
success: orch_complete
error: error
---
# Orchestrator
Decomposes complex multi-module tasks into coordinated sub-tasks with parallel execution and dependency management.
## Phase 2: Context & Complexity Assessment
| Input | Source | Required |
|-------|--------|----------|
| Task description | From coordinator | Yes |
| Plan document | Session plan/ | Yes |
| Exploration cache | Session explorations/ | No |
### Step 1: Load Context
Extract session path from task description. Read plan document to understand scope and requirements.
### Step 2: Complexity Analysis
Assess task complexity across dimensions:
| Dimension | Indicators | Weight |
|-----------|-----------|--------|
| Module count | Number of modules affected | High |
| Dependency depth | Cross-module dependencies | High |
| Technology stack | Multiple tech stacks involved | Medium |
| Integration points | External system integrations | Medium |
### Step 3: Decomposition Strategy
| Complexity | Strategy |
|------------|----------|
| 2-3 modules, shallow deps | Simple parallel split |
| 4-6 modules, moderate deps | Phased parallel with integration checkpoints |
| 7+ modules, deep deps | Hierarchical decomposition with sub-orchestrators |
### Step 4: Exploration
If complexity is High, delegate to explorer utility member for codebase context gathering.
## Phase 3: Task Decomposition & Coordination
### Step 1: Generate Sub-Tasks
Break down into parallel tracks:
| Track Type | Characteristics | Owner Role |
|------------|----------------|------------|
| Frontend | UI components, state management | fe-developer |
| Backend | API, business logic, data access | executor |
| Data | Schema, migrations, ETL | data-engineer |
| Infrastructure | Deployment, CI/CD | devops-engineer |
### Step 2: Dependency Mapping
Create dependency graph:
- Identify shared interfaces (API contracts, data schemas)
- Mark blocking dependencies (schema before backend, API before frontend)
- Identify parallel-safe tracks
### Step 3: Priority Assignment
Assign priority levels:
| Priority | Criteria | Impact |
|----------|----------|--------|
| P0 | Blocking dependencies, critical path | Execute first |
| P1 | Standard implementation | Execute after P0 |
| P2 | Nice-to-have, non-blocking | Execute last |
### Step 4: Spawn Coordination
Create sub-tasks via coordinator message:
```
SendMessage({
type: "spawn_request",
recipient: "coordinator",
content: {
sub_tasks: [
{ id: "IMPL-FE-001", role: "fe-developer", priority: "P1", blockedBy: ["IMPL-BE-001"] },
{ id: "IMPL-BE-001", role: "executor", priority: "P0", blockedBy: [] },
{ id: "DATA-001", role: "data-engineer", priority: "P0", blockedBy: [] }
],
parallel_groups: [
["IMPL-BE-001", "DATA-001"],
["IMPL-FE-001"]
]
}
})
```
## Phase 4: Integration & Validation
### Step 1: Monitor Progress
Track sub-task completion via message bus. Wait for all sub-tasks in current parallel group to complete.
### Step 2: Integration Check
Validate integration points:
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| API contracts | Compare spec vs implementation | All endpoints match |
| Data schemas | Validate migrations applied | Schema version consistent |
| Type consistency | Cross-module type checking | No type mismatches |
### Step 3: Artifact Registry
Generate artifact manifest for orchestration result:
```javascript
Write("artifact-manifest.json", JSON.stringify({
artifact_id: `orchestrator-integration-${Date.now()}`,
creator_role: "orchestrator",
artifact_type: "integration",
version: "1.0.0",
path: "integration-report.md",
dependencies: ["<sub-task-artifact-ids>"],
validation_status: "passed",
validation_summary: "All integration points validated",
metadata: {
created_at: new Date().toISOString(),
task_id: "<current-task-id>",
sub_task_count: <count>,
parallel_groups: <groups>
}
}))
```
### Step 4: Report
Generate integration report with:
- Sub-task completion status
- Integration validation results
- Identified issues and resolutions
- Next steps or recommendations

View File

@@ -0,0 +1,98 @@
---
role: planner
prefix: PLAN
inner_loop: true
discuss_rounds: []
input_artifact_types: [spec, architecture]
message_types:
success: plan_ready
revision: plan_revision
error: error
---
# Planner — Phase 2-4
## Phase 1.5: Load Spec Context (Full-Lifecycle)
If `<session-folder>/spec/` exists → load requirements/_index.md, architecture/_index.md, epics/_index.md, spec-config.json. Otherwise → impl-only mode.
**Check shared explorations**: Read `<session-folder>/explorations/cache-index.json` to see if analyst already cached useful explorations. Reuse rather than re-explore.
## Phase 2: Multi-Angle Exploration
**Objective**: Explore codebase to inform planning.
**Complexity routing**:
| Complexity | Criteria | Strategy |
|------------|----------|----------|
| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only |
| Medium | 200-500 chars or moderate scope | 2-3 angle explore subagent |
| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle explore subagent |
For each angle, use CLI exploration (cache-aware — check cache-index.json before each call):
```
Bash({
command: `ccw cli -p "PURPOSE: Explore codebase from <angle> perspective to inform planning
TASK: • Search for <angle>-specific patterns • Identify relevant files • Document integration points
MODE: analysis
CONTEXT: @**/* | Memory: Task keywords: <keywords>
EXPECTED: JSON with: relevant_files[], patterns[], integration_points[], recommendations[]
CONSTRAINTS: Focus on <angle> perspective" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`,
run_in_background: false
})
```
## Phase 3: Plan Generation
**Objective**: Generate structured implementation plan.
| Complexity | Strategy |
|------------|----------|
| Low | Direct planning → single TASK-001 with plan.json |
| Medium/High | cli-lite-planning-agent with exploration results |
**CLI call** (Medium/High):
```
Bash({
command: `ccw cli -p "PURPOSE: Generate structured implementation plan from exploration results
TASK: • Create plan.json with overview • Generate TASK-*.json files (2-7 tasks) • Define dependencies • Set convergence criteria
MODE: write
CONTEXT: @<session-folder>/explorations/*.json | Memory: Complexity: <complexity>
EXPECTED: Files: plan.json + .task/TASK-*.json. Schema: ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json
CONSTRAINTS: 2-7 tasks, include id/title/files[].change/convergence.criteria/depends_on" --tool gemini --mode write --rule planning-breakdown-task-steps`,
run_in_background: false
})
```
**Spec context** (full-lifecycle): Reference REQ-* IDs, follow ADR decisions, reuse Epic/Story decomposition.
## Phase 4: Submit for Approval
1. Read plan.json and TASK-*.json
2. Report to coordinator: complexity, task count, task list, approach, plan location
3. Wait for response: approved → complete; revision → update and resubmit
**Session files**:
```
<session-folder>/explorations/ (shared cache)
+-- cache-index.json
+-- explore-<angle>.json
<session-folder>/plan/
+-- explorations-manifest.json
+-- plan.json
+-- .task/TASK-*.json
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI exploration failure | Plan from description only |
| CLI planning failure | Fallback to direct planning |
| Plan rejected 3+ times | Notify coordinator, suggest alternative |
| Schema not found | Use basic structure |
| Cache index corrupt | Clear cache, re-explore all angles |

View File

@@ -0,0 +1,94 @@
---
role: reviewer
prefix: REVIEW
additional_prefixes: [QUALITY, IMPROVE]
inner_loop: false
discuss_rounds: [DISCUSS-003]
input_artifact_types: []
message_types:
success_review: review_result
success_quality: quality_result
fix: fix_required
error: error
---
# Reviewer — Phase 2-4
## Phase 2: Mode Detection
| Task Prefix | Mode | Dimensions | Discuss |
|-------------|------|-----------|---------|
| REVIEW-* | Code Review | quality, security, architecture, requirements | None |
| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage | DISCUSS-003 |
| IMPROVE-* | Spec Quality (recheck) | Same as QUALITY | DISCUSS-003 |
## Phase 3: Review Execution
### Code Review (REVIEW-*)
**Inputs**: Plan file, git diff, modified files, test results
**4 dimensions**:
| Dimension | Critical Issues |
|-----------|----------------|
| Quality | Empty catch, any in public APIs, @ts-ignore, console.log |
| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML |
| Architecture | Circular deps, parent imports >2 levels, files >500 lines |
| Requirements | Missing core functionality, incomplete acceptance criteria |
### Spec Quality (QUALITY-* / IMPROVE-*)
**Inputs**: All spec docs in session folder, quality gate config
**5 dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Completeness | 25% | All sections present with substance |
| Consistency | 20% | Terminology, format, references |
| Traceability | 25% | Goals -> Reqs -> Arch -> Stories chain |
| Depth | 20% | AC testable, ADRs justified, stories estimable |
| Coverage | 10% | Original requirements mapped |
**Quality gate**:
| Gate | Criteria |
|------|----------|
| PASS | Score >= 80% AND coverage >= 70% |
| REVIEW | Score 60-79% OR coverage 50-69% |
| FAIL | Score < 60% OR coverage < 50% |
**Artifacts**: readiness-report.md + spec-summary.md
## Phase 4: Verdict + Discuss
### Code Review Verdict
| Verdict | Criteria |
|---------|----------|
| BLOCK | Critical issues present |
| CONDITIONAL | High/medium only |
| APPROVE | Low or none |
### Spec Quality Discuss (DISCUSS-003)
After generating readiness-report.md, call discuss subagent:
- Artifact: `<session>/spec/readiness-report.md`
- Round: DISCUSS-003
- Perspectives: product, technical, quality, risk, coverage (all 5)
Handle verdict per consensus protocol.
> **Note**: DISCUSS-003 HIGH always triggers user pause (final sign-off gate).
**Report**: mode, verdict/gate, dimension scores, discuss verdict (QUALITY only), output paths.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Missing context | Request from coordinator |
| Invalid mode | Abort with error |
| Analysis failure | Retry, then fallback |
| Discuss subagent fails | Proceed without discuss, log warning |

View File

@@ -0,0 +1,76 @@
---
role: tester
prefix: TEST
inner_loop: false
discuss_rounds: []
input_artifact_types: []
message_types:
success: test_result
fix: fix_required
error: error
---
# Tester — Phase 2-4
## Phase 2: Framework Detection & Test Discovery
**Framework detection** (priority order):
| Priority | Method | Frameworks |
|----------|--------|-----------|
| 1 | package.json devDependencies | vitest, jest, mocha, pytest |
| 2 | package.json scripts.test | vitest, jest, mocha, pytest |
| 3 | Config files | vitest.config.*, jest.config.*, pytest.ini |
**Affected test discovery** from executor's modified files:
- Search variants: `<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts`
## Phase 3: Test Execution & Fix Cycle
**Config**: MAX_ITERATIONS=10, PASS_RATE_TARGET=95%, AFFECTED_TESTS_FIRST=true
1. Run affected tests → parse results
2. Pass rate met → run full suite
3. Failures → select strategy → fix → re-run → repeat
**Strategy selection**:
| Condition | Strategy | Behavior |
|-----------|----------|----------|
| Iteration <= 3 or pass >= 80% | Conservative | Fix one critical failure at a time |
| Critical failures < 5 | Surgical | Fix specific pattern everywhere |
| Pass < 50% or iteration > 7 | Aggressive | Fix all failures in batch |
**Test commands**:
| Framework | Affected | Full Suite |
|-----------|---------|------------|
| vitest | `vitest run <files>` | `vitest run` |
| jest | `jest <files> --no-coverage` | `jest --no-coverage` |
| pytest | `pytest <files> -v` | `pytest -v` |
## Phase 4: Result Analysis
**Failure classification**:
| Severity | Patterns |
|----------|----------|
| Critical | SyntaxError, cannot find module, undefined |
| High | Assertion failures, toBe/toEqual |
| Medium | Timeout, async errors |
| Low | Warnings, deprecations |
**Report routing**:
| Condition | Type |
|-----------|------|
| Pass rate >= target | test_result (success) |
| Pass rate < target after max iterations | fix_required |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Framework not detected | Prompt user |
| No tests found | Report to coordinator |
| Infinite fix loop | Abort after MAX_ITERATIONS |

View File

@@ -0,0 +1,139 @@
---
role: writer
prefix: DRAFT
inner_loop: true
discuss_rounds: [DISCUSS-002]
input_artifact_types: [spec]
message_types:
success: draft_ready
revision: draft_revision
error: error
---
# Writer — Phase 2-4
## Phase 2: Context Loading
**Objective**: Load all required inputs for document generation.
### 2a: Read Upstream Artifacts
Load `context-artifacts.json` to discover upstream artifacts:
```json
{
"artifacts": [
{
"artifact_id": "uuid-...",
"artifact_type": "spec",
"path": "./spec/discovery-context.json",
"creator_role": "analyst"
}
]
}
```
### 2b: Document Type Routing
| Task Subject Contains | Doc Type | Template | Validation |
|----------------------|----------|----------|------------|
| Product Brief | product-brief | templates/product-brief.md | self-validate |
| Requirements / PRD | requirements | templates/requirements-prd.md | DISCUSS-002 |
| Architecture | architecture | templates/architecture-doc.md | self-validate |
| Epics | epics | templates/epics-template.md | self-validate |
### 2c: Progressive Dependency Loading
| Doc Type | Requires |
|----------|----------|
| product-brief | discovery-context.json |
| requirements | + product-brief.md |
| architecture | + requirements/_index.md |
| epics | + architecture/_index.md |
**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to generation.
| Input | Source | Required |
|-------|--------|----------|
| Document standards | `../../specs/document-standards.md` | Yes |
| Template | From routing table | Yes |
| Spec config | `<session>/spec/spec-config.json` | Yes |
| Discovery context | `<session>/spec/discovery-context.json` | Yes |
| Discussion feedback | `<session>/discussions/<discuss-file>` | If exists |
| Prior decisions | context_accumulator (in-memory) | If prior tasks |
## Phase 3: Document Generation
**Objective**: Generate document using CLI tool.
```
Bash({
command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template and standards
TASK: • Load template • Apply spec config and discovery context • Integrate prior feedback • Generate all sections
MODE: write
CONTEXT: @<session>/spec/*.json @<template-path> | Memory: Prior decisions: <accumulator summary>
EXPECTED: Document at <output-path> with: YAML frontmatter, all sections, cross-references
CONSTRAINTS: Follow document-standards.md" --tool gemini --mode write --rule development-implement-feature --cd <session>`,
run_in_background: false
})
```
## Phase 4: Validation + Artifact Manifest
### 4a: Self-Validation (all doc types)
| Check | What to Verify |
|-------|---------------|
| has_frontmatter | Starts with YAML frontmatter |
| sections_complete | All template sections present |
| cross_references | session_id included |
| progressive_consistency | References to upstream docs are valid |
### 4b: Generate Artifact Manifest
Create `<session>/artifacts/<task-id>/artifact-manifest.json`:
```json
{
"artifact_id": "uuid-...",
"creator_role": "writer",
"artifact_type": "spec",
"version": "1.0.0",
"path": "./spec/<doc-type>/_index.md",
"dependencies": ["analyst-artifact-id"],
"validation_status": "passed | failed",
"validation_summary": "All sections complete, frontmatter valid",
"metadata": {
"doc_type": "product-brief | requirements | architecture | epics",
"sections_count": 8
}
}
```
### 4c: Validation Routing
| Doc Type | Validation Method |
|----------|------------------|
| product-brief | Self-validation only → report |
| requirements (PRD) | Self-validation + **DISCUSS-002** |
| architecture | Self-validation only → report |
| epics | Self-validation only → report |
**DISCUSS-002** (PRD only):
- Artifact: `<session>/spec/requirements/_index.md`
- Round: DISCUSS-002
- Perspectives: quality, product, coverage
Handle discuss verdict per consensus protocol.
**Report**: doc type, validation status, discuss verdict (PRD only), output path.
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI failure | Retry once with alternative tool. Still fails → log, continue next |
| Discuss subagent fails | Skip discuss, log warning |
| Cumulative 3 task failures | SendMessage to coordinator, STOP |
| Prior doc not found | Notify coordinator, request prerequisite |
| Discussion contradicts prior docs | Note conflict, flag for coordinator |

View File

@@ -0,0 +1,217 @@
# Command: dispatch (v3 Enhanced)
Create task chains based on execution mode with conditional routing, dynamic role injection, and priority assignment.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Mode | Phase 1 requirements | Yes |
| Session folder | Phase 2 session init | Yes |
| Scope | User requirements | Yes |
| Injected roles | Phase 1 keyword analysis | No |
| Complexity | Phase 1 assessment | No |
## Phase 3: Task Chain Creation
### Spec Pipeline (6 tasks, 3 discuss)
| # | Subject | Owner | BlockedBy | Description | Validation | Priority |
|---|---------|-------|-----------|-------------|------------|----------|
| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 | P0 |
| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | self-validate | P0 |
| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-002 | P0 |
| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | self-validate | P0 |
| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | self-validate | P0 |
| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-003 | P0 |
### Impl Pipeline - Conditional Routing (v3 NEW)
#### Low Complexity (1-2 modules, shallow deps)
| # | Subject | Owner | BlockedBy | Description | Priority |
|---|---------|-------|-----------|-------------|----------|
| 1 | PLAN-001 | planner | (none) | Planning with complexity assessment | P0 |
| 2 | IMPL-001 | executor | PLAN-001 | Code implementation | P0 |
| 3 | TEST-001 | tester | IMPL-001 | Test-fix cycles | P1 |
| 4 | REVIEW-001 | reviewer | IMPL-001 | 4-dimension code review | P1 |
#### Medium Complexity (3-4 modules, moderate deps)
| # | Subject | Owner | BlockedBy | Description | Priority |
|---|---------|-------|-----------|-------------|----------|
| 1 | PLAN-001 | planner | (none) | Planning with complexity assessment | P0 |
| 2 | ORCH-001 | orchestrator | PLAN-001 | Task decomposition & coordination | P0 |
| 3 | IMPL-001 | executor | ORCH-001 | Backend implementation | P0 |
| 4 | IMPL-002 | executor | ORCH-001 | Module 2 implementation | P0 |
| 5 | TEST-001 | tester | IMPL-001, IMPL-002 | Test-fix cycles | P1 |
| 6 | REVIEW-001 | reviewer | IMPL-001, IMPL-002 | 4-dimension code review | P1 |
#### High Complexity (5+ modules, deep deps)
| # | Subject | Owner | BlockedBy | Description | Priority |
|---|---------|-------|-----------|-------------|----------|
| 1 | PLAN-001 | planner | (none) | Planning with complexity assessment | P0 |
| 2 | ARCH-001 | architect | PLAN-001 | Architecture design | P0 |
| 3 | ORCH-001 | orchestrator | ARCH-001 | Task decomposition & coordination | P0 |
| 4 | IMPL-001 | executor | ORCH-001 | Backend implementation | P0 |
| 5 | IMPL-002 | executor | ORCH-001 | Module 2 implementation | P0 |
| 6 | IMPL-003 | executor | ORCH-001 | Module 3 implementation | P0 |
| 7 | TEST-001 | tester | IMPL-001, IMPL-002, IMPL-003 | Test-fix cycles | P1 |
| 8 | REVIEW-001 | reviewer | IMPL-001, IMPL-002, IMPL-003 | 4-dimension code review | P1 |
### FE Pipeline (3 tasks)
| # | Subject | Owner | BlockedBy | Description | Priority |
|---|---------|-------|-----------|-------------|----------|
| 1 | PLAN-001 | planner | (none) | Planning (frontend focus) | P0 |
| 2 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | P0 |
| 3 | QA-FE-001 | fe-qa | DEV-FE-001 | 5-dimension frontend QA | P1 |
### Fullstack Pipeline (6 tasks, parallel execution)
| # | Subject | Owner | BlockedBy | Description | Priority |
|---|---------|-------|-----------|-------------|----------|
| 1 | PLAN-001 | planner | (none) | Fullstack planning | P0 |
| 2 | IMPL-001 | executor | PLAN-001 | Backend implementation | P0 |
| 3 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation (parallel) | P0 |
| 4 | TEST-001 | tester | IMPL-001 | Backend test-fix | P1 |
| 5 | QA-FE-001 | fe-qa | DEV-FE-001 | Frontend QA (parallel) | P1 |
| 6 | REVIEW-001 | reviewer | TEST-001, QA-FE-001 | Full code review | P1 |
### Dynamic Role Injection (v3 NEW)
When specialist roles are injected, add corresponding tasks:
| Injected Role | Task ID | Owner | BlockedBy | Description | Priority |
|---------------|---------|-------|-----------|-------------|----------|
| security-expert | SECURITY-001 | security-expert | IMPL-001 | Security audit (OWASP Top 10) | P0 |
| performance-optimizer | PERF-001 | performance-optimizer | IMPL-001 | Performance profiling & optimization | P1 |
| data-engineer | DATA-001 | data-engineer | PLAN-001 | Data pipeline implementation (parallel) | P0 |
| devops-engineer | DEVOPS-001 | devops-engineer | IMPL-001 | CI/CD & infrastructure setup | P1 |
| ml-engineer | ML-001 | ml-engineer | PLAN-001 | ML pipeline implementation (parallel) | P0 |
**Injection Rules**:
- Security tasks: P0 priority, block REVIEW-001
- Performance tasks: P1 priority, parallel with TEST-001
- Data/ML tasks: P0 priority, parallel with IMPL-001
- DevOps tasks: P1 priority, after IMPL-001
### Composite Modes
| Mode | Construction | PLAN-001 BlockedBy |
|------|-------------|-------------------|
| full-lifecycle | Spec (6) + Impl (conditional) | QUALITY-001 |
| full-lifecycle-fe | Spec (6) + Fullstack (6) | QUALITY-001 |
### Task Description Template
```
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what> | Success: <criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Scope: <scope>
- Upstream: <artifacts>
- Priority: <P0|P1|P2>
EXPECTED: <deliverable> + <quality>
CONSTRAINTS: <scope limits>
---
Validation: <DISCUSS-NNN or self-validate>
InnerLoop: <true|false>
Priority: <P0|P1|P2>",
addBlockedBy: [<deps>]
})
```
### Complexity Assessment Logic (v3 NEW)
PLAN-001 task description includes complexity assessment instructions:
```
PURPOSE: Create implementation plan with complexity assessment | Success: Actionable plan with module breakdown and complexity rating
TASK:
- Analyze requirements and scope
- Identify modules and dependencies
- Assess complexity (Low/Medium/High)
- Generate implementation plan
- Write complexity assessment to plan.json
CONTEXT:
- Session: <session-folder>
- Spec artifacts: <paths>
- Complexity criteria:
* Low: 1-2 modules, shallow deps, single tech stack
* Medium: 3-4 modules, moderate deps, 2 tech stacks
* High: 5+ modules, deep deps, multiple tech stacks
EXPECTED: plan.json with complexity field + implementation plan document
Priority: P0
```
### Revision Task Template
```
TaskCreate({
subject: "<ORIGINAL-ID>-R1",
owner: "<same-role>",
description: "PURPOSE: Revision of <ORIGINAL-ID> | Success: Address feedback
TASK:
- Review original + feedback
- Apply fixes
- Validate
CONTEXT:
- Session: <session-folder>
- Original: <artifact-path>
- Feedback: <text>
- Priority: <inherit-from-original>
EXPECTED: Updated artifact + summary
---
Validation: <same-as-original>
InnerLoop: <same-as-original>
Priority: <inherit-from-original>",
addBlockedBy: []
})
```
## Phase 4: Artifact Manifest Generation
For each task, include artifact manifest generation instructions in task description:
```
---
Artifact Contract:
Generate artifact-manifest.json in Phase 4:
{
"artifact_id": "<role>-<type>-<timestamp>",
"creator_role": "<role>",
"artifact_type": "<type>",
"version": "1.0.0",
"path": "<relative-path>",
"dependencies": [<upstream-artifact-ids>],
"validation_status": "pending|passed|failed",
"validation_summary": "<summary>",
"metadata": {
"created_at": "<ISO8601>",
"task_id": "<task-id>",
"priority": "<P0|P1|P2>"
}
}
```
## Error Handling
| Error | Resolution |
|-------|------------|
| Invalid mode | Reject, ask to clarify |
| Complexity assessment missing | Default to Low complexity |
| Injected role not found | Log warning, skip injection |
| Priority conflict | P0 > P1 > P2, FIFO within same priority |
| Circular dependency | Detect, report, halt |

View File

@@ -0,0 +1,263 @@
# Command: monitor (v3 Enhanced)
Monitor team progress, handle callbacks, manage artifact registry, spawn next workers with priority scheduling.
## Handlers
| Handler | Trigger | Purpose |
|---------|---------|---------|
| handleCallback | Worker completion message | Process completion, validate artifacts, spawn next |
| handleCheck | User "check" command | Display current status |
| handleResume | User "resume" command | Advance pipeline |
| handleSpawnNext | Internal | Find ready tasks, priority sort, spawn workers |
| handleComplete | All tasks done | Trigger completion action |
---
## handleCallback
### Input
- Worker completion message via SendMessage
- Message contains: role, task_id, status, artifact_path
### Steps
1. **Parse Message**
- Extract role, task_id, status from message
- Load task via TaskGet
2. **Update Task Status**
- TaskUpdate(status="completed")
- Log completion to message bus
3. **Artifact Validation (v3 NEW)**
- Check if artifact-manifest.json exists
- If exists:
- Read manifest
- Check validation_status
- Register artifact in artifact-registry.json
- If validation_status == "failed":
- Block downstream spawn
- Create fix task
- STOP
- If validation_status == "pending":
- Prompt user for manual validation
- STOP
- If not exists (backward compatible):
- Continue without validation gating
4. **Checkpoint Detection**
- If task_id == "QUALITY-001":
- Display checkpoint output (see SKILL.md)
- Pause for user command
- STOP
- If task_id == "PLAN-001" (v3 NEW):
- Read plan.json for complexity assessment
- Display routing decision
- Apply conditional routing
- Continue
5. **Spawn Next**
- Call handleSpawnNext
- STOP
---
## handleSpawnNext (v3 Enhanced)
### Steps
1. **Find Ready Tasks**
- TaskList -> filter status="pending"
- For each pending task:
- Check blockedBy dependencies
- All blockedBy tasks completed? -> ready
2. **Priority Sorting (v3 NEW)**
- Sort ready tasks by priority:
- P0 tasks first
- P1 tasks second
- P2 tasks last
- Within same priority: FIFO (creation order)
3. **Parallel Grouping (v3 NEW)**
- Group tasks by stage (same blockedBy set)
- Tasks in same group can spawn in parallel
- Example: IMPL-001 and DEV-FE-001 both blocked by PLAN-001 -> parallel group
4. **Artifact Discovery (v3 NEW)**
- For each ready task:
- Query artifact registry for upstream artifacts
- Generate context-artifacts.json with artifact paths
- Write to session folder for worker Phase 2 consumption
5. **Spawn Workers**
- For each ready task (or parallel group):
- Spawn team-worker agent with role-spec
- Include priority in prompt
- Include context-artifacts.json path
- Log spawn to message bus
6. **Output Summary**
- List spawned tasks with priorities
- Show remaining pending count
- STOP
### Spawn Template (v3 Enhanced)
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-lifecycle-v3/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
priority: <P0|P1|P2>
context_artifacts: <session-folder>/context-artifacts.json
Read role_spec file to load Phase 2-4 domain instructions.
Read context_artifacts for upstream artifact paths (automatic discovery).
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
---
## handleCheck
### Steps
1. **Load Session State**
- Read team-session.json
- TaskList -> count by status
2. **Display Status**
- Session ID
- Mode
- Task counts: completed / in_progress / pending
- Current running workers
- Artifact registry summary (v3 NEW)
- Priority queue status (v3 NEW)
3. **STOP** (no advancement)
---
## handleResume
### Steps
1. **Reconcile State**
- TaskList -> find in_progress tasks
- Check if workers still running
- If worker missing:
- Reset task to pending
- Log orphan detection
2. **Fast-Advance Orphan Detection**
- Check message bus for fast_advance logs
- If fast_advance spawned wrong task:
- Reconcile task chain
- Respawn correct task
3. **Spawn Next**
- Call handleSpawnNext
- STOP
---
## handleComplete (v3 NEW)
### Trigger
- All tasks have status="completed"
- No tasks with status="pending" or "in_progress"
### Steps
1. **Generate Summary**
- Count total tasks, duration
- List deliverables with artifact paths
- Generate artifact registry summary
- Calculate quality metrics (discuss verdicts, review scores)
2. **Completion Action**
- Read completion_action from team-config.json
- If "interactive":
- AskUserQuestion (see coordinator role.md Phase 5)
- Execute user choice
- If "auto_archive":
- Update session status="completed"
- TeamDelete
- Archive artifacts
- If "auto_keep":
- Update session status="paused"
- Output resume instructions
3. **Cleanup**
- Write final session state
- Log completion to message bus
- STOP
---
## Artifact Registry Operations (v3 NEW)
### Register Artifact
```javascript
// Read existing registry
const registry = JSON.parse(Read("<session>/artifact-registry.json"))
// Add new artifact
registry.artifacts[artifact_id] = {
manifest: <artifact-manifest>,
discovered_at: new Date().toISOString(),
consumed_by: []
}
// Write back
Write("<session>/artifact-registry.json", JSON.stringify(registry))
```
### Generate Context Artifacts
```javascript
// Query registry for upstream artifacts
const upstreamArtifacts = []
for (const dep of task.blockedBy) {
const depTask = TaskGet(dep)
const artifactId = findArtifactByTaskId(registry, depTask.id)
if (artifactId) {
upstreamArtifacts.push(registry.artifacts[artifactId].manifest)
}
}
// Write context-artifacts.json for worker consumption
Write("<session>/context-artifacts.json", JSON.stringify({
task_id: task.id,
upstream_artifacts: upstreamArtifacts,
generated_at: new Date().toISOString()
}))
```
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Worker timeout | Mark task failed, ask user to retry |
| Artifact validation fails | Block downstream, create fix task |
| Artifact manifest missing | Continue without validation (backward compatible) |
| Priority conflict | P0 > P1 > P2, FIFO within same priority |
| Parallel spawn fails | Log error, spawn sequentially |
| Registry corruption | Rebuild from task artifacts |
| Completion action fails | Fallback to manual cleanup |

View File

@@ -0,0 +1,270 @@
# Coordinator Role (v3 Enhanced)
Orchestrate team-lifecycle-v3: team creation, task dispatching with priority scheduling, dynamic role injection, artifact registry management, progress monitoring. Uses **team-worker agent** for all worker spawns.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Inject roles -> Create team -> Dispatch tasks -> Monitor progress -> Manage artifacts -> Report
## v3 Enhancements
| Feature | Description |
|---------|-------------|
| Dynamic Role Injection | Analyze task keywords to inject specialist roles at runtime |
| Priority Scheduling | P0/P1/P2 task prioritization with critical path optimization |
| Artifact Registry | Maintain in-memory registry for automatic artifact discovery |
| Conditional Routing | Route based on complexity assessment from PLAN-001 |
| Parallel Orchestration | Spawn multiple workers in parallel stages |
## Boundaries
### MUST
- Parse user requirements and clarify via AskUserQuestion
- Analyze task description for specialist role injection
- Create team and spawn workers using **team-worker** agent type
- Dispatch tasks with proper dependency chains and priority levels
- Monitor progress via callbacks and route messages
- Maintain artifact registry for validation gating
- Maintain session state (team-session.json)
### MUST NOT
- Execute spec/impl/research work directly
- Modify task outputs
- Skip dependency validation
- Skip artifact validation gating
---
## Entry Router
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag | -> handleCallback |
| Status check | "check" or "status" | -> handleCheck |
| Manual resume | "resume" or "continue" | -> handleResume |
| Interrupted session | Active/paused session in `.workflow/.team/TLS-*` | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume: load `commands/monitor.md`, execute handler, STOP.
---
## Phase 0: Session Resume Check
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused
2. No sessions -> Phase 1
3. Single session -> resume (reconciliation)
4. Multiple -> AskUserQuestion
**Session Reconciliation**:
1. Audit TaskList, reconcile with session state
2. Reset in_progress -> pending (interrupted tasks)
3. Rebuild team if disbanded
4. Restore artifact registry from session
5. Create missing tasks with correct blockedBy
6. Kick first executable -> Phase 4
---
## Phase 1: Requirement Clarification
1. Parse arguments for mode, scope, focus
2. Ask missing parameters via AskUserQuestion:
- Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe
- Scope: project description
3. Frontend auto-detection (keyword + package.json scanning)
4. **v3 NEW**: Keyword analysis for specialist role injection
5. Store requirements
### Keyword Analysis (v3 NEW)
Scan task description for specialist role triggers:
| Keywords | Injected Role | Injection Point |
|----------|---------------|-----------------|
| security, vulnerability, OWASP, audit | security-expert | After PLAN-001 |
| performance, optimization, bottleneck, latency | performance-optimizer | After IMPL-* |
| data, pipeline, ETL, schema, migration | data-engineer | Parallel with IMPL-* |
| devops, CI/CD, deployment, docker, kubernetes | devops-engineer | After IMPL-* |
| ML, model, training, inference, neural | ml-engineer | Parallel with IMPL-* |
| orchestrate, complex, multi-module | orchestrator | Replace IMPL-* with ORCH-* |
---
## Phase 2: Create Team + Initialize Session
1. Generate session ID: `TLS-<slug>-<date>`
2. Create session folder: `.workflow/.team/<session-id>/`
3. **v3 NEW**: Create artifact registry: `<session-id>/artifact-registry.json`
4. TeamCreate
5. Initialize directories (spec/, discussions/, plan/, explorations/, artifacts/)
6. Write team-session.json with injected roles
7. Initialize meta.json via team_msg state_update:
```
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<mode>",
pipeline_stages: [<role-list>],
roles: [<all-roles>],
injected_roles: [<specialist-roles>],
team_name: "lifecycle-v3",
artifact_registry_enabled: true,
priority_scheduling_enabled: true
}
})
```
---
## Phase 3: Create Task Chain
Delegate to `commands/dispatch.md`:
1. Read Task Metadata Registry for task definitions
2. **v3 NEW**: Assess complexity from requirements (Low/Medium/High)
3. **v3 NEW**: Apply conditional routing based on complexity
4. **v3 NEW**: Inject specialist role tasks based on keywords
5. Create tasks via TaskCreate with correct blockedBy and priority
6. Include `Session: <session-folder>` in every task
7. Mark discuss rounds (DISCUSS-001, DISCUSS-002, DISCUSS-003) or "self-validate"
### Complexity Assessment (v3 NEW)
| Complexity | Indicators | Route |
|------------|-----------|-------|
| Low | 1-2 modules, shallow deps, single tech stack | Direct IMPL-001 |
| Medium | 3-4 modules, moderate deps, 2 tech stacks | ORCH-001 -> parallel IMPL-* |
| High | 5+ modules, deep deps, multiple tech stacks | ARCH-001 -> ORCH-001 -> parallel IMPL-* |
### Priority Assignment (v3 NEW)
| Task Type | Priority | Rationale |
|-----------|----------|-----------|
| Spec pipeline | P0 | Blocking all downstream |
| PLAN-001, ARCH-001 | P0 | Critical path |
| ORCH-001, parallel IMPL-* | P0 | Critical path |
| TEST-*, QA-* | P1 | Validation phase |
| REVIEW-*, specialist analysis | P1 | Quality gate |
| IMPROVE-*, optimization | P2 | Enhancement |
---
## Phase 4: Spawn-and-Stop
1. Load `commands/monitor.md`
2. Find ready tasks (pending + blockedBy resolved)
3. **v3 NEW**: Sort by priority (P0 > P1 > P2), FIFO within same priority
4. **v3 NEW**: Identify parallel groups (same stage, no mutual blockedBy)
5. Spawn team-worker for each ready task (parallel spawn for same group)
6. Output summary with priority levels
7. STOP
### Checkpoint Gate (QUALITY-001)
When QUALITY-001 completes:
1. Read readiness-report.md
2. Parse quality gate and dimension scores
3. Output Checkpoint Template (see SKILL.md)
4. Pause for user command
### Complexity Routing Gate (PLAN-001, v3 NEW)
When PLAN-001 completes:
1. Read plan.json for complexity assessment
2. Apply conditional routing:
- Low: spawn IMPL-001 directly
- Medium: spawn ORCH-001 first
- High: spawn ARCH-001 first
3. Output routing decision
4. Continue
---
## Phase 5: Report + Completion Action
1. Count completed tasks, duration
2. List deliverables with artifact paths
3. **v3 NEW**: Generate artifact registry summary
4. Update session status -> "completed"
5. **v3 NEW**: Trigger completion action (interactive/auto-archive/auto-keep)
### Completion Action (v3 NEW)
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
| Choice | Action |
|--------|--------|
| Archive & Clean | Update session status="completed", TeamDelete, archive artifacts |
| Keep Active | Update session status="paused", output resume instructions |
| Export Results | Copy deliverables to user-specified path, then Archive & Clean |
---
## Artifact Registry Management (v3 NEW)
### Registry Structure
```json
{
"artifacts": {
"<artifact-id>": {
"manifest": { ... },
"discovered_at": "timestamp",
"consumed_by": ["<role-name>"]
}
}
}
```
### Registry Operations
| Operation | When | Action |
|-----------|------|--------|
| Register | Worker Phase 5 callback | Add artifact manifest to registry |
| Validate | Before spawning downstream | Check validation_status |
| Discover | Worker Phase 2 request | Generate context-artifacts.json |
| Update | Worker consumes artifact | Add to consumed_by list |
### Validation Gating
Before spawning downstream worker:
1. Read artifact manifest from registry
2. Check validation_status:
- `passed`: spawn next worker
- `failed`: block spawn, trigger fix loop
- `pending`: wait or prompt manual validation
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report, halt |
| Invalid mode | Reject, ask to clarify |
| Session corruption | Attempt recovery |
| Artifact validation fails | Block downstream, create fix task |
| Role injection fails | Log warning, continue with core roles |
| Priority conflict | P0 > P1 > P2, FIFO within same priority |
| Parallel merge timeout | Report stall, prompt user intervention |

View File

@@ -0,0 +1,101 @@
# Artifact Contract Specification
## Overview
Every worker role must generate an artifact manifest in Phase 4 to enable quality gating and automatic artifact discovery.
## Manifest Schema
**Location**: `<session>/artifacts/<task-id>/artifact-manifest.json`
```json
{
"artifact_id": "uuid-...",
"creator_role": "role-name",
"artifact_type": "spec | architecture | plan | code | test | review",
"version": "1.0.0",
"path": "./artifacts/output.md",
"dependencies": ["upstream-artifact-id"],
"validation_status": "pending | passed | failed",
"validation_summary": "Details...",
"metadata": {
"complexity": "low | medium | high",
"priority": "P0 | P1 | P2"
}
}
```
## Field Definitions
| Field | Type | Description |
|-------|------|-------------|
| artifact_id | string | UUID for this artifact |
| creator_role | string | Role that created this artifact |
| artifact_type | enum | Type of artifact (spec/architecture/plan/code/test/review) |
| version | string | Semantic version |
| path | string | Relative path to artifact file |
| dependencies | array | List of upstream artifact IDs this depends on |
| validation_status | enum | pending/passed/failed |
| validation_summary | string | Human-readable validation result |
| metadata | object | Additional context (complexity, priority, etc.) |
## Validation Status
- **pending**: Artifact created, validation not yet run
- **passed**: All quality checks passed, ready for downstream consumption
- **failed**: Quality issues detected, blocks downstream spawn
## Coordinator Integration
The coordinator checks manifests in `handleCallback`:
1. Read `<session>/artifacts/<task-id>/artifact-manifest.json`
2. If `validation_status == "passed"`:
- Register to artifact_registry
- Spawn next dependent task
3. If `validation_status == "failed"`:
- Create fix task
- Notify user
- Block downstream tasks
## Context Artifacts Discovery
Workers read `context-artifacts.json` to discover upstream artifacts:
```json
{
"artifacts": [
{
"artifact_id": "uuid-...",
"artifact_type": "spec",
"path": "./spec/discovery-context.json",
"creator_role": "analyst"
}
]
}
```
## Auto-Discovery (v5)
In v5, workers declare `input_artifact_types: []` in frontmatter. The coordinator automatically discovers and provides matching artifacts without manual path configuration.
## Quality Gates
Validation checks vary by artifact type:
| Artifact Type | Required Checks |
|---------------|----------------|
| spec | Completeness, schema compliance |
| architecture | ADR presence, component diagram |
| plan | Task count (2-7), dependency graph validity |
| code | Syntax check, test coverage |
| test | Test count > 0, all passing |
| review | Issue count, severity distribution |
## Example Workflow
1. **Analyst** creates spec → manifest with `validation_status: "passed"`
2. **Coordinator** reads manifest → registers to artifact_registry
3. **Writer** spawned → reads `context-artifacts.json` → finds analyst's spec
4. **Writer** creates document → manifest with `validation_status: "passed"`
5. **Coordinator** spawns next role based on dependency graph

View File

@@ -0,0 +1,192 @@
# Document Standards
Defines format conventions, YAML frontmatter schema, naming rules, and content structure for all spec-generator outputs.
## When to Use
| Phase | Usage | Section |
|-------|-------|---------|
| All Phases | Frontmatter format | YAML Frontmatter Schema |
| All Phases | File naming | Naming Conventions |
| Phase 2-5 | Document structure | Content Structure |
| Phase 6 | Validation reference | All sections |
---
## YAML Frontmatter Schema
Every generated document MUST begin with YAML frontmatter:
```yaml
---
session_id: SPEC-{slug}-{YYYY-MM-DD}
phase: {1-6}
document_type: {product-brief|requirements|architecture|epics|readiness-report|spec-summary}
status: draft|review|complete
generated_at: {ISO8601 timestamp}
stepsCompleted: []
version: 1
dependencies:
- {list of input documents used}
---
```
### Field Definitions
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `session_id` | string | Yes | Session identifier matching spec-config.json |
| `phase` | number | Yes | Phase number that generated this document (1-6) |
| `document_type` | string | Yes | One of: product-brief, requirements, architecture, epics, readiness-report, spec-summary |
| `status` | enum | Yes | draft (initial), review (user reviewed), complete (finalized) |
| `generated_at` | string | Yes | ISO8601 timestamp of generation |
| `stepsCompleted` | array | Yes | List of step IDs completed during generation |
| `version` | number | Yes | Document version, incremented on re-generation |
| `dependencies` | array | No | List of input files this document depends on |
### Status Transitions
```
draft -> review -> complete
| ^
+-------------------+ (direct promotion in auto mode)
```
- **draft**: Initial generation, not yet user-reviewed
- **review**: User has reviewed and provided feedback
- **complete**: Finalized, ready for downstream consumption
In auto mode (`-y`), documents are promoted directly from `draft` to `complete`.
---
## Naming Conventions
### Session ID Format
```
SPEC-{slug}-{YYYY-MM-DD}
```
- **slug**: Lowercase, alphanumeric + Chinese characters, hyphens as separators, max 40 chars
- **date**: UTC+8 date in YYYY-MM-DD format
Examples:
- `SPEC-task-management-system-2026-02-11`
- `SPEC-user-auth-oauth-2026-02-11`
### Output Files
| File | Phase | Description |
|------|-------|-------------|
| `spec-config.json` | 1 | Session configuration and state |
| `discovery-context.json` | 1 | Codebase exploration results (optional) |
| `product-brief.md` | 2 | Product brief document |
| `requirements.md` | 3 | PRD document |
| `architecture.md` | 4 | Architecture decisions document |
| `epics.md` | 5 | Epic/Story breakdown document |
| `readiness-report.md` | 6 | Quality validation report |
| `spec-summary.md` | 6 | One-page executive summary |
### Output Directory
```
.workflow/.spec/{session-id}/
```
---
## Content Structure
### Heading Hierarchy
- `#` (H1): Document title only (one per document)
- `##` (H2): Major sections
- `###` (H3): Subsections
- `####` (H4): Detail items (use sparingly)
Maximum depth: 4 levels. Prefer flat structures.
### Section Ordering
Every document follows this general pattern:
1. **YAML Frontmatter** (mandatory)
2. **Title** (H1)
3. **Executive Summary** (2-3 sentences)
4. **Core Content Sections** (H2, document-specific)
5. **Open Questions / Risks** (if applicable)
6. **References / Traceability** (links to upstream/downstream docs)
### Formatting Rules
| Element | Format | Example |
|---------|--------|---------|
| Requirements | `REQ-{NNN}` prefix | REQ-001: User login |
| Acceptance criteria | Checkbox list | `- [ ] User can log in with email` |
| Architecture decisions | `ADR-{NNN}` prefix | ADR-001: Use PostgreSQL |
| Epics | `EPIC-{NNN}` prefix | EPIC-001: Authentication |
| Stories | `STORY-{EPIC}-{NNN}` prefix | STORY-001-001: Login form |
| Priority tags | MoSCoW labels | `[Must]`, `[Should]`, `[Could]`, `[Won't]` |
| Mermaid diagrams | Fenced code blocks | ````mermaid ... ``` `` |
| Code examples | Language-tagged blocks | ````typescript ... ``` `` |
### Cross-Reference Format
Use relative references between documents:
```markdown
See [Product Brief](product-brief.md#section-name) for details.
Derived from [REQ-001](requirements.md#req-001).
```
### Language
- Document body: Follow user's input language (Chinese or English)
- Technical identifiers: Always English (REQ-001, ADR-001, EPIC-001)
- YAML frontmatter keys: Always English
---
## spec-config.json Schema
```json
{
"session_id": "string (required)",
"seed_input": "string (required) - original user input",
"input_type": "text|file (required)",
"timestamp": "ISO8601 (required)",
"mode": "interactive|auto (required)",
"complexity": "simple|moderate|complex (required)",
"depth": "light|standard|comprehensive (required)",
"focus_areas": ["string array"],
"seed_analysis": {
"problem_statement": "string",
"target_users": ["string array"],
"domain": "string",
"constraints": ["string array"],
"dimensions": ["string array - 3-5 exploration dimensions"]
},
"has_codebase": "boolean",
"phasesCompleted": [
{
"phase": "number (1-6)",
"name": "string (phase name)",
"output_file": "string (primary output file)",
"completed_at": "ISO8601"
}
]
}
```
---
## Validation Checklist
- [ ] Every document starts with valid YAML frontmatter
- [ ] `session_id` matches across all documents in a session
- [ ] `status` field reflects current document state
- [ ] All cross-references resolve to valid targets
- [ ] Heading hierarchy is correct (no skipped levels)
- [ ] Technical identifiers use correct prefixes
- [ ] Output files are in the correct directory

View File

@@ -0,0 +1,207 @@
# Quality Gates
Per-phase quality gate criteria and scoring dimensions for spec-generator outputs.
## When to Use
| Phase | Usage | Section |
|-------|-------|---------|
| Phase 2-5 | Post-generation self-check | Per-Phase Gates |
| Phase 6 | Cross-document validation | Cross-Document Validation |
| Phase 6 | Final scoring | Scoring Dimensions |
---
## Quality Thresholds
| Gate | Score | Action |
|------|-------|--------|
| **Pass** | >= 80% | Continue to next phase |
| **Review** | 60-79% | Log warnings, continue with caveats |
| **Fail** | < 60% | Must address issues before continuing |
In auto mode (`-y`), Review-level issues are logged but do not block progress.
---
## Scoring Dimensions
### 1. Completeness (25%)
All required sections present with substantive content.
| Score | Criteria |
|-------|----------|
| 100% | All template sections filled with detailed content |
| 75% | All sections present, some lack detail |
| 50% | Major sections present but minor sections missing |
| 25% | Multiple major sections missing or empty |
| 0% | Document is a skeleton only |
### 2. Consistency (25%)
Terminology, formatting, and references are uniform across documents.
| Score | Criteria |
|-------|----------|
| 100% | All terms consistent, all references valid, formatting uniform |
| 75% | Minor terminology variations, all references valid |
| 50% | Some inconsistent terms, 1-2 broken references |
| 25% | Frequent inconsistencies, multiple broken references |
| 0% | Documents contradict each other |
### 3. Traceability (25%)
Requirements, architecture decisions, and stories trace back to goals.
| Score | Criteria |
|-------|----------|
| 100% | Every story traces to a requirement, every requirement traces to a goal |
| 75% | Most items traceable, few orphans |
| 50% | Partial traceability, some disconnected items |
| 25% | Weak traceability, many orphan items |
| 0% | No traceability between documents |
### 4. Depth (25%)
Content provides sufficient detail for execution teams.
| Score | Criteria |
|-------|----------|
| 100% | Acceptance criteria specific and testable, architecture decisions justified, stories estimable |
| 75% | Most items detailed enough, few vague areas |
| 50% | Mix of detailed and vague content |
| 25% | Mostly high-level, lacking actionable detail |
| 0% | Too abstract for execution |
---
## Per-Phase Quality Gates
### Phase 1: Discovery
| Check | Criteria | Severity |
|-------|----------|----------|
| Session ID valid | Matches `SPEC-{slug}-{date}` format | Error |
| Problem statement exists | Non-empty, >= 20 characters | Error |
| Target users identified | >= 1 user group | Error |
| Dimensions generated | 3-5 exploration dimensions | Warning |
| Constraints listed | >= 0 (can be empty with justification) | Info |
### Phase 2: Product Brief
| Check | Criteria | Severity |
|-------|----------|----------|
| Vision statement | Clear, 1-3 sentences | Error |
| Problem statement | Specific and measurable | Error |
| Target users | >= 1 persona with needs described | Error |
| Goals defined | >= 2 measurable goals | Error |
| Success metrics | >= 2 quantifiable metrics | Warning |
| Scope boundaries | In-scope and out-of-scope listed | Warning |
| Multi-perspective | >= 2 CLI perspectives synthesized | Info |
### Phase 3: Requirements (PRD)
| Check | Criteria | Severity |
|-------|----------|----------|
| Functional requirements | >= 3 with REQ-NNN IDs | Error |
| Acceptance criteria | Every requirement has >= 1 criterion | Error |
| MoSCoW priority | Every requirement tagged | Error |
| Non-functional requirements | >= 1 (performance, security, etc.) | Warning |
| User stories | >= 1 per Must-have requirement | Warning |
| Traceability | Requirements trace to product brief goals | Warning |
### Phase 4: Architecture
| Check | Criteria | Severity |
|-------|----------|----------|
| Component diagram | Present (Mermaid or ASCII) | Error |
| Tech stack specified | Languages, frameworks, key libraries | Error |
| ADR present | >= 1 Architecture Decision Record | Error |
| ADR has alternatives | Each ADR lists >= 2 options considered | Warning |
| Integration points | External systems/APIs identified | Warning |
| Data model | Key entities and relationships described | Warning |
| Codebase mapping | Mapped to existing code (if has_codebase) | Info |
### Phase 5: Epics & Stories
| Check | Criteria | Severity |
|-------|----------|----------|
| Epics defined | 3-7 epics with EPIC-NNN IDs | Error |
| MVP subset | >= 1 epic tagged as MVP | Error |
| Stories per epic | 2-5 stories per epic | Error |
| Story format | "As a...I want...So that..." pattern | Warning |
| Dependency map | Cross-epic dependencies documented | Warning |
| Estimation hints | Relative sizing (S/M/L/XL) per story | Info |
| Traceability | Stories trace to requirements | Warning |
### Phase 6: Readiness Check
| Check | Criteria | Severity |
|-------|----------|----------|
| All documents exist | product-brief, requirements, architecture, epics | Error |
| Frontmatter valid | All YAML frontmatter parseable and correct | Error |
| Cross-references valid | All document links resolve | Error |
| Overall score >= 60% | Weighted average across 4 dimensions | Error |
| No unresolved Errors | All Error-severity issues addressed | Error |
| Summary generated | spec-summary.md created | Warning |
---
## Cross-Document Validation
Checks performed during Phase 6 across all documents:
### Completeness Matrix
```
Product Brief goals -> Requirements (each goal has >= 1 requirement)
Requirements -> Architecture (each Must requirement has design coverage)
Requirements -> Epics (each Must requirement appears in >= 1 story)
Architecture ADRs -> Epics (tech choices reflected in implementation stories)
```
### Consistency Checks
| Check | Documents | Rule |
|-------|-----------|------|
| Terminology | All | Same term used consistently (no synonyms for same concept) |
| User personas | Brief + PRD + Epics | Same user names/roles throughout |
| Scope | Brief + PRD | PRD scope does not exceed brief scope |
| Tech stack | Architecture + Epics | Stories reference correct technologies |
### Traceability Matrix Format
```markdown
| Goal | Requirements | Architecture | Epics |
|------|-------------|--------------|-------|
| G-001: ... | REQ-001, REQ-002 | ADR-001 | EPIC-001 |
| G-002: ... | REQ-003 | ADR-002 | EPIC-002, EPIC-003 |
```
---
## Issue Classification
### Error (Must Fix)
- Missing required document or section
- Broken cross-references
- Contradictory information between documents
- Empty acceptance criteria on Must-have requirements
- No MVP subset defined in epics
### Warning (Should Fix)
- Vague acceptance criteria
- Missing non-functional requirements
- No success metrics defined
- Incomplete traceability
- Missing architecture review notes
### Info (Nice to Have)
- Could add more detailed personas
- Consider additional ADR alternatives
- Story estimation hints missing
- Mermaid diagrams could be more detailed

View File

@@ -0,0 +1,65 @@
# Role Library - Team Lifecycle v3
Dynamic role specification library for team-lifecycle-v3. Role definitions are loaded at runtime to extend the built-in role detection table.
## Purpose
- Extend role inference beyond hardcoded defaults
- Support domain-specific specialist roles
- Enable dynamic role injection based on task keywords
- Maintain backward compatibility with v2 core roles
## Role Categories
### Core Pipeline Roles (v2 inherited)
- analyst, writer, planner, executor, tester, reviewer
- architect, fe-developer, fe-qa
### Specialist Roles (v3 new)
- **orchestrator**: Complex task decomposition and parallel coordination
- **security-expert**: Security analysis and vulnerability scanning
- **performance-optimizer**: Performance profiling and optimization
- **data-engineer**: Data pipeline and schema design
- **devops-engineer**: Infrastructure as code and CI/CD
- **ml-engineer**: Machine learning pipeline implementation
## Dynamic Role Injection
Specialist roles are injected at runtime when coordinator detects matching keywords in task descriptions:
| Keywords | Injected Role |
|----------|---------------|
| security, vulnerability, OWASP | security-expert |
| performance, optimization, bottleneck | performance-optimizer |
| data, pipeline, ETL, schema | data-engineer |
| devops, CI/CD, deployment, docker | devops-engineer |
| machine learning, ML, model, training | ml-engineer |
| orchestrate, complex, multi-module | orchestrator |
## Role Definition Format
Each role definition is a `.role.md` file with YAML frontmatter + description.
### Schema
```yaml
---
role: <role-name>
keywords: [<keyword1>, <keyword2>, ...]
responsibility_type: <Orchestration|Code generation|Validation|Read-only analysis>
task_prefix: <PREFIX>
default_inner_loop: <true|false>
category: <domain-category>
capabilities: [<capability1>, <capability2>, ...]
---
<Role description and responsibilities>
```
## Usage
Role library is loaded by coordinator during Phase 1 (Requirements Collection) to extend role detection capabilities. Custom roles override built-in roles with same `role` identifier.
## Extensibility
Users can add custom role definitions by creating new `.role.md` files in this directory following the schema above.

View File

@@ -0,0 +1,37 @@
---
role: data-engineer
keywords: [data, pipeline, ETL, database, schema, migration, analytics]
responsibility_type: Code generation
task_prefix: DATA
default_inner_loop: false
category: data
capabilities:
- data_pipeline_design
- schema_design
- etl_implementation
---
# Data Engineer
Designs and implements data pipelines, schemas, and ETL processes.
## Responsibilities
- Design database schemas and data models
- Implement ETL pipelines for data processing
- Create data migration scripts
- Optimize data storage and retrieval
- Implement data validation and quality checks
## Typical Tasks
- Design and implement data warehouse schema
- Build ETL pipeline for analytics
- Create database migration scripts
- Implement data validation framework
## Integration Points
- Called by coordinator when data keywords detected
- Works with executor for backend integration
- Coordinates with planner for data architecture

View File

@@ -0,0 +1,37 @@
---
role: devops-engineer
keywords: [devops, CI/CD, deployment, infrastructure, docker, kubernetes, terraform]
responsibility_type: Code generation
task_prefix: DEVOPS
default_inner_loop: false
category: devops
capabilities:
- infrastructure_as_code
- ci_cd_pipeline
- deployment_automation
---
# DevOps Engineer
Implements infrastructure as code, CI/CD pipelines, and deployment automation.
## Responsibilities
- Design and implement CI/CD pipelines
- Create infrastructure as code (Terraform, CloudFormation)
- Implement deployment automation
- Configure monitoring and alerting
- Manage containerization and orchestration
## Typical Tasks
- Set up CI/CD pipeline for new project
- Implement infrastructure as code for cloud resources
- Create Docker containerization strategy
- Configure Kubernetes deployment
## Integration Points
- Called by coordinator when devops keywords detected
- Works with executor for deployment integration
- Coordinates with planner for infrastructure architecture

View File

@@ -0,0 +1,37 @@
---
role: ml-engineer
keywords: [machine learning, ML, model, training, inference, neural network, AI]
responsibility_type: Code generation
task_prefix: ML
default_inner_loop: false
category: machine-learning
capabilities:
- model_training
- feature_engineering
- model_deployment
---
# ML Engineer
Implements machine learning pipelines, model training, and inference systems.
## Responsibilities
- Design and implement ML training pipelines
- Perform feature engineering and data preprocessing
- Train and evaluate ML models
- Implement model serving and inference
- Monitor model performance and drift
## Typical Tasks
- Build ML training pipeline
- Implement feature engineering pipeline
- Deploy model serving infrastructure
- Create model monitoring system
## Integration Points
- Called by coordinator when ML keywords detected
- Works with data-engineer for data pipeline integration
- Coordinates with planner for ML architecture

View File

@@ -0,0 +1,39 @@
---
role: orchestrator
keywords: [orchestrate, coordinate, complex, multi-module, decompose, parallel, dependency]
responsibility_type: Orchestration
task_prefix: ORCH
default_inner_loop: false
category: orchestration
weight: 1.5
capabilities:
- task_decomposition
- parallel_coordination
- dependency_management
---
# Orchestrator
Decomposes complex multi-module tasks into coordinated sub-tasks with dependency management and parallel execution support.
## Responsibilities
- Analyze complex requirements and decompose into manageable sub-tasks
- Coordinate parallel execution of multiple implementation tracks
- Manage dependencies between sub-tasks
- Integrate results from parallel workers
- Validate integration points and cross-module consistency
## Typical Tasks
- Break down large features into frontend + backend + data components
- Coordinate multi-team parallel development
- Manage complex refactoring across multiple modules
- Orchestrate migration strategies with phased rollout
## Integration Points
- Works with planner to receive high-level plans
- Spawns multiple executor/fe-developer workers in parallel
- Integrates with tester for cross-module validation
- Reports to coordinator with integration status

View File

@@ -0,0 +1,37 @@
---
role: performance-optimizer
keywords: [performance, optimization, bottleneck, latency, throughput, profiling, benchmark]
responsibility_type: Read-only analysis
task_prefix: PERF
default_inner_loop: false
category: performance
capabilities:
- performance_profiling
- bottleneck_identification
- optimization_recommendations
---
# Performance Optimizer
Analyzes code and architecture for performance bottlenecks and provides optimization recommendations.
## Responsibilities
- Profile code execution and identify bottlenecks
- Analyze database query performance
- Review caching strategies and effectiveness
- Assess resource utilization (CPU, memory, I/O)
- Recommend optimization strategies
## Typical Tasks
- Performance audit of critical paths
- Database query optimization review
- Caching strategy assessment
- Load testing analysis and recommendations
## Integration Points
- Called by coordinator when performance keywords detected
- Works with reviewer for performance-focused code review
- Reports findings with impact levels and optimization priorities

View File

@@ -0,0 +1,37 @@
---
role: security-expert
keywords: [security, vulnerability, OWASP, compliance, audit, penetration, threat]
responsibility_type: Read-only analysis
task_prefix: SECURITY
default_inner_loop: false
category: security
capabilities:
- vulnerability_scanning
- threat_modeling
- compliance_checking
---
# Security Expert
Performs security analysis, vulnerability scanning, and compliance checking for code and architecture.
## Responsibilities
- Scan code for OWASP Top 10 vulnerabilities
- Perform threat modeling and attack surface analysis
- Check compliance with security standards (GDPR, HIPAA, etc.)
- Review authentication and authorization implementations
- Assess data protection and encryption strategies
## Typical Tasks
- Security audit of authentication module
- Vulnerability assessment of API endpoints
- Compliance review for data handling
- Threat modeling for new features
## Integration Points
- Called by coordinator when security keywords detected
- Works with reviewer for security-focused code review
- Reports findings with severity levels (Critical/High/Medium/Low)

View File

@@ -0,0 +1,254 @@
# Architecture Document Template (Directory Structure)
Template for generating architecture decision documents as a directory of individual ADR files in Phase 4.
## Usage Context
| Phase | Usage |
|-------|-------|
| Phase 4 (Architecture) | Generate `architecture/` directory from requirements analysis |
| Output Location | `{workDir}/architecture/` |
## Output Structure
```
{workDir}/architecture/
├── _index.md # Overview, components, tech stack, data model, security
├── ADR-001-{slug}.md # Individual Architecture Decision Record
├── ADR-002-{slug}.md
└── ...
```
---
## Template: _index.md
```markdown
---
session_id: {session_id}
phase: 4
document_type: architecture-index
status: draft
generated_at: {timestamp}
version: 1
dependencies:
- ../spec-config.json
- ../product-brief.md
- ../requirements/_index.md
---
# Architecture: {product_name}
{executive_summary - high-level architecture approach and key decisions}
## System Overview
### Architecture Style
{description of chosen architecture style: microservices, monolith, serverless, etc.}
### System Context Diagram
```mermaid
C4Context
title System Context Diagram
Person(user, "User", "Primary user")
System(system, "{product_name}", "Core system")
System_Ext(ext1, "{external_system}", "{description}")
Rel(user, system, "Uses")
Rel(system, ext1, "Integrates with")
```
## Component Architecture
### Component Diagram
```mermaid
graph TD
subgraph "{product_name}"
A[Component A] --> B[Component B]
B --> C[Component C]
A --> D[Component D]
end
B --> E[External Service]
```
### Component Descriptions
| Component | Responsibility | Technology | Dependencies |
|-----------|---------------|------------|--------------|
| {component_name} | {what it does} | {tech stack} | {depends on} |
## Technology Stack
### Core Technologies
| Layer | Technology | Version | Rationale |
|-------|-----------|---------|-----------|
| Frontend | {technology} | {version} | {why chosen} |
| Backend | {technology} | {version} | {why chosen} |
| Database | {technology} | {version} | {why chosen} |
| Infrastructure | {technology} | {version} | {why chosen} |
### Key Libraries & Frameworks
| Library | Purpose | License |
|---------|---------|---------|
| {library_name} | {purpose} | {license} |
## Architecture Decision Records
| ADR | Title | Status | Key Choice |
|-----|-------|--------|------------|
| [ADR-001](ADR-001-{slug}.md) | {title} | Accepted | {one-line summary} |
| [ADR-002](ADR-002-{slug}.md) | {title} | Accepted | {one-line summary} |
| [ADR-003](ADR-003-{slug}.md) | {title} | Proposed | {one-line summary} |
## Data Architecture
### Data Model
```mermaid
erDiagram
ENTITY_A ||--o{ ENTITY_B : "has many"
ENTITY_A {
string id PK
string name
datetime created_at
}
ENTITY_B {
string id PK
string entity_a_id FK
string value
}
```
### Data Storage Strategy
| Data Type | Storage | Retention | Backup |
|-----------|---------|-----------|--------|
| {type} | {storage solution} | {retention policy} | {backup strategy} |
## API Design
### API Overview
| Endpoint | Method | Purpose | Auth |
|----------|--------|---------|------|
| {/api/resource} | {GET/POST/etc} | {purpose} | {auth type} |
## Security Architecture
### Security Controls
| Control | Implementation | Requirement |
|---------|---------------|-------------|
| Authentication | {approach} | [NFR-S-{NNN}](../requirements/NFR-S-{NNN}-{slug}.md) |
| Authorization | {approach} | [NFR-S-{NNN}](../requirements/NFR-S-{NNN}-{slug}.md) |
| Data Protection | {approach} | [NFR-S-{NNN}](../requirements/NFR-S-{NNN}-{slug}.md) |
## Infrastructure & Deployment
### Deployment Architecture
{description of deployment model: containers, serverless, VMs, etc.}
### Environment Strategy
| Environment | Purpose | Configuration |
|-------------|---------|---------------|
| Development | Local development | {config} |
| Staging | Pre-production testing | {config} |
| Production | Live system | {config} |
## Codebase Integration
{if has_codebase is true:}
### Existing Code Mapping
| New Component | Existing Module | Integration Type | Notes |
|--------------|----------------|------------------|-------|
| {component} | {existing module path} | Extend/Replace/New | {notes} |
### Migration Notes
{any migration considerations for existing code}
## Quality Attributes
| Attribute | Target | Measurement | ADR Reference |
|-----------|--------|-------------|---------------|
| Performance | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
| Scalability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
| Reliability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
## Risks & Mitigations
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| {risk} | High/Medium/Low | High/Medium/Low | {mitigation approach} |
## Open Questions
- [ ] {architectural question 1}
- [ ] {architectural question 2}
## References
- Derived from: [Requirements](../requirements/_index.md), [Product Brief](../product-brief.md)
- Next: [Epics & Stories](../epics/_index.md)
```
---
## Template: ADR-NNN-{slug}.md (Individual Architecture Decision Record)
```markdown
---
id: ADR-{NNN}
status: Accepted
traces_to: [{REQ-NNN}, {NFR-X-NNN}]
date: {timestamp}
---
# ADR-{NNN}: {decision_title}
## Context
{what is the situation that motivates this decision}
## Decision
{what is the chosen approach}
## Alternatives Considered
| Option | Pros | Cons |
|--------|------|------|
| {option_1 - chosen} | {pros} | {cons} |
| {option_2} | {pros} | {cons} |
| {option_3} | {pros} | {cons} |
## Consequences
- **Positive**: {positive outcomes}
- **Negative**: {tradeoffs accepted}
- **Risks**: {risks to monitor}
## Traces
- **Requirements**: [REQ-{NNN}](../requirements/REQ-{NNN}-{slug}.md), [NFR-X-{NNN}](../requirements/NFR-X-{NNN}-{slug}.md)
- **Implemented by**: [EPIC-{NNN}](../epics/EPIC-{NNN}-{slug}.md) (added in Phase 5)
```
---
## Variable Descriptions
| Variable | Source | Description |
|----------|--------|-------------|
| `{session_id}` | spec-config.json | Session identifier |
| `{timestamp}` | Runtime | ISO8601 generation timestamp |
| `{product_name}` | product-brief.md | Product/feature name |
| `{NNN}` | Auto-increment | ADR/requirement number |
| `{slug}` | Auto-generated | Kebab-case from decision title |
| `{has_codebase}` | spec-config.json | Whether existing codebase exists |

View File

@@ -0,0 +1,196 @@
# Epics & Stories Template (Directory Structure)
Template for generating epic/story breakdown as a directory of individual Epic files in Phase 5.
## Usage Context
| Phase | Usage |
|-------|-------|
| Phase 5 (Epics & Stories) | Generate `epics/` directory from requirements decomposition |
| Output Location | `{workDir}/epics/` |
## Output Structure
```
{workDir}/epics/
├── _index.md # Overview table + dependency map + MVP scope + execution order
├── EPIC-001-{slug}.md # Individual Epic with its Stories
├── EPIC-002-{slug}.md
└── ...
```
---
## Template: _index.md
```markdown
---
session_id: {session_id}
phase: 5
document_type: epics-index
status: draft
generated_at: {timestamp}
version: 1
dependencies:
- ../spec-config.json
- ../product-brief.md
- ../requirements/_index.md
- ../architecture/_index.md
---
# Epics & Stories: {product_name}
{executive_summary - overview of epic structure and MVP scope}
## Epic Overview
| Epic ID | Title | Priority | MVP | Stories | Est. Size |
|---------|-------|----------|-----|---------|-----------|
| [EPIC-001](EPIC-001-{slug}.md) | {title} | Must | Yes | {n} | {S/M/L/XL} |
| [EPIC-002](EPIC-002-{slug}.md) | {title} | Must | Yes | {n} | {S/M/L/XL} |
| [EPIC-003](EPIC-003-{slug}.md) | {title} | Should | No | {n} | {S/M/L/XL} |
## Dependency Map
```mermaid
graph LR
EPIC-001 --> EPIC-002
EPIC-001 --> EPIC-003
EPIC-002 --> EPIC-004
EPIC-003 --> EPIC-005
```
### Dependency Notes
{explanation of why these dependencies exist and suggested execution order}
### Recommended Execution Order
1. [EPIC-{NNN}](EPIC-{NNN}-{slug}.md): {reason - foundational}
2. [EPIC-{NNN}](EPIC-{NNN}-{slug}.md): {reason - depends on #1}
3. ...
## MVP Scope
### MVP Epics
{list of epics included in MVP with justification, linking to each}
### MVP Definition of Done
- [ ] {MVP completion criterion 1}
- [ ] {MVP completion criterion 2}
- [ ] {MVP completion criterion 3}
## Traceability Matrix
| Requirement | Epic | Stories | Architecture |
|-------------|------|---------|--------------|
| [REQ-001](../requirements/REQ-001-{slug}.md) | [EPIC-001](EPIC-001-{slug}.md) | STORY-001-001, STORY-001-002 | [ADR-001](../architecture/ADR-001-{slug}.md) |
| [REQ-002](../requirements/REQ-002-{slug}.md) | [EPIC-001](EPIC-001-{slug}.md) | STORY-001-003 | Component B |
| [REQ-003](../requirements/REQ-003-{slug}.md) | [EPIC-002](EPIC-002-{slug}.md) | STORY-002-001 | [ADR-002](../architecture/ADR-002-{slug}.md) |
## Estimation Summary
| Size | Meaning | Count |
|------|---------|-------|
| S | Small - well-understood, minimal risk | {n} |
| M | Medium - some complexity, moderate risk | {n} |
| L | Large - significant complexity, should consider splitting | {n} |
| XL | Extra Large - high complexity, must split before implementation | {n} |
## Risks & Considerations
| Risk | Affected Epics | Mitigation |
|------|---------------|------------|
| {risk description} | [EPIC-{NNN}](EPIC-{NNN}-{slug}.md) | {mitigation} |
## Open Questions
- [ ] {question about scope or implementation 1}
- [ ] {question about scope or implementation 2}
## References
- Derived from: [Requirements](../requirements/_index.md), [Architecture](../architecture/_index.md)
- Handoff to: execution workflows (lite-plan, plan, req-plan)
```
---
## Template: EPIC-NNN-{slug}.md (Individual Epic)
```markdown
---
id: EPIC-{NNN}
priority: {Must|Should|Could}
mvp: {true|false}
size: {S|M|L|XL}
requirements: [REQ-{NNN}]
architecture: [ADR-{NNN}]
dependencies: [EPIC-{NNN}]
status: draft
---
# EPIC-{NNN}: {epic_title}
**Priority**: {Must|Should|Could}
**MVP**: {Yes|No}
**Estimated Size**: {S|M|L|XL}
## Description
{detailed epic description}
## Requirements
- [REQ-{NNN}](../requirements/REQ-{NNN}-{slug}.md): {title}
- [REQ-{NNN}](../requirements/REQ-{NNN}-{slug}.md): {title}
## Architecture
- [ADR-{NNN}](../architecture/ADR-{NNN}-{slug}.md): {title}
- Component: {component_name}
## Dependencies
- [EPIC-{NNN}](EPIC-{NNN}-{slug}.md) (blocking): {reason}
- [EPIC-{NNN}](EPIC-{NNN}-{slug}.md) (soft): {reason}
## Stories
### STORY-{EPIC}-001: {story_title}
**User Story**: As a {persona}, I want to {action} so that {benefit}.
**Acceptance Criteria**:
- [ ] {criterion 1}
- [ ] {criterion 2}
- [ ] {criterion 3}
**Size**: {S|M|L|XL}
**Traces to**: [REQ-{NNN}](../requirements/REQ-{NNN}-{slug}.md)
---
### STORY-{EPIC}-002: {story_title}
**User Story**: As a {persona}, I want to {action} so that {benefit}.
**Acceptance Criteria**:
- [ ] {criterion 1}
- [ ] {criterion 2}
**Size**: {S|M|L|XL}
**Traces to**: [REQ-{NNN}](../requirements/REQ-{NNN}-{slug}.md)
```
---
## Variable Descriptions
| Variable | Source | Description |
|----------|--------|-------------|
| `{session_id}` | spec-config.json | Session identifier |
| `{timestamp}` | Runtime | ISO8601 generation timestamp |
| `{product_name}` | product-brief.md | Product/feature name |
| `{EPIC}` | Auto-increment | Epic number (3 digits) |
| `{NNN}` | Auto-increment | Story/requirement number |
| `{slug}` | Auto-generated | Kebab-case from epic/story title |
| `{S\|M\|L\|XL}` | CLI analysis | Relative size estimate |

View File

@@ -0,0 +1,133 @@
# Product Brief Template
Template for generating product brief documents in Phase 2.
## Usage Context
| Phase | Usage |
|-------|-------|
| Phase 2 (Product Brief) | Generate product-brief.md from multi-CLI analysis |
| Output Location | `{workDir}/product-brief.md` |
---
## Template
```markdown
---
session_id: {session_id}
phase: 2
document_type: product-brief
status: draft
generated_at: {timestamp}
stepsCompleted: []
version: 1
dependencies:
- spec-config.json
---
# Product Brief: {product_name}
{executive_summary - 2-3 sentences capturing the essence of the product/feature}
## Vision
{vision_statement - clear, aspirational 1-3 sentence statement of what success looks like}
## Problem Statement
### Current Situation
{description of the current state and pain points}
### Impact
{quantified impact of the problem - who is affected, how much, how often}
## Target Users
{for each user persona:}
### {Persona Name}
- **Role**: {user's role/context}
- **Needs**: {primary needs related to this product}
- **Pain Points**: {current frustrations}
- **Success Criteria**: {what success looks like for this user}
## Goals & Success Metrics
| Goal ID | Goal | Success Metric | Target |
|---------|------|----------------|--------|
| G-001 | {goal description} | {measurable metric} | {specific target} |
| G-002 | {goal description} | {measurable metric} | {specific target} |
## Scope
### In Scope
- {feature/capability 1}
- {feature/capability 2}
- {feature/capability 3}
### Out of Scope
- {explicitly excluded item 1}
- {explicitly excluded item 2}
### Assumptions
- {key assumption 1}
- {key assumption 2}
## Competitive Landscape
| Aspect | Current State | Proposed Solution | Advantage |
|--------|--------------|-------------------|-----------|
| {aspect} | {how it's done now} | {our approach} | {differentiator} |
## Constraints & Dependencies
### Technical Constraints
- {constraint 1}
- {constraint 2}
### Business Constraints
- {constraint 1}
### Dependencies
- {external dependency 1}
- {external dependency 2}
## Multi-Perspective Synthesis
### Product Perspective
{summary of product/market analysis findings}
### Technical Perspective
{summary of technical feasibility and constraints}
### User Perspective
{summary of user journey and UX considerations}
### Convergent Themes
{themes where all perspectives agree}
### Conflicting Views
{areas where perspectives differ, with notes on resolution approach}
## Open Questions
- [ ] {unresolved question 1}
- [ ] {unresolved question 2}
## References
- Derived from: [spec-config.json](spec-config.json)
- Next: [Requirements PRD](requirements.md)
```
## Variable Descriptions
| Variable | Source | Description |
|----------|--------|-------------|
| `{session_id}` | spec-config.json | Session identifier |
| `{timestamp}` | Runtime | ISO8601 generation timestamp |
| `{product_name}` | Seed analysis | Product/feature name |
| `{executive_summary}` | CLI synthesis | 2-3 sentence summary |
| `{vision_statement}` | CLI product perspective | Aspirational vision |
| All `{...}` fields | CLI analysis outputs | Filled from multi-perspective analysis |

View File

@@ -0,0 +1,224 @@
# Requirements PRD Template (Directory Structure)
Template for generating Product Requirements Document as a directory of individual requirement files in Phase 3.
## Usage Context
| Phase | Usage |
|-------|-------|
| Phase 3 (Requirements) | Generate `requirements/` directory from product brief expansion |
| Output Location | `{workDir}/requirements/` |
## Output Structure
```
{workDir}/requirements/
├── _index.md # Summary + MoSCoW table + traceability matrix + links
├── REQ-001-{slug}.md # Individual functional requirement
├── REQ-002-{slug}.md
├── NFR-P-001-{slug}.md # Non-functional: Performance
├── NFR-S-001-{slug}.md # Non-functional: Security
├── NFR-SC-001-{slug}.md # Non-functional: Scalability
├── NFR-U-001-{slug}.md # Non-functional: Usability
└── ...
```
---
## Template: _index.md
```markdown
---
session_id: {session_id}
phase: 3
document_type: requirements-index
status: draft
generated_at: {timestamp}
version: 1
dependencies:
- ../spec-config.json
- ../product-brief.md
---
# Requirements: {product_name}
{executive_summary - brief overview of what this PRD covers and key decisions}
## Requirement Summary
| Priority | Count | Coverage |
|----------|-------|----------|
| Must Have | {n} | {description of must-have scope} |
| Should Have | {n} | {description of should-have scope} |
| Could Have | {n} | {description of could-have scope} |
| Won't Have | {n} | {description of explicitly excluded} |
## Functional Requirements
| ID | Title | Priority | Traces To |
|----|-------|----------|-----------|
| [REQ-001](REQ-001-{slug}.md) | {title} | Must | [G-001](../product-brief.md#goals--success-metrics) |
| [REQ-002](REQ-002-{slug}.md) | {title} | Must | [G-001](../product-brief.md#goals--success-metrics) |
| [REQ-003](REQ-003-{slug}.md) | {title} | Should | [G-002](../product-brief.md#goals--success-metrics) |
## Non-Functional Requirements
### Performance
| ID | Title | Target |
|----|-------|--------|
| [NFR-P-001](NFR-P-001-{slug}.md) | {title} | {target value} |
### Security
| ID | Title | Standard |
|----|-------|----------|
| [NFR-S-001](NFR-S-001-{slug}.md) | {title} | {standard/framework} |
### Scalability
| ID | Title | Target |
|----|-------|--------|
| [NFR-SC-001](NFR-SC-001-{slug}.md) | {title} | {target value} |
### Usability
| ID | Title | Target |
|----|-------|--------|
| [NFR-U-001](NFR-U-001-{slug}.md) | {title} | {target value} |
## Data Requirements
### Data Entities
| Entity | Description | Key Attributes |
|--------|-------------|----------------|
| {entity_name} | {description} | {attr1, attr2, attr3} |
### Data Flows
{description of key data flows, optionally with Mermaid diagram}
## Integration Requirements
| System | Direction | Protocol | Data Format | Notes |
|--------|-----------|----------|-------------|-------|
| {system_name} | Inbound/Outbound/Both | {REST/gRPC/etc} | {JSON/XML/etc} | {notes} |
## Constraints & Assumptions
### Constraints
- {technical or business constraint 1}
- {technical or business constraint 2}
### Assumptions
- {assumption 1 - must be validated}
- {assumption 2 - must be validated}
## Priority Rationale
{explanation of MoSCoW prioritization decisions, especially for Should/Could boundaries}
## Traceability Matrix
| Goal | Requirements |
|------|-------------|
| G-001 | [REQ-001](REQ-001-{slug}.md), [REQ-002](REQ-002-{slug}.md), [NFR-P-001](NFR-P-001-{slug}.md) |
| G-002 | [REQ-003](REQ-003-{slug}.md), [NFR-S-001](NFR-S-001-{slug}.md) |
## Open Questions
- [ ] {unresolved question 1}
- [ ] {unresolved question 2}
## References
- Derived from: [Product Brief](../product-brief.md)
- Next: [Architecture](../architecture/_index.md)
```
---
## Template: REQ-NNN-{slug}.md (Individual Functional Requirement)
```markdown
---
id: REQ-{NNN}
type: functional
priority: {Must|Should|Could|Won't}
traces_to: [G-{NNN}]
status: draft
---
# REQ-{NNN}: {requirement_title}
**Priority**: {Must|Should|Could|Won't}
## Description
{detailed requirement description}
## User Story
As a {persona}, I want to {action} so that {benefit}.
## Acceptance Criteria
- [ ] {specific, testable criterion 1}
- [ ] {specific, testable criterion 2}
- [ ] {specific, testable criterion 3}
## Traces
- **Goal**: [G-{NNN}](../product-brief.md#goals--success-metrics)
- **Architecture**: [ADR-{NNN}](../architecture/ADR-{NNN}-{slug}.md) (if applicable)
- **Implemented by**: [EPIC-{NNN}](../epics/EPIC-{NNN}-{slug}.md) (added in Phase 5)
```
---
## Template: NFR-{type}-NNN-{slug}.md (Individual Non-Functional Requirement)
```markdown
---
id: NFR-{type}-{NNN}
type: non-functional
category: {Performance|Security|Scalability|Usability}
priority: {Must|Should|Could}
status: draft
---
# NFR-{type}-{NNN}: {requirement_title}
**Category**: {Performance|Security|Scalability|Usability}
**Priority**: {Must|Should|Could}
## Requirement
{detailed requirement description}
## Metric & Target
| Metric | Target | Measurement Method |
|--------|--------|--------------------|
| {metric} | {target value} | {how measured} |
## Traces
- **Goal**: [G-{NNN}](../product-brief.md#goals--success-metrics)
- **Architecture**: [ADR-{NNN}](../architecture/ADR-{NNN}-{slug}.md) (if applicable)
```
---
## Variable Descriptions
| Variable | Source | Description |
|----------|--------|-------------|
| `{session_id}` | spec-config.json | Session identifier |
| `{timestamp}` | Runtime | ISO8601 generation timestamp |
| `{product_name}` | product-brief.md | Product/feature name |
| `{NNN}` | Auto-increment | Requirement number (zero-padded 3 digits) |
| `{slug}` | Auto-generated | Kebab-case from requirement title |
| `{type}` | Category | P (Performance), S (Security), SC (Scalability), U (Usability) |
| `{Must\|Should\|Could\|Won't}` | User input / auto | MoSCoW priority tag |

View File

@@ -111,7 +111,7 @@ When coordinator spawns workers, use `team-worker` agent with role-spec path:
```
Agent({
subagent_type: "team-worker",
agent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",

View File

@@ -43,7 +43,7 @@ message_types:
| architecture | + requirements/_index.md |
| epics | + architecture/_index.md |
**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to subagent.
**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to CLI tool.
| Input | Source | Required |
|-------|--------|----------|

View File

@@ -129,7 +129,7 @@ Collect task states from TaskList()
+- team_msg log -> task_unblocked
+- Spawn team-worker:
Agent({
subagent_type: "team-worker",
agent_type: "team-worker",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",

View File

@@ -97,7 +97,7 @@
"type": "explore-agent",
"callable_by": ["analyst", "planner", "any"],
"purpose": "Codebase exploration with centralized cache",
"implementation": "Agent with subagent_type: Explore"
"implementation": "Agent with agent_type: Explore"
},
"doc-generation": {
"type": "cli-tool",

View File

@@ -31,7 +31,7 @@
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"subagents": ["explore"],
"delegates_to": [],
"message_types": {
"success": "profile_complete",
"error": "error"
@@ -51,7 +51,7 @@
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": ["DISCUSS-OPT"],
"subagents": ["discuss"],
"delegates_to": [],
"message_types": {
"success": "strategy_complete",
"error": "error"
@@ -71,7 +71,7 @@
"inner_loop": true,
"additional_prefixes": ["FIX"],
"discuss_rounds": [],
"subagents": ["explore"],
"delegates_to": [],
"message_types": {
"success": "impl_complete",
"error": "error",
@@ -92,7 +92,7 @@
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"subagents": [],
"delegates_to": [],
"message_types": {
"success": "bench_complete",
"error": "error",
@@ -113,7 +113,7 @@
"inner_loop": false,
"additional_prefixes": ["QUALITY"],
"discuss_rounds": ["DISCUSS-REVIEW"],
"subagents": ["discuss"],
"delegates_to": [],
"message_types": {
"success": "review_complete",
"error": "error",
@@ -193,24 +193,6 @@
"diagram": "See pipeline-diagram section"
},
"subagents": [
{
"name": "explore",
"agent_type": "cli-explore-agent",
"callable_by": ["profiler", "optimizer"],
"purpose": "Shared codebase exploration for performance-critical code paths",
"has_cache": true,
"cache_domain": "explorations"
},
{
"name": "discuss",
"agent_type": "cli-discuss-agent",
"callable_by": ["strategist", "reviewer"],
"purpose": "Multi-perspective discussion for optimization approaches and review findings",
"has_cache": false
}
],
"shared_resources": [
{
"name": "Performance Baseline",

View File

@@ -1,7 +1,6 @@
---
prefix: QAANA
inner_loop: false
additional_members: []
message_types:
success: analysis_ready
report: quality_report

View File

@@ -2,7 +2,6 @@
prefix: QARUN
inner_loop: true
additional_prefixes: [QARUN-gc]
additional_members: []
message_types:
success: tests_passed
failure: tests_failed

View File

@@ -2,7 +2,6 @@
prefix: QAGEN
inner_loop: false
additional_prefixes: [QAGEN-fix]
additional_members: []
message_types:
success: tests_generated
revised: tests_revised

View File

@@ -1,7 +1,6 @@
---
prefix: SCOUT
inner_loop: false
additional_members: []
message_types:
success: scan_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: QASTRAT
inner_loop: false
additional_members: []
message_types:
success: strategy_ready
error: error

View File

@@ -1,6 +1,8 @@
---
prefix: TDFIX
inner_loop: true
cli_tools:
- gemini --mode write
message_types:
success: fix_complete
progress: fix_progress

View File

@@ -1,6 +1,8 @@
---
prefix: TDSCAN
inner_loop: false
cli_tools:
- gemini --mode analysis
message_types:
success: scan_complete
error: error

View File

@@ -70,6 +70,9 @@ Execute 4-layer validation (all commands in worktree):
run_in_background: false
})
```
- Re-run validation checks after fix attempt
})
```
- Re-run checks after fix attempt
## Phase 4: Compare & Report

View File

@@ -1,7 +1,6 @@
---
prefix: RESEARCH
inner_loop: false
additional_members: [explore]
message_types:
success: research_ready
progress: research_progress

View File

@@ -2,7 +2,6 @@
prefix: ANALYZE
inner_loop: false
additional_prefixes: [ANALYZE-fix]
additional_members: []
message_types:
success: analysis_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: DISCUSS
inner_loop: false
additional_members: []
message_types:
success: discussion_processed
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: EXPLORE
inner_loop: false
additional_members: []
message_types:
success: exploration_ready
error: error

View File

@@ -1,7 +1,6 @@
---
prefix: SYNTH
inner_loop: false
additional_members: []
message_types:
success: synthesis_ready
error: error