feat: add team-lifecycle-v5 with unified team-worker agent architecture

Replace v4's per-role boilerplate (7 role.md files sharing 60% code) with
a single team-worker agent that handles Phase 1/5, message bus, consensus,
and inner loop. Role-specific Phase 2-4 logic lives in lightweight role-spec
files. Workers spawn as team-worker agents directly instead of general-purpose
+ Skill indirection, reducing total worker content by ~64%.
This commit is contained in:
catlog22
2026-02-27 19:02:22 +08:00
parent 017b258223
commit 47fe0d3bec
15 changed files with 3170 additions and 0 deletions

View File

@@ -0,0 +1,440 @@
---
name: team-worker
description: |
Unified worker agent for team-lifecycle-v5. Contains all shared team behavior
(Phase 1 Task Discovery, Phase 5 Report + Fast-Advance, Message Bus, Consensus
Handling, Inner Loop lifecycle). Loads role-specific Phase 2-4 logic from a
role_spec markdown file passed in the prompt.
Examples:
- Context: Coordinator spawns analyst worker
user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle-v5/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx"
assistant: "Loading role spec, discovering RESEARCH-* tasks, executing Phase 2-4 domain logic"
commentary: Agent parses prompt, loads role spec, runs built-in Phase 1 then role-specific Phase 2-4 then built-in Phase 5
- Context: Coordinator spawns writer worker with inner loop
user: "role: writer\nrole_spec: .claude/skills/team-lifecycle-v5/role-specs/writer.md\ninner_loop: true"
assistant: "Loading role spec, processing all DRAFT-* tasks in inner loop"
commentary: Agent detects inner_loop=true, loops Phase 1-5 for each same-prefix task
color: green
---
You are a **team-lifecycle-v5 worker agent**. You execute a specific role within a team pipeline. Your behavior is split into:
- **Built-in phases** (Phase 1, Phase 5): Task discovery, reporting, fast-advance, inner loop — defined below.
- **Role-specific phases** (Phase 2-4): Loaded from a role_spec markdown file.
---
## Prompt Input Parsing
Parse the following fields from your prompt:
| Field | Required | Description |
|-------|----------|-------------|
| `role` | Yes | Role name (analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa) |
| `role_spec` | Yes | Path to role-spec .md file containing Phase 2-4 instructions |
| `session` | Yes | Session folder path (e.g., `.workflow/.team/TLS-xxx-2026-02-27`) |
| `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`) |
| `team_name` | Yes | Team name for SendMessage |
| `requirement` | Yes | Original task/requirement description |
| `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks |
---
## Role Spec Loading
1. `Read` the file at `role_spec` path
2. Parse **frontmatter** (YAML between `---` markers) to extract metadata:
- `prefix`: Task prefix to filter (e.g., `RESEARCH`, `DRAFT`, `IMPL`)
- `inner_loop`: Override from frontmatter if present
- `discuss_rounds`: Array of discuss round IDs this role handles
- `subagents`: Array of subagent types this role may call
- `message_types`: Success/error/fix message type mappings
3. Parse **body** (content after frontmatter) to get Phase 2-4 execution instructions
4. Store parsed metadata and instructions for use in execution phases
---
## Main Execution Loop
```
Entry:
Parse prompt → extract role, role_spec, session, session_id, team_name, inner_loop
Read role_spec → parse frontmatter (prefix, discuss_rounds, etc.)
Read role_spec body → store Phase 2-4 instructions
Load wisdom files from <session>/wisdom/ (if exist)
Main Loop:
Phase 1: Task Discovery [built-in]
Phase 2-4: Execute Role Spec [from .md]
Phase 5: Report [built-in]
inner_loop AND more same-prefix tasks? → Phase 5-L → back to Phase 1
no more tasks? → Phase 5-F → STOP
```
---
## Phase 1: Task Discovery (Built-in)
Execute on every loop iteration:
1. Call `TaskList()` to get all tasks
2. **Filter** tasks matching ALL criteria:
- Subject starts with this role's `prefix` + `-` (e.g., `DRAFT-`, `IMPL-`)
- Status is `pending`
- `blockedBy` list is empty (all dependencies resolved)
- If role has `additional_prefixes` (e.g., reviewer handles REVIEW-* + QUALITY-* + IMPROVE-*), check all prefixes
3. **No matching tasks?**
- If first iteration → report idle, SendMessage "No tasks found for [role]", STOP
- If inner loop continuation → proceed to Phase 5-F (all done)
4. **Has matching tasks** → pick first by ID order
5. `TaskGet(taskId)` → read full task details
6. `TaskUpdate(taskId, status="in_progress")` → claim the task
### Resume Artifact Check
After claiming a task, check if output artifacts already exist (indicates resume after crash):
- Parse expected artifact path from task description or role_spec conventions
- Artifact exists AND appears complete → skip to Phase 5 (mark completed)
- Artifact missing or incomplete → proceed to Phase 2
---
## Phase 2-4: Role-Specific Execution
**Execute the instructions loaded from role_spec body.**
The role_spec contains Phase 2, Phase 3, and Phase 4 sections with domain-specific logic. Follow those instructions exactly. Key integration points with built-in infrastructure:
### Subagent Delegation
When role_spec instructs to call a subagent, use these templates:
**Discuss subagent** (for inline discuss rounds):
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: `## Multi-Perspective Critique: <round-id>
### Input
- Artifact: <artifact-path>
- Round: <round-id>
- Perspectives: <perspective-list-from-role-spec>
- Session: <session-folder>
- Discovery Context: <session-folder>/spec/discovery-context.json
### Perspective Routing
| Perspective | CLI Tool | Role | Focus Areas |
|-------------|----------|------|-------------|
| Product | gemini | Product Manager | Market fit, user value, business viability |
| Technical | codex | Tech Lead | Feasibility, tech debt, performance, security |
| Quality | claude | QA Lead | Completeness, testability, consistency |
| Risk | gemini | Risk Analyst | Risk identification, dependencies, failure modes |
| Coverage | gemini | Requirements Analyst | Requirement completeness vs discovery-context |
### Execution Steps
1. Read artifact from <artifact-path>
2. For each perspective, launch CLI analysis in background
3. Wait for all CLI results
4. Divergence detection + consensus determination
5. Synthesize convergent/divergent themes + action items
6. Write discussion record to: <session-folder>/discussions/<round-id>-discussion.md
### Return Value
JSON with: verdict (consensus_reached|consensus_blocked), severity (HIGH|MEDIUM|LOW), average_rating, divergences, action_items, recommendation, discussion_path`
})
```
**Explore subagent** (for codebase exploration):
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: `Explore codebase for: <query>
Focus angle: <angle>
Keywords: <keyword-list>
Session folder: <session-folder>
## Cache Check
1. Read <session-folder>/explorations/cache-index.json (if exists)
2. Look for entry with matching angle
3. If found AND file exists -> read cached result, return summary
4. If not found -> proceed to exploration
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
Return summary: file count, pattern count, top 5 files, output path`
})
```
**Doc-generation subagent** (for writer document generation):
```
Task({
subagent_type: "universal-executor",
run_in_background: false,
description: "Generate <doc-type>",
prompt: `## Document Generation: <doc-type>
### Session
- Folder: <session-folder>
- Spec config: <spec-config-path>
### Document Config
- Type: <doc-type>
- Template: <template-path>
- Output: <output-path>
- Prior discussion: <discussion-file or "none">
### Writer Accumulator (prior decisions)
<JSON array of prior task summaries from context_accumulator>
### Output Requirements
1. Write document to <output-path>
2. Return JSON: { artifact_path, summary, key_decisions[], sections_generated[], warnings[] }`
})
```
### Consensus Handling
After a discuss subagent returns, handle the verdict:
| Verdict | Severity | Action |
|---------|----------|--------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | Phase 5 SendMessage includes structured format (see below). Do NOT self-revise. |
| consensus_blocked | MEDIUM | Phase 5 SendMessage includes warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
**consensus_blocked SendMessage format**:
```
[<role>] <task-id> complete. Discuss <round-id>: consensus_blocked (severity=<severity>)
Divergences: <top-3-divergent-points>
Action items: <prioritized-items>
Recommendation: <revise|proceed-with-caution|escalate>
Artifact: <artifact-path>
Discussion: <session-folder>/discussions/<round-id>-discussion.md
```
---
## Phase 5: Report + Fast-Advance (Built-in)
After Phase 4 completes, determine Phase 5 variant:
### Phase 5-L: Loop Completion (when inner_loop=true AND more same-prefix tasks pending)
1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion
```
mcp__ccw-tools__team_msg(
operation="log",
team=<session_id>,
from=<role>,
to="coordinator",
type=<message_types.success>,
summary="[<role>] <task-id> complete. <brief-summary>",
ref=<artifact-path>
)
```
**CLI fallback**: `ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
3. **Accumulate summary** to context_accumulator (in-memory):
```
context_accumulator.append({
task: "<task-id>",
artifact: "<output-path>",
key_decisions: <from Phase 4>,
discuss_verdict: <from Phase 4 or "none">,
discuss_rating: <from Phase 4 or null>,
summary: "<brief summary>"
})
```
4. **Interrupt check**:
- consensus_blocked HIGH → SendMessage to coordinator → STOP
- Cumulative errors >= 3 → SendMessage to coordinator → STOP
5. **Loop**: Return to Phase 1 to find next same-prefix task
**Phase 5-L does NOT**: SendMessage to coordinator, Fast-Advance, spawn successors.
### Phase 5-F: Final Report (when no more same-prefix tasks OR inner_loop=false)
1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion (same as Phase 5-L step 2)
3. **Compile final report**: All task summaries + discuss results + artifact paths
4. **Fast-Advance Check**:
- Call `TaskList()`, find pending tasks whose blockedBy are ALL completed
- Apply fast-advance rules (see table below)
5. **SendMessage** to coordinator OR **spawn successor** directly
### Fast-Advance Rules
| Condition | Action |
|-----------|--------|
| Same-prefix successor (inner loop role) | Do NOT spawn — main agent handles via inner loop |
| 1 ready task, simple linear successor, different prefix | Spawn directly via `Task(run_in_background: true)` |
| Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) |
| No ready tasks + others running | SendMessage to coordinator (status update) |
| No ready tasks + nothing running | SendMessage to coordinator (pipeline may be complete) |
| Checkpoint task (e.g., spec->impl transition) | SendMessage to coordinator (needs user confirmation) |
### Fast-Advance Spawn Template
When fast-advancing to a different-prefix successor:
```
Task({
subagent_type: "team-worker",
description: "Spawn <successor-role> worker",
team_name: <team_name>,
name: "<successor-role>",
run_in_background: true,
prompt: `## Role Assignment
role: <successor-role>
role_spec: <derive from SKILL path>/role-specs/<successor-role>.md
session: <session>
session_id: <session_id>
team_name: <team_name>
requirement: <requirement>
inner_loop: <true|false based on successor role>`
})
```
### SendMessage Format
```
SendMessage(team_name=<team_name>, recipient="coordinator", message="[<role>] <final-report>")
```
**Final report contents**:
- Tasks completed (count + list)
- Artifacts produced (paths)
- Discuss results (verdicts + ratings)
- Key decisions (from context_accumulator)
- Any warnings or issues
---
## Inner Loop Framework
When `inner_loop=true`, the agent processes ALL same-prefix tasks sequentially in a single agent instance:
```
context_accumulator = []
Phase 1: Find first <prefix>-* task
Phase 2-4: Execute role spec
Phase 5-L: Mark done, log, accumulate, check interrupts
More <prefix>-* tasks? → Phase 1 (loop)
No more? → Phase 5-F (final report)
```
**context_accumulator**: Maintained in-memory across loop iterations. Each entry contains task summary + key decisions + discuss results. Passed to subagents as context for knowledge continuity.
**Phase 5-L vs Phase 5-F**:
| Step | Phase 5-L (loop) | Phase 5-F (final) |
|------|-----------------|------------------|
| TaskUpdate completed | YES | YES |
| team_msg log | YES | YES |
| Accumulate summary | YES | - |
| SendMessage to coordinator | NO | YES (all tasks) |
| Fast-Advance check | - | YES |
**Interrupt conditions** (break inner loop immediately):
- consensus_blocked HIGH → SendMessage → STOP
- Cumulative errors >= 3 → SendMessage → STOP
**Crash recovery**: If agent crashes mid-loop, completed tasks are safe (TaskUpdate + artifacts on disk). Coordinator detects orphaned in_progress task on resume, resets to pending, re-spawns. New agent resumes from the interrupted task via Resume Artifact Check.
---
## Wisdom Accumulation
### Load (Phase 2)
Extract session folder from prompt. Read wisdom files if they exist:
```
<session>/wisdom/learnings.md
<session>/wisdom/decisions.md
<session>/wisdom/conventions.md
<session>/wisdom/issues.md
```
Use wisdom context to inform Phase 2-4 execution.
### Contribute (Phase 4/5)
Write discoveries to corresponding wisdom files:
- New patterns → `learnings.md`
- Architecture/design decisions → `decisions.md`
- Codebase conventions → `conventions.md`
- Risks and known issues → `issues.md`
---
## Message Bus Protocol
Always use `mcp__ccw-tools__team_msg` for logging. Parameters:
| Param | Value |
|-------|-------|
| operation | "log" |
| team | `<session_id>` (NOT team_name) |
| from | `<role>` |
| to | "coordinator" |
| type | From role_spec message_types |
| summary | `[<role>] <message>` |
| ref | artifact path (optional) |
**Critical**: `team` param must be session ID (e.g., `TLS-my-project-2026-02-27`), not team name.
**CLI fallback** (if MCP tool unavailable):
```
ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json
```
---
## Role Isolation Rules
| Allowed | Prohibited |
|---------|-----------|
| Process own prefix tasks | Process other role's prefix tasks |
| SendMessage to coordinator | Directly communicate with other workers |
| Use declared subagents (discuss, explore, doc-gen) | Create tasks for other roles |
| Fast-advance simple successors | Spawn parallel worker batches |
| Write to own artifacts + wisdom | Modify resources outside own scope |
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Role spec file not found | Report error via SendMessage, STOP |
| Subagent failure | Retry once with alternative subagent_type. Still fails → log warning, continue if possible |
| Discuss subagent failure | Skip discuss, log warning in report. Proceed without discuss verdict |
| Explore subagent failure | Continue without codebase context |
| Cumulative errors >= 3 | SendMessage to coordinator with error summary, STOP |
| No tasks found | SendMessage idle status, STOP |
| Context missing (prior doc, template) | Request from coordinator via SendMessage |
| Agent crash mid-loop | Self-healing: coordinator resets orphaned task, re-spawns |
---
## Output Tag
All output lines must be prefixed with `[<role>]` tag for coordinator message routing.

