feat: Add Role Analysis Reviewer Agent and validation template

- Introduced Role Analysis Reviewer Agent to validate role analysis outputs against templates and quality standards.
- Created a detailed validation ruleset for the system-architect role, including mandatory and recommended sections.
- Added JSON validation report structure for output.
- Implemented execution command for validation process.

test: Add UX tests for HookCard component

- Created comprehensive tests for HookCard component, focusing on delete confirmation UX pattern.
- Verified confirmation dialog appearance, deletion functionality, and button interactions.
- Ensured proper handling of state updates and visual feedback for enabled/disabled status.

test: Add UX tests for ThemeSelector component

- Developed tests for ThemeSelector component, emphasizing delete confirmation UX pattern.
- Validated confirmation dialog display, deletion actions, and toast notifications for undo functionality.
- Ensured proper management of theme slots and state updates.

feat: Implement useDebounce hook

- Added useDebounce hook to delay expensive computations or API calls, enhancing performance.

feat: Create System Architect Analysis Template

- Developed a comprehensive template for system architect role analysis, covering required sections such as architecture overview, data model, state machine, error handling strategy, observability requirements, configuration model, and boundary scenarios.
- Included examples and templates for each section to guide users in producing SPEC.md-level precision modeling.
This commit is contained in:
catlog22
2026-03-05 19:58:10 +08:00
parent bc7a556985
commit 3fd55ebd4b
55 changed files with 4262 additions and 1138 deletions

View File