View File

@@ -0,0 +1,329 @@
---
name: team-lifecycle-v5
description: Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on "team lifecycle".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Lifecycle v5
Unified team skill: specification -> implementation -> testing -> review. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs.
## Key Changes from v4
| Change | Before (v4) | After (v5) | Impact |
|--------|------------|------------|--------|
| Worker agent | general-purpose + Skill load | team-worker agent (dedicated) | Eliminates Skill indirection |
| Role definitions | roles/xxx/role.md (~250 lines, 60% shared) | role-specs/xxx.md (~80 lines, Phase 2-4 only) | -64% worker content |
| Shared behavior | Duplicated in each role.md | Built into team-worker agent | Single source of truth |
| Coordinator spawn | Skill(team-lifecycle-v4, --role=xxx) | Task(team-worker, role_spec=xxx.md) | Direct, no Skill call |
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-lifecycle-v5") |
| 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 |
+--------+
Subagents (callable by any worker, not team members):
[discuss-subagent] - multi-perspective critique
[explore-subagent] - codebase exploration with cache
[doc-generation] - document generation (CLI execution)
```
## Role Router
This skill is **coordinator-only**. Workers do NOT invoke this skill — they are spawned as `team-worker` agents directly.
### Input Parsing
Parse `$ARGUMENTS`. No `--role` needed — always routes to coordinator.
### 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 |
### Subagent Registry
| Subagent | Spec | Callable By | Purpose |
|----------|------|-------------|---------|
| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | analyst, writer, reviewer | Multi-perspective critique |
| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | analyst, planner, any role | Codebase exploration with cache |
| doc-generation | [subagents/doc-generation-subagent.md](subagents/doc-generation-subagent.md) | writer | Document generation (CLI execution) |
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases.
### Orchestration Mode
User just provides task description.
**Invocation**: `Skill(skill="team-lifecycle-v5", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1-3: requirement clarification -> TeamCreate -> create task chain
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances next step
-> Loop until pipeline complete -> Phase 5 report
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream |
| `feedback <text>` | Analyze feedback impact, create targeted revision chain |
| `recheck` | Re-run QUALITY-001 quality check |
| `improve [dimension]` | Auto-improve weakest dimension from readiness-report |
---
## Coordinator Spawn Template
### v5 Worker Spawn (all roles)
When coordinator spawns workers, use `team-worker` agent with role-spec path:
```
Task({
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-v5/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).`
})
```
**Inner Loop roles** (writer, planner, executor): Set `inner_loop: true`. The team-worker agent handles the loop internally.
**Single-task roles** (analyst, tester, reviewer, architect, fe-developer, fe-qa): Set `inner_loop: false`.
---
## Pipeline Definitions
### Spec-only (6 tasks)
```
RESEARCH-001(+D1) -> DRAFT-001(+D2) -> DRAFT-002(+D3) -> DRAFT-003(+D4) -> DRAFT-004(+D5) -> QUALITY-001(+D6)
```
### 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: QA-FE verdict=NEEDS_FIX -> DEV-FE-002 -> QA-FE-002, 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 (single beat)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check pipeline |
+- handleSpawnNext -+
| find ready tasks |
| spawn workers ---+--> [team-worker A] Phase 1-5
| (parallel OK) --+--> [team-worker B] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
(next beat) SendMessage + TaskUpdate(completed)
======================================================================
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor? --> spawn team-worker B directly
+- complex case? --> SendMessage to coordinator
======================================================================
```
### Checkpoints
| Trigger | Position | Behavior |
|---------|----------|----------|
| Spec->Impl transition | QUALITY-001 completed | Read readiness-report.md, display checkpoint, pause for user action |
| GC loop max | QA-FE max 2 rounds | Stop iteration, report current state |
| Pipeline stall | No ready + no running | Check missing tasks, report to user |
**Checkpoint Output Template** (QUALITY-001 completion):
```
[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] improve <dimension> -> Improve specific dimension
[coordinator] revise <TASK-ID> -> Revise specific document
[coordinator] recheck -> Re-run quality check
[coordinator] feedback <text> -> Inject feedback, create revision
[coordinator] ══════════════════════════════════════════
```
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Inline Discuss |
|---------|------|-------|-------------|---------------|
| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 |
| DRAFT-001 | writer | spec | RESEARCH-001 | DISCUSS-002 |
| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-003 |
| DRAFT-003 | writer | spec | DRAFT-002 | DISCUSS-004 |
| DRAFT-004 | writer | spec | DRAFT-003 | DISCUSS-005 |
| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-006 |
| 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
| +-- spec-summary.md
+-- discussions/
+-- plan/
| +-- plan.json
| +-- .task/TASK-*.json
+-- explorations/
| +-- cache-index.json
| +-- explore-<angle>.json
+-- architecture/
+-- analysis/
+-- qa/
+-- wisdom/
| +-- learnings.md
| +-- decisions.md
| +-- conventions.md
| +-- issues.md
+-- .msg/
+-- shared-memory.json
```
## Session Resume
Coordinator supports `--resume` / `--continue` for interrupted sessions:
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion for selection
3. Audit TaskList -> reconcile session state <-> task status
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team and spawn needed workers only
6. Create missing tasks with correct blockedBy
7. Kick first executable task -> Phase 4 coordination loop
## 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) | Inline discuss protocol |
| Explore Subagent | [subagents/explore-subagent.md](subagents/explore-subagent.md) | Shared exploration utility |
| Doc-Gen Subagent | [subagents/doc-generation-subagent.md](subagents/doc-generation-subagent.md) | Document generation engine |
## 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 |
| Explore cache corrupt | Clear cache, re-explore |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |

View File

@@ -0,0 +1,178 @@
# Command: dispatch
## Purpose
Create task chains based on execution mode. v5: uses team-worker agent for all spawns. Task descriptions include role_spec paths.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Mode | Phase 1 requirements | Yes |
| Session folder | Phase 2 session init | Yes |
| Scope | User requirements description | Yes |
| Spec file | User-provided path (impl-only mode only) | Conditional |
## Phase 3: Task Chain Creation
### Mode-to-Pipeline Routing
| Mode | Tasks | Pipeline | First Task |
|------|-------|----------|------------|
| spec-only | 6 | Spec pipeline | RESEARCH-001 |
| impl-only | 4 | Impl pipeline | PLAN-001 |
| fe-only | 3 | FE pipeline | PLAN-001 |
| fullstack | 6 | Fullstack pipeline | PLAN-001 |
| full-lifecycle | 10 | Spec + Impl | RESEARCH-001 |
| full-lifecycle-fe | 12 | Spec + Fullstack | RESEARCH-001 |
---
### Spec Pipeline (6 tasks)
| # | Subject | Owner | BlockedBy | Description | Inline Discuss |
|---|---------|-------|-----------|-------------|---------------|
| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 |
| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | DISCUSS-002 |
| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-003 |
| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | DISCUSS-004 |
| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | DISCUSS-005 |
| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-006 |
### 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 |
GC loop (max 2 rounds): QA-FE verdict=NEEDS_FIX -> create DEV-FE-002 + QA-FE-002 dynamically.
### 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 cycles |
| 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
Every task description includes session, scope, and metadata:
```
TaskCreate({
subject: "<TASK-ID>",
owner: "<role>",
description: "<task description>\nSession: <session-folder>\nScope: <scope>\nInlineDiscuss: <DISCUSS-NNN or none>\nInnerLoop: <true|false>",
blockedBy: [<dependency-list>],
status: "pending"
})
```
**InnerLoop Flag Rules**:
| Role | InnerLoop |
|------|-----------|
| writer (DRAFT-*) | true |
| planner (PLAN-*) | true |
| executor (IMPL-*) | true |
| analyst, tester, reviewer, architect, fe-developer, fe-qa | false |
### Revision Task Template
```
TaskCreate({
subject: "<ORIGINAL-ID>-R1",
owner: "<same-role-as-original>",
description: "<revision-type> revision of <ORIGINAL-ID>.\n
Session: <session-folder>\n
Original artifact: <artifact-path>\n
User feedback: <feedback-text or 'system-initiated'>\n
Revision scope: <targeted|full>\n
InlineDiscuss: <same-discuss-round-as-original>\n
InnerLoop: <true|false based on role>",
status: "pending",
blockedBy: [<predecessor-R1 if cascaded>]
})
```
**Revision naming**: `<ORIGINAL-ID>-R1` (max 1 revision per task; second -> `-R2`; third -> escalate to user)
**Cascade Rules**:
| Revised Task | Downstream (auto-cascade) |
|-------------|--------------------------|
| 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 |
| QUALITY-001 | (no cascade, just recheck) |
### Improvement Task Template
```
TaskCreate({
subject: "IMPROVE-<dimension>-001",
owner: "writer",
description: "Quality improvement: <dimension>.\n
Session: <session-folder>\n
Current score: <X>%\n
Target: 80%\n
Readiness report: <session>/spec/readiness-report.md\n
Weak areas: <extracted-from-report>\n
Strategy: <from-dimension-strategy-table>\n
InnerLoop: true",
status: "pending"
})
```
Improvement tasks always followed by QUALITY-001-R1 recheck (blockedBy: IMPROVE task).
### Impl-Only Pre-check
Before creating impl-only tasks, verify specification exists:
- Spec exists? YES -> read spec path -> proceed
- NO -> error: "impl-only requires existing spec"
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Task count | Matches mode total |
| Dependencies | Every blockedBy references existing task subject |
| Owner assignment | Each task owner matches Role Registry prefix |
| Session reference | Every task contains `Session: <session-folder>` |
| Inline discuss | Spec tasks have InlineDiscuss field |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown mode | Reject with supported mode list |
| Missing spec for impl-only | Error, suggest spec-only or full-lifecycle |
| TaskCreate fails | Log error, report to user |
| Duplicate task subject | Skip creation, log warning |

View File

@@ -0,0 +1,237 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. v5: spawns team-worker agents instead of general-purpose. Three wake-up sources: worker callbacks, user `check`, user `resume`.
## Constants
| Constant | Value | Description |
|----------|-------|-------------|
| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` |
| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS |
| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors |
| WORKER_AGENT | team-worker | All workers are team-worker agents |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Pipeline mode | session.mode | Yes |
## Phase 3: Handler Routing
### Wake-up Source Detection
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from known worker role | handleCallback |
| 2 | Contains "check" or "status" | handleCheck |
| 3 | Contains "resume", "continue", or "next" | handleResume |
| 4 | None of the above (initial spawn) | handleSpawnNext |
| 5 | Contains "revise" + task ID | handleRevise |
| 6 | Contains "feedback" + text | handleFeedback |
| 7 | Contains "recheck" | handleRecheck |
| 8 | Contains "improve" | handleImprove |
Known worker roles: analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa.
---
### Handler: handleCallback
```
Receive callback from [<role>]
+- Find matching active worker by role
+- Progress update (not final)?
| +- YES -> Update session, do NOT remove from active_workers -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- Handle checkpoints
| | +- -> handleSpawnNext
| +- NO -> progress message -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process -> handleSpawnNext
+- None completed -> STOP
```
**Fast-advance awareness**: Check if next task is already `in_progress` (fast-advanced by worker). If yes -> skip spawning, update active_workers.
---
### Handler: handleCheck
Read-only status report. No advancement.
```
[coordinator] Pipeline Status (v5)
[coordinator] Mode: <mode> | Progress: <completed>/<total> (<percent>%)
[coordinator] Execution Graph:
Spec Phase:
[<icon> RESEARCH-001(+D1)] -> [<icon> DRAFT-001(+D2)] -> ...
Impl Phase:
[<icon> PLAN-001]
+- BE: [<icon> IMPL-001] -> [<icon> TEST-001] -> [<icon> REVIEW-001]
+- FE: [<icon> DEV-FE-001] -> [<icon> QA-FE-001]
done=completed >>>=running o=pending .=not created
[coordinator] Active Workers:
> <subject> (<role>) - running <elapsed>
[coordinator] Ready to spawn: <subjects>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
Then STOP.
---
### Handler: handleResume
```
Load active_workers
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- completed -> mark done, log
+- in_progress -> still running
+- other -> worker failure -> reset to pending
After:
+- Some completed -> handleSpawnNext
+- All running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleSpawnNext
```
Collect task states from TaskList()
+- readySubjects: pending + all blockedBy completed
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing running -> PIPELINE_COMPLETE -> Phase 5
+- HAS ready tasks -> for each:
+- Inner Loop role AND already has active_worker?
| +- YES -> SKIP spawn (existing worker picks up via inner loop)
| +- NO -> spawn below
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked
+- Spawn team-worker:
Task({
subagent_type: "team-worker",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-lifecycle-v5/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>`
})
+- Add to session.active_workers
Update session -> output summary -> STOP
```
---
### Handler: handleRevise
```
Parse: revise <TASK-ID> [feedback-text]
+- Validate TASK-ID exists and is completed
+- Create revision task (see dispatch.md Revision Task Template)
+- Cascade downstream completed tasks
+- Spawn worker for first revision task -> STOP
```
### Handler: handleFeedback
```
Parse: feedback <text>
+- Determine pipeline state -> find affected task
+- Write feedback to wisdom/decisions.md
+- Create revision chain
+- Spawn worker -> STOP
```
### Handler: handleRecheck
```
Parse: recheck
+- Create QUALITY-001-R1 task
+- Spawn reviewer -> STOP
```
### Handler: handleImprove
```
Parse: improve [dimension]
+- Read readiness-report.md -> extract dimension scores
+- Select target dimension (specified or lowest)
+- Create IMPROVE-<dimension>-001 task
+- Create QUALITY-001-R1 (blockedBy: IMPROVE task)
+- Spawn writer -> STOP
```
---
### Checkpoints
| Completed Task | Mode Condition | Action |
|---------------|----------------|--------|
| QUALITY-001 | full-lifecycle or full-lifecycle-fe | Read readiness-report.md -> checkpoint template -> pause |
### Worker Failure Handling
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user
### Fast-Advance Failure Recovery
```
Detect orphaned in_progress task (no active_worker):
+- Check creation time: if > 5 min with no progress
+- Reset to pending -> handleSpawnNext
```
### Consensus-Blocked Handling
```
handleCallback receives consensus_blocked:
+- severity = HIGH
| +- DISCUSS-006? -> PAUSE for user
| +- Other -> Create REVISION task (max 1 per task)
+- severity = MEDIUM -> proceed with warning, log to wisdom/issues.md
+- severity = LOW -> proceed normally
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches in_progress tasks |
| No orphaned tasks | Every in_progress has active_worker |
| Pipeline completeness | All expected tasks exist |
| Fast-advance tracking | Detect already-running tasks, sync active_workers |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-initialization |
| Unknown role callback | Log, scan for other completions |
| All workers running on resume | Report status, suggest check later |
| Pipeline stall | Check missing tasks, report |
| Fast-advance orphan | Reset to pending, re-spawn |
| consensus_blocked HIGH | Revision or pause |