@@ -6,440 +6,218 @@ allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), Task
# Team Lifecycle v3
Enhanced lifecycle: specification → implementation → testing → review with parallel execution, conditional routing, and dynamic specialist role injection. Built on **team-worker agent architecture** with **artifact contracts** and **automatic discovery**.
Enhanced lifecycle: specification → implementation → testing → review with parallel execution, conditional routing, and dynamic specialist role injection.
## Purpose
## Architecture
Team Lifecycle v3 orchestrates multi-agent software development workflows from initial requirements through implementation, testing, and review. It automatically coordinates specialized agents, manages artifact dependencies, validates quality gates, and dynamically injects expert roles based on task complexity.
**Key Capabilities**:
- Parallel execution of independent tasks
- Dynamic specialist role injection (security, performance, data, devops, ML)
- Artifact-based validation gating
- Conditional routing based on complexity assessment
- Priority-based task scheduling (P0/P1/P2)
- Quality checkpoints with user feedback loops
## Problem Statement
Complex software development tasks require diverse expertise—security audits, performance optimization, data pipeline design, DevOps configuration, and ML model integration. Coordinating multiple specialized agents manually is error-prone, inefficient, and difficult to scale. Developers face several challenges:
1. **Manual Coordination Overhead**: Tracking dependencies between agents, ensuring artifacts are validated before downstream work begins, and managing parallel execution requires constant human oversight.
2. **Expertise Gaps**: Not all tasks require all specialists. Injecting the right expert roles at the right time based on task complexity and keywords is a manual, subjective process prone to under- or over-staffing.
3. **Quality Assurance Bottlenecks**: Without automated quality gates and validation checkpoints, defects propagate downstream, requiring expensive rework.
4. **Lack of Observability**: Understanding where a multi-agent workflow is stalled, which artifacts are blocking progress, and what actions are needed requires manual inspection of scattered state.
Team Lifecycle v3 solves these problems by providing an event-driven orchestration system that automatically manages agent coordination, artifact validation, specialist injection, and quality checkpoints—turning multi-agent workflows into a repeatable, observable, and scalable process.
## Goals
- **Automated Agent Coordination**: Spawn workers based on task dependencies, manage parallel execution, and handle completion callbacks without manual intervention.
- **Artifact-Based Validation Gating**: Block downstream work until upstream artifacts pass validation, preventing defect propagation.
- **Dynamic Specialist Injection**: Analyze task descriptions and complexity to automatically inject expert roles (security, performance, data, devops, ML) when needed.
- **Conditional Routing**: Route tasks to appropriate implementation strategies (direct, orchestrated, architecture-first) based on quantifiable complexity assessment.
- **Priority-Based Scheduling**: Execute critical-path tasks (P0) before dependent tasks (P1/P2), optimizing workflow throughput.
- **Quality Checkpoints**: Pause at key milestones for user review, with actionable commands (resume, improve, revise, recheck) to maintain quality.
- **Session Persistence**: Support pause/resume across process restarts, preserving artifact registry and task state.
- **Observability**: Provide clear status reporting, task state visibility, and actionable error messages.
## Non-Goals
- **General-Purpose Workflow Engine**: Team Lifecycle v3 is specialized for software development workflows with agent coordination. It is not a generic DAG executor or distributed job scheduler.
- **Project Management Tool**: The system does not manage backlogs, sprints, or roadmaps. It executes individual tasks with clear requirements.
- **Prescriptive Agent Implementations**: The skill defines role specifications and contracts but does not mandate specific agent implementations or tools.
- **Ticket/PR Management**: State transitions, comments, and PR creation are the responsibility of individual agents using their own tools, not the orchestrator.
- **Approval/Sandbox Policies**: The skill does not enforce specific approval workflows or sandboxing. Implementations may add these based on their trust model.
- **Real-Time Collaboration**: The system is event-driven with asynchronous agent execution, not a real-time collaborative editing environment.
## Mandatory Reading
Before using this skill, read these documents to understand the foundational concepts:
| Document | Purpose | Priority |
|----------|---------|----------|
| [specs/core-concepts.md](specs/core-concepts.md) | Foundational principles: team-worker architecture, artifact contracts, quality gating, dynamic role injection, priority scheduling | **P0 - Critical** |
| [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) | Artifact manifest schema and validation rules | **P0 - Critical** |
| [specs/execution-flow.md](specs/execution-flow.md) | End-to-end execution walkthrough with pipeline definitions | **P1 - High** |
## Documentation Structure
This skill is organized into the following directories:
### `/roles` - Agent Role Specifications
- **`coordinator/`**: Orchestrator agent that manages workflow, task dependencies, and role injection
- `role.md`: Coordinator specification
- `commands/`: User command handlers (dispatch, monitor)
- **`pipeline/`**: Core pipeline roles (always present)
- `analyst.md`, `writer.md`, `planner.md`, `executor.md`, `tester.md`, `reviewer.md`
- `architect.md`, `fe-developer.md`, `fe-qa.md` (consulting roles)
- **`specialists/`**: Specialist roles (dynamically injected)
- `orchestrator.role.md`, `security-expert.role.md`, `performance-optimizer.role.md`
- `data-engineer.role.md`, `devops-engineer.role.md`, `ml-engineer.role.md`
### `/specs` - Specifications and Standards
- **`core-concepts.md`**: Foundational principles (mandatory reading)
- **`execution-flow.md`**: End-to-end execution walkthrough
- **`artifact-contract-spec.md`**: Artifact manifest schema
- **`quality-gates.md`**: Quality validation criteria
- **`document-standards.md`**: Document formatting standards
- **`team-config.json`**: Role registry and pipeline definitions
### `/templates` - Document Templates
- `product-brief.md`: DRAFT-001 template
- `requirements-prd.md`: DRAFT-002 template
- `architecture-doc.md`: DRAFT-003 template
- `epics-template.md`: DRAFT-004 template
### `/subagents` - Utility Subagents
- `discuss-subagent.md`: 3-round discussion protocol
- `explorer-subagent.md`: Shared exploration with cache
- `doc-generator-subagent.md`: Template-based doc generation
## Quick Start
### Basic Usage
```
+---------------------------------------------------+
| Skill(skill="team-lifecycle-v3") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (inline)
Phase 0-5 orchestration
+ Dynamic role injection
+ Priority scheduling
+ Artifact registry
|
+----+-----+-------+-------+-------+-------+-------+
v v v v v v v v
[team-worker agents, each loaded with a role-spec]
Core Pipeline (9 roles from v2):
analyst writer planner executor tester reviewer
architect fe-developer fe-qa
Specialist Roles (6 new roles, injected on-demand):
orchestrator security-expert performance-optimizer
data-engineer devops-engineer ml-engineer
Utility Members (3):
[explorer] [discussant] [doc-generator]
Skill(skill="team-lifecycle-v3", args="<task description>")
```
## Role Router
Coordinator-only. Workers spawned as `team-worker` agents.
### Role Registry
| Role | Spec | Task Prefix | Type | Inner Loop | Injection |
|------|------|-------------|------|------------|-----------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | Always |
| analyst | [role-specs/analyst.md](role-specs/analyst.md) | RESEARCH-* | pipeline | false | Always |
| writer | [role-specs/writer.md](role-specs/writer.md) | DRAFT-* | pipeline | true | Always |
| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true | Always |
| executor | [role-specs/executor.md](role-specs/executor.md) | IMPL-* | pipeline | true | Always |
| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | pipeline | false | Always |
| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* + QUALITY-* + IMPROVE-* | pipeline | false | Always |
| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | consulting | false | High complexity |
| fe-developer | [role-specs/fe-developer.md](role-specs/fe-developer.md) | DEV-FE-* | frontend | false | Frontend tasks |
| fe-qa | [role-specs/fe-qa.md](role-specs/fe-qa.md) | QA-FE-* | frontend | false | Frontend tasks |
| **orchestrator** | [role-specs/orchestrator.md](role-specs/orchestrator.md) | ORCH-* | specialist | false | **Multi-module** |
| **security-expert** | [role-specs/security-expert.md](role-specs/security-expert.md) | SECURITY-* | specialist | false | **security keywords** |
| **performance-optimizer** | [role-specs/performance-optimizer.md](role-specs/performance-optimizer.md) | PERF-* | specialist | false | **performance keywords** |
| **data-engineer** | [role-specs/data-engineer.md](role-specs/data-engineer.md) | DATA-* | specialist | false | **data keywords** |
| **devops-engineer** | [role-specs/devops-engineer.md](role-specs/devops-engineer.md) | DEVOPS-* | specialist | false | **devops keywords** |
| **ml-engineer** | [role-specs/ml-engineer.md](role-specs/ml-engineer.md) | ML-* | specialist | false | **ML keywords** |
### CLI Tool Usage in Workers
Workers use CLI tools for complex analysis:
| Capability | CLI Command | Used By |
|------------|-------------|---------|
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect |
| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer |
| Document generation | `ccw cli --tool gemini --mode write` | writer |
### Coordinator-Only Utility Members
**⚠️ COORDINATOR ONLY**: Utility members can only be spawned by Coordinator.
Workers CANNOT call Agent() to spawn utility members.
Coordinator can spawn utility members for team-level orchestration:
| Utility Member | Purpose | When | Callable By |
|----------------|---------|------|-------------|
| explorer | Parallel multi-angle exploration | High complexity analysis | **Coordinator only** |
| discussant | Aggregate multi-CLI critique | Critical decision points | **Coordinator only** |
### Worker Alternatives
Workers needing similar capabilities must use CLI tools:
| Capability | CLI Command | Example |
|------------|-------------|---------|
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | Explore architecture patterns |
| Multi-perspective critique | Parallel CLI calls | Security + performance + quality reviews |
| Document generation | `ccw cli --tool gemini --mode write` | Generate PRD from research |
### Dynamic Role Injection
Coordinator analyzes task description and plan complexity to inject specialist roles at runtime:
| Trigger | Injected Role | Injection Point |
|---------|---------------|-----------------|
| Keywords: security, vulnerability, OWASP | security-expert | After PLAN-001 |
| Keywords: performance, optimization, bottleneck | performance-optimizer | After IMPL-* |
| Keywords: data, pipeline, ETL, schema | data-engineer | Parallel with IMPL-* |
| Keywords: devops, CI/CD, deployment, docker | devops-engineer | After IMPL-* |
| Keywords: ML, model, training, inference | ml-engineer | Parallel with IMPL-* |
| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* |
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md`.
### Orchestration Mode
**Invocation**: `Skill(skill="team-lifecycle-v3", args="task description")`
**Lifecycle**:
**Example**:
```
User provides task description
-> coordinator Phase 1-3: clarify -> TeamCreate -> analyze complexity -> inject roles -> create task chain
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances
-> Loop until pipeline complete -> Phase 5 report + completion action
Skill(skill="team-lifecycle-v3", args="Implement user authentication with OAuth2")
```
**User Commands**:
### Execution Flow
1. **User provides task description** → Coordinator clarifies requirements
2. **Coordinator creates team** → TeamCreate with session folder
3. **Coordinator analyzes complexity** → Injects specialist roles if needed
4. **Coordinator creates task chain** → Based on pipeline selection (spec-only, impl-only, full-lifecycle)
5. **Coordinator spawns first batch** → Workers execute in background
6. **Workers report completion** → SendMessage callback to coordinator
7. **Coordinator advances pipeline** → Spawns next ready tasks
8. **Quality checkpoints** → User can review, improve, or revise
9. **Coordinator generates report** → Final summary and completion action
### User Commands
During execution, you can use these commands:
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream |
| `feedback <text>` | Analyze feedback, create targeted revision |
| `recheck` | Re-run QUALITY-001 quality check |
| `improve [dimension]` | Auto-improve weakest dimension |
| `check` / `status` | View current execution status |
| `resume` / `continue` | Advance to next step |
| `revise <TASK-ID> [feedback]` | Revise specific task with feedback |
| `feedback <text>` | Provide feedback for targeted revision |
| `recheck` | Re-run quality check |
| `improve [dimension]` | Auto-improve weakest quality dimension |
---
## Pipeline Options
## Coordinator Spawn Template
The coordinator selects the appropriate pipeline based on task requirements:
### Spec-only Pipeline (6 tasks)
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-lifecycle-v3/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
priority: <P0|P1|P2>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001
```
Use for: Documentation, requirements gathering, design work
---
## Pipeline Definitions
### Spec-only (6 tasks, 3 discuss)
### Impl-only Pipeline (4 tasks)
```
RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3)
PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001
```
Use for: Quick implementations with clear requirements
### Impl-only (4 tasks)
### Full-lifecycle Pipeline (10 tasks)
```
PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001
[Spec pipeline] → PLAN-001 IMPL-001 TEST-001 + REVIEW-001
```
Use for: Complete feature development from requirements to implementation
### Full-lifecycle (10 tasks, v2 compatible)
## Advanced Features
```
[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001
```
### Dynamic Role Injection
### Enhanced Parallel Pipeline (v3 NEW)
Specialist roles are automatically injected based on keywords in task description:
```
RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3)
|
v
PLAN-001 (complexity assessment)
|
+---------------+---------------+
| | |
Low: IMPL-001 Med: ORCH-001 High: ARCH-001
| -> IMPL-* -> ORCH-001
| -> IMPL-*
v
IMPL-001 || DEV-FE-001 (parallel, P0)
|
v
TEST-001 || QA-FE-001 (parallel, P1)
|
v
REVIEW-001 (P1)
```
- **security**, **vulnerability**, **OWASP**`security-expert`
- **performance**, **optimization**, **bottleneck**`performance-optimizer`
- **data**, **pipeline**, **ETL**, **schema**`data-engineer`
- **devops**, **CI/CD**, **deployment**, **docker**`devops-engineer`
- **ML**, **model**, **training**, **inference**`ml-engineer`
### Conditional Routing (v3 NEW)
### Conditional Routing
PLAN-001 assesses complexity and routes accordingly:
PLAN-001 assesses complexity and routes to appropriate implementation strategy:
| Complexity | Route | Roles |
|------------|-------|-------|
| Low (1-2 modules, shallow deps) | Direct IMPL | executor |
| Medium (3-4 modules, moderate deps) | Orchestrated IMPL | orchestrator -> executor (parallel) |
| High (5+ modules, deep deps) | Architecture + Orchestrated IMPL | architect -> orchestrator -> executor (parallel) |
- **Low complexity** (1-2 modules) → Direct implementation
- **Medium complexity** (3-4 modules) → Orchestrated parallel implementation
- **High complexity** (5+ modules) → Architecture design + orchestrated implementation
### Dynamic Injection Example (v3 NEW)
### Quality Checkpoints
Task description: "Implement user authentication with OAuth2, add security audit, optimize login performance"
At key milestones, the coordinator pauses for user review:
Injected roles:
- security-expert (keyword: security, audit)
- performance-optimizer (keyword: optimize, performance)
- **Spec Phase Complete** (QUALITY-001): Review specification quality, choose to proceed, improve, or revise
- **Implementation Complete**: Review code quality and test coverage
Pipeline becomes:
```
PLAN-001 -> IMPL-001 || SECURITY-001 || PERF-001 -> TEST-001 -> REVIEW-001
```
## Troubleshooting
### Cadence Control
### Common Issues
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
| Issue | Solution |
|-------|----------|
| Pipeline stalled | Use `status` to check task states, `resume` to advance |
| Quality gate failed | Use `improve` to auto-improve or `revise <TASK-ID>` to manually fix |
| Wrong specialist injected | Provide clearer keywords in task description |
| Session lost after restart | Use session resume to restore from `.workflow/.team/TLS-*` |
```
Beat Cycle (v3 Enhanced)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check artifacts | <- v3: artifact validation
| update registry | <- v3: artifact registry
+- handleSpawnNext -+
| find ready tasks |
| priority sort | <- v3: P0/P1/P2 scheduling
| inject roles | <- v3: dynamic injection
| spawn workers ---+--> [team-worker] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor?
| --> spawn team-worker B directly
| --> log fast_advance to message bus
+- complex case? --> SendMessage to coordinator
======================================================================
```
### Checkpoints
| Trigger | Position | Behavior |
|---------|----------|----------|
| Spec->Impl transition | QUALITY-001 completed | Display checkpoint, pause for user |
| Complexity routing | PLAN-001 completed | Display routing decision, continue |
| Parallel merge | All parallel tasks complete | Validate integration, continue |
| GC loop max | QA-FE max 2 rounds | Stop iteration, report |
| Pipeline stall | No ready + no running | Report to user |
**Checkpoint Output Template** (QUALITY-001):
```
[coordinator] ══════════════════════════════════════════
[coordinator] SPEC PHASE COMPLETE
[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%)
[coordinator]
[coordinator] Dimension Scores:
[coordinator] Completeness: <bar> <n>%
[coordinator] Consistency: <bar> <n>%
[coordinator] Traceability: <bar> <n>%
[coordinator] Depth: <bar> <n>%
[coordinator] Coverage: <bar> <n>%
[coordinator]
[coordinator] Available Actions:
[coordinator] resume -> Proceed to implementation
[coordinator] improve -> Auto-improve weakest dimension
[coordinator] revise <TASK-ID> -> Revise specific document
[coordinator] recheck -> Re-run quality check
[coordinator] feedback <text> -> Inject feedback
[coordinator] ══════════════════════════════════════════
```
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Discuss | Priority |
|---------|------|-------|-------------|---------|----------|
| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | P0 |
| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate | P0 |
| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 | P0 |
| DRAFT-003 | writer | spec | DRAFT-002 | self-validate | P0 |
| DRAFT-004 | writer | spec | DRAFT-003 | self-validate | P0 |
| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 | P0 |
| PLAN-001 | planner | impl | (none or QUALITY-001) | - | P0 |
| ARCH-001 | architect | impl | PLAN-001 | - | P0 (if High complexity) |
| ORCH-001 | orchestrator | impl | PLAN-001 or ARCH-001 | - | P0 (if Med/High complexity) |
| IMPL-001 | executor | impl | PLAN-001 or ORCH-001 | - | P0 |
| DEV-FE-001 | fe-developer | impl | PLAN-001 or ORCH-001 | - | P0 (parallel with IMPL-001) |
| TEST-001 | tester | impl | IMPL-001 | - | P1 |
| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | P1 (parallel with TEST-001) |
| REVIEW-001 | reviewer | impl | IMPL-001 | - | P1 |
| SECURITY-001 | security-expert | impl | IMPL-001 | - | P0 (if injected) |
| PERF-001 | performance-optimizer | impl | IMPL-001 | - | P1 (if injected) |
| DATA-001 | data-engineer | impl | PLAN-001 | - | P0 (if injected, parallel) |
| DEVOPS-001 | devops-engineer | impl | IMPL-001 | - | P1 (if injected) |
| ML-001 | ml-engineer | impl | PLAN-001 | - | P0 (if injected, parallel) |
---
## v3 Artifact Contract
All workers generate `artifact-manifest.json` alongside deliverables for validation gating and automatic discovery.
### Manifest Schema
```json
{
"artifact_id": "string",
"creator_role": "string",
"artifact_type": "string",
"version": "string",
"path": "string",
"dependencies": ["string"],
"validation_status": "pending|passed|failed",
"validation_summary": "string",
"metadata": {
"created_at": "ISO8601 timestamp",
"task_id": "string",
"priority": "P0|P1|P2"
}
}
```
### Validation Gating
Coordinator checks `validation_status` before spawning downstream workers:
| Status | Action |
|--------|--------|
| `passed` | Spawn next worker |
| `failed` | Block spawn, trigger fix loop |
| `pending` | Wait or prompt manual validation |
### Artifact Registry
Coordinator maintains in-memory artifact registry for automatic discovery:
```json
{
"artifacts": {
"<artifact-id>": {
"manifest": { ... },
"discovered_at": "timestamp",
"consumed_by": ["<role-name>"]
}
}
}
```
Workers read `context-artifacts.json` in Phase 2 to discover upstream artifacts automatically.
---
## Session Directory
```
.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json
+-- artifact-registry.json <- v3 NEW
+-- spec/
| +-- spec-config.json
| +-- discovery-context.json
| +-- product-brief.md
| +-- requirements/
| +-- architecture/
| +-- epics/
| +-- readiness-report.md
+-- discussions/
+-- plan/
| +-- plan.json
| +-- .task/TASK-*.json
+-- explorations/
+-- artifacts/ <- v3 NEW: artifact manifests
| +-- artifact-manifest-*.json
+-- .msg/
+-- shared-memory.json
```
## Session Resume
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion
3. Audit TaskList -> reconcile session state
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team, spawn needed workers only
6. Restore artifact registry from session
7. Kick first executable task
## Shared Resources
| Resource | Path | Usage |
|----------|------|-------|
| Document Standards | [specs/document-standards.md](specs/document-standards.md) | YAML frontmatter, naming, structure |
| Quality Gates | [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gates |
| Team Config | [specs/team-config.json](specs/team-config.json) | Role registry, pipeline definitions |
| Artifact Contract | [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) | Artifact manifest schema |
| Role Library | [specs/role-library/](specs/role-library/) | Dynamic role definitions |
| Product Brief Template | [templates/product-brief.md](templates/product-brief.md) | DRAFT-001 |
| Requirements Template | [templates/requirements-prd.md](templates/requirements-prd.md) | DRAFT-002 |
| Architecture Template | [templates/architecture-doc.md](templates/architecture-doc.md) | DRAFT-003 |
| Epics Template | [templates/epics-template.md](templates/epics-template.md) | DRAFT-004 |
| Discuss Subagent | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | 3-round discuss protocol |
| Explorer Subagent | [subagents/explorer-subagent.md](subagents/explorer-subagent.md) | Shared exploration with cache |
| Doc Generator Subagent | [subagents/doc-generator-subagent.md](subagents/doc-generator-subagent.md) | Template-based doc generation |
## Error Handling
### Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown command | Error with available command list |
| Role spec file not found | Error with expected path |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Worker proceeds without discuss, logs warning |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| Artifact validation fails | Block downstream, trigger fix loop |
| Dynamic role injection fails | Log warning, continue with core roles |
| Priority conflict | P0 > P1 > P2, FIFO within same priority |
| Parallel merge timeout | Report stall, prompt user intervention |
## Reference Documents
For detailed information, see:
- [specs/core-concepts.md](specs/core-concepts.md) - Foundational principles
- [specs/execution-flow.md](specs/execution-flow.md) - Detailed execution walkthrough
- [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) - Artifact manifest specification
- [specs/quality-gates.md](specs/quality-gates.md) - Quality validation criteria
- [specs/document-standards.md](specs/document-standards.md) - Document formatting standards
- [roles/coordinator/role.md](roles/coordinator/role.md) - Coordinator specification
- [roles/README.md](roles/README.md) - Role directory guide

View File

@@ -0,0 +1,232 @@
# Role Directory Guide
This directory contains all agent role specifications for Team Lifecycle v3.
## Directory Structure
```
roles/
├── README.md # This file
├── coordinator/ # Orchestrator agent
│ ├── role.md # Coordinator specification
│ └── commands/ # User command handlers
│ ├── dispatch.md
│ └── monitor.md
├── pipeline/ # Core pipeline roles (always present)
│ ├── analyst.md # Research and discovery
│ ├── writer.md # Document drafting
│ ├── planner.md # Implementation planning
│ ├── executor.md # Code implementation
│ ├── tester.md # Test generation
│ ├── reviewer.md # Quality review
│ ├── architect.md # Architecture design (consulting)
│ ├── fe-developer.md # Frontend development (consulting)
│ └── fe-qa.md # Frontend QA (consulting)
└── specialists/ # Specialist roles (dynamically injected)
├── orchestrator.role.md # Multi-module coordination
├── security-expert.role.md # Security analysis
├── performance-optimizer.role.md # Performance optimization
├── data-engineer.role.md # Data pipeline work
├── devops-engineer.role.md # DevOps and deployment
└── ml-engineer.role.md # ML/AI implementation
```
## Role Types
### Coordinator (Orchestrator)
**Location**: `coordinator/`
**Purpose**: Manages workflow orchestration, task dependencies, role injection, and artifact registry.
**Key Responsibilities**:
- Parse user requests and clarify requirements
- Create and manage team sessions
- Analyze complexity and inject specialist roles
- Create task chains with dependencies
- Spawn workers and handle callbacks
- Validate artifacts and advance pipeline
- Display checkpoints and handle user commands
**Always Present**: Yes
**Spawned By**: Skill invocation
### Pipeline Roles (Core Team)
**Location**: `pipeline/`
**Purpose**: Execute standard development workflow tasks.
**Always Present**: Yes (based on pipeline selection)
**Spawned By**: Coordinator
#### Core Pipeline Roles
| Role | File | Purpose | Task Prefix |
|------|------|---------|-------------|
| analyst | `analyst.md` | Research and discovery | RESEARCH-* |
| writer | `writer.md` | Document drafting | DRAFT-* |
| planner | `planner.md` | Implementation planning | PLAN-* |
| executor | `executor.md` | Code implementation | IMPL-* |
| tester | `tester.md` | Test generation and execution | TEST-* |
| reviewer | `reviewer.md` | Quality review and improvement | REVIEW-*, QUALITY-*, IMPROVE-* |
#### Consulting Roles
| Role | File | Purpose | Task Prefix | Injection Trigger |
|------|------|---------|-------------|-------------------|
| architect | `architect.md` | Architecture design | ARCH-* | High complexity |
| fe-developer | `fe-developer.md` | Frontend development | DEV-FE-* | Frontend tasks |
| fe-qa | `fe-qa.md` | Frontend QA | QA-FE-* | Frontend tasks |
### Specialist Roles (Dynamic Injection)
**Location**: `specialists/`
**Purpose**: Provide expert capabilities for specific domains.
**Always Present**: No (injected based on task analysis)
**Spawned By**: Coordinator (after complexity/keyword analysis)
| Role | File | Purpose | Task Prefix | Injection Trigger |
|------|------|---------|-------------|-------------------|
| orchestrator | `orchestrator.role.md` | Multi-module coordination | ORCH-* | Medium/High complexity |
| security-expert | `security-expert.role.md` | Security analysis and audit | SECURITY-* | Keywords: security, vulnerability, OWASP, auth |
| performance-optimizer | `performance-optimizer.role.md` | Performance optimization | PERF-* | Keywords: performance, optimization, bottleneck |
| data-engineer | `data-engineer.role.md` | Data pipeline work | DATA-* | Keywords: data, pipeline, ETL, schema |
| devops-engineer | `devops-engineer.role.md` | DevOps and deployment | DEVOPS-* | Keywords: devops, CI/CD, deployment, docker |
| ml-engineer | `ml-engineer.role.md` | ML/AI implementation | ML-* | Keywords: ML, model, training, inference |
## Role Specification Format
All role specifications follow this structure:
```markdown
---
role: <role-name>
type: <coordinator|pipeline|specialist>
task_prefix: <TASK-PREFIX>
priority: <P0|P1|P2>
injection_trigger: <always|complexity|keywords>
---
# Role: <Role Name>
## Purpose
Brief description of role purpose.
## Responsibilities
- Responsibility 1
- Responsibility 2
## Phase Execution
### Phase 1: Task Discovery
...
### Phase 2: Context Gathering
...
### Phase 3: Domain Work
...
### Phase 4: Artifact Generation
...
### Phase 5: Reporting
...
## Tools & Capabilities
- Tool 1
- Tool 2
## Artifact Contract
Expected artifacts and manifest schema.
```
## Worker Execution Model
All workers (pipeline and specialist roles) follow the **5-phase execution model**:
1. **Phase 1: Task Discovery** - Read task metadata, understand requirements
2. **Phase 2: Context Gathering** - Discover upstream artifacts, gather context
3. **Phase 3: Domain Work** - Execute role-specific work
4. **Phase 4: Artifact Generation** - Generate deliverables with manifest
5. **Phase 5: Reporting** - Report completion to coordinator
## CLI Tool Integration
Workers can use CLI tools for complex analysis:
| Capability | CLI Command | Used By |
|------------|-------------|---------|
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect |
| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer |
| Document generation | `ccw cli --tool gemini --mode write` | writer |
**Note**: Workers CANNOT spawn utility members (explorer, discussant). Only the coordinator can spawn utility members.
## Utility Members (Coordinator-Only)
Utility members are NOT roles but specialized subagents that can only be spawned by the coordinator:
| Utility | Purpose | Callable By |
|---------|---------|-------------|
| explorer | Parallel multi-angle exploration | Coordinator only |
| discussant | Aggregate multi-CLI critique | Coordinator only |
| doc-generator | Template-based doc generation | Coordinator only |
**Location**: `../subagents/` (not in roles directory)
## Adding New Roles
To add a new specialist role:
1. Create role specification file in `specialists/` directory
2. Follow the role specification format
3. Define injection trigger (keywords or complexity)
4. Update `../specs/team-config.json` role registry
5. Update coordinator's role injection logic
6. Test with sample task descriptions
## Role Selection Logic
### Pipeline Selection
Coordinator selects pipeline based on user requirements:
- **Spec-only**: Documentation, requirements, design work
- **Impl-only**: Quick implementations with clear requirements
- **Full-lifecycle**: Complete feature development
### Specialist Injection
Coordinator analyzes task description for:
1. **Keywords**: Specific domain terms (security, performance, data, etc.)
2. **Complexity**: Module count, dependency depth
3. **Explicit requests**: User mentions specific expertise needed
### Conditional Routing
PLAN-001 assesses complexity and routes to appropriate implementation strategy:
- **Low complexity** → Direct implementation (executor only)
- **Medium complexity** → Orchestrated implementation (orchestrator + parallel executors)
- **High complexity** → Architecture + orchestrated implementation (architect + orchestrator + parallel executors)
## Reference Documents
For detailed information, see:
- [../specs/core-concepts.md](../specs/core-concepts.md) - Foundational principles
- [../specs/execution-flow.md](../specs/execution-flow.md) - Execution walkthrough
- [../specs/artifact-contract-spec.md](../specs/artifact-contract-spec.md) - Artifact manifest specification
- [coordinator/role.md](coordinator/role.md) - Coordinator specification

View File

@@ -0,0 +1,61 @@
# Specifications Directory
This directory contains all specification documents for Team Lifecycle v3.
## Core Specifications (Mandatory Reading)
| Document | Purpose | When to Read |
|----------|---------|--------------|
| [core-concepts.md](core-concepts.md) | Foundational principles: team-worker architecture, artifact contracts, quality gating, dynamic role injection, priority scheduling | **Before using the skill** - P0 Critical |
| [domain-model.md](domain-model.md) | Core entity definitions (Task, Artifact, Role, Session) with JSON schemas, relationships, and state machines | **Before using the skill** - P0 Critical |
| [artifact-contract-spec.md](artifact-contract-spec.md) | Artifact manifest schema and validation rules | **Before using the skill** - P0 Critical |
| [execution-flow.md](execution-flow.md) | End-to-end execution walkthrough with pipeline definitions, beat cycle, conditional routing, and examples | **When understanding workflow** - P1 High |
## Supporting Specifications
| Document | Purpose | When to Read |
|----------|---------|--------------|
| [quality-gates.md](quality-gates.md) | Quality validation criteria for each phase | When reviewing quality checkpoints |
| [document-standards.md](document-standards.md) | Document formatting standards (YAML frontmatter, naming conventions) | When creating new documents |
| [team-config.json](team-config.json) | Role registry and pipeline definitions (machine-readable) | When modifying role configuration |
## Document Hierarchy
```
specs/
├── README.md # This file
├── core-concepts.md # P0 - Foundational principles
├── artifact-contract-spec.md # P0 - Artifact manifest schema
├── execution-flow.md # P1 - Execution walkthrough
├── quality-gates.md # Supporting - Quality criteria
├── document-standards.md # Supporting - Formatting standards
└── team-config.json # Supporting - Role registry
```
## Reading Path
### For New Users
1. **Start here**: [core-concepts.md](core-concepts.md) - Understand the system architecture and principles
2. **Then read**: [artifact-contract-spec.md](artifact-contract-spec.md) - Learn how artifacts flow between agents
3. **Finally read**: [execution-flow.md](execution-flow.md) - See how tasks execute end-to-end
### For Developers Extending the Skill
1. Read all core specifications above
2. Review [quality-gates.md](quality-gates.md) for validation logic
3. Review [document-standards.md](document-standards.md) for formatting rules
4. Modify [team-config.json](team-config.json) for role changes
### For Troubleshooting
1. Check [execution-flow.md](execution-flow.md) for pipeline definitions
2. Check [artifact-contract-spec.md](artifact-contract-spec.md) for validation rules
3. Check [quality-gates.md](quality-gates.md) for quality criteria
## Cross-References
- **Role specifications**: See [../roles/README.md](../roles/README.md)
- **Templates**: See [../templates/README.md](../templates/README.md)
- **Subagents**: See [../subagents/](../subagents/)
- **Main entry**: See [../SKILL.md](../SKILL.md)

View File

@@ -0,0 +1,264 @@
# Core Concepts
## Overview
Team Lifecycle v3 is an enhanced multi-agent orchestration system that manages the complete software development lifecycle from specification to implementation, testing, and review. It uses a **team-worker agent architecture** with **artifact contracts** and **automatic discovery** to coordinate parallel execution across specialized roles.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-lifecycle-v3") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (inline)
Phase 0-5 orchestration
+ Dynamic role injection
+ Priority scheduling
+ Artifact registry
|
+----+-----+-------+-------+-------+-------+-------+
v v v v v v v v
[team-worker agents, each loaded with a role-spec]
Core Pipeline (9 roles from v2):
analyst writer planner executor tester reviewer
architect fe-developer fe-qa
Specialist Roles (6 new roles, injected on-demand):
orchestrator security-expert performance-optimizer
data-engineer devops-engineer ml-engineer
Utility Members (3):
[explorer] [discussant] [doc-generator]
```
## Foundational Principles
### 1. Team-Worker Agent Architecture
The system uses a **coordinator-worker pattern**:
- **Coordinator**: Orchestrates the workflow, manages task dependencies, injects specialist roles dynamically, and maintains the artifact registry
- **Workers**: Specialized agents (analyst, writer, planner, executor, etc.) that execute specific tasks and produce artifacts
- **Communication**: Workers report completion via `SendMessage` callbacks to the coordinator
**Key Benefits**:
- Clear separation of concerns (orchestration vs execution)
- Parallel execution of independent tasks
- Dynamic scaling with specialist role injection
### 2. Artifact Contracts
All workers generate **artifact manifests** alongside their deliverables for validation gating and automatic discovery.
**Manifest Schema**:
```json
{
"artifact_id": "string",
"creator_role": "string",
"artifact_type": "string",
"version": "string",
"path": "string",
"dependencies": ["string"],
"validation_status": "pending|passed|failed",
"validation_summary": "string",
"metadata": {
"created_at": "ISO8601 timestamp",
"task_id": "string",
"priority": "P0|P1|P2"
}
}
```
**Validation Gating**:
- Coordinator checks `validation_status` before spawning downstream workers
- `passed` → spawn next worker
- `failed` → block spawn, trigger fix loop
- `pending` → wait or prompt manual validation
**Automatic Discovery**:
- Coordinator maintains in-memory artifact registry
- Workers read `context-artifacts.json` in Phase 2 to discover upstream artifacts automatically
- No manual artifact passing required
### 3. Quality Gating
Quality gates ensure artifact quality before proceeding to next phase:
- **Spec Phase Gate** (QUALITY-001): Multi-dimensional quality check
- Completeness, Consistency, Traceability, Depth, Coverage
- Checkpoint with user actions: resume, improve, revise, recheck, feedback
- **Implementation Gate**: Test coverage and review approval
- **Per-Artifact Validation**: Manifest-based validation status
### 4. Dynamic Role Injection
Coordinator analyzes task description and plan complexity to inject specialist roles at runtime:
| Trigger | Injected Role | Injection Point |
|---------|---------------|-----------------|
| Keywords: security, vulnerability, OWASP | security-expert | After PLAN-001 |
| Keywords: performance, optimization, bottleneck | performance-optimizer | After IMPL-* |
| Keywords: data, pipeline, ETL, schema | data-engineer | Parallel with IMPL-* |
| Keywords: devops, CI/CD, deployment, docker | devops-engineer | After IMPL-* |
| Keywords: ML, model, training, inference | ml-engineer | Parallel with IMPL-* |
| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* |
**Benefits**:
- Automatic expertise injection based on task requirements
- No manual role configuration needed
- Scales from simple to complex tasks
### 5. Priority Scheduling
Tasks are assigned priorities for execution ordering:
- **P0**: Critical path tasks (RESEARCH, DRAFT, PLAN, core IMPL)
- **P1**: Dependent tasks (TEST, REVIEW, QA)
- **P2**: Optional enhancements
**Scheduling Rules**:
- P0 > P1 > P2
- FIFO within same priority
- Parallel execution for independent tasks at same priority
### 6. Conditional Routing
PLAN-001 assesses complexity and routes accordingly:
| Complexity | Route | Roles |
|------------|-------|-------|
| Low (1-2 modules, shallow deps) | Direct IMPL | executor |
| Medium (3-4 modules, moderate deps) | Orchestrated IMPL | orchestrator → executor (parallel) |
| High (5+ modules, deep deps) | Architecture + Orchestrated IMPL | architect → orchestrator → executor (parallel) |
### 7. Beat-Based Cadence
Event-driven execution model where each beat = coordinator wake → process → spawn → STOP:
```
Beat Cycle (v3 Enhanced)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check artifacts | <- v3: artifact validation
| update registry | <- v3: artifact registry
+- handleSpawnNext -+
| find ready tasks |
| priority sort | <- v3: P0/P1/P2 scheduling
| inject roles | <- v3: dynamic injection
| spawn workers ---+--> [team-worker] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
```
**Fast-Advance Optimization**:
- Workers can spawn simple linear successors directly
- Skips coordinator for simple cases
- Logs fast_advance to message bus
## Role Types
### Core Pipeline Roles (Always Present)
| Role | Purpose | Task Prefix |
|------|---------|-------------|
| analyst | Research and discovery | RESEARCH-* |
| writer | Document drafting | DRAFT-* |
| planner | Implementation planning | PLAN-* |
| executor | Code implementation | IMPL-* |
| tester | Test generation and execution | TEST-* |
| reviewer | Quality review and improvement | REVIEW-*, QUALITY-*, IMPROVE-* |
### Consulting Roles (High Complexity)
| Role | Purpose | Task Prefix |
|------|---------|-------------|
| architect | Architecture design | ARCH-* |
| fe-developer | Frontend development | DEV-FE-* |
| fe-qa | Frontend QA | QA-FE-* |
### Specialist Roles (Dynamic Injection)
| Role | Purpose | Task Prefix | Injection Trigger |
|------|---------|-------------|-------------------|
| orchestrator | Multi-module coordination | ORCH-* | Multi-module complexity |
| security-expert | Security analysis | SECURITY-* | Security keywords |
| performance-optimizer | Performance optimization | PERF-* | Performance keywords |
| data-engineer | Data pipeline work | DATA-* | Data keywords |
| devops-engineer | DevOps and deployment | DEVOPS-* | DevOps keywords |
| ml-engineer | ML/AI implementation | ML-* | ML keywords |
### Utility Members (Coordinator-Only)
| Utility | Purpose | Callable By |
|---------|---------|-------------|
| explorer | Parallel multi-angle exploration | Coordinator only |
| discussant | Aggregate multi-CLI critique | Coordinator only |
**Note**: Workers cannot spawn utility members. Workers needing similar capabilities must use CLI tools (`ccw cli --tool gemini --mode analysis`).
## CLI Tool Integration
Workers use CLI tools for complex analysis:
| Capability | CLI Command | Used By |
|------------|-------------|---------|
| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect |
| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer |
| Document generation | `ccw cli --tool gemini --mode write` | writer |
## Session Management
### Session Directory Structure
```
.workflow/.team/TLS-<slug>-<date>/
+-- team-session.json
+-- artifact-registry.json <- v3 NEW
+-- spec/
| +-- spec-config.json
| +-- discovery-context.json
| +-- product-brief.md
| +-- requirements/
| +-- architecture/
| +-- epics/
| +-- readiness-report.md
+-- discussions/
+-- plan/
| +-- plan.json
| +-- .task/TASK-*.json
+-- explorations/
+-- artifacts/ <- v3 NEW: artifact manifests
| +-- artifact-manifest-*.json
+-- .msg/
+-- shared-memory.json
```
### Session Resume
1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions
2. Multiple matches → AskUserQuestion
3. Audit TaskList → reconcile session state
4. Reset in_progress → pending (interrupted tasks)
5. Rebuild team, spawn needed workers only
6. Restore artifact registry from session
7. Kick first executable task
## User Commands
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream |
| `feedback <text>` | Analyze feedback, create targeted revision |
| `recheck` | Re-run QUALITY-001 quality check |
| `improve [dimension]` | Auto-improve weakest dimension |

View File

@@ -0,0 +1,619 @@
# Domain Model
This document defines the core entities, schemas, relationships, and state machines for Team Lifecycle v3.
## 1. Core Entities
### 1.1 Task
A **Task** represents a unit of work assigned to a specific role. Tasks have dependencies, priorities, and lifecycle states.
**Definition**: An atomic work item with a unique identifier, assigned role, execution phase, dependency constraints, and status tracking.
**Fields**:
- `id` (string): Unique task identifier following pattern `{PREFIX}-{NNN}` (e.g., `IMPL-001`, `TEST-001`)
- `role` (string): Role name responsible for execution (e.g., `executor`, `tester`, `reviewer`)
- `phase` (string): Execution phase (`spec`, `impl`, `test`, `review`)
- `dependencies` (array): List of task IDs that must complete before this task can start (blockedBy)
- `status` (enum): Current task state (`pending`, `ready`, `in_progress`, `completed`, `failed`)
- `priority` (enum): Execution priority (`P0`, `P1`, `P2`)
- `metadata` (object): Additional context (created_at, updated_at, attempt_count, error_message)
### 1.2 Artifact
An **Artifact** represents a deliverable produced by a worker, with validation status and dependency tracking.
**Definition**: A versioned output (document, code, test suite) with a manifest describing its type, creator, validation status, and dependencies.
**Fields**:
- `artifact_id` (string): Unique artifact identifier (e.g., `product-brief-v1`, `impl-auth-service`)
- `artifact_type` (string): Type classification (`document`, `code`, `test`, `config`, `report`)
- `path` (string): File system path relative to session directory
- `creator_role` (string): Role that produced this artifact
- `version` (string): Semantic version (e.g., `1.0`, `1.1`)
- `validation_status` (enum): Validation state (`pending`, `passed`, `failed`)
- `validation_summary` (string): Human-readable validation result
- `dependencies` (array): List of artifact IDs this artifact depends on
- `metadata` (object): Additional context (created_at, task_id, priority, file_size, checksum)
### 1.3 Role
A **Role** defines a specialized agent's capabilities, task prefix, and injection trigger.
**Definition**: A specification for an agent type, including its responsibilities, task naming convention, and conditions for activation.
**Fields**:
- `name` (string): Role identifier (e.g., `executor`, `security-expert`, `orchestrator`)
- `type` (enum): Role classification (`coordinator`, `pipeline`, `specialist`, `utility`)
- `task_prefix` (string): Task ID prefix pattern (e.g., `IMPL-*`, `SECURITY-*`, `ORCH-*`)
- `injection_trigger` (enum): Activation condition (`always`, `complexity`, `keywords`, `manual`)
- `injection_criteria` (object): Specific trigger conditions (keywords, complexity_threshold)
- `capabilities` (array): List of capabilities (e.g., `code_generation`, `security_audit`, `performance_analysis`)
- `inner_loop` (boolean): Whether role supports iterative refinement
- `phase_execution` (array): List of execution phases (1-5)
### 1.4 Session
A **Session** represents a complete workflow execution instance with persistent state.
**Definition**: A stateful execution context that tracks all tasks, artifacts, and coordination state for a single workflow run.
**Fields**:
- `session_id` (string): Unique session identifier (e.g., `TLS-auth-impl-20260305`)
- `slug` (string): Human-readable short name derived from task description
- `created_at` (string): ISO8601 timestamp of session creation
- `updated_at` (string): ISO8601 timestamp of last state change
- `status` (enum): Session lifecycle state (`created`, `active`, `paused`, `completed`, `archived`, `failed`)
- `pipeline_type` (enum): Selected pipeline (`spec-only`, `impl-only`, `full-lifecycle`, `enhanced-parallel`)
- `artifact_registry` (object): Map of artifact_id → Artifact manifest
- `task_list` (array): Ordered list of Task objects
- `injected_roles` (array): List of dynamically injected specialist roles
- `checkpoint_history` (array): Record of user checkpoint interactions
- `session_directory` (string): File system path to session workspace
---
## 2. Entity Schemas
### 2.1 Task Schema (JSON Schema)
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Task",
"required": ["id", "role", "phase", "status", "priority"],
"properties": {
"id": {
"type": "string",
"pattern": "^[A-Z]+-[0-9]{3}$",
"description": "Unique task identifier (e.g., IMPL-001)"
},
"role": {
"type": "string",
"description": "Role name responsible for execution"
},
"phase": {
"type": "string",
"enum": ["spec", "impl", "test", "review"],
"description": "Execution phase"
},
"dependencies": {
"type": "array",
"items": {"type": "string", "pattern": "^[A-Z]+-[0-9]{3}$"},
"default": [],
"description": "List of task IDs that must complete first"
},
"status": {
"type": "string",
"enum": ["pending", "ready", "in_progress", "completed", "failed"],
"description": "Current task state"
},
"priority": {
"type": "string",
"enum": ["P0", "P1", "P2"],
"description": "Execution priority (P0 = highest)"
},
"metadata": {
"type": "object",
"properties": {
"created_at": {"type": "string", "format": "date-time"},
"updated_at": {"type": "string", "format": "date-time"},
"attempt_count": {"type": "integer", "minimum": 0},
"error_message": {"type": "string"}
}
}
}
}
```
### 2.2 Artifact Schema (JSON Schema)
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Artifact",
"required": ["artifact_id", "artifact_type", "path", "creator_role", "validation_status"],
"properties": {
"artifact_id": {
"type": "string",
"description": "Unique artifact identifier"
},
"artifact_type": {
"type": "string",
"enum": ["document", "code", "test", "config", "report"],
"description": "Type classification"
},
"path": {
"type": "string",
"description": "File system path relative to session directory"
},
"creator_role": {
"type": "string",
"description": "Role that produced this artifact"
},
"version": {
"type": "string",
"pattern": "^[0-9]+\\.[0-9]+$",
"description": "Semantic version (e.g., 1.0)"
},
"validation_status": {
"type": "string",
"enum": ["pending", "passed", "failed"],
"description": "Validation state"
},
"validation_summary": {
"type": "string",
"description": "Human-readable validation result"
},
"dependencies": {
"type": "array",
"items": {"type": "string"},
"default": [],
"description": "List of artifact IDs this depends on"
},
"metadata": {
"type": "object",
"properties": {
"created_at": {"type": "string", "format": "date-time"},
"task_id": {"type": "string", "pattern": "^[A-Z]+-[0-9]{3}$"},
"priority": {"type": "string", "enum": ["P0", "P1", "P2"]},
"file_size": {"type": "integer", "minimum": 0},
"checksum": {"type": "string"}
}
}
}
}
```
### 2.3 Role Schema (JSON Schema)
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Role",
"required": ["name", "type", "task_prefix", "injection_trigger"],
"properties": {
"name": {
"type": "string",
"description": "Role identifier"
},
"type": {
"type": "string",
"enum": ["coordinator", "pipeline", "specialist", "utility"],
"description": "Role classification"
},
"task_prefix": {
"type": "string",
"pattern": "^[A-Z]+-\\*$",
"description": "Task ID prefix pattern (e.g., IMPL-*)"
},
"injection_trigger": {
"type": "string",
"enum": ["always", "complexity", "keywords", "manual"],
"description": "Activation condition"
},
"injection_criteria": {
"type": "object",
"properties": {
"keywords": {"type": "array", "items": {"type": "string"}},
"complexity_threshold": {"type": "string", "enum": ["low", "medium", "high"]}
}
},
"capabilities": {
"type": "array",
"items": {"type": "string"},
"description": "List of capabilities"
},
"inner_loop": {
"type": "boolean",
"description": "Supports iterative refinement"
},
"phase_execution": {
"type": "array",
"items": {"type": "integer", "minimum": 1, "maximum": 5},
"description": "Execution phases (1-5)"
}
}
}
```
### 2.4 Session Schema (JSON Schema)
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Session",
"required": ["session_id", "slug", "status", "pipeline_type"],
"properties": {
"session_id": {
"type": "string",
"pattern": "^TLS-[a-z0-9-]+-[0-9]{8}$",
"description": "Unique session identifier"
},
"slug": {
"type": "string",
"description": "Human-readable short name"
},
"created_at": {
"type": "string",
"format": "date-time",
"description": "Session creation timestamp"
},
"updated_at": {
"type": "string",
"format": "date-time",
"description": "Last state change timestamp"
},
"status": {
"type": "string",
"enum": ["created", "active", "paused", "completed", "archived", "failed"],
"description": "Session lifecycle state"
},
"pipeline_type": {
"type": "string",
"enum": ["spec-only", "impl-only", "full-lifecycle", "enhanced-parallel"],
"description": "Selected pipeline"
},
"artifact_registry": {
"type": "object",
"additionalProperties": {"$ref": "#/definitions/Artifact"},
"description": "Map of artifact_id to Artifact manifest"
},
"task_list": {
"type": "array",
"items": {"$ref": "#/definitions/Task"},
"description": "Ordered list of tasks"
},
"injected_roles": {
"type": "array",
"items": {"type": "string"},
"description": "Dynamically injected specialist roles"
},
"checkpoint_history": {
"type": "array",
"items": {
"type": "object",
"properties": {
"checkpoint_id": {"type": "string"},
"timestamp": {"type": "string", "format": "date-time"},
"user_action": {"type": "string", "enum": ["resume", "improve", "revise", "recheck", "feedback"]},
"context": {"type": "string"}
}
}
},
"session_directory": {
"type": "string",
"description": "File system path to session workspace"
}
}
}
```
---
## 3. Entity Relationships
```
┌─────────────────────────────────────────────────────────────────┐
│ Session │
│ - session_id │
│ - status: created|active|paused|completed|archived|failed │
│ - pipeline_type: spec-only|impl-only|full-lifecycle|enhanced │
├─────────────────────────────────────────────────────────────────┤
│ artifact_registry: Map<artifact_id, Artifact> │
│ task_list: Task[] │
│ injected_roles: string[] │
│ checkpoint_history: Checkpoint[] │
└──────────────┬──────────────────────────────┬───────────────────┘
│ │
│ 1:N │ 1:N
▼ ▼
┌───────────────┐ ┌──────────────┐
│ Artifact │ │ Task │
├───────────────┤ ├──────────────┤
│ artifact_id │ │ id │
│ artifact_type │ │ role ────────┼──┐
│ path │ │ phase │ │
│ creator_role ─┼──┐ │ dependencies │ │ N:1
│ validation_ │ │ │ status │ │
│ status │ │ │ priority │ │
│ dependencies ─┼──┼───┐ └──────┬───────┘ │
└───────────────┘ │ │ │ │
│ │ │ produces │
│ │ │ 1:1 │
│ │ ▼ │
│ │ ┌──────────────┐ │
│ └──────▶│ Artifact │ │
│ └──────────────┘ │
│ │
│ N:1 │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Role │ │ Role │
├──────────────┤ ├──────────────┤
│ name │ │ name │
│ type │ │ type │
│ task_prefix │ │ task_prefix │
│ injection_ │ │ injection_ │
│ trigger │ │ trigger │
│ capabilities │ │ capabilities │
└──────────────┘ └──────────────┘
```
**Relationship Descriptions**:
1. **Session → Task** (1:N): A session contains multiple tasks in its task_list
2. **Session → Artifact** (1:N): A session tracks multiple artifacts in its artifact_registry
3. **Task → Role** (N:1): Each task is assigned to one role for execution
4. **Task → Artifact** (1:1): Each task produces one primary artifact upon completion
5. **Task → Task** (N:N): Tasks can depend on other tasks (dependencies field)
6. **Artifact → Role** (N:1): Each artifact is created by one role (creator_role)
7. **Artifact → Artifact** (N:N): Artifacts can depend on other artifacts (dependencies field)
---
## 4. State Machines
### 4.1 Task Status State Machine
```
┌─────────────┐
│ pending │ (initial state)
└──────┬──────┘
│ dependencies met
┌─────────────┐
│ ready │
└──────┬──────┘
│ worker spawned
┌─────────────┐
│ in_progress │
└──────┬──────┘
┌──────────┴──────────┐
│ │
│ success │ failure
▼ ▼
┌─────────────┐ ┌─────────────┐
│ completed │ │ failed │
└─────────────┘ └──────┬──────┘
│ retry (attempt_count++)
┌─────────────┐
│ pending │
└─────────────┘
```
**State Transitions**:
- `pending → ready`: All dependencies completed
- `ready → in_progress`: Worker spawned by coordinator
- `in_progress → completed`: Worker reports success via SendMessage
- `in_progress → failed`: Worker reports failure or timeout
- `failed → pending`: Coordinator triggers retry (with exponential backoff)
**Terminal States**: `completed`
**Retry Logic**: Failed tasks return to `pending` with incremented `attempt_count`. Max retries configurable (default: 3).
### 4.2 Session Lifecycle State Machine
```
┌─────────────┐
│ created │ (initial state)
└──────┬──────┘
│ first task spawned
┌─────────────┐
│ active │◀──────────┐
└──────┬──────┘ │
│ │
┌──────────┴──────────┐ │
│ │ │
│ user pause │ resume│
▼ │ │
┌─────────────┐ │ │
│ paused │──────────────┘ │
└─────────────┘ │
┌─────────────┐ │
│ active │───────────┘
└──────┬──────┘
┌──────────┴──────────┐
│ │
│ all tasks done │ unrecoverable error
▼ ▼
┌─────────────┐ ┌─────────────┐
│ completed │ │ failed │
└──────┬──────┘ └──────┬──────┘
│ │
│ archive │ archive
▼ ▼
┌─────────────┐ ┌─────────────┐
│ archived │ │ archived │
└─────────────┘ └─────────────┘
```
**State Transitions**:
- `created → active`: Coordinator spawns first batch of tasks
- `active → paused`: User issues pause command or checkpoint requires review
- `paused → active`: User issues resume command
- `active → completed`: All tasks in task_list reach `completed` status
- `active → failed`: Unrecoverable error (e.g., circular dependency, resource exhaustion)
- `completed → archived`: Session archived after retention period
- `failed → archived`: Failed session archived after investigation
**Terminal States**: `archived`
**Checkpoint Behavior**: Session transitions to `paused` at quality checkpoints (e.g., after QUALITY-001). User actions (`resume`, `improve`, `revise`) transition back to `active`.
### 4.3 Artifact Validation State Machine
```
┌─────────────┐
│ pending │ (initial state)
└──────┬──────┘
│ validation triggered
┌─────────────┐
│ validating │
└──────┬──────┘
┌──────────┴──────────┐
│ │
│ validation success │ validation failure
▼ ▼
┌─────────────┐ ┌─────────────┐
│ passed │ │ failed │
└─────────────┘ └──────┬──────┘
│ fix applied
┌─────────────┐
│ pending │
└─────────────┘
```
**State Transitions**:
- `pending → validating`: Coordinator triggers validation (e.g., quality gate check)
- `validating → passed`: Artifact meets quality criteria
- `validating → failed`: Artifact fails quality criteria
- `failed → pending`: Worker applies fix and re-submits artifact
**Terminal States**: `passed`
**Validation Gating**: Downstream tasks blocked until upstream artifacts reach `passed` state.
---
## 5. Invariants and Constraints
### 5.1 Task Invariants
1. **Unique Task IDs**: No two tasks in a session can have the same `id`
2. **Acyclic Dependencies**: Task dependency graph must be a DAG (no cycles)
3. **Valid Dependencies**: All task IDs in `dependencies` array must exist in session's task_list
4. **Priority Ordering**: P0 tasks execute before P1, P1 before P2 (within same dependency level)
5. **Single Active Worker**: A task can only be `in_progress` for one worker at a time
### 5.2 Artifact Invariants
1. **Unique Artifact IDs**: No two artifacts in a session can have the same `artifact_id`
2. **Valid Creator Role**: `creator_role` must match a defined role in the system
3. **Path Uniqueness**: No two artifacts can have the same `path` within a session
4. **Dependency Validity**: All artifact IDs in `dependencies` array must exist in artifact_registry
### 5.3 Session Invariants
1. **Unique Session IDs**: No two sessions can have the same `session_id`
2. **Monotonic Timestamps**: `updated_at` >= `created_at`
3. **Task Completeness**: All tasks in `task_list` must reach terminal state before session can be `completed`
4. **Artifact Registry Consistency**: All artifacts referenced in task metadata must exist in `artifact_registry`
---
## 6. Usage Examples
### 6.1 Creating a Task
```json
{
"id": "IMPL-001",
"role": "executor",
"phase": "impl",
"dependencies": ["PLAN-001"],
"status": "pending",
"priority": "P0",
"metadata": {
"created_at": "2026-03-05T10:00:00Z",
"updated_at": "2026-03-05T10:00:00Z",
"attempt_count": 0
}
}
```
### 6.2 Creating an Artifact Manifest
```json
{
"artifact_id": "auth-service-impl-v1",
"artifact_type": "code",
"path": "artifacts/auth-service.ts",
"creator_role": "executor",
"version": "1.0",
"validation_status": "passed",
"validation_summary": "Code review passed: 95% test coverage, no security issues",
"dependencies": ["auth-service-plan-v1"],
"metadata": {
"created_at": "2026-03-05T11:30:00Z",
"task_id": "IMPL-001",
"priority": "P0",
"file_size": 15420,
"checksum": "sha256:abc123..."
}
}
```
### 6.3 Session State Example
```json
{
"session_id": "TLS-auth-impl-20260305",
"slug": "auth-impl",
"created_at": "2026-03-05T09:00:00Z",
"updated_at": "2026-03-05T12:00:00Z",
"status": "active",
"pipeline_type": "impl-only",
"artifact_registry": {
"auth-service-plan-v1": { ... },
"auth-service-impl-v1": { ... }
},
"task_list": [
{"id": "PLAN-001", "status": "completed", ...},
{"id": "IMPL-001", "status": "in_progress", ...},
{"id": "TEST-001", "status": "pending", ...}
],
"injected_roles": ["security-expert"],
"checkpoint_history": [],
"session_directory": ".workflow/.team/TLS-auth-impl-20260305/"
}
```
---
## 7. Cross-References
- **Artifact Contract Specification**: [artifact-contract-spec.md](artifact-contract-spec.md)
- **Execution Flow**: [execution-flow.md](execution-flow.md)
- **Core Concepts**: [core-concepts.md](core-concepts.md)
- **Role Specifications**: [../roles/README.md](../roles/README.md)

View File

@@ -0,0 +1,643 @@
# Execution Flow
This document provides a detailed walkthrough of how tasks flow through the Team Lifecycle v3 system, from initial user request to final completion.
## Table of Contents
1. [Overview](#overview)
2. [Pipeline Definitions](#pipeline-definitions)
3. [Execution Lifecycle](#execution-lifecycle)
4. [Beat-Based Cadence](#beat-based-cadence)
5. [Conditional Routing](#conditional-routing)
6. [Dynamic Role Injection](#dynamic-role-injection)
7. [Quality Checkpoints](#quality-checkpoints)
8. [Task Metadata Registry](#task-metadata-registry)
## Overview
Team Lifecycle v3 uses an **event-driven, beat-based execution model**:
1. User provides task description
2. Coordinator clarifies requirements and creates team
3. Coordinator analyzes complexity and injects specialist roles
4. Coordinator creates task chain based on pipeline selection
5. Coordinator spawns first batch of workers (background execution)
6. Workers execute and report completion via SendMessage callbacks
7. Coordinator advances pipeline, spawning next ready tasks
8. Process repeats until pipeline complete
9. Coordinator generates final report
## Pipeline Definitions
### Spec-only Pipeline (6 tasks, 3 discussions)
For documentation, requirements gathering, and design work.
```
RESEARCH-001(+D1) → DRAFT-001 → DRAFT-002(+D2) → DRAFT-003 → DRAFT-004 → QUALITY-001(+D3)
```
**Tasks**:
- **RESEARCH-001** (analyst): Research and discovery with DISCUSS-001
- **DRAFT-001** (writer): Product brief with self-validation
- **DRAFT-002** (writer): Requirements PRD with DISCUSS-002
- **DRAFT-003** (writer): Architecture document with self-validation
- **DRAFT-004** (writer): Epics breakdown with self-validation
- **QUALITY-001** (reviewer): Multi-dimensional quality check with DISCUSS-003
**Checkpoint**: After QUALITY-001, user can review, improve, or revise before proceeding.
### Impl-only Pipeline (4 tasks)
For quick implementations with clear requirements.
```
PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001
```
**Tasks**:
- **PLAN-001** (planner): Implementation planning and complexity assessment
- **IMPL-001** (executor): Code implementation
- **TEST-001** (tester): Test generation and execution (parallel with REVIEW-001)
- **REVIEW-001** (reviewer): Code quality review (parallel with TEST-001)
### Full-lifecycle Pipeline (10 tasks, v2 compatible)
Complete feature development from requirements to implementation.
```
[Spec pipeline] → PLAN-001(blockedBy: QUALITY-001) → IMPL-001 → TEST-001 + REVIEW-001
```
**Checkpoint**: After QUALITY-001, user reviews spec quality before proceeding to implementation.
### Enhanced Parallel Pipeline (v3 NEW)
Advanced pipeline with conditional routing and parallel execution.
```
RESEARCH-001(+D1) → DRAFT-001 → DRAFT-002(+D2) → DRAFT-003 → DRAFT-004 → QUALITY-001(+D3)
|
v
PLAN-001 (complexity assessment)
|
+---------------+---------------+
| | |
Low: IMPL-001 Med: ORCH-001 High: ARCH-001
| → IMPL-* → ORCH-001
| → IMPL-*
v
IMPL-001 || DEV-FE-001 (parallel, P0)
|
v
TEST-001 || QA-FE-001 (parallel, P1)
|
v
REVIEW-001 (P1)
```
**Key Features**:
- Conditional routing based on complexity assessment
- Parallel execution of independent tasks (IMPL-001 || DEV-FE-001)
- Priority-based scheduling (P0 > P1 > P2)
- Dynamic specialist role injection
## Execution Lifecycle
### Phase 0: User Request
User invokes the skill with a task description:
```
Skill(skill="team-lifecycle-v3", args="Implement user authentication with OAuth2")
```
### Phase 1: Clarification & Team Creation
**Coordinator Actions**:
1. Parse task description
2. Ask clarifying questions if needed (via AskUserQuestion)
3. Determine pipeline type (spec-only, impl-only, full-lifecycle)
4. Create team session folder: `.workflow/.team/TLS-<slug>-<date>/`
5. Initialize team via TeamCreate
**Output**: Team session created, requirements clarified
### Phase 2: Complexity Analysis & Role Injection
**Coordinator Actions**:
1. Analyze task description for keywords
2. Assess complexity indicators (module count, dependencies)
3. Inject specialist roles based on triggers:
- Security keywords → `security-expert`
- Performance keywords → `performance-optimizer`
- Data keywords → `data-engineer`
- DevOps keywords → `devops-engineer`
- ML keywords → `ml-engineer`
- High complexity → `orchestrator`, `architect`
**Output**: Role injection plan, updated task chain
### Phase 3: Task Chain Creation
**Coordinator Actions**:
1. Select pipeline based on requirements
2. Create task metadata for each step
3. Assign priorities (P0/P1/P2)
4. Establish dependencies (blockedBy relationships)
5. Register tasks via TaskCreate
**Output**: Complete task chain with dependencies
### Phase 4: Worker Spawning & Execution
**Coordinator Actions**:
1. Find ready tasks (no unmet dependencies)
2. Sort by priority (P0 > P1 > P2)
3. Spawn workers via Agent tool (background execution)
4. Update task status to `in_progress`
5. Enter idle state (STOP)
**Worker Actions**:
1. Load role specification
2. Execute Phase 1-5 (task discovery, domain work, reporting)
3. Generate artifacts with manifest
4. Send completion callback to coordinator via SendMessage
**Output**: Workers executing in background
### Phase 5: Callback Handling & Advancement
**Coordinator Actions** (on callback):
1. Mark completed task
2. Validate artifact (check manifest validation_status)
3. Update artifact registry
4. Find next ready tasks
5. Check for checkpoints (e.g., QUALITY-001 complete)
6. If checkpoint: display status, wait for user command
7. If no checkpoint: spawn next batch, return to idle
**Output**: Pipeline advances, next workers spawned
### Phase 6: Completion & Reporting
**Coordinator Actions** (when all tasks complete):
1. Generate final report
2. Summarize artifacts produced
3. Display completion status
4. Offer completion actions (archive session, continue work)
**Output**: Final report, session complete
## Beat-Based Cadence
The system uses an **event-driven beat model** where each beat = coordinator wake → process → spawn → STOP.
### Beat Cycle (v3 Enhanced)
```
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check artifacts | <- v3: artifact validation
| update registry | <- v3: artifact registry
+- handleSpawnNext -+
| find ready tasks |
| priority sort | <- v3: P0/P1/P2 scheduling
| inject roles | <- v3: dynamic injection
| spawn workers ---+--> [team-worker] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
======================================================================
```
### Fast-Advance Optimization
For simple linear successors, workers can spawn the next worker directly:
```
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor?
| --> spawn team-worker B directly
| --> log fast_advance to message bus
+- complex case? --> SendMessage to coordinator
======================================================================
```
**Benefits**:
- Reduces coordinator overhead for simple chains
- Faster execution for linear pipelines
- Coordinator still maintains authority via message bus logs
## Conditional Routing
PLAN-001 assesses complexity and routes to appropriate implementation strategy.
### Complexity Assessment Algorithm
**Module Definition**: A **module** is a cohesive unit of code with clear boundaries and a single primary responsibility. Typically corresponds to:
- A file or class with related functionality
- A directory containing related files (e.g., `auth/`, `payment/`)
- A service or component with well-defined interfaces
**Quantifiable Complexity Criteria**:
| Metric | Low | Medium | High |
|--------|-----|--------|------|
| **Module Count** | 1-2 modules | 3-5 modules | 6+ modules |
| **Lines of Code (LOC)** | <500 LOC | 500-2000 LOC | 2000+ LOC |
| **Dependency Depth** | 1-2 levels | 3-4 levels | 5+ levels |
| **Responsibilities** | Single responsibility | 2-3 responsibilities | 4+ responsibilities |
| **Cross-Cutting Concerns** | None | 1-2 (e.g., logging, validation) | 3+ (e.g., auth, caching, monitoring) |
| **External Integrations** | 0-1 (e.g., database) | 2-3 (e.g., DB, API, cache) | 4+ (e.g., DB, APIs, queues, storage) |
**Complexity Score Calculation** (Pseudocode):
```
function assessComplexity(plan):
score = 0
// Module count (weight: 3)
if plan.module_count >= 6:
score += 3 * 3
else if plan.module_count >= 3:
score += 2 * 3
else:
score += 1 * 3
// Lines of code (weight: 2)
if plan.estimated_loc >= 2000:
score += 3 * 2
else if plan.estimated_loc >= 500:
score += 2 * 2
else:
score += 1 * 2
// Dependency depth (weight: 2)
if plan.dependency_depth >= 5:
score += 3 * 2
else if plan.dependency_depth >= 3:
score += 2 * 2
else:
score += 1 * 2
// Responsibilities (weight: 1)
if plan.responsibilities >= 4:
score += 3 * 1
else if plan.responsibilities >= 2:
score += 2 * 1
else:
score += 1 * 1
// Cross-cutting concerns (weight: 1)
if plan.cross_cutting_concerns >= 3:
score += 3 * 1
else if plan.cross_cutting_concerns >= 1:
score += 2 * 1
else:
score += 1 * 1
// External integrations (weight: 1)
if plan.external_integrations >= 4:
score += 3 * 1
else if plan.external_integrations >= 2:
score += 2 * 1
else:
score += 1 * 1
// Total score range: 10-30
// Low: 10-15, Medium: 16-22, High: 23-30
if score >= 23:
return "High"
else if score >= 16:
return "Medium"
else:
return "Low"
```
**Routing Decision Tree**:
```
┌─────────────────────┐
│ PLAN-001 Complete │
│ Assess Complexity │
└──────────┬──────────┘
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ Low │ │ Medium │ │ High │
│ Score:10-15│ │ Score:16-22│ │ Score:23-30│
└──────┬─────┘ └──────┬─────┘ └──────┬─────┘
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ IMPL-001 │ │ ORCH-001 │ │ ARCH-001 │
│ (direct) │ │ (parallel) │ │ (design) │
└──────┬─────┘ └──────┬─────┘ └──────┬─────┘
│ │ │
│ ▼ ▼
│ ┌────────────┐ ┌────────────┐
│ │ IMPL-001 │ │ ORCH-001 │
│ │ IMPL-002 │ │ (parallel) │
│ │ IMPL-003 │ └──────┬─────┘
│ │ (parallel) │ │
│ └──────┬─────┘ ▼
│ │ ┌────────────┐
│ │ │ IMPL-001 │
│ │ │ IMPL-002 │
│ │ │ ... │
│ │ │ (parallel) │
│ │ └──────┬─────┘
│ │ │
└──────────────┴──────────────┘
┌────────────┐
│ TEST-001 │
│ REVIEW-001 │
│ (parallel) │
└────────────┘
```
### Complexity Assessment Criteria
| Complexity | Module Count | Dependency Depth | Routing Decision |
|------------|--------------|------------------|------------------|
| Low | 1-2 modules | Shallow (1-2 levels) | Direct IMPL |
| Medium | 3-5 modules | Moderate (3-4 levels) | Orchestrated IMPL |
| High | 6+ modules | Deep (5+ levels) | Architecture + Orchestrated IMPL |
### Routing Paths
#### Low Complexity Route
```
PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001
```
**Roles**: planner → executor → tester + reviewer
**Use Case**: Simple feature, single module, clear implementation path
#### Medium Complexity Route
```
PLAN-001 → ORCH-001 → IMPL-001 || IMPL-002 || IMPL-003 → TEST-001 + REVIEW-001
```
**Roles**: planner → orchestrator → executor (parallel) → tester + reviewer
**Use Case**: Multi-module feature, moderate dependencies, parallel implementation possible
#### High Complexity Route
```
PLAN-001 → ARCH-001 → ORCH-001 → IMPL-001 || IMPL-002 || ... → TEST-001 + REVIEW-001
```
**Roles**: planner → architect → orchestrator → executor (parallel) → tester + reviewer
**Use Case**: Complex feature, many modules, deep dependencies, architecture design needed
## Dynamic Role Injection
Specialist roles are automatically injected based on task analysis.
### Injection Triggers
| Trigger | Injected Role | Injection Point | Priority |
|---------|---------------|-----------------|----------|
| Keywords: security, vulnerability, OWASP, auth | security-expert | After PLAN-001 | P0 |
| Keywords: performance, optimization, bottleneck, latency | performance-optimizer | After IMPL-* | P1 |
| Keywords: data, pipeline, ETL, schema, database | data-engineer | Parallel with IMPL-* | P0 |
| Keywords: devops, CI/CD, deployment, docker, kubernetes | devops-engineer | After IMPL-* | P1 |
| Keywords: ML, model, training, inference, AI | ml-engineer | Parallel with IMPL-* | P0 |
| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* | P0 |
| Complexity: High + deep dependencies | architect | Before ORCH-* | P0 |
### Injection Example
**Task Description**: "Implement user authentication with OAuth2, add security audit, optimize login performance"
**Analysis**:
- Keywords detected: "authentication", "OAuth2", "security", "audit", "optimize", "performance"
- Complexity: Medium (3-4 modules)
**Injected Roles**:
- `security-expert` (keywords: security, audit, authentication)
- `performance-optimizer` (keywords: optimize, performance)
**Resulting Pipeline**:
```
PLAN-001 → IMPL-001 || SECURITY-001 || PERF-001 → TEST-001 → REVIEW-001
```
## Quality Checkpoints
Checkpoints pause execution for user review and feedback.
### Checkpoint 1: Spec Phase Complete (QUALITY-001)
**Trigger**: QUALITY-001 task completes
**Coordinator Output**:
```
[coordinator] ══════════════════════════════════════════
[coordinator] SPEC PHASE COMPLETE
[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%)
[coordinator]
[coordinator] Dimension Scores:
[coordinator] Completeness: ████████░░ 80%
[coordinator] Consistency: █████████░ 90%
[coordinator] Traceability: ███████░░░ 70%
[coordinator] Depth: ████████░░ 80%
[coordinator] Coverage: ██████████ 100%
[coordinator]
[coordinator] Available Actions:
[coordinator] resume -> Proceed to implementation
[coordinator] improve -> Auto-improve weakest dimension
[coordinator] revise <TASK-ID> -> Revise specific document
[coordinator] recheck -> Re-run quality check
[coordinator] feedback <text> -> Inject feedback
[coordinator] ══════════════════════════════════════════
```
**User Actions**:
- `resume` → Proceed to PLAN-001
- `improve` → Auto-improve weakest dimension (Traceability in example)
- `revise DRAFT-003` → Revise architecture document
- `recheck` → Re-run QUALITY-001
- `feedback "Add more API examples"` → Targeted revision
### Checkpoint 2: Complexity Routing Decision (PLAN-001)
**Trigger**: PLAN-001 completes with complexity assessment
**Coordinator Output**:
```
[coordinator] ══════════════════════════════════════════
[coordinator] COMPLEXITY ASSESSMENT COMPLETE
[coordinator] Complexity: Medium (3 modules, moderate dependencies)
[coordinator] Routing: Orchestrated Implementation
[coordinator]
[coordinator] Next Steps:
[coordinator] ORCH-001: Coordinate parallel implementation
[coordinator] IMPL-001: Core authentication module
[coordinator] IMPL-002: OAuth2 integration
[coordinator] IMPL-003: Session management
[coordinator]
[coordinator] Continuing automatically...
[coordinator] ══════════════════════════════════════════
```
**Note**: This checkpoint is informational only; execution continues automatically.
### Checkpoint 3: Parallel Merge (All Parallel Tasks Complete)
**Trigger**: All parallel tasks at same level complete
**Coordinator Actions**:
1. Validate integration (check for conflicts)
2. Merge artifacts if needed
3. Continue to next phase
**Note**: If integration issues detected, coordinator may pause for user intervention.
### Checkpoint 4: Pipeline Stall (No Ready + No Running)
**Trigger**: No tasks ready to execute and no tasks currently running
**Coordinator Output**:
```
[coordinator] ══════════════════════════════════════════
[coordinator] PIPELINE STALLED
[coordinator] Reason: Circular dependency or missing task
[coordinator]
[coordinator] Current State:
[coordinator] Completed: 5 tasks
[coordinator] Blocked: 2 tasks (waiting on IMPL-001)
[coordinator] Running: 0 tasks
[coordinator]
[coordinator] Action Required: Check task dependencies
[coordinator] ══════════════════════════════════════════
```
**User Actions**: Investigate and resolve dependency issues
## Task Metadata Registry
Complete task metadata for all pipeline tasks.
| Task ID | Role | Phase | Dependencies | Discuss | Priority | Notes |
|---------|------|-------|-------------|---------|----------|-------|
| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | P0 | Initial research |
| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate | P0 | Product brief |
| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 | P0 | Requirements PRD |
| DRAFT-003 | writer | spec | DRAFT-002 | self-validate | P0 | Architecture doc |
| DRAFT-004 | writer | spec | DRAFT-003 | self-validate | P0 | Epics breakdown |
| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 | P0 | Quality gate |
| PLAN-001 | planner | impl | (none or QUALITY-001) | - | P0 | Implementation plan |
| ARCH-001 | architect | impl | PLAN-001 | - | P0 | Architecture design (if High complexity) |
| ORCH-001 | orchestrator | impl | PLAN-001 or ARCH-001 | - | P0 | Orchestration (if Med/High complexity) |
| IMPL-001 | executor | impl | PLAN-001 or ORCH-001 | - | P0 | Core implementation |
| DEV-FE-001 | fe-developer | impl | PLAN-001 or ORCH-001 | - | P0 | Frontend (parallel with IMPL-001) |
| TEST-001 | tester | impl | IMPL-001 | - | P1 | Test generation |
| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | P1 | Frontend QA (parallel with TEST-001) |
| REVIEW-001 | reviewer | impl | IMPL-001 | - | P1 | Code review |
| SECURITY-001 | security-expert | impl | IMPL-001 | - | P0 | Security audit (if injected) |
| PERF-001 | performance-optimizer | impl | IMPL-001 | - | P1 | Performance optimization (if injected) |
| DATA-001 | data-engineer | impl | PLAN-001 | - | P0 | Data pipeline (if injected, parallel) |
| DEVOPS-001 | devops-engineer | impl | IMPL-001 | - | P1 | DevOps setup (if injected) |
| ML-001 | ml-engineer | impl | PLAN-001 | - | P0 | ML implementation (if injected, parallel) |
### Task State Transitions
```
pending → ready → in_progress → completed
→ failed → pending (retry)
```
**States**:
- `pending`: Task created, waiting for dependencies
- `ready`: Dependencies met, ready to execute
- `in_progress`: Worker spawned, executing
- `completed`: Worker finished successfully
- `failed`: Worker encountered error (triggers retry)
### Dependency Resolution
**Rules**:
1. Task becomes `ready` when all `blockedBy` tasks are `completed`
2. Coordinator checks dependencies on each beat
3. Failed tasks block downstream until retry succeeds
4. Parallel tasks (no dependencies) execute simultaneously
## Execution Examples
### Example 1: Simple Implementation (Low Complexity)
**Task**: "Add logging to user service"
**Pipeline**: Impl-only
```
PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001
```
**Execution**:
1. Beat 1: Spawn PLAN-001 (planner)
2. Beat 2: PLAN-001 completes → Spawn IMPL-001 (executor)
3. Beat 3: IMPL-001 completes → Spawn TEST-001 + REVIEW-001 (parallel)
4. Beat 4: Both complete → Generate report
**Duration**: ~4 beats
### Example 2: Full Lifecycle with Specialist Injection (High Complexity)
**Task**: "Implement user authentication with OAuth2, add security audit, optimize login performance"
**Pipeline**: Full-lifecycle with injections
```
RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001
→ PLAN-001 → ARCH-001 → ORCH-001 → IMPL-001 || SECURITY-001 || PERF-001
→ TEST-001 → REVIEW-001
```
**Execution**:
1. Beat 1-6: Spec phase (RESEARCH → DRAFT-* → QUALITY)
2. Checkpoint: User reviews spec quality, chooses `resume`
3. Beat 7: Spawn PLAN-001 (planner)
4. Beat 8: PLAN-001 completes (High complexity) → Spawn ARCH-001 (architect)
5. Beat 9: ARCH-001 completes → Spawn ORCH-001 (orchestrator)
6. Beat 10: ORCH-001 completes → Spawn IMPL-001 || SECURITY-001 || PERF-001 (parallel, P0)
7. Beat 11: All parallel tasks complete → Spawn TEST-001 (P1)
8. Beat 12: TEST-001 completes → Spawn REVIEW-001 (P1)
9. Beat 13: REVIEW-001 completes → Generate report
**Duration**: ~13 beats + 1 checkpoint
### Example 3: Spec-only with Revision Loop
**Task**: "Design API for payment processing"
**Pipeline**: Spec-only
```
RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001
```
**Execution**:
1. Beat 1-6: Spec phase completes
2. Checkpoint: User reviews, quality score 65% (FAIL)
3. User: `improve` → Auto-improve weakest dimension (Traceability)
4. Beat 7: Spawn IMPROVE-001 (reviewer)
5. Beat 8: IMPROVE-001 completes → Spawn QUALITY-001 (recheck)
6. Beat 9: QUALITY-001 completes, quality score 85% (PASS)
7. Checkpoint: User reviews, chooses `resume` → Generate report
**Duration**: ~9 beats + 2 checkpoints

View File

@@ -0,0 +1,78 @@
# Templates Directory
This directory contains document templates used by workers during execution.
## Available Templates
| Template | Used By | Task | Purpose |
|----------|---------|------|---------|
| [product-brief.md](product-brief.md) | writer | DRAFT-001 | Product vision and high-level requirements |
| [requirements-prd.md](requirements-prd.md) | writer | DRAFT-002 | Detailed product requirements document |
| [architecture-doc.md](architecture-doc.md) | writer | DRAFT-003 | System architecture and design decisions |
| [epics-template.md](epics-template.md) | writer | DRAFT-004 | Epic breakdown and user stories |
## Template Structure
All templates follow this structure:
```markdown
---
title: <Document Title>
type: <product-brief|requirements|architecture|epics>
version: 1.0
created: <ISO8601 timestamp>
author: <role-name>
---
# <Document Title>
## Section 1
...
## Section 2
...
```
## Usage
### By Workers
Workers load templates during Phase 3 (Domain Work):
1. Read template file
2. Fill in sections based on research/context
3. Generate artifact with proper frontmatter
4. Create artifact manifest
### By Coordinator
Coordinator references templates when creating tasks:
- DRAFT-001 → `product-brief.md`
- DRAFT-002 → `requirements-prd.md`
- DRAFT-003 → `architecture-doc.md`
- DRAFT-004 → `epics-template.md`
## Template Customization
To customize templates:
1. Modify template files in this directory
2. Ensure YAML frontmatter structure is preserved
3. Update section headings as needed
4. Test with a sample task
## Document Standards
All generated documents must follow:
- **Formatting**: See [../specs/document-standards.md](../specs/document-standards.md)
- **Quality criteria**: See [../specs/quality-gates.md](../specs/quality-gates.md)
- **Artifact contract**: See [../specs/artifact-contract-spec.md](../specs/artifact-contract-spec.md)
## Cross-References
- **Specifications**: See [../specs/README.md](../specs/README.md)
- **Role specifications**: See [../roles/README.md](../roles/README.md)
- **Writer role**: See [../roles/pipeline/writer.md](../roles/pipeline/writer.md)
- **Main entry**: See [../SKILL.md](../SKILL.md)