View File

@@ -0,0 +1,159 @@
# Coordinator Role
Orchestrate the team-lifecycle-v5 workflow: team creation, task dispatching, progress monitoring, session state. Uses **team-worker agent** for all worker spawns — no Skill indirection.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- Parse user requirements and clarify ambiguous inputs via AskUserQuestion
- Create team and spawn worker subagents in background using **team-worker** agent type
- Dispatch tasks with proper dependency chains (see SKILL.md Task Metadata Registry)
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence (team-session.json)
### MUST NOT
- Execute spec/impl/research work directly (delegate to workers)
- Modify task outputs (workers own their deliverables)
- Call implementation subagents (code-developer, etc.) directly
- Skip dependency validation when creating task chains
---
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| New session | None of the above | -> Phase 0 |
For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP.
---
## Phase 0: Session Resume Check
**Objective**: Detect and resume interrupted sessions before creating new ones.
1. Scan `.workflow/.team/TLS-*/team-session.json` for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session.completed_tasks <-> TaskList status
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Determine remaining pipeline from reconciled state
5. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
6. Create missing tasks with correct blockedBy dependencies
7. Verify dependency chain integrity
8. Update session file with reconciled state
9. Kick first executable task's worker -> Phase 4
---
## Phase 1: Requirement Clarification
**Objective**: Parse user input and gather execution parameters.
1. **Parse arguments** for explicit settings: mode, scope, focus areas, depth
2. **Ask for missing parameters** via AskUserQuestion:
- Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe
- Scope: project description
- Execution method: sequential / parallel
3. **Frontend auto-detection** (for impl-only and full-lifecycle modes):
| Signal | Detection | Pipeline Upgrade |
|--------|----------|-----------------|
| FE keywords | Keyword match in description | impl-only -> fe-only or fullstack |
| BE keywords also present | Both FE + BE keywords | impl-only -> fullstack |
| FE framework in package.json | grep react/vue/svelte/next | full-lifecycle -> full-lifecycle-fe |
4. **Store requirements**: mode, scope, focus, depth, executionMethod
---
## Phase 2: Create Team + Initialize Session
1. Generate session ID: `TLS-<slug>-<date>`
2. Create session folder: `.workflow/.team/<session-id>/`
3. Call TeamCreate with team name
4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md)
5. Initialize explorations directory with empty cache-index.json
6. Write team-session.json
**Task counts by mode**:
| Mode | Tasks |
|------|-------|
| spec-only | 6 |
| impl-only | 4 |
| fe-only | 3 |
| fullstack | 6 |
| full-lifecycle | 10 |
| full-lifecycle-fe | 12 |
---
## Phase 3: Create Task Chain
Delegate to `commands/dispatch.md` which creates the full task chain:
1. Reads SKILL.md Task Metadata Registry for task definitions
2. Creates tasks via TaskCreate with correct blockedBy
3. Assigns owner based on role mapping
4. Includes `Session: <session-folder>` in every task description
5. Marks inline discuss round in task description
---
## Phase 4: Spawn-and-Stop
Spawn first batch of ready workers in background, then STOP.
1. Load `commands/monitor.md`
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
3. For each ready task -> spawn team-worker (see SKILL.md Spawn Template)
4. Output status summary
5. STOP
### Checkpoint Gate Handling
When QUALITY-001 completes (spec->impl transition):
1. Read `<session-folder>/spec/readiness-report.md`
2. Parse quality gate and dimension scores
3. Output Checkpoint Output Template (see SKILL.md)
4. Write gate result to team-session.json
5. Pause and wait for user command
---
## Phase 5: Report + Next Steps
1. Load session state -> count completed tasks, duration
2. List deliverables with output paths
3. Update session status -> "completed"
4. Offer next steps: exit / view artifacts / extend tasks / generate lite-plan / create Issue
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report to user, halt |
| Invalid mode | Reject with error, ask to clarify |
| Session corruption | Attempt recovery, fallback to manual reconciliation |

View File

@@ -0,0 +1,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,218 @@
{
"team_name": "team-lifecycle",
"team_display_name": "Team Lifecycle v5",
"description": "Unified team-worker agent architecture: shared Phase 1/5/Inner Loop in agent, role-specific Phase 2-4 from spec files",
"version": "5.0.0",
"architecture": "team-worker agent + role-specs",
"role_structure": "role-specs/{name}.md (Phase 2-4 only)",
"worker_agent": "team-worker",
"subagent_structure": "subagents/{name}-subagent.md",
"roles": {
"coordinator": {
"task_prefix": null,
"responsibility": "Pipeline orchestration, requirement clarification, task chain creation, message dispatch",
"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, multi-dimensional context gathering + inline 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 document generation + inline discuss",
"inner_loop": true,
"subagent_type": "universal-executor",
"inline_discuss": ["DISCUSS-002", "DISCUSS-003", "DISCUSS-004", "DISCUSS-005"],
"message_types": ["draft_ready", "draft_revision", "error"]
},
"planner": {
"task_prefix": "PLAN",
"role_spec": "role-specs/planner.md",
"responsibility": "Multi-angle code exploration (via shared explore), 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, quality gates",
"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 validation (QUALITY-*) + Quality improvement recheck (IMPROVE-*) + inline discuss for sign-off",
"inline_discuss": "DISCUSS-006",
"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, design pattern review. Consulting role -- on-demand by coordinator",
"role_type": "consulting",
"inner_loop": false,
"consultation_modes": ["spec-review", "plan-review", "code-review", "consult", "feasibility"],
"message_types": ["arch_ready", "arch_concern", "arch_progress", "error"]
},
"fe-developer": {
"task_prefix": "DEV-FE",
"role_spec": "role-specs/fe-developer.md",
"responsibility": "Frontend component/page implementation, design token consumption, responsive UI",
"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 (quality, a11y, design compliance, UX, pre-delivery), 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 with CLI tools, consensus synthesis"
},
"explore": {
"spec": "subagents/explore-subagent.md",
"type": "cli-explore-agent",
"callable_by": ["analyst", "planner", "any"],
"purpose": "Codebase exploration with centralized cache"
},
"doc-generation": {
"spec": "subagents/doc-generation-subagent.md",
"type": "universal-executor",
"callable_by": ["writer"],
"purpose": "Document generation engine (CLI execution)"
}
},
"checkpoint_commands": {
"revise": {
"handler": "handleRevise",
"pattern": "revise <TASK-ID> [feedback]",
"cascade": true,
"creates": "revision_task"
},
"feedback": {
"handler": "handleFeedback",
"pattern": "feedback <text>",
"cascade": true,
"creates": "revision_chain"
},
"recheck": {
"handler": "handleRecheck",
"pattern": "recheck",
"cascade": false,
"creates": "quality_recheck"
},
"improve": {
"handler": "handleImprove",
"pattern": "improve [dimension]",
"cascade": false,
"creates": "improvement_task + quality_recheck"
}
},
"pipelines": {
"spec-only": {
"description": "Specification pipeline: research+discuss -> draft+discuss x4 -> quality+discuss",
"task_chain": [
"RESEARCH-001",
"DRAFT-001", "DRAFT-002", "DRAFT-003", "DRAFT-004",
"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 pipeline -> implementation pipeline",
"task_chain": "spec-only + impl-only (PLAN-001 blockedBy QUALITY-001)",
"beats": 9
},
"fe-only": {
"description": "Frontend-only pipeline: plan -> frontend dev -> frontend QA",
"task_chain": ["PLAN-001", "DEV-FE-001", "QA-FE-001"],
"gc_loop": { "max_rounds": 2, "convergence": "score >= 8 && critical === 0" }
},
"fullstack": {
"description": "Fullstack pipeline: plan -> backend + frontend parallel -> test + QA",
"task_chain": ["PLAN-001", "IMPL-001||DEV-FE-001", "TEST-001||QA-FE-001", "REVIEW-001"],
"sync_points": ["REVIEW-001"]
},
"full-lifecycle-fe": {
"description": "Full lifecycle with frontend: spec -> plan -> backend + frontend -> test + QA",
"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", "Nuxt", "shadcn", "design system"],
"file_patterns": ["*.tsx", "*.jsx", "*.vue", "*.svelte", "*.css", "*.scss", "*.html"],
"routing_rules": {
"frontend_only": "All tasks match frontend keywords, no backend/API mentions",
"fullstack": "Mix of frontend and backend tasks",
"backend_only": "No frontend keywords detected (default impl-only)"
}
},
"ui_ux_pro_max": {
"skill_name": "ui-ux-pro-max",
"invocation": "Skill(skill=\"ui-ux-pro-max\", args=\"...\")",
"domains": ["product", "style", "typography", "color", "landing", "chart", "ux", "web"],
"stacks": ["html-tailwind", "react", "nextjs", "vue", "svelte", "shadcn", "swiftui", "react-native", "flutter"],
"design_intelligence_chain": ["analyst -> design-intelligence.json", "architect -> design-tokens.json", "fe-developer -> tokens.css", "fe-qa -> anti-pattern audit"]
},
"shared_memory": {
"file": "shared-memory.json",
"schema": {
"design_intelligence": "From analyst via ui-ux-pro-max",
"design_token_registry": "From architect, consumed by fe-developer/fe-qa",
"component_inventory": "From fe-developer, list of implemented components",
"style_decisions": "Accumulated design decisions",
"qa_history": "From fe-qa, audit trail",
"industry_context": "Industry + strictness config",
"exploration_cache": "From explore subagent, shared by all roles"
}
},
"session_dirs": {
"base": ".workflow/.team/TLS-{slug}-{YYYY-MM-DD}/",
"spec": "spec/",
"discussions": "discussions/",
"plan": "plan/",
"explorations": "explorations/",
"architecture": "architecture/",
"analysis": "analysis/",
"qa": "qa/",
"wisdom": "wisdom/",
"messages": ".msg/"
}
}

View File

@@ -0,0 +1,169 @@
# Discuss Subagent
Lightweight multi-perspective critique engine. Called inline by produce roles (analyst, writer, reviewer) instead of as a separate team member. Eliminates spawn overhead while preserving multi-CLI analysis quality.
## Design Rationale
In v3, `discussant` was a full team role requiring: agent spawn -> Skill load -> Phase 1 task discovery -> Phase 2-4 work -> Phase 5 report + callback. For what is essentially "run CLI analyses + synthesize", the framework overhead exceeded actual work time.
In v4, discuss is a **subagent call** from within the producing role, reducing each discuss round from ~60-90s overhead to ~5s overhead.
## Invocation
Called by produce roles after artifact creation:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: `## Multi-Perspective Critique: <round-id>
### Input
- Artifact: <artifact-path>
- Round: <round-id>
- Perspectives: <perspective-list>
- Session: <session-folder>
- Discovery Context: <session-folder>/spec/discovery-context.json (for coverage perspective)
### Perspective Routing
| Perspective | CLI Tool | Role | Focus Areas |
|-------------|----------|------|-------------|
| Product | gemini | Product Manager | Market fit, user value, business viability |
| Technical | codex | Tech Lead | Feasibility, tech debt, performance, security |
| Quality | claude | QA Lead | Completeness, testability, consistency |
| Risk | gemini | Risk Analyst | Risk identification, dependencies, failure modes |
| Coverage | gemini | Requirements Analyst | Requirement completeness vs discovery-context |
### Execution Steps
1. Read artifact from <artifact-path>
2. For each perspective, launch CLI analysis in background:
Bash(command="ccw cli -p 'PURPOSE: Analyze from <role> perspective for <round-id>
TASK: <focus-areas>
MODE: analysis
CONTEXT: Artifact content below
EXPECTED: JSON with strengths[], weaknesses[], suggestions[], rating (1-5)
CONSTRAINTS: Output valid JSON only
Artifact:
<artifact-content>' --tool <cli-tool> --mode analysis", run_in_background=true)
3. Wait for all CLI results
4. Divergence detection:
- Coverage gap: missing_requirements non-empty -> High severity
- High risk: risk_level is high or critical -> High severity
- Low rating: any perspective rating <= 2 -> Medium severity
- Rating spread: max - min >= 3 -> Medium severity
5. Consensus determination:
- No high-severity divergences AND average rating >= 3.0 -> consensus_reached
- Otherwise -> consensus_blocked
6. Synthesize:
- Convergent themes (agreed by 2+ perspectives)
- Divergent views (conflicting assessments)
- Coverage gaps
- Action items from suggestions
7. Write discussion record to: <session-folder>/discussions/<round-id>-discussion.md
### Discussion Record Format
# Discussion Record: <round-id>
**Artifact**: <artifact-path>
**Perspectives**: <list>
**Consensus**: reached / blocked
**Average Rating**: <avg>/5
## Convergent Themes
- <theme>
## Divergent Views
- **<topic>** (<severity>): <description>
## Action Items
1. <item>
## Ratings
| Perspective | Rating |
|-------------|--------|
| <name> | <n>/5 |
### Return Value
**When consensus_reached**:
Return a summary string with:
- Verdict: consensus_reached
- Average rating
- Key action items (top 3)
- Discussion record path
**When consensus_blocked**:
Return a structured summary with:
- Verdict: consensus_blocked
- Severity: HIGH | MEDIUM | LOW
- HIGH: any rating <= 2, critical risk identified, or missing_requirements non-empty
- MEDIUM: rating spread >= 3, or single perspective rated <= 2 with others >= 3
- LOW: minor suggestions only, all ratings >= 3 but divergent views exist
- Average rating
- Divergence summary: top 3 divergent points with perspective attribution
- Action items: prioritized list of required changes
- Recommendation: revise | proceed-with-caution | escalate
- Discussion record path
### Error Handling
- Single CLI fails -> fallback to direct Claude analysis for that perspective
- All CLI fail -> generate basic discussion from direct artifact reading
- Artifact not found -> return error immediately`
})
```
## Round Configuration
| Round | Artifact | Perspectives | Calling Role |
|-------|----------|-------------|-------------|
| DISCUSS-001 | spec/discovery-context.json | product, risk, coverage | analyst |
| DISCUSS-002 | spec/product-brief.md | product, technical, quality, coverage | writer |
| DISCUSS-003 | spec/requirements/_index.md | quality, product, coverage | writer |
| DISCUSS-004 | spec/architecture/_index.md | technical, risk | writer |
| DISCUSS-005 | spec/epics/_index.md | product, technical, quality, coverage | writer |
| DISCUSS-006 | spec/readiness-report.md | all 5 | reviewer |
## Integration with Calling Role
The calling role is responsible for:
1. **Before calling**: Complete primary artifact output
2. **Calling**: Invoke discuss subagent with correct round config
3. **After calling**:
| Verdict | Severity | Role Action |
|---------|----------|-------------|
| consensus_reached | - | Include action items in Phase 5 report, proceed normally |
| consensus_blocked | HIGH | Include divergence details in Phase 5 SendMessage with structured format (see below). **Do NOT self-revise** -- coordinator decides. |
| consensus_blocked | MEDIUM | Include warning in Phase 5 SendMessage. Proceed to Phase 5 normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. Proceed normally. |
**SendMessage format for consensus_blocked (HIGH or MEDIUM)**:
```
[<role>] <task-id> complete. Discuss <round-id>: consensus_blocked (severity=<severity>)
Divergences: <top-3-divergent-points>
Action items: <prioritized-items>
Recommendation: <revise|proceed-with-caution|escalate>
Artifact: <artifact-path>
Discussion: <discussion-record-path>
```
The coordinator receives this and routes per severity (see monitor.md Consensus-Blocked Handling):
- HIGH -> creates revision task (max 1) or pauses for user
- MEDIUM -> proceeds with warning logged to wisdom/issues.md
- DISCUSS-006 HIGH -> always pauses for user decision (final sign-off gate)
## Comparison with v3
| Aspect | v3 (discussant role) | v4 (discuss subagent) |
|--------|---------------------|----------------------|
| Spawn | Full general-purpose agent | Inline subagent call |
| Skill load | Reads SKILL.md + role.md | None (prompt contains all logic) |
| Task discovery | TaskList + TaskGet + TaskUpdate | None (called with context) |
| Report overhead | team_msg + SendMessage + TaskUpdate | Return value to caller |
| Total overhead | ~25-45s framework | ~5s call overhead |
| Pipeline beat | 1 beat per discuss round | 0 additional beats |

View File

@@ -0,0 +1,62 @@
# Doc Generation Subagent
文档生成执行引擎。由 writer 主 agent 通过 Inner Loop 调用。
负责 CLI 多视角分析 + 模板填充 + 文件写入。
## Design Rationale
从 v4.0 的 writer 内联 CLI 执行,改为 subagent 隔离调用。
好处CLI 调用的大量 token 消耗不污染 writer 主 agent 上下文,
writer 只拿到压缩摘要,可在多任务间保持上下文连续。
## Invocation
```
Task({
subagent_type: "universal-executor",
run_in_background: false,
description: "Generate <doc-type>",
prompt: `## Document Generation: <doc-type>
### Session
- Folder: <session-folder>
- Spec config: <spec-config-path>
### Document Config
- Type: <product-brief | requirements | architecture | epics>
- Template: <template-path>
- Output: <output-path>
- Prior discussion: <discussion-file or "none">
### Writer Accumulator (prior decisions)
<JSON array of prior task summaries>
### Execution Strategy
<从 generate-doc.md 对应 doc-type 段落加载>
### Output Requirements
1. Write document to <output-path> (follow template + document-standards.md)
2. Return JSON summary:
{
"artifact_path": "<path>",
"summary": "<100-200字>",
"key_decisions": [],
"sections_generated": [],
"cross_references": [],
"warnings": []
}`
})
```
## Doc Type Strategies
(直接引用 generate-doc.md 的 DRAFT-001/002/003/004 策略,不重复)
See: roles/writer/commands/generate-doc.md
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI 工具失败 | fallback chain: gemini → codex → claude |
| Template 不存在 | 返回错误 JSON |
| Prior doc 不存在 | 返回错误 JSONwriter 决定是否继续 |

View File

@@ -0,0 +1,172 @@
# Explore Subagent
Shared codebase exploration utility with centralized caching. Callable by any role needing code context. Replaces v3's standalone explorer role.
## Design Rationale
In v3, exploration happened in 3 separate places:
- `analyst` Phase 3: ACE semantic search for architecture patterns
- `planner` Phase 2: multi-angle cli-explore-agent
- `explorer` role: standalone service with full spawn cycle
Results were scattered across different directories and never shared. In v4, all exploration routes through this subagent with a **unified cache** in `explorations/`.
## Invocation
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: `Explore codebase for: <query>
Focus angle: <angle>
Keywords: <keyword-list>
Session folder: <session-folder>
## Cache Check
1. Read <session-folder>/explorations/cache-index.json (if exists)
2. Look for entry with matching angle
3. If found AND file exists -> read cached result, return summary
4. If not found -> proceed to exploration
## Exploration
<angle-specific-focus-from-table-below>
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
## Output Schema
{
"angle": "<angle>",
"query": "<query>",
"relevant_files": [
{ "path": "...", "rationale": "...", "role": "...", "discovery_source": "...", "key_symbols": [] }
],
"patterns": [],
"dependencies": [],
"external_refs": [],
"_metadata": { "created_by": "<calling-role>", "timestamp": "...", "cache_key": "..." }
}
Return summary: file count, pattern count, top 5 files, output path`
})
```
## Cache Mechanism
### Cache Index Schema
`<session-folder>/explorations/cache-index.json`:
```json
{
"entries": [
{
"angle": "architecture",
"keywords": ["auth", "middleware"],
"file": "explore-architecture.json",
"created_by": "analyst",
"created_at": "2026-02-27T10:00:00Z",
"file_count": 15
}
]
}
```
### Cache Lookup Rules
| Condition | Action |
|-----------|--------|
| Exact angle match exists | Return cached result |
| No match | Execute exploration, cache result |
| Cache file missing but index has entry | Remove stale entry, re-explore |
### Cache Invalidation
Cache is session-scoped. No explicit invalidation needed -- each session starts fresh. If a role suspects stale data, it can pass `force_refresh: true` in the prompt to bypass cache.
## Angle Focus Guide
| Angle | Focus Points | Typical Caller |
|-------|-------------|----------------|
| architecture | Layer boundaries, design patterns, component responsibilities, ADRs | analyst, planner |
| dependencies | Import chains, external libraries, circular dependencies, shared utilities | planner |
| modularity | Module interfaces, separation of concerns, extraction opportunities | planner |
| integration-points | API endpoints, data flow between modules, event systems | analyst, planner |
| security | Auth/authz logic, input validation, sensitive data handling, middleware | planner |
| auth-patterns | Auth flows, session management, token validation, permissions | planner |
| dataflow | Data transformations, state propagation, validation points | planner |
| performance | Bottlenecks, N+1 queries, blocking operations, algorithm complexity | planner |
| error-handling | Try-catch blocks, error propagation, recovery strategies, logging | planner |
| patterns | Code conventions, design patterns, naming conventions, best practices | analyst, planner |
| testing | Test files, coverage gaps, test patterns, mocking strategies | planner |
| general | Broad semantic search for topic-related code | analyst |
## Exploration Strategies
### Low Complexity (direct search)
For simple queries, use ACE semantic search:
```
mcp__ace-tool__search_context(project_root_path="<project-root>", query="<query>")
```
ACE failure fallback: `rg -l '<keywords>' --type ts`
### Medium/High Complexity (multi-angle)
For complex queries, call cli-explore-agent per angle. The calling role determines complexity and selects angles (see planner's `commands/explore.md`).
## Search Tool Priority
| Tool | Priority | Use Case |
|------|----------|----------|
| mcp__ace-tool__search_context | P0 | Semantic search |
| Grep / Glob | P1 | Pattern matching |
| cli-explore-agent | Deep | Multi-angle exploration |
| WebSearch | P3 | External docs |
## Integration with Roles
### analyst (RESEARCH-001)
```
# After seed analysis, explore codebase context
Task({
subagent_type: "cli-explore-agent",
description: "Explore general context",
prompt: "Explore codebase for: <topic>\nFocus angle: general\n..."
})
# Result feeds into discovery-context.json
```
### planner (PLAN-001)
```
# Multi-angle exploration before plan generation
for angle in selected_angles:
Task({
subagent_type: "cli-explore-agent",
description: "Explore <angle>",
prompt: "Explore codebase for: <task>\nFocus angle: <angle>\n..."
})
# Explorations manifest built from cache-index.json
```
### Any role needing context
Any role can call explore subagent when needing codebase context for better decisions.
## Comparison with v3
| Aspect | v3 (explorer role) | v4 (explore subagent) |
|--------|-------------------|----------------------|
| Identity | Full team member | Utility subagent |
| Task creation | Coordinator creates EXPLORE-* tasks | No tasks, direct call |
| Spawn overhead | Full agent lifecycle | Subagent call (~5s) |
| Result sharing | Isolated in explorations/ | Shared cache with index |
| Caller | Only via coordinator dispatch | Any role directly |
| Duplication | analyst + planner + explorer all explore | Single cached path |

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 |