mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-28 09:23:08 +08:00
feat: add templates for architecture documents, epics, product briefs, and requirements PRD
- Introduced architecture document template for Phase 4, including structure and individual ADR records. - Added epics & stories template for Phase 5, detailing epic breakdown and dependencies. - Created product brief template for Phase 2, summarizing product vision, problem statement, and target users. - Developed requirements PRD template for Phase 3, outlining functional and non-functional requirements with traceability. - Implemented spec command for project spec management with subcommands for loading, listing, rebuilding, and initializing specs.
This commit is contained in:
299
.claude/skills/team-lifecycle-v3/SKILL.md
Normal file
299
.claude/skills/team-lifecycle-v3/SKILL.md
Normal file
@@ -0,0 +1,299 @@
|
||||
---
|
||||
name: team-lifecycle-v3
|
||||
description: Unified team skill for full lifecycle - spec/impl/test. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team lifecycle".
|
||||
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
|
||||
---
|
||||
|
||||
# Team Lifecycle v3
|
||||
|
||||
Unified team skill: specification → implementation → testing → review. All team members invoke with `--role=xxx` to route to role-specific execution.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌───────────────────────────────────────────────────┐
|
||||
│ Skill(skill="team-lifecycle-v3") │
|
||||
│ args="任务描述" 或 args="--role=xxx" │
|
||||
└───────────────────┬───────────────────────────────┘
|
||||
│ Role Router
|
||||
┌──── --role present? ────┐
|
||||
│ NO │ YES
|
||||
↓ ↓
|
||||
Orchestration Mode Role Dispatch
|
||||
(auto → coordinator) (route to role.md)
|
||||
│
|
||||
┌────┴────┬───────┬───────┬───────┬───────┬───────┬───────┐
|
||||
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
|
||||
coordinator analyst writer discussant planner executor tester reviewer
|
||||
↑ ↑
|
||||
on-demand by coordinator
|
||||
┌──────────┐ ┌─────────┐
|
||||
│ explorer │ │architect│
|
||||
└──────────┘ └─────────┘
|
||||
┌──────────────┐ ┌──────┐
|
||||
│ fe-developer │ │fe-qa │
|
||||
└──────────────┘ └──────┘
|
||||
```
|
||||
|
||||
## Role Router
|
||||
|
||||
### Input Parsing
|
||||
|
||||
Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator).
|
||||
|
||||
### Role Registry
|
||||
|
||||
| Role | File | Task Prefix | Type |
|
||||
|------|------|-------------|------|
|
||||
| coordinator | roles/coordinator/role.md | (none) | orchestrator |
|
||||
| analyst | roles/analyst/role.md | RESEARCH-* | pipeline |
|
||||
| writer | roles/writer/role.md | DRAFT-* | pipeline |
|
||||
| discussant | roles/discussant/role.md | DISCUSS-* | pipeline |
|
||||
| planner | roles/planner/role.md | PLAN-* | pipeline |
|
||||
| executor | roles/executor/role.md | IMPL-* | pipeline |
|
||||
| tester | roles/tester/role.md | TEST-* | pipeline |
|
||||
| reviewer | roles/reviewer/role.md | REVIEW-* + QUALITY-* | pipeline |
|
||||
| explorer | roles/explorer/role.md | EXPLORE-* | service (on-demand) |
|
||||
| architect | roles/architect/role.md | ARCH-* | consulting (on-demand) |
|
||||
| fe-developer | roles/fe-developer/role.md | DEV-FE-* | frontend pipeline |
|
||||
| fe-qa | roles/fe-qa/role.md | QA-FE-* | frontend pipeline |
|
||||
|
||||
### Dispatch
|
||||
|
||||
1. Extract `--role` from arguments
|
||||
2. If no `--role` → route to coordinator (Orchestration Mode)
|
||||
3. Look up role in registry → Read the role file → Execute its phases
|
||||
|
||||
### Orchestration Mode
|
||||
|
||||
When invoked without `--role`, coordinator auto-starts. User just provides task description.
|
||||
|
||||
**Invocation**: `Skill(skill="team-lifecycle-v3", args="任务描述")`
|
||||
|
||||
**Lifecycle**:
|
||||
```
|
||||
用户提供任务描述
|
||||
→ coordinator Phase 1-3: 需求澄清 → TeamCreate → 创建任务链
|
||||
→ coordinator Phase 4: spawn 首批 worker (后台) → STOP
|
||||
→ Worker 执行 → SendMessage 回调 → coordinator 推进下一步
|
||||
→ 循环直到 pipeline 完成 → Phase 5 汇报
|
||||
```
|
||||
|
||||
**User Commands** (唤醒已暂停的 coordinator):
|
||||
|
||||
| Command | Action |
|
||||
|---------|--------|
|
||||
| `check` / `status` | 输出执行状态图,不推进 |
|
||||
| `resume` / `continue` | 检查 worker 状态,推进下一步 |
|
||||
|
||||
---
|
||||
|
||||
## Shared Infrastructure
|
||||
|
||||
以下模板适用于所有 worker 角色。每个 role.md 只需写 **Phase 2-4** 的角色特有逻辑。
|
||||
|
||||
### Worker Phase 1: Task Discovery (所有 worker 共享)
|
||||
|
||||
每个 worker 启动后执行相同的任务发现流程:
|
||||
|
||||
1. 调用 `TaskList()` 获取所有任务
|
||||
2. 筛选: subject 匹配本角色前缀 + owner 是本角色 + status 为 pending + blockedBy 为空
|
||||
3. 无任务 → idle 等待
|
||||
4. 有任务 → `TaskGet` 获取详情 → `TaskUpdate` 标记 in_progress
|
||||
|
||||
**Resume Artifact Check** (防止恢复后重复产出):
|
||||
- 检查本任务的输出产物是否已存在
|
||||
- 产物完整 → 跳到 Phase 5 报告完成
|
||||
- 产物不完整或不存在 → 正常执行 Phase 2-4
|
||||
|
||||
### Worker Phase 5: Report (所有 worker 共享)
|
||||
|
||||
任务完成后的标准报告流程:
|
||||
|
||||
1. **Message Bus**: 调用 `mcp__ccw-tools__team_msg` 记录消息
|
||||
- 参数: operation="log", team=<team-name>, from=<role>, to="coordinator", type=<消息类型>, summary="[<role>] <摘要>", ref=<产物路径>
|
||||
- **CLI fallback**: 当 MCP 不可用时 → `ccw team log --team <team> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
|
||||
2. **SendMessage**: 发送结果给 coordinator (content 和 summary 都带 `[<role>]` 前缀)
|
||||
3. **TaskUpdate**: 标记任务 completed
|
||||
4. **Loop**: 回到 Phase 1 检查下一个任务
|
||||
|
||||
### Wisdom Accumulation (所有角色)
|
||||
|
||||
跨任务知识积累。Coordinator 在 session 初始化时创建 `wisdom/` 目录。
|
||||
|
||||
**目录**:
|
||||
```
|
||||
<session-folder>/wisdom/
|
||||
├── learnings.md # 模式和洞察
|
||||
├── decisions.md # 架构和设计决策
|
||||
├── conventions.md # 代码库约定
|
||||
└── issues.md # 已知风险和问题
|
||||
```
|
||||
|
||||
**Worker 加载** (Phase 2): 从 task description 提取 `Session: <path>`, 读取 wisdom 目录下各文件。
|
||||
**Worker 贡献** (Phase 4/5): 将本任务发现写入对应 wisdom 文件。
|
||||
|
||||
### Role Isolation Rules
|
||||
|
||||
| 允许 | 禁止 |
|
||||
|------|------|
|
||||
| 处理自己前缀的任务 | 处理其他角色前缀的任务 |
|
||||
| SendMessage 给 coordinator | 直接与其他 worker 通信 |
|
||||
| 使用 Toolbox 中声明的工具 | 为其他角色创建任务 |
|
||||
| 委派给 commands/ 中的命令 | 修改不属于本职责的资源 |
|
||||
|
||||
Coordinator 额外禁止: 直接编写/修改代码、调用实现类 subagent、直接执行分析/测试/审查。
|
||||
|
||||
---
|
||||
|
||||
## Pipeline Definitions
|
||||
|
||||
### Spec-only (12 tasks)
|
||||
|
||||
```
|
||||
RESEARCH-001 → DISCUSS-001 → DRAFT-001 → DISCUSS-002
|
||||
→ DRAFT-002 → DISCUSS-003 → DRAFT-003 → DISCUSS-004
|
||||
→ DRAFT-004 → DISCUSS-005 → QUALITY-001 → DISCUSS-006
|
||||
```
|
||||
|
||||
### Impl-only / Backend (4 tasks)
|
||||
|
||||
```
|
||||
PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001
|
||||
```
|
||||
|
||||
### Full-lifecycle (16 tasks)
|
||||
|
||||
```
|
||||
[Spec pipeline] → PLAN-001(blockedBy: DISCUSS-006) → 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
|
||||
```
|
||||
|
||||
### Task Metadata Registry
|
||||
|
||||
| Task ID | Role | Phase | Dependencies | Description |
|
||||
|---------|------|-------|-------------|-------------|
|
||||
| RESEARCH-001 | analyst | spec | (none) | Seed analysis and context gathering |
|
||||
| DISCUSS-001 | discussant | spec | RESEARCH-001 | Critique research findings |
|
||||
| DRAFT-001 | writer | spec | DISCUSS-001 | Generate Product Brief |
|
||||
| DISCUSS-002 | discussant | spec | DRAFT-001 | Critique Product Brief |
|
||||
| DRAFT-002 | writer | spec | DISCUSS-002 | Generate Requirements/PRD |
|
||||
| DISCUSS-003 | discussant | spec | DRAFT-002 | Critique Requirements/PRD |
|
||||
| DRAFT-003 | writer | spec | DISCUSS-003 | Generate Architecture Document |
|
||||
| DISCUSS-004 | discussant | spec | DRAFT-003 | Critique Architecture Document |
|
||||
| DRAFT-004 | writer | spec | DISCUSS-004 | Generate Epics & Stories |
|
||||
| DISCUSS-005 | discussant | spec | DRAFT-004 | Critique Epics |
|
||||
| QUALITY-001 | reviewer | spec | DISCUSS-005 | 5-dimension spec quality validation |
|
||||
| DISCUSS-006 | discussant | spec | QUALITY-001 | Final review discussion and sign-off |
|
||||
| PLAN-001 | planner | impl | (none or DISCUSS-006) | Multi-angle exploration and planning |
|
||||
| IMPL-001 | executor | impl | PLAN-001 | Code implementation |
|
||||
| TEST-001 | tester | impl | IMPL-001 | Test-fix cycles |
|
||||
| REVIEW-001 | reviewer | impl | IMPL-001 | 4-dimension code review |
|
||||
| DEV-FE-001 | fe-developer | impl | PLAN-001 | Frontend implementation |
|
||||
| QA-FE-001 | fe-qa | impl | DEV-FE-001 | 5-dimension frontend QA |
|
||||
|
||||
## Coordinator Spawn Template
|
||||
|
||||
When coordinator spawns workers, use background mode (Spawn-and-Stop):
|
||||
|
||||
```
|
||||
Task({
|
||||
subagent_type: "general-purpose",
|
||||
description: "Spawn <role> worker",
|
||||
team_name: <team-name>,
|
||||
name: "<role>",
|
||||
run_in_background: true,
|
||||
prompt: `你是 team "<team-name>" 的 <ROLE>.
|
||||
|
||||
## 首要指令
|
||||
你的所有工作必须通过调用 Skill 获取角色定义后执行:
|
||||
Skill(skill="team-lifecycle-v3", args="--role=<role>")
|
||||
|
||||
当前需求: <task-description>
|
||||
Session: <session-folder>
|
||||
|
||||
## 角色准则
|
||||
- 只处理 <PREFIX>-* 任务,不执行其他角色工作
|
||||
- 所有输出带 [<role>] 标识前缀
|
||||
- 仅与 coordinator 通信
|
||||
- 不使用 TaskCreate 为其他角色创建任务
|
||||
- 每次 SendMessage 前先调用 mcp__ccw-tools__team_msg 记录
|
||||
|
||||
## 工作流程
|
||||
1. 调用 Skill → 获取角色定义和执行逻辑
|
||||
2. 按 role.md 5-Phase 流程执行
|
||||
3. team_msg + SendMessage 结果给 coordinator
|
||||
4. TaskUpdate completed → 检查下一个任务`
|
||||
})
|
||||
```
|
||||
|
||||
## Session Directory
|
||||
|
||||
```
|
||||
.workflow/.team/TLS-<slug>-<date>/
|
||||
├── team-session.json # Session state
|
||||
├── spec/ # Spec artifacts
|
||||
│ ├── spec-config.json
|
||||
│ ├── discovery-context.json
|
||||
│ ├── product-brief.md
|
||||
│ ├── requirements/
|
||||
│ ├── architecture/
|
||||
│ ├── epics/
|
||||
│ ├── readiness-report.md
|
||||
│ └── spec-summary.md
|
||||
├── discussions/ # Discussion records
|
||||
├── plan/ # Plan artifacts
|
||||
│ ├── plan.json
|
||||
│ └── .task/TASK-*.json
|
||||
├── explorations/ # Explorer output (cached)
|
||||
├── architecture/ # Architect assessments
|
||||
├── qa/ # QA audit reports
|
||||
├── wisdom/ # Cross-task knowledge
|
||||
│ ├── learnings.md
|
||||
│ ├── decisions.md
|
||||
│ ├── conventions.md
|
||||
│ └── issues.md
|
||||
└── shared-memory.json # Cross-role state
|
||||
```
|
||||
|
||||
## 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 Spec Resources
|
||||
|
||||
| Resource | Path | Usage |
|
||||
|----------|------|-------|
|
||||
| Document Standards | specs/document-standards.md | YAML frontmatter, naming, structure |
|
||||
| Quality Gates | specs/quality-gates.md | Per-phase quality gates |
|
||||
| Product Brief Template | templates/product-brief.md | DRAFT-001 |
|
||||
| Requirements Template | templates/requirements-prd.md | DRAFT-002 |
|
||||
| Architecture Template | templates/architecture-doc.md | DRAFT-003 |
|
||||
| Epics Template | templates/epics-template.md | DRAFT-004 |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Unknown --role value | Error with available role list |
|
||||
| Missing --role arg | Orchestration Mode → coordinator |
|
||||
| Role file not found | Error with expected path |
|
||||
| Command file not found | Fallback to inline execution |
|
||||
108
.claude/skills/team-lifecycle-v3/roles/analyst/role.md
Normal file
108
.claude/skills/team-lifecycle-v3/roles/analyst/role.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# Role: analyst
|
||||
|
||||
Seed analysis, codebase exploration, and multi-dimensional context gathering. Maps to spec-generator Phase 1 (Discovery).
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `analyst` | **Prefix**: `RESEARCH-*` | **Tag**: `[analyst]`
|
||||
- **Responsibility**: Seed Analysis → Codebase Exploration → Context Packaging → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process RESEARCH-* tasks
|
||||
- Communicate only with coordinator
|
||||
- Generate discovery-context.json and spec-config.json
|
||||
- Support file reference input (@ prefix or .md/.txt extension)
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks for other roles
|
||||
- Directly contact other workers
|
||||
- Modify spec documents (only create discovery artifacts)
|
||||
- Skip seed analysis step
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| research_ready | → coordinator | Research complete |
|
||||
| research_progress | → coordinator | Long research progress update |
|
||||
| error | → coordinator | Unrecoverable error |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| ccw cli --tool gemini --mode analysis | Seed analysis |
|
||||
| mcp__ace-tool__search_context | Codebase semantic search |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Seed Analysis
|
||||
|
||||
**Objective**: Extract structured seed information from the topic/idea.
|
||||
|
||||
**Workflow**:
|
||||
1. Extract session folder from task description (`Session: <path>`)
|
||||
2. Parse topic from task description (first non-metadata line)
|
||||
3. If topic starts with `@` or ends with `.md`/`.txt` → Read the referenced file as topic content
|
||||
4. Run Gemini CLI seed analysis:
|
||||
|
||||
```
|
||||
Bash({
|
||||
command: `ccw cli -p "PURPOSE: Analyze topic and extract structured seed information.
|
||||
TASK: • Extract problem statement • Identify target users • Determine domain context
|
||||
• List constraints and assumptions • Identify 3-5 exploration dimensions • Assess complexity
|
||||
TOPIC: <topic-content>
|
||||
MODE: analysis
|
||||
EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[], complexity_assessment" --tool gemini --mode analysis`,
|
||||
run_in_background: true
|
||||
})
|
||||
```
|
||||
|
||||
5. Wait for CLI result, parse seed analysis JSON
|
||||
|
||||
**Success**: Seed analysis parsed with problem statement, dimensions, complexity.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Codebase Exploration (conditional)
|
||||
|
||||
**Objective**: Gather codebase context if an existing project is detected.
|
||||
|
||||
| Condition | Action |
|
||||
|-----------|--------|
|
||||
| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore codebase |
|
||||
| No project files | Skip → codebase context = null |
|
||||
|
||||
**When project detected**:
|
||||
1. Report progress: "种子分析完成, 开始代码库探索"
|
||||
2. ACE semantic search for architecture patterns related to topic
|
||||
3. Detect tech stack from package files
|
||||
4. Build codebase context: tech_stack, architecture_patterns, conventions, integration_points
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Context Packaging
|
||||
|
||||
**Objective**: Generate spec-config.json and discovery-context.json.
|
||||
|
||||
**spec-config.json** → `<session-folder>/spec/spec-config.json`:
|
||||
- session_id, topic, status="research_complete", complexity, depth, focus_areas, mode="interactive"
|
||||
|
||||
**discovery-context.json** → `<session-folder>/spec/discovery-context.json`:
|
||||
- session_id, phase=1, seed_analysis (all fields), codebase_context (or null), recommendations
|
||||
|
||||
**Report**: complexity, codebase presence, problem statement, exploration dimensions, output paths.
|
||||
|
||||
**Success**: Both JSON files created, report sent.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Gemini CLI failure | Fallback to direct Claude analysis |
|
||||
| Codebase detection failed | Continue as new project |
|
||||
| Topic too vague | Report with clarification questions |
|
||||
@@ -0,0 +1,193 @@
|
||||
# Command: assess
|
||||
|
||||
## Purpose
|
||||
|
||||
Multi-mode architecture assessment. Auto-detects consultation mode from task subject prefix, runs mode-specific analysis, and produces a verdict with concerns and recommendations.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
### Common Context (all modes)
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Session folder | Task description `Session:` field | Yes |
|
||||
| Wisdom | `<session_folder>/wisdom/` (all files) | No |
|
||||
| Project tech | `.workflow/project-tech.json` | No |
|
||||
| Explorations | `<session_folder>/explorations/` | No |
|
||||
|
||||
### Mode-Specific Context
|
||||
|
||||
| Mode | Task Pattern | Additional Context |
|
||||
|------|-------------|-------------------|
|
||||
| spec-review | ARCH-SPEC-* | `spec/architecture/_index.md`, `spec/architecture/ADR-*.md` |
|
||||
| plan-review | ARCH-PLAN-* | `plan/plan.json`, `plan/.task/TASK-*.json` |
|
||||
| code-review | ARCH-CODE-* | `git diff --name-only`, changed file contents |
|
||||
| consult | ARCH-CONSULT-* | Question extracted from task description |
|
||||
| feasibility | ARCH-FEASIBILITY-* | Proposal from task description, codebase search results |
|
||||
|
||||
## Phase 3: Mode-Specific Assessment
|
||||
|
||||
### Mode: spec-review
|
||||
|
||||
Review architecture documents for technical soundness across 4 dimensions.
|
||||
|
||||
**Assessment dimensions**:
|
||||
|
||||
| Dimension | Weight | Focus |
|
||||
|-----------|--------|-------|
|
||||
| Consistency | 25% | ADR decisions align with each other and with architecture index |
|
||||
| Scalability | 25% | Design supports growth, no single-point bottlenecks |
|
||||
| Security | 25% | Auth model, data protection, API security addressed |
|
||||
| Tech fitness | 25% | Technology choices match project-tech.json and problem domain |
|
||||
|
||||
**Checks**:
|
||||
- Read architecture index and all ADR files
|
||||
- Cross-reference ADR decisions for contradictions
|
||||
- Verify tech choices align with project-tech.json
|
||||
- Score each dimension 0-100
|
||||
|
||||
---
|
||||
|
||||
### Mode: plan-review
|
||||
|
||||
Review implementation plan for architectural soundness.
|
||||
|
||||
**Checks**:
|
||||
|
||||
| Check | What | Severity if Failed |
|
||||
|-------|------|-------------------|
|
||||
| Dependency cycles | Build task graph, detect cycles via DFS | High |
|
||||
| Task granularity | Flag tasks touching >8 files | Medium |
|
||||
| Convention compliance | Verify plan follows wisdom/conventions.md | Medium |
|
||||
| Architecture alignment | Verify plan doesn't contradict wisdom/decisions.md | High |
|
||||
|
||||
**Dependency cycle detection flow**:
|
||||
1. Parse all TASK-*.json files -> extract id and depends_on
|
||||
2. Build directed graph
|
||||
3. DFS traversal -> flag any node visited twice in same stack
|
||||
4. Report cycle path if found
|
||||
|
||||
---
|
||||
|
||||
### Mode: code-review
|
||||
|
||||
Assess architectural impact of code changes.
|
||||
|
||||
**Checks**:
|
||||
|
||||
| Check | Method | Severity if Found |
|
||||
|-------|--------|-------------------|
|
||||
| Layer violations | Detect upward imports (deeper layer importing shallower) | High |
|
||||
| New dependencies | Parse package.json diff for added deps | Medium |
|
||||
| Module boundary changes | Flag index.ts/index.js modifications | Medium |
|
||||
| Architectural impact | Score based on file count and boundary changes | Info |
|
||||
|
||||
**Impact scoring**:
|
||||
|
||||
| Condition | Impact Level |
|
||||
|-----------|-------------|
|
||||
| Changed files > 10 | High |
|
||||
| index.ts/index.js or package.json modified | Medium |
|
||||
| All other cases | Low |
|
||||
|
||||
**Detection example** (find changed files):
|
||||
|
||||
```bash
|
||||
Bash(command="git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Mode: consult
|
||||
|
||||
Answer architecture decision questions. Route by question complexity.
|
||||
|
||||
**Complexity detection**:
|
||||
|
||||
| Condition | Classification |
|
||||
|-----------|---------------|
|
||||
| Question > 200 chars OR matches: architect, design, pattern, refactor, migrate, scalab | Complex |
|
||||
| All other questions | Simple |
|
||||
|
||||
**Complex questions** -> delegate to CLI exploration:
|
||||
|
||||
```bash
|
||||
Bash(command="ccw cli -p \"PURPOSE: Architecture consultation for: <question_summary>
|
||||
TASK: Search codebase for relevant patterns, analyze architectural implications, provide options with trade-offs
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Options with trade-offs, file references, architectural implications
|
||||
CONSTRAINTS: Advisory only, provide options not decisions\" --tool gemini --mode analysis --rule analysis-review-architecture", timeout=300000)
|
||||
```
|
||||
|
||||
**Simple questions** -> direct analysis using available context (wisdom, project-tech, codebase search).
|
||||
|
||||
---
|
||||
|
||||
### Mode: feasibility
|
||||
|
||||
Evaluate technical feasibility of a proposal.
|
||||
|
||||
**Assessment areas**:
|
||||
|
||||
| Area | Method | Output |
|
||||
|------|--------|--------|
|
||||
| Tech stack compatibility | Compare proposal needs against project-tech.json | Compatible / Requires additions |
|
||||
| Codebase readiness | Search for integration points using Grep/Glob | Touch-point count |
|
||||
| Effort estimation | Based on touch-point count (see table below) | Low / Medium / High |
|
||||
| Risk assessment | Based on effort + tech compatibility | Risks + mitigations |
|
||||
|
||||
**Effort estimation**:
|
||||
|
||||
| Touch Points | Effort | Implication |
|
||||
|-------------|--------|-------------|
|
||||
| <= 5 | Low | Straightforward implementation |
|
||||
| 6 - 20 | Medium | Moderate refactoring needed |
|
||||
| > 20 | High | Significant refactoring, consider phasing |
|
||||
|
||||
**Verdict for feasibility**:
|
||||
|
||||
| Condition | Verdict |
|
||||
|-----------|---------|
|
||||
| Low/medium effort, compatible stack | FEASIBLE |
|
||||
| High touch-points OR new tech required | RISKY |
|
||||
| Fundamental incompatibility or unreasonable effort | INFEASIBLE |
|
||||
|
||||
---
|
||||
|
||||
### Verdict Routing (all modes except feasibility)
|
||||
|
||||
| Verdict | Criteria |
|
||||
|---------|----------|
|
||||
| BLOCK | >= 2 high-severity concerns |
|
||||
| CONCERN | >= 1 high-severity OR >= 3 medium-severity concerns |
|
||||
| APPROVE | All other cases |
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
### Output Format
|
||||
|
||||
Write assessment to `<session_folder>/architecture/arch-<slug>.json`.
|
||||
|
||||
**Report content sent to coordinator**:
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| mode | Consultation mode used |
|
||||
| verdict | APPROVE / CONCERN / BLOCK (or FEASIBLE / RISKY / INFEASIBLE) |
|
||||
| concern_count | Number of concerns by severity |
|
||||
| recommendations | Actionable suggestions with trade-offs |
|
||||
| output_path | Path to full assessment file |
|
||||
|
||||
**Wisdom contribution**: Append significant decisions to `<session_folder>/wisdom/decisions.md`.
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Architecture docs not found | Assess from available context, note limitation in report |
|
||||
| Plan file missing | Report to coordinator via arch_concern |
|
||||
| Git diff fails (no commits) | Use staged changes or skip code-review mode |
|
||||
| CLI exploration timeout | Provide partial assessment, flag as incomplete |
|
||||
| Exploration results unparseable | Fall back to direct analysis without exploration |
|
||||
| Insufficient context | Request explorer assistance via coordinator |
|
||||
99
.claude/skills/team-lifecycle-v3/roles/architect/role.md
Normal file
99
.claude/skills/team-lifecycle-v3/roles/architect/role.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# Role: architect
|
||||
|
||||
Architecture consultant. Advice on decisions, feasibility, design patterns.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `architect` | **Prefix**: `ARCH-*` | **Tag**: `[architect]`
|
||||
- **Type**: Consulting (on-demand, advisory only)
|
||||
- **Responsibility**: Context loading → Mode detection → Analysis → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process ARCH-* tasks
|
||||
- Auto-detect mode from task subject prefix
|
||||
- Provide options with trade-offs (not final decisions)
|
||||
|
||||
### MUST NOT
|
||||
- Modify source code
|
||||
- Make final decisions (advisory only)
|
||||
- Execute implementation or testing
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| arch_ready | → coordinator | Assessment complete |
|
||||
| arch_concern | → coordinator | Significant risk found |
|
||||
| error | → coordinator | Analysis failure |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/assess.md | Multi-mode assessment |
|
||||
| cli-explore-agent | Deep architecture exploration |
|
||||
| ccw cli --tool gemini --mode analysis | Architecture analysis |
|
||||
|
||||
---
|
||||
|
||||
## Consultation Modes
|
||||
|
||||
| Task Pattern | Mode | Focus |
|
||||
|-------------|------|-------|
|
||||
| ARCH-SPEC-* | spec-review | Review architecture docs |
|
||||
| ARCH-PLAN-* | plan-review | Review plan soundness |
|
||||
| ARCH-CODE-* | code-review | Assess code change impact |
|
||||
| ARCH-CONSULT-* | consult | Answer architecture questions |
|
||||
| ARCH-FEASIBILITY-* | feasibility | Technical feasibility |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
**Common**: session folder, wisdom, project-tech.json, explorations
|
||||
|
||||
**Mode-specific**:
|
||||
|
||||
| Mode | Additional Context |
|
||||
|------|-------------------|
|
||||
| spec-review | architecture/_index.md, ADR-*.md |
|
||||
| plan-review | plan/plan.json |
|
||||
| code-review | git diff, changed files |
|
||||
| consult | Question from task description |
|
||||
| feasibility | Requirements + codebase |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Assessment
|
||||
|
||||
Delegate to `commands/assess.md`. Output: mode, verdict (APPROVE/CONCERN/BLOCK), dimensions[], concerns[], recommendations[].
|
||||
|
||||
For complex questions → Gemini CLI with architecture review rule.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Report
|
||||
|
||||
Output to `<session-folder>/architecture/arch-<slug>.json`. Contribute decisions to wisdom/decisions.md.
|
||||
|
||||
**Report**: mode, verdict, concern count, recommendations, output path.
|
||||
|
||||
---
|
||||
|
||||
## Coordinator Integration
|
||||
|
||||
| Timing | Task |
|
||||
|--------|------|
|
||||
| After DRAFT-003 | ARCH-SPEC-001: 架构文档评审 |
|
||||
| After PLAN-001 | ARCH-PLAN-001: 计划架构审查 |
|
||||
| On-demand | ARCH-CONSULT-001: 架构咨询 |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Docs not found | Assess from available context |
|
||||
| CLI timeout | Partial assessment |
|
||||
| Insufficient context | Request explorer via coordinator |
|
||||
174
.claude/skills/team-lifecycle-v3/roles/coordinator/role.md
Normal file
174
.claude/skills/team-lifecycle-v3/roles/coordinator/role.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# Coordinator Role
|
||||
|
||||
Orchestrate the team-lifecycle workflow: team creation, task dispatching, progress monitoring, session state.
|
||||
|
||||
## 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
|
||||
- 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, first detect the invocation type:
|
||||
|
||||
| Detection | Condition | Handler |
|
||||
|-----------|-----------|---------|
|
||||
| Worker callback | Message contains `[role-name]` tag from a known worker role | → handleCallback: auto-advance pipeline |
|
||||
| Status check | Arguments contain "check" or "status" | → handleCheck: output execution graph, no advancement |
|
||||
| Manual resume | Arguments contain "resume" or "continue" | → handleResume: check worker states, advance pipeline |
|
||||
| New session | None of the above | → Phase 0 (Session Resume Check) |
|
||||
|
||||
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.
|
||||
|
||||
**Workflow**:
|
||||
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 (bidirectional sync)
|
||||
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.
|
||||
|
||||
**Workflow**:
|
||||
|
||||
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 (component, page, UI, React, Vue, CSS...) | Keyword match in description | impl-only → fe-only or fullstack |
|
||||
| BE keywords also present (API, database, server...) | 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
|
||||
|
||||
**Success**: All parameters captured, mode finalized.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Create Team + Initialize Session
|
||||
|
||||
**Objective**: Initialize team, session file, and wisdom directory.
|
||||
|
||||
**Workflow**:
|
||||
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. Write team-session.json with: session_id, mode, scope, status="active", tasks_total, tasks_completed=0
|
||||
|
||||
**Task counts by mode**:
|
||||
|
||||
| Mode | Tasks |
|
||||
|------|-------|
|
||||
| spec-only | 12 |
|
||||
| impl-only | 4 |
|
||||
| fe-only | 3 |
|
||||
| fullstack | 6 |
|
||||
| full-lifecycle | 16 |
|
||||
| full-lifecycle-fe | 18 |
|
||||
|
||||
**Success**: Team created, session file written, wisdom initialized.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Create Task Chain
|
||||
|
||||
**Objective**: Dispatch tasks based on mode with proper dependencies.
|
||||
|
||||
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
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Spawn-and-Stop
|
||||
|
||||
**Objective**: Spawn first batch of ready workers in background, then STOP.
|
||||
|
||||
**Design**: Spawn-and-Stop + Callback pattern.
|
||||
- Spawn workers with `Task(run_in_background: true)` → immediately return
|
||||
- Worker completes → SendMessage callback → auto-advance
|
||||
- User can use "check" / "resume" to manually advance
|
||||
- Coordinator does one operation per invocation, then STOPS
|
||||
|
||||
**Workflow**:
|
||||
1. Load `commands/monitor.md`
|
||||
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
|
||||
3. For each ready task → spawn worker (see SKILL.md Spawn Template)
|
||||
4. Output status summary
|
||||
5. STOP
|
||||
|
||||
**Pipeline advancement** driven by three wake sources:
|
||||
- Worker callback (automatic) → Entry Router → handleCallback
|
||||
- User "check" → handleCheck (status only)
|
||||
- User "resume" → handleResume (advance)
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Report + Next Steps
|
||||
|
||||
**Objective**: Completion report and follow-up options.
|
||||
|
||||
**Workflow**:
|
||||
1. Load session state → count completed tasks, duration
|
||||
2. List deliverables with output paths
|
||||
3. Update session status → "completed"
|
||||
4. Offer next steps: 退出 / 查看产物 / 扩展任务 / 生成 lite-plan / 创建 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 |
|
||||
117
.claude/skills/team-lifecycle-v3/roles/discussant/role.md
Normal file
117
.claude/skills/team-lifecycle-v3/roles/discussant/role.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Role: discussant
|
||||
|
||||
Multi-perspective critique, consensus building, and conflict escalation. Ensures quality feedback between each phase transition.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `discussant` | **Prefix**: `DISCUSS-*` | **Tag**: `[discussant]`
|
||||
- **Responsibility**: Load Artifact → Multi-Perspective Critique → Synthesize Consensus → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process DISCUSS-* tasks
|
||||
- Execute multi-perspective critique via CLI tools
|
||||
- Detect coverage gaps from coverage perspective
|
||||
- Synthesize consensus with convergent/divergent analysis
|
||||
- Write discussion records to `discussions/` folder
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks
|
||||
- Contact other workers directly
|
||||
- Modify spec documents directly
|
||||
- Skip perspectives defined in round config
|
||||
- Ignore critical divergences
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| discussion_ready | → coordinator | Consensus reached |
|
||||
| discussion_blocked | → coordinator | Cannot reach consensus |
|
||||
| error | → coordinator | Input artifact missing |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/critique.md | Multi-perspective CLI critique |
|
||||
| gemini CLI | Product, Risk, Coverage perspectives |
|
||||
| codex CLI | Technical perspective |
|
||||
| claude CLI | Quality perspective |
|
||||
|
||||
---
|
||||
|
||||
## Perspective Model
|
||||
|
||||
| Perspective | Focus | CLI Tool |
|
||||
|-------------|-------|----------|
|
||||
| Product | Market fit, user value, business viability | gemini |
|
||||
| Technical | Feasibility, tech debt, performance, security | codex |
|
||||
| Quality | Completeness, testability, consistency | claude |
|
||||
| Risk | Risk identification, dependency analysis, failure modes | gemini |
|
||||
| Coverage | Requirement completeness vs original intent, gap detection | gemini |
|
||||
|
||||
## Round Configuration
|
||||
|
||||
| Round | Artifact | Perspectives | Focus |
|
||||
|-------|----------|-------------|-------|
|
||||
| DISCUSS-001 | spec/discovery-context.json | product, risk, coverage | Scope confirmation |
|
||||
| DISCUSS-002 | spec/product-brief.md | product, technical, quality, coverage | Positioning, feasibility |
|
||||
| DISCUSS-003 | spec/requirements/_index.md | quality, product, coverage | Completeness, priority |
|
||||
| DISCUSS-004 | spec/architecture/_index.md | technical, risk | Tech choices, security |
|
||||
| DISCUSS-005 | spec/epics/_index.md | product, technical, quality, coverage | MVP scope, estimation |
|
||||
| DISCUSS-006 | spec/readiness-report.md | all 5 | Final sign-off |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Artifact Loading
|
||||
|
||||
**Objective**: Load target artifact and determine discussion parameters.
|
||||
|
||||
**Workflow**:
|
||||
1. Extract session folder and round number from task subject (`DISCUSS-<NNN>`)
|
||||
2. Look up round config from table above
|
||||
3. Load target artifact from `<session-folder>/<artifact-path>`
|
||||
4. Create `<session-folder>/discussions/` directory
|
||||
5. Load prior discussion records for continuity
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Multi-Perspective Critique
|
||||
|
||||
**Objective**: Run parallel CLI analyses from each required perspective.
|
||||
|
||||
Delegate to `commands/critique.md` -- launches parallel CLI calls per perspective with focused prompts and designated tools.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Consensus Synthesis
|
||||
|
||||
**Objective**: Synthesize into consensus with actionable outcomes.
|
||||
|
||||
**Synthesis process**:
|
||||
1. Extract convergent themes (agreed by 2+ perspectives)
|
||||
2. Extract divergent views (conflicting perspectives, with severity)
|
||||
3. Check coverage gaps from coverage perspective
|
||||
4. Compile action items and open questions
|
||||
|
||||
**Consensus routing**:
|
||||
|
||||
| Condition | Status | Report |
|
||||
|-----------|--------|--------|
|
||||
| No high-severity divergences | consensus_reached | Action items, open questions, record path |
|
||||
| Any high-severity divergences | consensus_blocked | Escalate divergence points to coordinator |
|
||||
|
||||
Write discussion record to `<session-folder>/discussions/<output-file>`.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Target artifact not found | Notify coordinator |
|
||||
| CLI perspective failure | Fallback to direct Claude analysis |
|
||||
| All CLI analyses fail | Generate basic discussion from direct reading |
|
||||
| All perspectives diverge | Escalate as discussion_blocked |
|
||||
103
.claude/skills/team-lifecycle-v3/roles/executor/role.md
Normal file
103
.claude/skills/team-lifecycle-v3/roles/executor/role.md
Normal file
@@ -0,0 +1,103 @@
|
||||
# Role: executor
|
||||
|
||||
Code implementation following approved plans. Multi-backend execution with self-validation.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `executor` | **Prefix**: `IMPL-*` | **Tag**: `[executor]`
|
||||
- **Responsibility**: Load plan → Route to backend → Implement → Self-validate → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process IMPL-* tasks
|
||||
- Follow approved plan exactly
|
||||
- Use declared execution backends
|
||||
- Self-validate all implementations
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks
|
||||
- Contact other workers directly
|
||||
- Modify plan files
|
||||
- Skip self-validation
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| impl_complete | → coordinator | Implementation success |
|
||||
| impl_progress | → coordinator | Batch progress |
|
||||
| error | → coordinator | Implementation failure |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/implement.md | Multi-backend implementation |
|
||||
| code-developer agent | Simple tasks (synchronous) |
|
||||
| ccw cli --tool codex --mode write | Complex tasks |
|
||||
| ccw cli --tool gemini --mode write | Alternative backend |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Task & Plan Loading
|
||||
|
||||
**Objective**: Load plan and determine execution strategy.
|
||||
|
||||
1. Load plan.json and .task/TASK-*.json from `<session-folder>/plan/`
|
||||
|
||||
**Backend selection** (priority order):
|
||||
|
||||
| Priority | Source | Method |
|
||||
|----------|--------|--------|
|
||||
| 1 | Task metadata | task.metadata.executor field |
|
||||
| 2 | Plan default | "Execution Backend:" in plan |
|
||||
| 3 | Auto-select | Simple (< 200 chars, no refactor) → agent; Complex → codex |
|
||||
|
||||
**Code review selection**:
|
||||
|
||||
| Priority | Source | Method |
|
||||
|----------|--------|--------|
|
||||
| 1 | Task metadata | task.metadata.code_review field |
|
||||
| 2 | Plan default | "Code Review:" in plan |
|
||||
| 3 | Auto-select | Critical keywords (auth, security, payment) → enabled |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Code Implementation
|
||||
|
||||
**Objective**: Execute implementation across batches.
|
||||
|
||||
**Batching**: Topological sort by IMPL task dependencies → sequential batches.
|
||||
|
||||
Delegate to `commands/implement.md` for prompt building and backend routing:
|
||||
|
||||
| Backend | Invocation | Use Case |
|
||||
|---------|-----------|----------|
|
||||
| agent | Task({ subagent_type: "code-developer", run_in_background: false }) | Simple, direct edits |
|
||||
| codex | ccw cli --tool codex --mode write (background) | Complex, architecture |
|
||||
| gemini | ccw cli --tool gemini --mode write (background) | Analysis-heavy |
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Self-Validation
|
||||
|
||||
| Step | Method | Pass Criteria |
|
||||
|------|--------|--------------|
|
||||
| Syntax check | `tsc --noEmit` (30s) | Exit code 0 |
|
||||
| Acceptance criteria | Match criteria keywords vs implementation | All addressed |
|
||||
| Test detection | Find .test.ts/.spec.ts for modified files | Tests identified |
|
||||
| Code review (optional) | gemini analysis or codex review | No blocking issues |
|
||||
|
||||
**Report**: task ID, status, files modified, validation results, backend used.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Syntax errors | Retry with error context (max 3) |
|
||||
| Missing dependencies | Request from coordinator |
|
||||
| Backend unavailable | Fallback to agent |
|
||||
| Circular dependencies | Abort, report graph |
|
||||
91
.claude/skills/team-lifecycle-v3/roles/explorer/role.md
Normal file
91
.claude/skills/team-lifecycle-v3/roles/explorer/role.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# Role: explorer
|
||||
|
||||
Code search, pattern discovery, dependency tracing. Service role, on-demand.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `explorer` | **Prefix**: `EXPLORE-*` | **Tag**: `[explorer]`
|
||||
- **Type**: Service (on-demand, not on main pipeline)
|
||||
- **Responsibility**: Parse request → Multi-strategy search → Package results
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process EXPLORE-* tasks
|
||||
- Output structured JSON
|
||||
- Cache results in `<session>/explorations/`
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks or modify source code
|
||||
- Execute analysis, planning, or implementation
|
||||
- Make architectural decisions (only discover patterns)
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| explore_ready | → coordinator | Search complete |
|
||||
| task_failed | → coordinator | Search failure |
|
||||
|
||||
## Search Tools (priority order)
|
||||
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Request Parsing
|
||||
|
||||
Parse from task description:
|
||||
|
||||
| Field | Pattern | Default |
|
||||
|-------|---------|---------|
|
||||
| Session | `Session: <path>` | .workflow/.tmp |
|
||||
| Mode | `Mode: codebase\|external\|hybrid` | codebase |
|
||||
| Angles | `Angles: <list>` | general |
|
||||
| Keywords | `Keywords: <list>` | from subject |
|
||||
| Requester | `Requester: <role>` | coordinator |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Multi-Strategy Search
|
||||
|
||||
Execute strategies in priority order, accumulating findings:
|
||||
|
||||
1. **ACE (P0)**: Per keyword → semantic search → relevant_files
|
||||
2. **Grep (P1)**: Per keyword → class/function/export definitions → relevant_files
|
||||
3. **Dependency trace**: Top 10 files → Read imports → dependencies
|
||||
4. **Deep exploration** (multi-angle): Per angle → cli-explore-agent → merge
|
||||
5. **External (P3)** (external/hybrid mode): Top 3 keywords → WebSearch
|
||||
|
||||
Deduplicate by path.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Package Results
|
||||
|
||||
Write JSON to `<output-dir>/explore-<slug>.json`:
|
||||
- relevant_files[], patterns[], dependencies[], external_refs[], _metadata
|
||||
|
||||
**Report**: file count, pattern count, top files, output path.
|
||||
|
||||
---
|
||||
|
||||
## Coordinator Integration
|
||||
|
||||
| Trigger | Example Task |
|
||||
|---------|-------------|
|
||||
| RESEARCH needs context | EXPLORE-001: 代码库搜索 |
|
||||
| PLAN needs exploration | EXPLORE-002: 实现代码探索 |
|
||||
| DISCUSS needs practices | EXPLORE-003: 外部文档 |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| ACE unavailable | Fallback to Grep |
|
||||
| No results | Report empty, suggest broader keywords |
|
||||
111
.claude/skills/team-lifecycle-v3/roles/fe-developer/role.md
Normal file
111
.claude/skills/team-lifecycle-v3/roles/fe-developer/role.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# Role: fe-developer
|
||||
|
||||
Frontend development. Consumes plan/architecture output, implements components, pages, styles.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `fe-developer` | **Prefix**: `DEV-FE-*` | **Tag**: `[fe-developer]`
|
||||
- **Type**: Frontend pipeline worker
|
||||
- **Responsibility**: Context loading → Design token consumption → Component implementation → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process DEV-FE-* tasks
|
||||
- Follow existing design tokens and component specs (if available)
|
||||
- Generate accessible frontend code (semantic HTML, ARIA, keyboard nav)
|
||||
- Follow project's frontend tech stack
|
||||
|
||||
### MUST NOT
|
||||
- Modify backend code or API interfaces
|
||||
- Contact other workers directly
|
||||
- Introduce new frontend dependencies without architecture review
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| dev_fe_complete | → coordinator | Implementation done |
|
||||
| dev_fe_progress | → coordinator | Long task progress |
|
||||
| error | → coordinator | Implementation failure |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| code-developer agent | Component implementation |
|
||||
| ccw cli --tool gemini --mode write | Complex frontend generation |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
**Inputs to load**:
|
||||
- Plan: `<session-folder>/plan/plan.json`
|
||||
- Design tokens: `<session-folder>/architecture/design-tokens.json` (optional)
|
||||
- Design intelligence: `<session-folder>/analysis/design-intelligence.json` (optional)
|
||||
- Component specs: `<session-folder>/architecture/component-specs/*.md` (optional)
|
||||
- Shared memory, wisdom
|
||||
|
||||
**Tech stack detection**:
|
||||
|
||||
| Signal | Framework | Styling |
|
||||
|--------|-----------|---------|
|
||||
| react/react-dom in deps | react | - |
|
||||
| vue in deps | vue | - |
|
||||
| next in deps | nextjs | - |
|
||||
| tailwindcss in deps | - | tailwind |
|
||||
| @shadcn/ui in deps | - | shadcn |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Frontend Implementation
|
||||
|
||||
**Step 1**: Generate design token CSS (if tokens available)
|
||||
- Convert design-tokens.json → CSS custom properties (`:root { --color-*, --space-*, --text-* }`)
|
||||
- Include dark mode overrides via `@media (prefers-color-scheme: dark)`
|
||||
- Write to `src/styles/tokens.css`
|
||||
|
||||
**Step 2**: Implement components
|
||||
|
||||
| Task Size | Strategy |
|
||||
|-----------|----------|
|
||||
| Simple (≤ 3 files, single component) | code-developer agent (synchronous) |
|
||||
| Complex (system, multi-component) | ccw cli --tool gemini --mode write (background) |
|
||||
|
||||
**Coding standards** (include in agent/CLI prompt):
|
||||
- Use design token CSS variables, never hardcode colors/spacing
|
||||
- Interactive elements: cursor: pointer
|
||||
- Transitions: 150-300ms
|
||||
- Text contrast: minimum 4.5:1
|
||||
- Include focus-visible styles
|
||||
- Support prefers-reduced-motion
|
||||
- Responsive: mobile-first
|
||||
- No emoji as functional icons
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Self-Validation
|
||||
|
||||
| Check | What |
|
||||
|-------|------|
|
||||
| hardcoded-color | No #hex outside tokens.css |
|
||||
| cursor-pointer | Interactive elements have cursor: pointer |
|
||||
| focus-styles | Interactive elements have focus styles |
|
||||
| responsive | Has responsive breakpoints |
|
||||
| reduced-motion | Animations respect prefers-reduced-motion |
|
||||
| emoji-icon | No emoji as functional icons |
|
||||
|
||||
Contribute to wisdom/conventions.md. Update shared-memory.json with component inventory.
|
||||
|
||||
**Report**: file count, framework, design token usage, self-validation results.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Design tokens not found | Use project defaults |
|
||||
| Tech stack undetected | Default HTML + CSS |
|
||||
| Subagent failure | Fallback to CLI write mode |
|
||||
@@ -0,0 +1,152 @@
|
||||
# Command: pre-delivery-checklist
|
||||
|
||||
## Purpose
|
||||
|
||||
CSS-level pre-delivery checks for frontend files. Validates accessibility, interaction, design compliance, and layout patterns before final delivery.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Changed frontend files | git diff --name-only (filtered to .tsx, .jsx, .css, .scss) | Yes |
|
||||
| File contents | Read each changed file | Yes |
|
||||
| Design tokens path | `src/styles/tokens.css` or equivalent | No |
|
||||
| Session folder | Task description `Session:` field | Yes |
|
||||
|
||||
## Phase 3: Checklist Execution
|
||||
|
||||
### Category 1: Accessibility (6 items)
|
||||
|
||||
| # | Check | Pattern to Detect | Severity |
|
||||
|---|-------|--------------------|----------|
|
||||
| 1 | Images have alt text | `<img` without `alt=` | CRITICAL |
|
||||
| 2 | Form inputs have labels | `<input` without `<label` or `aria-label` | HIGH |
|
||||
| 3 | Focus states visible | Interactive elements without `:focus` styles | HIGH |
|
||||
| 4 | Color contrast 4.5:1 | Light text on light background patterns | HIGH |
|
||||
| 5 | prefers-reduced-motion | Animations without `@media (prefers-reduced-motion)` | MEDIUM |
|
||||
| 6 | Heading hierarchy | Skipped heading levels (h1 followed by h3) | MEDIUM |
|
||||
|
||||
**Do / Don't**:
|
||||
|
||||
| # | Do | Don't |
|
||||
|---|-----|-------|
|
||||
| 1 | Always provide descriptive alt text | Leave alt empty without `role="presentation"` |
|
||||
| 2 | Associate every input with a label | Use placeholder as sole label |
|
||||
| 3 | Add `focus-visible` outline | Remove default focus ring without replacement |
|
||||
| 4 | Ensure 4.5:1 minimum contrast ratio | Use low-contrast decorative text for content |
|
||||
| 5 | Wrap in `@media (prefers-reduced-motion: no-preference)` | Force animations on all users |
|
||||
| 6 | Use sequential heading levels | Skip levels for visual sizing |
|
||||
|
||||
---
|
||||
|
||||
### Category 2: Interaction (4 items)
|
||||
|
||||
| # | Check | Pattern to Detect | Severity |
|
||||
|---|-------|--------------------|----------|
|
||||
| 7 | cursor-pointer on clickable | Buttons/links without `cursor: pointer` | MEDIUM |
|
||||
| 8 | Transitions 150-300ms | Duration outside 150-300ms range | LOW |
|
||||
| 9 | Loading states | Async operations without loading indicator | MEDIUM |
|
||||
| 10 | Error states | Async operations without error handling UI | HIGH |
|
||||
|
||||
**Do / Don't**:
|
||||
|
||||
| # | Do | Don't |
|
||||
|---|-----|-------|
|
||||
| 7 | Add `cursor: pointer` to all clickable elements | Leave default cursor on buttons |
|
||||
| 8 | Use 150-300ms for micro-interactions | Use >500ms or <100ms transitions |
|
||||
| 9 | Show skeleton/spinner during fetch | Leave blank screen while loading |
|
||||
| 10 | Show user-friendly error message | Silently fail or show raw error |
|
||||
|
||||
---
|
||||
|
||||
### Category 3: Design Compliance (4 items)
|
||||
|
||||
| # | Check | Pattern to Detect | Severity |
|
||||
|---|-------|--------------------|----------|
|
||||
| 11 | No hardcoded colors | Hex values (`#XXXXXX`) outside tokens file | HIGH |
|
||||
| 12 | No hardcoded spacing | Raw `px` values for margin/padding | MEDIUM |
|
||||
| 13 | No emoji as icons | Unicode emoji (U+1F300-1F9FF) in UI code | HIGH |
|
||||
| 14 | Dark mode support | No `prefers-color-scheme` or `.dark` class | MEDIUM |
|
||||
|
||||
**Do / Don't**:
|
||||
|
||||
| # | Do | Don't |
|
||||
|---|-----|-------|
|
||||
| 11 | Use `var(--color-*)` design tokens | Hardcode `#hex` values |
|
||||
| 12 | Use `var(--space-*)` spacing tokens | Hardcode pixel values |
|
||||
| 13 | Use proper SVG/icon library | Use emoji for functional icons |
|
||||
| 14 | Support light/dark themes | Design for light mode only |
|
||||
|
||||
---
|
||||
|
||||
### Category 4: Layout (2 items)
|
||||
|
||||
| # | Check | Pattern to Detect | Severity |
|
||||
|---|-------|--------------------|----------|
|
||||
| 15 | Responsive breakpoints | No `md:`/`lg:`/`@media` queries | MEDIUM |
|
||||
| 16 | No horizontal scroll | Fixed widths greater than viewport | HIGH |
|
||||
|
||||
**Do / Don't**:
|
||||
|
||||
| # | Do | Don't |
|
||||
|---|-----|-------|
|
||||
| 15 | Mobile-first responsive design | Desktop-only layout |
|
||||
| 16 | Use relative/fluid widths | Set fixed pixel widths on containers |
|
||||
|
||||
---
|
||||
|
||||
### Check Execution Strategy
|
||||
|
||||
| Check Scope | Applies To | Method |
|
||||
|-------------|-----------|--------|
|
||||
| Per-file checks | Items 1-4, 7-8, 10-13, 16 | Run against each changed file individually |
|
||||
| Global checks | Items 5-6, 9, 14-15 | Run against concatenated content of all files |
|
||||
|
||||
**Detection example** (check for hardcoded colors):
|
||||
|
||||
```bash
|
||||
Grep(pattern="#[0-9a-fA-F]{6}", path="<file_path>", output_mode="content", "-n"=true)
|
||||
```
|
||||
|
||||
**Detection example** (check for missing alt text):
|
||||
|
||||
```bash
|
||||
Grep(pattern="<img\\s(?![^>]*alt=)", path="<file_path>", output_mode="content", "-n"=true)
|
||||
```
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
### Pass/Fail Criteria
|
||||
|
||||
| Condition | Result |
|
||||
|-----------|--------|
|
||||
| Zero CRITICAL + zero HIGH failures | PASS |
|
||||
| Zero CRITICAL, some HIGH | CONDITIONAL (list fixes needed) |
|
||||
| Any CRITICAL failure | FAIL |
|
||||
|
||||
### Output Format
|
||||
|
||||
```
|
||||
## Pre-Delivery Checklist Results
|
||||
|
||||
- Total checks: <n>
|
||||
- Passed: <n> / <total>
|
||||
- Failed: <n>
|
||||
|
||||
### Failed Items
|
||||
- [CRITICAL] #1 Images have alt text -- <file_path>
|
||||
- [HIGH] #11 No hardcoded colors -- <file_path>:<line>
|
||||
- [MEDIUM] #7 cursor-pointer on clickable -- <file_path>
|
||||
|
||||
### Recommendations
|
||||
(Do/Don't guidance for each failed item)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| No frontend files to check | Report empty checklist, all checks N/A |
|
||||
| File read error | Skip file, note in report |
|
||||
| Regex match error | Skip check, note in report |
|
||||
| Design tokens file not found | Skip items 11-12, adjust total |
|
||||
113
.claude/skills/team-lifecycle-v3/roles/fe-qa/role.md
Normal file
113
.claude/skills/team-lifecycle-v3/roles/fe-qa/role.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# Role: fe-qa
|
||||
|
||||
Frontend quality assurance. 5-dimension review + Generator-Critic loop.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `fe-qa` | **Prefix**: `QA-FE-*` | **Tag**: `[fe-qa]`
|
||||
- **Type**: Frontend pipeline worker
|
||||
- **Responsibility**: Context loading → 5-dimension review → GC feedback → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process QA-FE-* tasks
|
||||
- Execute 5-dimension review
|
||||
- Support Generator-Critic loop (max 2 rounds)
|
||||
- Provide actionable fix suggestions (Do/Don't format)
|
||||
|
||||
### MUST NOT
|
||||
- Modify source code directly (review only)
|
||||
- Contact other workers directly
|
||||
- Mark pass when score below threshold
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| qa_fe_passed | → coordinator | All dimensions pass |
|
||||
| qa_fe_result | → coordinator | Review complete (may have issues) |
|
||||
| fix_required | → coordinator | Critical issues found |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/pre-delivery-checklist.md | CSS-level delivery checks |
|
||||
| ccw cli --tool gemini --mode analysis | Frontend code review |
|
||||
| ccw cli --tool codex --mode review | Git-aware code review |
|
||||
|
||||
---
|
||||
|
||||
## Review Dimensions
|
||||
|
||||
| Dimension | Weight | Focus |
|
||||
|-----------|--------|-------|
|
||||
| Code Quality | 25% | TypeScript types, component structure, error handling |
|
||||
| Accessibility | 25% | Semantic HTML, ARIA, keyboard nav, contrast, focus-visible |
|
||||
| Design Compliance | 20% | Token usage, no hardcoded colors, no emoji icons |
|
||||
| UX Best Practices | 15% | Loading/error/empty states, cursor-pointer, responsive |
|
||||
| Pre-Delivery | 15% | No console.log, dark mode, i18n readiness |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
**Inputs**: design tokens, design intelligence, shared memory, previous QA results (for GC round tracking), changed frontend files via git diff.
|
||||
|
||||
Determine GC round from previous QA results count. Max 2 rounds.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: 5-Dimension Review
|
||||
|
||||
For each changed frontend file, check against all 5 dimensions. Score each dimension 0-10, deducting for issues found.
|
||||
|
||||
**Scoring deductions**:
|
||||
|
||||
| Severity | Deduction |
|
||||
|----------|-----------|
|
||||
| High | -2 to -3 |
|
||||
| Medium | -1 to -1.5 |
|
||||
| Low | -0.5 |
|
||||
|
||||
**Overall score** = weighted sum of dimension scores.
|
||||
|
||||
**Verdict routing**:
|
||||
|
||||
| Condition | Verdict |
|
||||
|-----------|---------|
|
||||
| Score ≥ 8 AND no critical issues | PASS |
|
||||
| GC round ≥ max AND score ≥ 6 | PASS_WITH_WARNINGS |
|
||||
| GC round ≥ max AND score < 6 | FAIL |
|
||||
| Otherwise | NEEDS_FIX |
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Report
|
||||
|
||||
Write audit to `<session-folder>/qa/audit-fe-<task>-r<round>.json`. Update wisdom and shared memory.
|
||||
|
||||
**Report**: round, verdict, overall score, dimension scores, critical issues with Do/Don't format, action required (if NEEDS_FIX).
|
||||
|
||||
---
|
||||
|
||||
## Generator-Critic Loop
|
||||
|
||||
Orchestrated by coordinator:
|
||||
```
|
||||
Round 1: DEV-FE-001 → QA-FE-001
|
||||
if NEEDS_FIX → coordinator creates DEV-FE-002 + QA-FE-002
|
||||
Round 2: DEV-FE-002 → QA-FE-002
|
||||
if still NEEDS_FIX → PASS_WITH_WARNINGS or FAIL (max 2)
|
||||
```
|
||||
|
||||
**Convergence**: score ≥ 8 AND critical_count = 0
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| No changed files | Report empty, score N/A |
|
||||
| Design tokens not found | Skip design compliance, adjust weights |
|
||||
| Max GC rounds exceeded | Force verdict |
|
||||
120
.claude/skills/team-lifecycle-v3/roles/planner/role.md
Normal file
120
.claude/skills/team-lifecycle-v3/roles/planner/role.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# Role: planner
|
||||
|
||||
Multi-angle code exploration and structured implementation planning. Submits plans to coordinator for approval.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `planner` | **Prefix**: `PLAN-*` | **Tag**: `[planner]`
|
||||
- **Responsibility**: Complexity assessment → Code exploration → Plan generation → Approval
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process PLAN-* tasks
|
||||
- Assess complexity before planning
|
||||
- Execute multi-angle exploration for Medium/High complexity
|
||||
- Generate plan.json + .task/TASK-*.json
|
||||
- Load spec context in full-lifecycle mode
|
||||
- Submit plan for coordinator approval
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks for other roles
|
||||
- Implement code
|
||||
- Modify spec documents
|
||||
- Skip complexity assessment
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| plan_ready | → coordinator | Plan complete |
|
||||
| plan_revision | → coordinator | Plan revised per feedback |
|
||||
| error | → coordinator | Exploration or planning failure |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/explore.md | Multi-angle codebase exploration |
|
||||
| cli-explore-agent | Per-angle exploration |
|
||||
| cli-lite-planning-agent | Plan generation |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1.5: Load Spec Context (Full-Lifecycle)
|
||||
|
||||
If `<session-folder>/spec/` exists → load requirements/_index.md, architecture/_index.md, epics/_index.md, spec-config.json. Otherwise → impl-only mode.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Multi-Angle Exploration
|
||||
|
||||
**Objective**: Explore codebase to inform planning.
|
||||
|
||||
**Complexity routing**:
|
||||
|
||||
| Complexity | Criteria | Strategy |
|
||||
|------------|----------|----------|
|
||||
| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only |
|
||||
| Medium | 200-500 chars or moderate scope | 2-3 angle cli-explore-agent |
|
||||
| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle cli-explore-agent |
|
||||
|
||||
Delegate to `commands/explore.md` for angle selection and parallel execution.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Plan Generation
|
||||
|
||||
**Objective**: Generate structured implementation plan.
|
||||
|
||||
| Complexity | Strategy |
|
||||
|------------|----------|
|
||||
| Low | Direct planning → single TASK-001 with plan.json |
|
||||
| Medium/High | cli-lite-planning-agent with exploration results |
|
||||
|
||||
**Agent call** (Medium/High):
|
||||
|
||||
```
|
||||
Task({
|
||||
subagent_type: "cli-lite-planning-agent",
|
||||
run_in_background: false,
|
||||
description: "Generate implementation plan",
|
||||
prompt: "Generate plan.
|
||||
Output: <plan-dir>/plan.json + <plan-dir>/.task/TASK-*.json
|
||||
Schema: cat ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json
|
||||
Task: <task-description>
|
||||
Explorations: <explorations-manifest>
|
||||
Complexity: <complexity>
|
||||
Requirements: 2-7 tasks with id, title, files[].change, convergence.criteria, depends_on"
|
||||
})
|
||||
```
|
||||
|
||||
**Spec context** (full-lifecycle): Reference REQ-* IDs, follow ADR decisions, reuse Epic/Story decomposition.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Submit for Approval
|
||||
|
||||
1. Read plan.json and TASK-*.json
|
||||
2. Report to coordinator: complexity, task count, task list, approach, plan location
|
||||
3. Wait for response: approved → complete; revision → update and resubmit
|
||||
|
||||
**Session files**:
|
||||
```
|
||||
<session-folder>/plan/
|
||||
├── exploration-<angle>.json
|
||||
├── explorations-manifest.json
|
||||
├── plan.json
|
||||
└── .task/TASK-*.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Exploration agent failure | Plan from description only |
|
||||
| Planning agent failure | Fallback to direct planning |
|
||||
| Plan rejected 3+ times | Notify coordinator, suggest alternative |
|
||||
| Schema not found | Use basic structure |
|
||||
@@ -0,0 +1,163 @@
|
||||
# Command: code-review
|
||||
|
||||
## Purpose
|
||||
|
||||
4-dimension code review analyzing quality, security, architecture, and requirements compliance. Produces a verdict (BLOCK/CONDITIONAL/APPROVE) with categorized findings.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Plan file | `<session_folder>/plan/plan.json` | Yes |
|
||||
| Git diff | `git diff HEAD~1` or `git diff --cached` | Yes |
|
||||
| Modified files | From git diff --name-only | Yes |
|
||||
| Test results | Tester output (if available) | No |
|
||||
| Wisdom | `<session_folder>/wisdom/` | No |
|
||||
|
||||
## Phase 3: 4-Dimension Review
|
||||
|
||||
### Dimension Overview
|
||||
|
||||
| Dimension | Focus | Weight |
|
||||
|-----------|-------|--------|
|
||||
| Quality | Code correctness, type safety, clean code | Equal |
|
||||
| Security | Vulnerability patterns, secret exposure | Equal |
|
||||
| Architecture | Module structure, coupling, file size | Equal |
|
||||
| Requirements | Acceptance criteria coverage, completeness | Equal |
|
||||
|
||||
---
|
||||
|
||||
### Dimension 1: Quality
|
||||
|
||||
Scan each modified file for quality anti-patterns.
|
||||
|
||||
| Severity | Pattern | What to Detect |
|
||||
|----------|---------|----------------|
|
||||
| Critical | Empty catch blocks | `catch(e) {}` with no handling |
|
||||
| High | @ts-ignore without justification | Suppression comment < 10 chars explanation |
|
||||
| High | `any` type in public APIs | `any` outside comments and generic definitions |
|
||||
| High | console.log in production | `console.(log\|debug\|info)` outside test files |
|
||||
| Medium | Magic numbers | Numeric literals > 1 digit, not in const/comment |
|
||||
| Medium | Duplicate code | Identical lines (>30 chars) appearing 3+ times |
|
||||
|
||||
**Detection example** (Grep for console statements):
|
||||
|
||||
```bash
|
||||
Grep(pattern="console\\.(log|debug|info)", path="<file_path>", output_mode="content", "-n"=true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Dimension 2: Security
|
||||
|
||||
Scan for vulnerability patterns across all modified files.
|
||||
|
||||
| Severity | Pattern | What to Detect |
|
||||
|----------|---------|----------------|
|
||||
| Critical | Hardcoded secrets | `api_key=`, `password=`, `secret=`, `token=` with string values (20+ chars) |
|
||||
| Critical | SQL injection | String concatenation in `query()`/`execute()` calls |
|
||||
| High | eval/exec usage | `eval()`, `new Function()`, `setTimeout(string)` |
|
||||
| High | XSS vectors | `innerHTML`, `dangerouslySetInnerHTML` |
|
||||
| Medium | Insecure random | `Math.random()` in security context (token/key/password/session) |
|
||||
| Low | Missing input validation | Functions with parameters but no validation in first 5 lines |
|
||||
|
||||
---
|
||||
|
||||
### Dimension 3: Architecture
|
||||
|
||||
Assess structural health of modified files.
|
||||
|
||||
| Severity | Pattern | What to Detect |
|
||||
|----------|---------|----------------|
|
||||
| Critical | Circular dependencies | File A imports B, B imports A |
|
||||
| High | Excessive parent imports | Import traverses >2 parent directories (`../../../`) |
|
||||
| Medium | Large files | Files exceeding 500 lines |
|
||||
| Medium | Tight coupling | >5 imports from same base module |
|
||||
| Medium | Long functions | Functions exceeding 50 lines |
|
||||
| Medium | Module boundary changes | Modifications to index.ts/index.js files |
|
||||
|
||||
**Detection example** (check for deep parent imports):
|
||||
|
||||
```bash
|
||||
Grep(pattern="from\\s+['\"](\\.\\./){3,}", path="<file_path>", output_mode="content", "-n"=true)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Dimension 4: Requirements
|
||||
|
||||
Verify implementation against plan acceptance criteria.
|
||||
|
||||
| Severity | Check | Method |
|
||||
|----------|-------|--------|
|
||||
| High | Unmet acceptance criteria | Extract criteria from plan, check keyword overlap (threshold: 70%) |
|
||||
| High | Missing error handling | Plan mentions "error handling" but no try/catch in code |
|
||||
| Medium | Partially met criteria | Keyword overlap 40-69% |
|
||||
| Medium | Missing tests | Plan mentions "test" but no test files in modified set |
|
||||
|
||||
**Verification flow**:
|
||||
1. Read plan file → extract acceptance criteria section
|
||||
2. For each criterion → extract keywords (4+ char meaningful words)
|
||||
3. Search modified files for keyword matches
|
||||
4. Score: >= 70% match = met, 40-69% = partial, < 40% = unmet
|
||||
|
||||
---
|
||||
|
||||
### Verdict Routing
|
||||
|
||||
| Verdict | Criteria | Action |
|
||||
|---------|----------|--------|
|
||||
| BLOCK | Any critical-severity issues found | Must fix before merge |
|
||||
| CONDITIONAL | High or medium issues, no critical | Should address, can merge with tracking |
|
||||
| APPROVE | Only low issues or none | Ready to merge |
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
### Report Format
|
||||
|
||||
The review report follows this structure:
|
||||
|
||||
```
|
||||
# Code Review Report
|
||||
|
||||
**Verdict**: <BLOCK|CONDITIONAL|APPROVE>
|
||||
|
||||
## Blocking Issues (if BLOCK)
|
||||
- **<type>** (<file>:<line>): <message>
|
||||
|
||||
## Review Dimensions
|
||||
|
||||
### Quality Issues
|
||||
**CRITICAL** (<count>)
|
||||
- <message> (<file>:<line>)
|
||||
|
||||
### Security Issues
|
||||
(same format per severity)
|
||||
|
||||
### Architecture Issues
|
||||
(same format per severity)
|
||||
|
||||
### Requirements Issues
|
||||
(same format per severity)
|
||||
|
||||
## Recommendations
|
||||
1. <actionable recommendation>
|
||||
```
|
||||
|
||||
### Summary Counts
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| Total issues | Sum across all dimensions and severities |
|
||||
| Critical count | Must be 0 for APPROVE |
|
||||
| Blocking issues | Listed explicitly in report header |
|
||||
| Dimensions covered | Must be 4/4 |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Plan file not found | Skip requirements dimension, note in report |
|
||||
| Git diff empty | Report no changes to review |
|
||||
| File read fails | Skip file, note in report |
|
||||
| No modified files | Report empty review |
|
||||
@@ -0,0 +1,201 @@
|
||||
# Command: spec-quality
|
||||
|
||||
## Purpose
|
||||
|
||||
5-dimension spec quality check with weighted scoring, quality gate determination, and readiness report generation.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Spec documents | `<session_folder>/spec/` (all .md files) | Yes |
|
||||
| Original requirements | Product brief objectives section | Yes |
|
||||
| Quality gate config | specs/quality-gates.md | No |
|
||||
| Session folder | Task description `Session:` field | Yes |
|
||||
|
||||
**Spec document phases** (matched by filename/directory):
|
||||
|
||||
| Phase | Expected Path |
|
||||
|-------|--------------|
|
||||
| product-brief | spec/product-brief.md |
|
||||
| prd | spec/requirements/*.md |
|
||||
| architecture | spec/architecture/_index.md + ADR-*.md |
|
||||
| user-stories | spec/epics/*.md |
|
||||
| implementation-plan | plan/plan.json |
|
||||
| test-strategy | spec/test-strategy.md |
|
||||
|
||||
## Phase 3: 5-Dimension Scoring
|
||||
|
||||
### Dimension Weights
|
||||
|
||||
| Dimension | Weight | Focus |
|
||||
|-----------|--------|-------|
|
||||
| Completeness | 25% | All required sections present with substance |
|
||||
| Consistency | 20% | Terminology, format, references, naming |
|
||||
| Traceability | 25% | Goals -> Reqs -> Components -> Stories chain |
|
||||
| Depth | 20% | AC testable, ADRs justified, stories estimable |
|
||||
| Coverage | 10% | Original requirements mapped to spec |
|
||||
|
||||
---
|
||||
|
||||
### Dimension 1: Completeness (25%)
|
||||
|
||||
Check each spec document for required sections.
|
||||
|
||||
**Required sections by phase**:
|
||||
|
||||
| Phase | Required Sections |
|
||||
|-------|------------------|
|
||||
| product-brief | Vision Statement, Problem Statement, Target Audience, Success Metrics, Constraints |
|
||||
| prd | Goals, Requirements, User Stories, Acceptance Criteria, Non-Functional Requirements |
|
||||
| architecture | System Overview, Component Design, Data Models, API Specifications, Technology Stack |
|
||||
| user-stories | Story List, Acceptance Criteria, Priority, Estimation |
|
||||
| implementation-plan | Task Breakdown, Dependencies, Timeline, Resource Allocation |
|
||||
| test-strategy | Test Scope, Test Cases, Coverage Goals, Test Environment |
|
||||
|
||||
**Scoring formula**:
|
||||
- Section present: 50% credit
|
||||
- Section has substantial content (>100 chars beyond header): additional 50% credit
|
||||
- Per-document score = (present_ratio * 50) + (substantial_ratio * 50)
|
||||
- Overall = average across all documents
|
||||
|
||||
---
|
||||
|
||||
### Dimension 2: Consistency (20%)
|
||||
|
||||
Check cross-document consistency across four areas.
|
||||
|
||||
| Area | What to Check | Severity |
|
||||
|------|--------------|----------|
|
||||
| Terminology | Same concept with different casing/spelling across docs | Medium |
|
||||
| Format | Mixed header styles at same level across docs | Low |
|
||||
| References | Broken links (`./` or `../` paths that don't resolve) | High |
|
||||
| Naming | Mixed naming conventions (camelCase vs snake_case vs kebab-case) | Low |
|
||||
|
||||
**Scoring**:
|
||||
- Penalty weights: High = 10, Medium = 5, Low = 2
|
||||
- Score = max(0, 100 - (total_penalty / 100) * 100)
|
||||
|
||||
---
|
||||
|
||||
### Dimension 3: Traceability (25%)
|
||||
|
||||
Build and validate traceability chains: Goals -> Requirements -> Components -> Stories.
|
||||
|
||||
**Chain building flow**:
|
||||
1. Extract goals from product-brief (pattern: `- Goal: <text>`)
|
||||
2. Extract requirements from PRD (pattern: `- REQ-NNN: <text>`)
|
||||
3. Extract components from architecture (pattern: `- Component: <text>`)
|
||||
4. Extract stories from user-stories (pattern: `- US-NNN: <text>`)
|
||||
5. Link by keyword overlap (threshold: 30% keyword match)
|
||||
|
||||
**Chain completeness**: A chain is complete when a goal links to at least one requirement, one component, and one story.
|
||||
|
||||
**Scoring**: (complete chains / total chains) * 100
|
||||
|
||||
**Weak link identification**: For each incomplete chain, report which link is missing (no requirements, no components, or no stories).
|
||||
|
||||
---
|
||||
|
||||
### Dimension 4: Depth (20%)
|
||||
|
||||
Assess the analytical depth of spec content across four sub-dimensions.
|
||||
|
||||
| Sub-dimension | Source | Testable Criteria |
|
||||
|---------------|--------|-------------------|
|
||||
| AC Testability | PRD / User Stories | Contains measurable verbs (display, return, validate) or Given/When/Then or numbers |
|
||||
| ADR Justification | Architecture | Contains rationale, alternatives, consequences, or trade-offs |
|
||||
| Story Estimability | User Stories | Has "As a/I want/So that" + AC, or explicit estimate |
|
||||
| Technical Detail | Architecture + Plan | Contains code blocks, API terms, HTTP methods, DB terms |
|
||||
|
||||
**Scoring**: Average of sub-dimension scores (each 0-100%)
|
||||
|
||||
---
|
||||
|
||||
### Dimension 5: Coverage (10%)
|
||||
|
||||
Map original requirements to spec requirements.
|
||||
|
||||
**Flow**:
|
||||
1. Extract original requirements from product-brief objectives section
|
||||
2. Extract spec requirements from all documents (pattern: `- REQ-NNN:` or `- Requirement:` or `- Feature:`)
|
||||
3. For each original requirement, check keyword overlap with any spec requirement (threshold: 40%)
|
||||
4. Score = (covered_count / total_original) * 100
|
||||
|
||||
---
|
||||
|
||||
### Quality Gate Decision Table
|
||||
|
||||
| Gate | Criteria | Message |
|
||||
|------|----------|---------|
|
||||
| PASS | Overall score >= 80% AND coverage >= 70% | Ready for implementation |
|
||||
| FAIL | Overall score < 60% OR coverage < 50% | Major revisions required |
|
||||
| REVIEW | All other cases | Improvements needed, may proceed with caution |
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
### Readiness Report Format
|
||||
|
||||
Write to `<session_folder>/spec/readiness-report.md`:
|
||||
|
||||
```
|
||||
# Specification Readiness Report
|
||||
|
||||
**Generated**: <timestamp>
|
||||
**Overall Score**: <score>%
|
||||
**Quality Gate**: <PASS|REVIEW|FAIL> - <message>
|
||||
**Recommended Action**: <action>
|
||||
|
||||
## Dimension Scores
|
||||
|
||||
| Dimension | Score | Weight | Weighted Score |
|
||||
|-----------|-------|--------|----------------|
|
||||
| Completeness | <n>% | 25% | <n>% |
|
||||
| Consistency | <n>% | 20% | <n>% |
|
||||
| Traceability | <n>% | 25% | <n>% |
|
||||
| Depth | <n>% | 20% | <n>% |
|
||||
| Coverage | <n>% | 10% | <n>% |
|
||||
|
||||
## Completeness Analysis
|
||||
(per-phase breakdown: sections present/expected, missing sections)
|
||||
|
||||
## Consistency Analysis
|
||||
(issues by area: terminology, format, references, naming)
|
||||
|
||||
## Traceability Analysis
|
||||
(complete chains / total, weak links)
|
||||
|
||||
## Depth Analysis
|
||||
(per sub-dimension scores)
|
||||
|
||||
## Requirement Coverage
|
||||
(covered / total, uncovered requirements list)
|
||||
```
|
||||
|
||||
### Spec Summary Format
|
||||
|
||||
Write to `<session_folder>/spec/spec-summary.md`:
|
||||
|
||||
```
|
||||
# Specification Summary
|
||||
|
||||
**Overall Quality Score**: <score>%
|
||||
**Quality Gate**: <gate>
|
||||
|
||||
## Documents Reviewed
|
||||
(per document: phase, path, size, section list)
|
||||
|
||||
## Key Findings
|
||||
### Strengths (dimensions scoring >= 80%)
|
||||
### Areas for Improvement (dimensions scoring < 70%)
|
||||
### Recommendations
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Spec folder empty | FAIL gate, report no documents found |
|
||||
| Missing phase document | Score 0 for that phase in completeness, note in report |
|
||||
| No original requirements found | Score coverage at 100% (nothing to cover) |
|
||||
| Broken references | Flag in consistency, do not fail entire review |
|
||||
104
.claude/skills/team-lifecycle-v3/roles/reviewer/role.md
Normal file
104
.claude/skills/team-lifecycle-v3/roles/reviewer/role.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# Role: reviewer
|
||||
|
||||
Dual-mode review: code review (REVIEW-*) and spec quality validation (QUALITY-*). Auto-switches by task prefix.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `reviewer` | **Prefix**: `REVIEW-*` + `QUALITY-*` | **Tag**: `[reviewer]`
|
||||
- **Responsibility**: Branch by Prefix → Review/Score → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Process REVIEW-* and QUALITY-* tasks
|
||||
- Generate readiness-report.md for QUALITY tasks
|
||||
- Cover all required dimensions per mode
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks
|
||||
- Modify source code
|
||||
- Skip quality dimensions
|
||||
- Approve without verification
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| review_result | → coordinator | Code review complete |
|
||||
| quality_result | → coordinator | Spec quality complete |
|
||||
| fix_required | → coordinator | Critical issues found |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/code-review.md | 4-dimension code review |
|
||||
| commands/spec-quality.md | 5-dimension spec quality |
|
||||
|
||||
---
|
||||
|
||||
## Mode Detection
|
||||
|
||||
| Task Prefix | Mode | Dimensions |
|
||||
|-------------|------|-----------|
|
||||
| REVIEW-* | Code Review | quality, security, architecture, requirements |
|
||||
| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage |
|
||||
|
||||
---
|
||||
|
||||
## Code Review (REVIEW-*)
|
||||
|
||||
**Inputs**: Plan file, git diff, modified files, test results (if available)
|
||||
|
||||
**4 dimensions** (delegate to commands/code-review.md):
|
||||
|
||||
| Dimension | Critical Issues |
|
||||
|-----------|----------------|
|
||||
| Quality | Empty catch, any in public APIs, @ts-ignore, console.log |
|
||||
| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML |
|
||||
| Architecture | Circular deps, parent imports >2 levels, files >500 lines |
|
||||
| Requirements | Missing core functionality, incomplete acceptance criteria |
|
||||
|
||||
**Verdict**:
|
||||
|
||||
| Verdict | Criteria |
|
||||
|---------|----------|
|
||||
| BLOCK | Critical issues present |
|
||||
| CONDITIONAL | High/medium only |
|
||||
| APPROVE | Low or none |
|
||||
|
||||
---
|
||||
|
||||
## Spec Quality (QUALITY-*)
|
||||
|
||||
**Inputs**: All spec docs in session folder, quality gate config
|
||||
|
||||
**5 dimensions** (delegate to commands/spec-quality.md):
|
||||
|
||||
| Dimension | Weight | Focus |
|
||||
|-----------|--------|-------|
|
||||
| Completeness | 25% | All sections present with substance |
|
||||
| Consistency | 20% | Terminology, format, references |
|
||||
| Traceability | 25% | Goals → Reqs → Arch → Stories chain |
|
||||
| Depth | 20% | AC testable, ADRs justified, stories estimable |
|
||||
| Coverage | 10% | Original requirements mapped |
|
||||
|
||||
**Quality gate**:
|
||||
|
||||
| Gate | Criteria |
|
||||
|------|----------|
|
||||
| PASS | Score ≥ 80% AND coverage ≥ 70% |
|
||||
| REVIEW | Score 60-79% OR coverage 50-69% |
|
||||
| FAIL | Score < 60% OR coverage < 50% |
|
||||
|
||||
**Artifacts**: readiness-report.md + spec-summary.md
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Missing context | Request from coordinator |
|
||||
| Invalid mode | Abort with error |
|
||||
| Analysis failure | Retry, then fallback template |
|
||||
@@ -0,0 +1,152 @@
|
||||
# Command: validate
|
||||
|
||||
## Purpose
|
||||
|
||||
Test-fix cycle with strategy engine: detect framework, run tests, classify failures, select fix strategy, iterate until pass rate target is met or max iterations exhausted.
|
||||
|
||||
## Constants
|
||||
|
||||
| Constant | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| MAX_ITERATIONS | 10 | Maximum test-fix cycle attempts |
|
||||
| PASS_RATE_TARGET | 95% | Minimum pass rate to succeed |
|
||||
| AFFECTED_TESTS_FIRST | true | Run affected tests before full suite |
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
Load from task description and executor output:
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Framework | Auto-detected (see below) | Yes |
|
||||
| Modified files | Executor task output / git diff | Yes |
|
||||
| Affected tests | Derived from modified files | No |
|
||||
| Session folder | Task description `Session:` field | Yes |
|
||||
| Wisdom | `<session_folder>/wisdom/` | No |
|
||||
|
||||
**Framework detection** (priority order):
|
||||
|
||||
| Priority | Method | Check |
|
||||
|----------|--------|-------|
|
||||
| 1 | package.json devDependencies | vitest, jest, mocha, pytest |
|
||||
| 2 | package.json scripts.test | Command contains framework name |
|
||||
| 3 | Config file existence | vitest.config.*, jest.config.*, pytest.ini |
|
||||
|
||||
**Affected test discovery** from modified files:
|
||||
- For each modified file `<name>.<ext>`, search:
|
||||
`<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts`
|
||||
|
||||
## Phase 3: Test-Fix Cycle
|
||||
|
||||
### Test Command Table
|
||||
|
||||
| Framework | Affected Tests | Full Suite |
|
||||
|-----------|---------------|------------|
|
||||
| vitest | `vitest run <files> --reporter=verbose` | `vitest run --reporter=verbose` |
|
||||
| jest | `jest <files> --no-coverage --verbose` | `jest --no-coverage --verbose` |
|
||||
| mocha | `mocha <files> --reporter spec` | `mocha --reporter spec` |
|
||||
| pytest | `pytest <files> -v --tb=short` | `pytest -v --tb=short` |
|
||||
|
||||
### Iteration Flow
|
||||
|
||||
```
|
||||
Iteration 1
|
||||
├─ Run affected tests (or full suite if none)
|
||||
├─ Parse results → pass rate
|
||||
├─ Pass rate >= 95%?
|
||||
│ ├─ YES + affected-only → run full suite to confirm
|
||||
│ │ ├─ Full suite passes → SUCCESS
|
||||
│ │ └─ Full suite fails → continue with full results
|
||||
│ └─ YES + full suite → SUCCESS
|
||||
└─ NO → classify failures → select strategy → apply fixes
|
||||
|
||||
Iteration 2..10
|
||||
├─ Re-run tests
|
||||
├─ Track best pass rate across iterations
|
||||
├─ Pass rate >= 95% → SUCCESS
|
||||
├─ No failures to fix → STOP (anomaly)
|
||||
└─ Failures remain → classify → select strategy → apply fixes
|
||||
|
||||
After iteration 10
|
||||
└─ FAIL: max iterations reached, report best pass rate
|
||||
```
|
||||
|
||||
**Progress update**: When iteration > 5, send progress to coordinator with current pass rate and iteration count.
|
||||
|
||||
### Strategy Selection Matrix
|
||||
|
||||
| Condition | Strategy | Behavior |
|
||||
|-----------|----------|----------|
|
||||
| Iteration <= 3 OR pass rate >= 80% | Conservative | Fix one failure at a time, highest severity first |
|
||||
| Critical failures exist AND count < 5 | Surgical | Identify common error pattern, fix all matching occurrences |
|
||||
| Pass rate < 50% OR iteration > 7 | Aggressive | Fix all critical + high failures in batch |
|
||||
| Default (no other match) | Conservative | Safe fallback |
|
||||
|
||||
### Failure Classification Table
|
||||
|
||||
| Severity | Error Patterns |
|
||||
|----------|---------------|
|
||||
| Critical | SyntaxError, cannot find module, is not defined |
|
||||
| High | Assertion mismatch (expected/received), toBe/toEqual failures |
|
||||
| Medium | Timeout, async errors |
|
||||
| Low | Warnings, deprecation notices |
|
||||
|
||||
### Fix Approach by Error Type
|
||||
|
||||
| Error Type | Pattern | Fix Approach |
|
||||
|------------|---------|-------------|
|
||||
| missing_import | "Cannot find module '<module>'" | Add import statement, resolve relative path from modified files |
|
||||
| undefined_variable | "<name> is not defined" | Check source for renamed/moved exports, update reference |
|
||||
| assertion_mismatch | "Expected: X, Received: Y" | Read test file at failure line, update expected value if behavior change is intentional |
|
||||
| timeout | "Timeout" | Increase timeout or add async/await |
|
||||
| syntax_error | "SyntaxError" | Read source at error line, fix syntax |
|
||||
|
||||
### Tool Call Example
|
||||
|
||||
Run tests with framework-appropriate command:
|
||||
|
||||
```bash
|
||||
Bash(command="vitest run src/utils/__tests__/parser.test.ts --reporter=verbose", timeout=120000)
|
||||
```
|
||||
|
||||
Read test file to analyze failure:
|
||||
|
||||
```bash
|
||||
Read(file_path="<test_file_path>")
|
||||
```
|
||||
|
||||
Apply fix via Edit:
|
||||
|
||||
```bash
|
||||
Edit(file_path="<file>", old_string="<old>", new_string="<new>")
|
||||
```
|
||||
|
||||
## Phase 4: Validation
|
||||
|
||||
### Success Criteria
|
||||
|
||||
| Check | Criteria | Required |
|
||||
|-------|----------|----------|
|
||||
| Pass rate | >= 95% | Yes |
|
||||
| Full suite run | At least one full suite pass | Yes |
|
||||
| No critical failures | Zero critical-severity failures remaining | Yes |
|
||||
| Best pass rate tracked | Reported in final result | Yes |
|
||||
|
||||
### Result Routing
|
||||
|
||||
| Outcome | Message Type | Content |
|
||||
|---------|-------------|---------|
|
||||
| Pass rate >= target | test_result | Success, iterations count, full suite confirmed |
|
||||
| Max iterations, pass rate < target | fix_required | Best pass rate, remaining failures, iteration count |
|
||||
| No tests found | error | Framework detected but no test files |
|
||||
| Framework not detected | error | Detection methods exhausted |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Framework not detected | Report error to coordinator, list detection attempts |
|
||||
| No test files found | Report to coordinator, suggest manual test path |
|
||||
| Test command fails (exit code != 0/1) | Check stderr for environment issues, retry once |
|
||||
| Fix application fails | Skip fix, try next iteration with different strategy |
|
||||
| Infinite loop (same failures repeat) | Abort after 3 identical result sets |
|
||||
108
.claude/skills/team-lifecycle-v3/roles/tester/role.md
Normal file
108
.claude/skills/team-lifecycle-v3/roles/tester/role.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# Role: tester
|
||||
|
||||
Adaptive test execution with fix cycles and quality gates.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `tester` | **Prefix**: `TEST-*` | **Tag**: `[tester]`
|
||||
- **Responsibility**: Detect Framework → Run Tests → Fix Cycle → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process TEST-* tasks
|
||||
- Detect test framework before running
|
||||
- Run affected tests before full suite
|
||||
- Use strategy engine for fix cycles
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks
|
||||
- Contact other workers directly
|
||||
- Modify production code beyond test fixes
|
||||
- Skip framework detection
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| test_result | → coordinator | Tests pass or final result |
|
||||
| fix_required | → coordinator | Failures after max iterations |
|
||||
| error | → coordinator | Framework not detected |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/validate.md | Test-fix cycle with strategy engine |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Framework Detection & Test Discovery
|
||||
|
||||
**Framework detection** (priority order):
|
||||
|
||||
| Priority | Method | Frameworks |
|
||||
|----------|--------|-----------|
|
||||
| 1 | package.json devDependencies | vitest, jest, mocha, pytest |
|
||||
| 2 | package.json scripts.test | vitest, jest, mocha, pytest |
|
||||
| 3 | Config files | vitest.config.*, jest.config.*, pytest.ini |
|
||||
|
||||
**Affected test discovery** from executor's modified files:
|
||||
- Search variants: `<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts`
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Test Execution & Fix Cycle
|
||||
|
||||
**Config**: MAX_ITERATIONS=10, PASS_RATE_TARGET=95%, AFFECTED_TESTS_FIRST=true
|
||||
|
||||
Delegate to `commands/validate.md`:
|
||||
1. Run affected tests → parse results
|
||||
2. Pass rate met → run full suite
|
||||
3. Failures → select strategy → fix → re-run → repeat
|
||||
|
||||
**Strategy selection**:
|
||||
|
||||
| Condition | Strategy | Behavior |
|
||||
|-----------|----------|----------|
|
||||
| Iteration ≤ 3 or pass ≥ 80% | Conservative | Fix one critical failure at a time |
|
||||
| Critical failures < 5 | Surgical | Fix specific pattern everywhere |
|
||||
| Pass < 50% or iteration > 7 | Aggressive | Fix all failures in batch |
|
||||
|
||||
**Test commands**:
|
||||
|
||||
| Framework | Affected | Full Suite |
|
||||
|-----------|---------|------------|
|
||||
| vitest | `vitest run <files>` | `vitest run` |
|
||||
| jest | `jest <files> --no-coverage` | `jest --no-coverage` |
|
||||
| pytest | `pytest <files> -v` | `pytest -v` |
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Result Analysis
|
||||
|
||||
**Failure classification**:
|
||||
|
||||
| Severity | Patterns |
|
||||
|----------|----------|
|
||||
| Critical | SyntaxError, cannot find module, undefined |
|
||||
| High | Assertion failures, toBe/toEqual |
|
||||
| Medium | Timeout, async errors |
|
||||
| Low | Warnings, deprecations |
|
||||
|
||||
**Report routing**:
|
||||
|
||||
| Condition | Type |
|
||||
|-----------|------|
|
||||
| Pass rate ≥ target | test_result (success) |
|
||||
| Pass rate < target after max iterations | fix_required |
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Framework not detected | Prompt user |
|
||||
| No tests found | Report to coordinator |
|
||||
| Infinite fix loop | Abort after MAX_ITERATIONS |
|
||||
96
.claude/skills/team-lifecycle-v3/roles/writer/role.md
Normal file
96
.claude/skills/team-lifecycle-v3/roles/writer/role.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Role: writer
|
||||
|
||||
Product Brief, Requirements/PRD, Architecture, and Epics & Stories document generation. Maps to spec-generator Phases 2-5.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `writer` | **Prefix**: `DRAFT-*` | **Tag**: `[writer]`
|
||||
- **Responsibility**: Load Context → Generate Document → Incorporate Feedback → Report
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Only process DRAFT-* tasks
|
||||
- Read templates before generating (from `../../templates/`)
|
||||
- Follow document-standards.md (from `../../specs/`)
|
||||
- Integrate discussion feedback when available
|
||||
- Generate proper YAML frontmatter
|
||||
|
||||
### MUST NOT
|
||||
- Create tasks for other roles
|
||||
- Skip template loading
|
||||
- Modify discussion records
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger |
|
||||
|------|-----------|---------|
|
||||
| draft_ready | → coordinator | Document writing complete |
|
||||
| draft_revision | → coordinator | Document revised per feedback |
|
||||
| error | → coordinator | Template missing, insufficient context |
|
||||
|
||||
## Toolbox
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| commands/generate-doc.md | Multi-CLI document generation |
|
||||
| gemini, codex, claude CLI | Multi-perspective content generation |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context & Discussion Loading
|
||||
|
||||
**Objective**: Load all required inputs for document generation.
|
||||
|
||||
**Document type routing**:
|
||||
|
||||
| Task Subject Contains | Doc Type | Template | Discussion Input |
|
||||
|----------------------|----------|----------|-----------------|
|
||||
| Product Brief | product-brief | templates/product-brief.md | discuss-001-scope.md |
|
||||
| Requirements / PRD | requirements | templates/requirements-prd.md | discuss-002-brief.md |
|
||||
| Architecture | architecture | templates/architecture-doc.md | discuss-003-requirements.md |
|
||||
| Epics | epics | templates/epics-template.md | discuss-004-architecture.md |
|
||||
|
||||
**Progressive dependency loading**:
|
||||
|
||||
| Doc Type | Requires |
|
||||
|----------|----------|
|
||||
| product-brief | discovery-context.json |
|
||||
| requirements | + product-brief.md |
|
||||
| architecture | + requirements/_index.md |
|
||||
| epics | + architecture/_index.md |
|
||||
|
||||
**Success**: Template loaded, discussion feedback loaded (if exists), prior docs loaded.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Document Generation
|
||||
|
||||
**Objective**: Generate document using template and multi-CLI analysis.
|
||||
|
||||
Delegate to `commands/generate-doc.md` with: doc type, session folder, spec config, discussion feedback, prior docs.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Self-Validation
|
||||
|
||||
**Objective**: Verify document meets standards.
|
||||
|
||||
| Check | What to Verify |
|
||||
|-------|---------------|
|
||||
| has_frontmatter | Starts with YAML frontmatter |
|
||||
| sections_complete | All template sections present |
|
||||
| cross_references | session_id included |
|
||||
| discussion_integrated | Reflects feedback (if exists) |
|
||||
|
||||
**Report**: doc type, validation status, summary, output path.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Prior doc not found | Notify coordinator, request prerequisite |
|
||||
| CLI failure | Retry with fallback tool |
|
||||
| Discussion contradicts prior docs | Note conflict, flag for next discussion |
|
||||
192
.claude/skills/team-lifecycle-v3/specs/document-standards.md
Normal file
192
.claude/skills/team-lifecycle-v3/specs/document-standards.md
Normal 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
|
||||
207
.claude/skills/team-lifecycle-v3/specs/quality-gates.md
Normal file
207
.claude/skills/team-lifecycle-v3/specs/quality-gates.md
Normal 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
|
||||
156
.claude/skills/team-lifecycle-v3/specs/team-config.json
Normal file
156
.claude/skills/team-lifecycle-v3/specs/team-config.json
Normal file
@@ -0,0 +1,156 @@
|
||||
{
|
||||
"team_name": "team-lifecycle",
|
||||
"team_display_name": "Team Lifecycle",
|
||||
"description": "Unified team skill covering spec-to-dev-to-test full lifecycle",
|
||||
"version": "2.0.0",
|
||||
"architecture": "folder-based",
|
||||
"role_structure": "roles/{name}/role.md + roles/{name}/commands/*.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",
|
||||
"responsibility": "Seed analysis, codebase exploration, multi-dimensional context gathering",
|
||||
"message_types": ["research_ready", "research_progress", "error"]
|
||||
},
|
||||
"writer": {
|
||||
"task_prefix": "DRAFT",
|
||||
"responsibility": "Product Brief / PRD / Architecture / Epics document generation",
|
||||
"message_types": ["draft_ready", "draft_revision", "impl_progress", "error"]
|
||||
},
|
||||
"discussant": {
|
||||
"task_prefix": "DISCUSS",
|
||||
"responsibility": "Multi-perspective critique, consensus building, conflict escalation",
|
||||
"message_types": ["discussion_ready", "discussion_blocked", "impl_progress", "error"]
|
||||
},
|
||||
"planner": {
|
||||
"task_prefix": "PLAN",
|
||||
"responsibility": "Multi-angle code exploration, structured implementation planning",
|
||||
"message_types": ["plan_ready", "plan_revision", "impl_progress", "error"]
|
||||
},
|
||||
"executor": {
|
||||
"task_prefix": "IMPL",
|
||||
"responsibility": "Code implementation following approved plans",
|
||||
"message_types": ["impl_complete", "impl_progress", "error"]
|
||||
},
|
||||
"tester": {
|
||||
"task_prefix": "TEST",
|
||||
"responsibility": "Adaptive test-fix cycles, progressive testing, quality gates",
|
||||
"message_types": ["test_result", "impl_progress", "fix_required", "error"]
|
||||
},
|
||||
"reviewer": {
|
||||
"task_prefix": "REVIEW",
|
||||
"additional_prefixes": ["QUALITY"],
|
||||
"responsibility": "Code review (REVIEW-*) + Spec quality validation (QUALITY-*)",
|
||||
"message_types": ["review_result", "quality_result", "fix_required", "error"]
|
||||
},
|
||||
"explorer": {
|
||||
"task_prefix": "EXPLORE",
|
||||
"responsibility": "Code search, pattern discovery, dependency tracing. Service role — on-demand by coordinator",
|
||||
"role_type": "service",
|
||||
"message_types": ["explore_ready", "explore_progress", "task_failed"]
|
||||
},
|
||||
"architect": {
|
||||
"task_prefix": "ARCH",
|
||||
"responsibility": "Architecture assessment, tech feasibility, design pattern review. Consulting role — on-demand by coordinator",
|
||||
"role_type": "consulting",
|
||||
"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",
|
||||
"responsibility": "Frontend component/page implementation, design token consumption, responsive UI",
|
||||
"role_type": "frontend-pipeline",
|
||||
"message_types": ["dev_fe_complete", "dev_fe_progress", "error"]
|
||||
},
|
||||
"fe-qa": {
|
||||
"task_prefix": "QA-FE",
|
||||
"responsibility": "5-dimension frontend review (quality, a11y, design compliance, UX, pre-delivery), GC loop",
|
||||
"role_type": "frontend-pipeline",
|
||||
"message_types": ["qa_fe_passed", "qa_fe_result", "fix_required", "error"]
|
||||
}
|
||||
},
|
||||
|
||||
"pipelines": {
|
||||
"spec-only": {
|
||||
"description": "Specification pipeline: research → discuss → draft → quality",
|
||||
"task_chain": [
|
||||
"RESEARCH-001",
|
||||
"DISCUSS-001", "DRAFT-001", "DISCUSS-002",
|
||||
"DRAFT-002", "DISCUSS-003", "DRAFT-003", "DISCUSS-004",
|
||||
"DRAFT-004", "DISCUSS-005", "QUALITY-001", "DISCUSS-006"
|
||||
]
|
||||
},
|
||||
"impl-only": {
|
||||
"description": "Implementation pipeline: plan → implement → test + review",
|
||||
"task_chain": ["PLAN-001", "IMPL-001", "TEST-001", "REVIEW-001"]
|
||||
},
|
||||
"full-lifecycle": {
|
||||
"description": "Full lifecycle: spec pipeline → implementation pipeline",
|
||||
"task_chain": "spec-only + impl-only (PLAN-001 blockedBy DISCUSS-006)"
|
||||
},
|
||||
"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 DISCUSS-006)"
|
||||
}
|
||||
},
|
||||
|
||||
"frontend_detection": {
|
||||
"keywords": ["component", "page", "UI", "前端", "frontend", "CSS", "HTML", "React", "Vue", "Tailwind", "组件", "页面", "样式", "layout", "responsive", "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",
|
||||
"install_command": "/plugin install ui-ux-pro-max@ui-ux-pro-max-skill",
|
||||
"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"],
|
||||
"fallback": "llm-general-knowledge",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
|
||||
"collaboration_patterns": ["CP-1", "CP-2", "CP-4", "CP-5", "CP-6", "CP-10"],
|
||||
|
||||
"session_dirs": {
|
||||
"base": ".workflow/.team/TLS-{slug}-{YYYY-MM-DD}/",
|
||||
"spec": "spec/",
|
||||
"discussions": "discussions/",
|
||||
"plan": "plan/",
|
||||
"explorations": "explorations/",
|
||||
"architecture": "architecture/",
|
||||
"wisdom": "wisdom/",
|
||||
"messages": ".workflow/.team-msg/{team-name}/"
|
||||
}
|
||||
}
|
||||
254
.claude/skills/team-lifecycle-v3/templates/architecture-doc.md
Normal file
254
.claude/skills/team-lifecycle-v3/templates/architecture-doc.md
Normal 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 |
|
||||
196
.claude/skills/team-lifecycle-v3/templates/epics-template.md
Normal file
196
.claude/skills/team-lifecycle-v3/templates/epics-template.md
Normal 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 |
|
||||
133
.claude/skills/team-lifecycle-v3/templates/product-brief.md
Normal file
133
.claude/skills/team-lifecycle-v3/templates/product-brief.md
Normal 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 |
|
||||
224
.claude/skills/team-lifecycle-v3/templates/requirements-prd.md
Normal file
224
.claude/skills/team-lifecycle-v3/templates/requirements-prd.md
Normal 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 |
|
||||
177
.claude/skills/workflow-lite-plan copy/SKILL.md
Normal file
177
.claude/skills/workflow-lite-plan copy/SKILL.md
Normal file
@@ -0,0 +1,177 @@
|
||||
---
|
||||
name: workflow-lite-plan
|
||||
description: Lightweight planning and execution skill - route to lite-plan or lite-execute with prompt enhancement. Triggers on "workflow:lite-plan", "workflow:lite-execute".
|
||||
allowed-tools: Skill, Task, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash, Glob, Grep
|
||||
---
|
||||
|
||||
# Workflow Lite-Plan
|
||||
|
||||
Unified lightweight planning and execution skill. Routes to lite-plan (planning pipeline) or lite-execute (execution engine) based on trigger, with prompt enhancement for both modes.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ SKILL.md (Router + Prompt Enhancement) │
|
||||
│ → Detect mode → Enhance prompt → Dispatch to phase │
|
||||
└──────────────────────┬──────────────────────────────┘
|
||||
│
|
||||
┌───────────┼───────────┐
|
||||
↓ ↓
|
||||
┌───────────┐ ┌───────────┐
|
||||
│ lite-plan │ │lite-execute│
|
||||
│ Phase 1 │ │ Phase 2 │
|
||||
│ Plan+Exec │─direct──→│ Standalone │
|
||||
└───────────┘ └───────────┘
|
||||
```
|
||||
|
||||
## Mode Detection & Routing
|
||||
|
||||
```javascript
|
||||
const args = $ARGUMENTS
|
||||
const mode = detectMode()
|
||||
|
||||
function detectMode() {
|
||||
if (skillName === 'workflow:lite-execute') return 'execute'
|
||||
return 'plan' // default: workflow:lite-plan
|
||||
}
|
||||
```
|
||||
|
||||
**Routing Table**:
|
||||
|
||||
| Trigger | Mode | Phase Document | Description |
|
||||
|---------|------|----------------|-------------|
|
||||
| `workflow:lite-plan` | plan | [phases/01-lite-plan.md](phases/01-lite-plan.md) | Full planning pipeline (explore → plan → confirm → execute) |
|
||||
| `workflow:lite-execute` | execute | [phases/02-lite-execute.md](phases/02-lite-execute.md) | Standalone execution (in-memory / prompt / file) |
|
||||
|
||||
## Interactive Preference Collection
|
||||
|
||||
Before dispatching, collect workflow preferences via AskUserQuestion:
|
||||
|
||||
```javascript
|
||||
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
|
||||
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)
|
||||
|
||||
if (autoYes) {
|
||||
// 自动模式:跳过所有询问,使用默认值
|
||||
workflowPreferences = { autoYes: true, forceExplore: false }
|
||||
} else if (mode === 'plan') {
|
||||
const prefResponse = AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "是否跳过所有确认步骤(自动模式)?",
|
||||
header: "Auto Mode",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Interactive (Recommended)", description: "交互模式,包含确认步骤" },
|
||||
{ label: "Auto", description: "跳过所有确认,自动执行" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "是否强制执行代码探索阶段?",
|
||||
header: "Exploration",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Auto-detect (Recommended)", description: "智能判断是否需要探索" },
|
||||
{ label: "Force explore", description: "强制执行代码探索" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
workflowPreferences = {
|
||||
autoYes: prefResponse.autoMode === 'Auto',
|
||||
forceExplore: prefResponse.exploration === 'Force explore'
|
||||
}
|
||||
} else if (mode !== 'plan') {
|
||||
// Execute mode (standalone, not in-memory)
|
||||
const prefResponse = AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "是否跳过所有确认步骤(自动模式)?",
|
||||
header: "Auto Mode",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Interactive (Recommended)", description: "交互模式,包含确认步骤" },
|
||||
{ label: "Auto", description: "跳过所有确认,自动执行" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
workflowPreferences = {
|
||||
autoYes: prefResponse.autoMode === 'Auto',
|
||||
forceExplore: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**workflowPreferences** is passed to phase execution as context variable, referenced as `workflowPreferences.autoYes` and `workflowPreferences.forceExplore` within phases.
|
||||
|
||||
## Prompt Enhancement
|
||||
|
||||
After collecting preferences, enhance context and dispatch:
|
||||
|
||||
```javascript
|
||||
// Step 0: Parse --from-analysis handoff (from analyze-with-file)
|
||||
const fromAnalysisMatch = args.match(/--from-analysis\s+(\S+)/)
|
||||
if (fromAnalysisMatch) {
|
||||
const handoffPath = fromAnalysisMatch[1]
|
||||
workflowPreferences.analysisHandoff = JSON.parse(Read(handoffPath))
|
||||
workflowPreferences.forceExplore = false
|
||||
// Strip flag from args, keep task description
|
||||
args = args.replace(/--from-analysis\s+\S+\s*/, '').trim()
|
||||
}
|
||||
|
||||
// Step 1: Check for project context files
|
||||
const hasProjectTech = fileExists('.workflow/project-tech.json')
|
||||
const hasProjectGuidelines = fileExists('.workflow/project-guidelines.json')
|
||||
|
||||
// Step 2: Log available context
|
||||
if (hasProjectTech) {
|
||||
console.log('Project tech context available: .workflow/project-tech.json')
|
||||
}
|
||||
if (hasProjectGuidelines) {
|
||||
console.log('Project guidelines available: .workflow/project-guidelines.json')
|
||||
}
|
||||
|
||||
// Step 3: Dispatch to phase (workflowPreferences available as context)
|
||||
if (mode === 'plan') {
|
||||
// Read phases/01-lite-plan.md and execute
|
||||
} else {
|
||||
// Read phases/02-lite-execute.md and execute
|
||||
}
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Plan Mode
|
||||
|
||||
```
|
||||
1. Collect preferences via AskUserQuestion (autoYes, forceExplore)
|
||||
2. Enhance prompt with project context availability
|
||||
3. Read phases/01-lite-plan.md
|
||||
4. Execute lite-plan pipeline (Phase 1-5 within the phase doc)
|
||||
5. lite-plan Phase 5 directly reads and executes Phase 2 (lite-execute) with executionContext
|
||||
```
|
||||
|
||||
### Execute Mode
|
||||
|
||||
```
|
||||
1. Collect preferences via AskUserQuestion (autoYes)
|
||||
2. Enhance prompt with project context availability
|
||||
3. Read phases/02-lite-execute.md
|
||||
4. Execute lite-execute pipeline (input detection → execution → review)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Plan mode and execute mode are triggered by skill name routing (see Mode Detection). Workflow preferences (auto mode, force explore) are collected interactively via AskUserQuestion before dispatching to phases.
|
||||
|
||||
**Plan mode**: Task description provided as arguments → interactive preference collection → planning pipeline
|
||||
**Execute mode**: Task description, file path, or in-memory context → interactive preference collection → execution pipeline
|
||||
|
||||
## Phase Reference Documents
|
||||
|
||||
| Phase | Document | Purpose |
|
||||
|-------|----------|---------|
|
||||
| 1 | [phases/01-lite-plan.md](phases/01-lite-plan.md) | Complete planning pipeline: exploration, clarification, planning, confirmation, handoff |
|
||||
| 2 | [phases/02-lite-execute.md](phases/02-lite-execute.md) | Complete execution engine: input modes, task grouping, batch execution, code review |
|
||||
770
.claude/skills/workflow-lite-plan copy/phases/01-lite-plan.md
Normal file
770
.claude/skills/workflow-lite-plan copy/phases/01-lite-plan.md
Normal file
@@ -0,0 +1,770 @@
|
||||
# Phase 1: Lite-Plan
|
||||
|
||||
Complete planning pipeline: task analysis, multi-angle exploration, clarification, adaptive planning, confirmation, and execution handoff.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Intelligent lightweight planning command with dynamic workflow adaptation based on task complexity. Focuses on planning phases (exploration, clarification, planning, confirmation) and delegates execution to Phase 2 (lite-execute).
|
||||
|
||||
**Core capabilities:**
|
||||
- Intelligent task analysis with automatic exploration detection
|
||||
- Dynamic code exploration (cli-explore-agent) when codebase understanding needed
|
||||
- Interactive clarification after exploration to gather missing information
|
||||
- Adaptive planning: Low complexity → Direct Claude; Medium/High → cli-lite-planning-agent
|
||||
- Two-step confirmation: plan display → multi-dimensional input collection
|
||||
- Execution handoff with complete context to lite-execute
|
||||
|
||||
## Input
|
||||
|
||||
```
|
||||
<task-description> Task description or path to .md file (required)
|
||||
```
|
||||
|
||||
Workflow preferences (`autoYes`, `forceExplore`) are collected by SKILL.md via AskUserQuestion and passed as `workflowPreferences` context variable.
|
||||
|
||||
## Output Artifacts
|
||||
|
||||
| Artifact | Description |
|
||||
|----------|-------------|
|
||||
| `exploration-{angle}.json` | Per-angle exploration results (1-4 files based on complexity) |
|
||||
| `explorations-manifest.json` | Index of all exploration files |
|
||||
| `planning-context.md` | Evidence paths + synthesized understanding |
|
||||
| `plan.json` | Plan overview with task_ids[] (plan-overview-base-schema.json) |
|
||||
| `.task/TASK-*.json` | Independent task files (one per task) |
|
||||
|
||||
**Output Directory**: `.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/`
|
||||
|
||||
**Agent Usage**:
|
||||
- Low complexity → Direct Claude planning (no agent)
|
||||
- Medium/High complexity → `cli-lite-planning-agent` generates `plan.json`
|
||||
|
||||
**Schema Reference**: `~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json`
|
||||
|
||||
## Auto Mode Defaults
|
||||
|
||||
When `workflowPreferences.autoYes === true`:
|
||||
- **Clarification Questions**: Skipped (no clarification phase)
|
||||
- **Plan Confirmation**: Auto-selected "Allow"
|
||||
- **Execution Method**: Auto-selected "Auto"
|
||||
- **Code Review**: Auto-selected "Skip"
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Phase 1: Task Analysis & Exploration
|
||||
├─ Parse input (description or .md file)
|
||||
├─ intelligent complexity assessment (Low/Medium/High)
|
||||
├─ Exploration decision (auto-detect or workflowPreferences.forceExplore)
|
||||
├─ Context protection: If file reading ≥50k chars → force cli-explore-agent
|
||||
└─ Decision:
|
||||
├─ needsExploration=true → Launch parallel cli-explore-agents (1-4 based on complexity)
|
||||
└─ needsExploration=false → Skip to Phase 2/3
|
||||
|
||||
Phase 2: Clarification (optional, multi-round)
|
||||
├─ Aggregate clarification_needs from all exploration angles
|
||||
├─ Deduplicate similar questions
|
||||
└─ Decision:
|
||||
├─ Has clarifications → AskUserQuestion (max 4 questions per round, multiple rounds allowed)
|
||||
└─ No clarifications → Skip to Phase 3
|
||||
|
||||
Phase 3: Planning (NO CODE EXECUTION - planning only)
|
||||
└─ Decision (based on Phase 1 complexity):
|
||||
├─ Low → Load schema: cat ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json → Direct Claude planning (following schema) → plan.json
|
||||
└─ Medium/High → cli-lite-planning-agent → plan.json (agent internally executes quality check)
|
||||
|
||||
Phase 4: Confirmation & Selection
|
||||
├─ Display plan summary (tasks, complexity, estimated time)
|
||||
└─ AskUserQuestion:
|
||||
├─ Confirm: Allow / Modify / Cancel
|
||||
├─ Execution: Agent / Codex / Auto
|
||||
└─ Review: Gemini / Agent / Skip
|
||||
|
||||
Phase 5: Execute
|
||||
├─ Build executionContext (plan + explorations + clarifications + selections)
|
||||
└─ Direct handoff: Read phases/02-lite-execute.md → Execute with executionContext (Mode 1)
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Intelligent Multi-Angle Exploration
|
||||
|
||||
**Session Setup** (MANDATORY - follow exactly):
|
||||
```javascript
|
||||
// Helper: Get UTC+8 (China Standard Time) ISO string
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const taskSlug = task_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40)
|
||||
const dateStr = getUtc8ISOString().substring(0, 10) // Format: 2025-11-29
|
||||
|
||||
const sessionId = `${taskSlug}-${dateStr}` // e.g., "implement-jwt-refresh-2025-11-29"
|
||||
const sessionFolder = `.workflow/.lite-plan/${sessionId}`
|
||||
|
||||
bash(`mkdir -p ${sessionFolder} && test -d ${sessionFolder} && echo "SUCCESS: ${sessionFolder}" || echo "FAILED: ${sessionFolder}"`)
|
||||
```
|
||||
|
||||
**Exploration Decision Logic**:
|
||||
```javascript
|
||||
// Analysis handoff: reconstruct exploration from upstream analysis artifacts
|
||||
if (workflowPreferences.analysisHandoff) {
|
||||
const handoff = workflowPreferences.analysisHandoff
|
||||
Write(`${sessionFolder}/exploration-from-analysis.json`, JSON.stringify({
|
||||
relevant_files: handoff.exploration_digest.relevant_files || [],
|
||||
patterns: handoff.exploration_digest.patterns || [],
|
||||
key_findings: handoff.exploration_digest.key_findings || [],
|
||||
clarification_needs: [], // analysis already did multi-round discussion
|
||||
_metadata: { exploration_angle: "from-analysis", source_session: handoff.source_session, reconstructed: true }
|
||||
}, null, 2))
|
||||
Write(`${sessionFolder}/explorations-manifest.json`, JSON.stringify({
|
||||
session_id: sessionId, task_description: task_description, timestamp: getUtc8ISOString(),
|
||||
complexity: complexity, exploration_count: 1, from_analysis: handoff.source_session,
|
||||
explorations: [{ angle: "from-analysis", file: "exploration-from-analysis.json",
|
||||
path: `${sessionFolder}/exploration-from-analysis.json`, index: 1 }]
|
||||
}, null, 2))
|
||||
needsExploration = false
|
||||
// clarification_needs=[] → Phase 2 naturally skipped → proceed to Phase 3
|
||||
}
|
||||
|
||||
needsExploration = needsExploration ?? (
|
||||
workflowPreferences.forceExplore ||
|
||||
task.mentions_specific_files ||
|
||||
task.requires_codebase_context ||
|
||||
task.needs_architecture_understanding ||
|
||||
task.modifies_existing_code
|
||||
)
|
||||
|
||||
if (!needsExploration) {
|
||||
// Skip to Phase 2 (Clarification) or Phase 3 (Planning)
|
||||
proceed_to_next_phase()
|
||||
}
|
||||
```
|
||||
|
||||
**⚠️ Context Protection**: File reading ≥50k chars → force `needsExploration=true` (delegate to cli-explore-agent)
|
||||
|
||||
**Complexity Assessment** (Intelligent Analysis):
|
||||
```javascript
|
||||
// analyzes task complexity based on:
|
||||
// - Scope: How many systems/modules are affected?
|
||||
// - Depth: Surface change vs architectural impact?
|
||||
// - Risk: Potential for breaking existing functionality?
|
||||
// - Dependencies: How interconnected is the change?
|
||||
|
||||
const complexity = analyzeTaskComplexity(task_description)
|
||||
// Returns: 'Low' | 'Medium' | 'High'
|
||||
// Low: ONLY truly trivial — single file, single function, zero cross-module impact, no new patterns
|
||||
// Examples: fix typo, rename variable, add log line, adjust constant value
|
||||
// Medium: Multiple files OR any integration point OR new pattern introduction OR moderate risk
|
||||
// Examples: add endpoint, implement feature, refactor module, fix bug spanning files
|
||||
// High: Cross-module, architectural, or systemic change
|
||||
// Examples: new subsystem, migration, security overhaul, API redesign
|
||||
// ⚠️ Default bias: When uncertain between Low and Medium, choose Medium
|
||||
|
||||
// Angle assignment based on task type (orchestrator decides, not agent)
|
||||
const ANGLE_PRESETS = {
|
||||
architecture: ['architecture', 'dependencies', 'modularity', 'integration-points'],
|
||||
security: ['security', 'auth-patterns', 'dataflow', 'validation'],
|
||||
performance: ['performance', 'bottlenecks', 'caching', 'data-access'],
|
||||
bugfix: ['error-handling', 'dataflow', 'state-management', 'edge-cases'],
|
||||
feature: ['patterns', 'integration-points', 'testing', 'dependencies']
|
||||
}
|
||||
|
||||
function selectAngles(taskDescription, count) {
|
||||
const text = taskDescription.toLowerCase()
|
||||
let preset = 'feature' // default
|
||||
|
||||
if (/refactor|architect|restructure|modular/.test(text)) preset = 'architecture'
|
||||
else if (/security|auth|permission|access/.test(text)) preset = 'security'
|
||||
else if (/performance|slow|optimi|cache/.test(text)) preset = 'performance'
|
||||
else if (/fix|bug|error|issue|broken/.test(text)) preset = 'bugfix'
|
||||
|
||||
return ANGLE_PRESETS[preset].slice(0, count)
|
||||
}
|
||||
|
||||
const selectedAngles = selectAngles(task_description, complexity === 'High' ? 4 : (complexity === 'Medium' ? 3 : 1))
|
||||
|
||||
// Planning strategy determination
|
||||
// Agent trigger: anything beyond trivial single-file change
|
||||
// - analysisHandoff → always agent (analysis validated non-trivial task)
|
||||
// - multi-angle exploration → agent (complexity warranted multiple angles)
|
||||
// - Medium/High complexity → agent
|
||||
// Direct Claude planning ONLY for truly trivial Low + no analysis + single angle
|
||||
const planningStrategy = (
|
||||
complexity === 'Low' && !workflowPreferences.analysisHandoff && selectedAngles.length <= 1
|
||||
) ? 'Direct Claude Planning'
|
||||
: 'cli-lite-planning-agent'
|
||||
|
||||
console.log(`
|
||||
## Exploration Plan
|
||||
|
||||
Task Complexity: ${complexity}
|
||||
Selected Angles: ${selectedAngles.join(', ')}
|
||||
Planning Strategy: ${planningStrategy}
|
||||
|
||||
Launching ${selectedAngles.length} parallel explorations...
|
||||
`)
|
||||
```
|
||||
|
||||
**Launch Parallel Explorations** - Orchestrator assigns angle to each agent:
|
||||
|
||||
**⚠️ CRITICAL - NO BACKGROUND EXECUTION**:
|
||||
- **MUST NOT use `run_in_background: true`** - exploration results are REQUIRED before planning
|
||||
|
||||
|
||||
```javascript
|
||||
// Launch agents with pre-assigned angles
|
||||
const explorationTasks = selectedAngles.map((angle, index) =>
|
||||
Task(
|
||||
subagent_type="cli-explore-agent",
|
||||
run_in_background=false, // ⚠️ MANDATORY: Must wait for results
|
||||
description=`Explore: ${angle}`,
|
||||
prompt=`
|
||||
## Task Objective
|
||||
Execute **${angle}** exploration for task planning context. Analyze codebase from this specific angle to discover relevant structure, patterns, and constraints.
|
||||
|
||||
## Output Location
|
||||
|
||||
**Session Folder**: ${sessionFolder}
|
||||
**Output File**: ${sessionFolder}/exploration-${angle}.json
|
||||
|
||||
## Assigned Context
|
||||
- **Exploration Angle**: ${angle}
|
||||
- **Task Description**: ${task_description}
|
||||
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
|
||||
|
||||
## Agent Initialization
|
||||
cli-explore-agent autonomously handles: project structure discovery, schema loading, project context loading (project-tech.json, project-guidelines.json), and keyword search. These steps execute automatically.
|
||||
|
||||
## Exploration Strategy (${angle} focus)
|
||||
|
||||
**Step 1: Structural Scan** (Bash)
|
||||
- get_modules_by_depth.sh → identify modules related to ${angle}
|
||||
- find/rg → locate files relevant to ${angle} aspect
|
||||
- Analyze imports/dependencies from ${angle} perspective
|
||||
|
||||
**Step 2: Semantic Analysis** (Gemini CLI)
|
||||
- How does existing code handle ${angle} concerns?
|
||||
- What patterns are used for ${angle}?
|
||||
- Where would new code integrate from ${angle} viewpoint?
|
||||
|
||||
**Step 3: Write Output**
|
||||
- Consolidate ${angle} findings into JSON
|
||||
- Identify ${angle}-specific clarification needs
|
||||
|
||||
## Expected Output
|
||||
|
||||
**Schema Reference**: explore-json-schema.json (auto-loaded by agent during initialization)
|
||||
|
||||
**Required Fields** (all ${angle} focused):
|
||||
- Follow explore-json-schema.json exactly (auto-loaded by agent)
|
||||
- All fields scoped to ${angle} perspective
|
||||
- Ensure rationale is specific and >10 chars (not generic)
|
||||
- Include file:line locations in integration_points
|
||||
- _metadata.exploration_angle: "${angle}"
|
||||
|
||||
## Success Criteria
|
||||
- [ ] get_modules_by_depth.sh executed
|
||||
- [ ] At least 3 relevant files identified with specific rationale + role
|
||||
- [ ] Every file has rationale >10 chars (not generic like "Related to ${angle}")
|
||||
- [ ] Every file has role classification (modify_target/dependency/etc.)
|
||||
- [ ] Patterns are actionable (code examples, not generic advice)
|
||||
- [ ] Integration points include file:line locations
|
||||
- [ ] Constraints are project-specific to ${angle}
|
||||
- [ ] JSON output follows schema exactly
|
||||
- [ ] clarification_needs includes options + recommended
|
||||
|
||||
## Execution
|
||||
**Write**: \`${sessionFolder}/exploration-${angle}.json\`
|
||||
**Return**: 2-3 sentence summary of ${angle} findings
|
||||
`
|
||||
)
|
||||
)
|
||||
|
||||
// Execute all exploration tasks in parallel
|
||||
```
|
||||
|
||||
**Auto-discover Generated Exploration Files**:
|
||||
```javascript
|
||||
// After explorations complete, auto-discover all exploration-*.json files
|
||||
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`)
|
||||
.split('\n')
|
||||
.filter(f => f.trim())
|
||||
|
||||
// Read metadata to build manifest
|
||||
const explorationManifest = {
|
||||
session_id: sessionId,
|
||||
task_description: task_description,
|
||||
timestamp: getUtc8ISOString(),
|
||||
complexity: complexity,
|
||||
exploration_count: explorationCount,
|
||||
explorations: explorationFiles.map(file => {
|
||||
const data = JSON.parse(Read(file))
|
||||
const filename = path.basename(file)
|
||||
return {
|
||||
angle: data._metadata.exploration_angle,
|
||||
file: filename,
|
||||
path: file,
|
||||
index: data._metadata.exploration_index
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Write(`${sessionFolder}/explorations-manifest.json`, JSON.stringify(explorationManifest, null, 2))
|
||||
|
||||
console.log(`
|
||||
## Exploration Complete
|
||||
|
||||
Generated exploration files in ${sessionFolder}:
|
||||
${explorationManifest.explorations.map(e => `- exploration-${e.angle}.json (angle: ${e.angle})`).join('\n')}
|
||||
|
||||
Manifest: explorations-manifest.json
|
||||
Angles explored: ${explorationManifest.explorations.map(e => e.angle).join(', ')}
|
||||
`)
|
||||
```
|
||||
|
||||
**Output**:
|
||||
- `${sessionFolder}/exploration-{angle1}.json`
|
||||
- `${sessionFolder}/exploration-{angle2}.json`
|
||||
- ... (1-4 files based on complexity)
|
||||
- `${sessionFolder}/explorations-manifest.json`
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Clarification (Optional, Multi-Round)
|
||||
|
||||
**Skip if**: No exploration or `clarification_needs` is empty across all explorations
|
||||
|
||||
**⚠️ CRITICAL**: AskUserQuestion tool limits max 4 questions per call. **MUST execute multiple rounds** to exhaust all clarification needs - do NOT stop at round 1.
|
||||
|
||||
**Aggregate clarification needs from all exploration angles**:
|
||||
```javascript
|
||||
// Load manifest and all exploration files
|
||||
const manifest = JSON.parse(Read(`${sessionFolder}/explorations-manifest.json`))
|
||||
const explorations = manifest.explorations.map(exp => ({
|
||||
angle: exp.angle,
|
||||
data: JSON.parse(Read(exp.path))
|
||||
}))
|
||||
|
||||
// Aggregate clarification needs from all explorations
|
||||
const allClarifications = []
|
||||
explorations.forEach(exp => {
|
||||
if (exp.data.clarification_needs?.length > 0) {
|
||||
exp.data.clarification_needs.forEach(need => {
|
||||
allClarifications.push({
|
||||
...need,
|
||||
source_angle: exp.angle
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Intelligent deduplication: analyze allClarifications by intent
|
||||
// - Identify questions with similar intent across different angles
|
||||
// - Merge similar questions: combine options, consolidate context
|
||||
// - Produce dedupedClarifications with unique intents only
|
||||
const dedupedClarifications = intelligentMerge(allClarifications)
|
||||
|
||||
const autoYes = workflowPreferences.autoYes
|
||||
|
||||
if (autoYes) {
|
||||
// Auto mode: Skip clarification phase
|
||||
console.log(`[Auto] Skipping ${dedupedClarifications.length} clarification questions`)
|
||||
console.log(`Proceeding to planning with exploration results...`)
|
||||
// Continue to Phase 3
|
||||
} else if (dedupedClarifications.length > 0) {
|
||||
// Interactive mode: Multi-round clarification
|
||||
const BATCH_SIZE = 4
|
||||
const totalRounds = Math.ceil(dedupedClarifications.length / BATCH_SIZE)
|
||||
|
||||
for (let i = 0; i < dedupedClarifications.length; i += BATCH_SIZE) {
|
||||
const batch = dedupedClarifications.slice(i, i + BATCH_SIZE)
|
||||
const currentRound = Math.floor(i / BATCH_SIZE) + 1
|
||||
|
||||
console.log(`### Clarification Round ${currentRound}/${totalRounds}`)
|
||||
|
||||
AskUserQuestion({
|
||||
questions: batch.map(need => ({
|
||||
question: `[${need.source_angle}] ${need.question}\n\nContext: ${need.context}`,
|
||||
header: need.source_angle.substring(0, 12),
|
||||
multiSelect: false,
|
||||
options: need.options.map((opt, index) => ({
|
||||
label: need.recommended === index ? `${opt} ★` : opt,
|
||||
description: need.recommended === index ? `Recommended` : `Use ${opt}`
|
||||
}))
|
||||
}))
|
||||
})
|
||||
|
||||
// Store batch responses in clarificationContext before next round
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output**: `clarificationContext` (in-memory)
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Planning
|
||||
|
||||
**Planning Strategy Selection** (based on Phase 1 complexity):
|
||||
|
||||
**IMPORTANT**: Phase 3 is **planning only** - NO code execution. All execution happens in Phase 5 via lite-execute.
|
||||
|
||||
**Executor Assignment** (Claude 智能分配,plan 生成后执行):
|
||||
|
||||
```javascript
|
||||
// 分配规则(优先级从高到低):
|
||||
// 1. 用户明确指定:"用 gemini 分析..." → gemini, "codex 实现..." → codex
|
||||
// 2. 默认 → agent
|
||||
|
||||
const executorAssignments = {} // { taskId: { executor: 'gemini'|'codex'|'agent', reason: string } }
|
||||
|
||||
// Load tasks from .task/ directory for executor assignment
|
||||
const taskFiles = Glob(`${sessionFolder}/.task/TASK-*.json`)
|
||||
taskFiles.forEach(taskPath => {
|
||||
const task = JSON.parse(Read(taskPath))
|
||||
// Claude 根据上述规则语义分析,为每个 task 分配 executor
|
||||
executorAssignments[task.id] = { executor: '...', reason: '...' }
|
||||
})
|
||||
```
|
||||
|
||||
**Low Complexity** - Direct planning by Claude:
|
||||
```javascript
|
||||
// Step 1: Read schema
|
||||
const schema = Bash(`cat ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json`)
|
||||
|
||||
// Step 2: ⚠️ MANDATORY - Read and review ALL exploration files
|
||||
const manifest = JSON.parse(Read(`${sessionFolder}/explorations-manifest.json`))
|
||||
manifest.explorations.forEach(exp => {
|
||||
const explorationData = Read(exp.path)
|
||||
console.log(`\n### Exploration: ${exp.angle}\n${explorationData}`)
|
||||
})
|
||||
|
||||
// Step 3: Generate task objects (Claude directly, no agent)
|
||||
// ⚠️ Tasks MUST incorporate insights from exploration files read in Step 2
|
||||
// Task fields use NEW names: convergence.criteria (not acceptance), files[].change (not modification_points), test (not verification)
|
||||
const tasks = [
|
||||
{
|
||||
id: "TASK-001",
|
||||
title: "...",
|
||||
description: "...",
|
||||
depends_on: [],
|
||||
convergence: { criteria: ["..."] },
|
||||
files: [{ path: "...", change: "..." }],
|
||||
implementation: ["..."],
|
||||
test: "..."
|
||||
},
|
||||
// ... more tasks
|
||||
]
|
||||
|
||||
// Step 4: Write task files to .task/ directory
|
||||
const taskDir = `${sessionFolder}/.task`
|
||||
Bash(`mkdir -p "${taskDir}"`)
|
||||
tasks.forEach(task => {
|
||||
Write(`${taskDir}/${task.id}.json`, JSON.stringify(task, null, 2))
|
||||
})
|
||||
|
||||
// Step 5: Generate plan overview (NO embedded tasks[])
|
||||
const plan = {
|
||||
summary: "...",
|
||||
approach: "...",
|
||||
task_ids: tasks.map(t => t.id),
|
||||
task_count: tasks.length,
|
||||
complexity: "Low",
|
||||
estimated_time: "...",
|
||||
recommended_execution: "Agent",
|
||||
_metadata: {
|
||||
timestamp: getUtc8ISOString(),
|
||||
source: "direct-planning",
|
||||
planning_mode: "direct",
|
||||
plan_type: "feature"
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6: Write plan overview to session folder
|
||||
Write(`${sessionFolder}/plan.json`, JSON.stringify(plan, null, 2))
|
||||
|
||||
// Step 7: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
|
||||
```
|
||||
|
||||
**Medium/High Complexity** - Invoke cli-lite-planning-agent:
|
||||
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="cli-lite-planning-agent",
|
||||
run_in_background=false,
|
||||
description="Generate detailed implementation plan",
|
||||
prompt=`
|
||||
Generate implementation plan and write plan.json.
|
||||
|
||||
## Output Location
|
||||
|
||||
**Session Folder**: ${sessionFolder}
|
||||
**Output Files**:
|
||||
- ${sessionFolder}/planning-context.md (evidence + understanding)
|
||||
- ${sessionFolder}/plan.json (plan overview -- NO embedded tasks[])
|
||||
- ${sessionFolder}/.task/TASK-*.json (independent task files, one per task)
|
||||
|
||||
## Output Schema Reference
|
||||
Execute: cat ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json (get schema reference before generating plan)
|
||||
|
||||
## Project Context (MANDATORY - Read Both Files)
|
||||
1. Read: .workflow/project-tech.json (technology stack, architecture, key components)
|
||||
2. Read: .workflow/project-guidelines.json (user-defined constraints and conventions)
|
||||
|
||||
**CRITICAL**: All generated tasks MUST comply with constraints in project-guidelines.json
|
||||
|
||||
## Task Description
|
||||
${task_description}
|
||||
|
||||
## Multi-Angle Exploration Context
|
||||
|
||||
${manifest.explorations.map(exp => `### Exploration: ${exp.angle} (${exp.file})
|
||||
Path: ${exp.path}
|
||||
|
||||
Read this file for detailed ${exp.angle} analysis.`).join('\n\n')}
|
||||
|
||||
Total explorations: ${manifest.exploration_count}
|
||||
Angles covered: ${manifest.explorations.map(e => e.angle).join(', ')}
|
||||
|
||||
Manifest: ${sessionFolder}/explorations-manifest.json
|
||||
|
||||
## User Clarifications
|
||||
${JSON.stringify(clarificationContext) || "None"}
|
||||
|
||||
## Complexity Level
|
||||
${complexity}
|
||||
|
||||
## Requirements
|
||||
Generate plan.json and .task/*.json following the schema obtained above. Key constraints:
|
||||
- _metadata.exploration_angles: ${JSON.stringify(manifest.explorations.map(e => e.angle))}
|
||||
|
||||
**Output Format**: Two-layer structure:
|
||||
- plan.json: Overview with task_ids[] referencing .task/ files (NO tasks[] array)
|
||||
- .task/TASK-*.json: Independent task files following task-schema.json
|
||||
|
||||
Follow plan-overview-base-schema.json (loaded via cat command above) for plan.json structure.
|
||||
Follow task-schema.json for .task/TASK-*.json structure.
|
||||
Note: Use files[].change (not modification_points), convergence.criteria (not acceptance).
|
||||
|
||||
## Task Grouping Rules
|
||||
1. **Group by feature**: All changes for one feature = one task (even if 3-5 files)
|
||||
2. **Group by context**: Tasks with similar context or related functional changes can be grouped together
|
||||
3. **Minimize agent count**: Simple, unrelated tasks can also be grouped to reduce agent execution overhead
|
||||
4. **Avoid file-per-task**: Do NOT create separate tasks for each file
|
||||
5. **Substantial tasks**: Each task should represent 15-60 minutes of work
|
||||
6. **True dependencies only**: Only use depends_on when Task B cannot start without Task A's output
|
||||
7. **Prefer parallel**: Most tasks should be independent (no depends_on)
|
||||
|
||||
## Execution
|
||||
1. Read schema file (cat command above)
|
||||
2. Execute CLI planning using Gemini (Qwen fallback)
|
||||
3. Read ALL exploration files for comprehensive context
|
||||
4. Synthesize findings and generate tasks + plan overview
|
||||
5. **Write**: \`${sessionFolder}/planning-context.md\` (evidence paths + understanding)
|
||||
6. **Create**: \`${sessionFolder}/.task/\` directory (mkdir -p)
|
||||
7. **Write**: \`${sessionFolder}/.task/TASK-001.json\`, \`TASK-002.json\`, etc. (one per task)
|
||||
8. **Write**: \`${sessionFolder}/plan.json\` (overview with task_ids[], NO tasks[])
|
||||
9. Return brief completion summary
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
**Output**: `${sessionFolder}/plan.json`
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Task Confirmation & Execution Selection
|
||||
|
||||
**Step 4.1: Display Plan**
|
||||
```javascript
|
||||
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
|
||||
|
||||
// Load tasks from .task/ directory
|
||||
const tasks = (plan.task_ids || []).map(id => {
|
||||
const taskPath = `${sessionFolder}/.task/${id}.json`
|
||||
return JSON.parse(Read(taskPath))
|
||||
})
|
||||
const taskList = tasks
|
||||
|
||||
console.log(`
|
||||
## Implementation Plan
|
||||
|
||||
**Summary**: ${plan.summary}
|
||||
**Approach**: ${plan.approach}
|
||||
|
||||
**Tasks** (${taskList.length}):
|
||||
${taskList.map((t, i) => `${i+1}. ${t.title} (${t.scope || t.files?.[0]?.path || ''})`).join('\n')}
|
||||
|
||||
**Complexity**: ${plan.complexity}
|
||||
**Estimated Time**: ${plan.estimated_time}
|
||||
**Recommended**: ${plan.recommended_execution}
|
||||
`)
|
||||
```
|
||||
|
||||
**Step 4.2: Collect Confirmation**
|
||||
```javascript
|
||||
const autoYes = workflowPreferences.autoYes
|
||||
|
||||
let userSelection
|
||||
|
||||
if (autoYes) {
|
||||
// Auto mode: Use defaults
|
||||
console.log(`[Auto] Auto-confirming plan:`)
|
||||
console.log(` - Confirmation: Allow`)
|
||||
console.log(` - Execution: Auto`)
|
||||
console.log(` - Review: Skip`)
|
||||
|
||||
userSelection = {
|
||||
confirmation: "Allow",
|
||||
execution_method: "Auto",
|
||||
code_review_tool: "Skip"
|
||||
}
|
||||
} else {
|
||||
// Interactive mode: Ask user
|
||||
// Note: Execution "Other" option allows specifying CLI tools from ~/.claude/cli-tools.json
|
||||
userSelection = AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Confirm plan? (${taskList.length} tasks, ${plan.complexity})`,
|
||||
header: "Confirm",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Allow", description: "Proceed as-is" },
|
||||
{ label: "Modify", description: "Adjust before execution" },
|
||||
{ label: "Cancel", description: "Abort workflow" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "Execution method:",
|
||||
header: "Execution",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "@code-developer agent" },
|
||||
{ label: "Codex", description: "codex CLI tool" },
|
||||
{ label: "Auto", description: `Auto: ${plan.complexity === 'Low' ? 'Agent' : 'Codex'}` }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "Code review after execution?",
|
||||
header: "Review",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Gemini Review", description: "Gemini CLI review" },
|
||||
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
|
||||
{ label: "Agent Review", description: "@code-reviewer agent" },
|
||||
{ label: "Skip", description: "No review" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 5: Handoff to Execution
|
||||
|
||||
**CRITICAL**: lite-plan NEVER executes code directly. ALL execution MUST go through lite-execute.
|
||||
|
||||
**Step 5.1: Build executionContext**
|
||||
|
||||
```javascript
|
||||
// Load manifest and all exploration files
|
||||
const manifest = JSON.parse(Read(`${sessionFolder}/explorations-manifest.json`))
|
||||
const explorations = {}
|
||||
|
||||
manifest.explorations.forEach(exp => {
|
||||
if (file_exists(exp.path)) {
|
||||
explorations[exp.angle] = JSON.parse(Read(exp.path))
|
||||
}
|
||||
})
|
||||
|
||||
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
|
||||
|
||||
executionContext = {
|
||||
planObject: plan, // plan overview (no tasks[])
|
||||
taskFiles: (plan.task_ids || []).map(id => ({
|
||||
id,
|
||||
path: `${sessionFolder}/.task/${id}.json`
|
||||
})),
|
||||
explorationsContext: explorations,
|
||||
explorationAngles: manifest.explorations.map(e => e.angle),
|
||||
explorationManifest: manifest,
|
||||
clarificationContext: clarificationContext || null,
|
||||
executionMethod: userSelection.execution_method, // 全局默认,可被 executorAssignments 覆盖
|
||||
codeReviewTool: userSelection.code_review_tool,
|
||||
originalUserInput: task_description,
|
||||
|
||||
// 任务级 executor 分配(优先于全局 executionMethod)
|
||||
executorAssignments: executorAssignments, // { taskId: { executor, reason } }
|
||||
|
||||
session: {
|
||||
id: sessionId,
|
||||
folder: sessionFolder,
|
||||
artifacts: {
|
||||
explorations: manifest.explorations.map(exp => ({
|
||||
angle: exp.angle,
|
||||
path: exp.path
|
||||
})),
|
||||
explorations_manifest: `${sessionFolder}/explorations-manifest.json`,
|
||||
plan: `${sessionFolder}/plan.json`,
|
||||
task_dir: `${sessionFolder}/.task`
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 5.2: Handoff**
|
||||
|
||||
```javascript
|
||||
// Direct phase handoff: Read and execute Phase 2 (lite-execute) with in-memory context
|
||||
// No Skill routing needed - executionContext is already set in Step 5.1
|
||||
Read("phases/02-lite-execute.md")
|
||||
// Execute Phase 2 with executionContext (Mode 1: In-Memory Plan)
|
||||
```
|
||||
|
||||
## Session Folder Structure
|
||||
|
||||
```
|
||||
.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/
|
||||
├── exploration-{angle1}.json # Exploration angle 1
|
||||
├── exploration-{angle2}.json # Exploration angle 2
|
||||
├── exploration-{angle3}.json # Exploration angle 3 (if applicable)
|
||||
├── exploration-{angle4}.json # Exploration angle 4 (if applicable)
|
||||
├── explorations-manifest.json # Exploration index
|
||||
├── planning-context.md # Evidence paths + understanding
|
||||
├── plan.json # Plan overview (task_ids[])
|
||||
└── .task/ # Task files directory
|
||||
├── TASK-001.json
|
||||
├── TASK-002.json
|
||||
└── ...
|
||||
```
|
||||
|
||||
**Example**:
|
||||
```
|
||||
.workflow/.lite-plan/implement-jwt-refresh-2025-11-25-14-30-25/
|
||||
├── exploration-architecture.json
|
||||
├── exploration-auth-patterns.json
|
||||
├── exploration-security.json
|
||||
├── explorations-manifest.json
|
||||
├── planning-context.md
|
||||
├── plan.json
|
||||
└── .task/
|
||||
├── TASK-001.json
|
||||
├── TASK-002.json
|
||||
└── TASK-003.json
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| Exploration agent failure | Skip exploration, continue with task description only |
|
||||
| Planning agent failure | Fallback to direct planning by Claude |
|
||||
| Clarification timeout | Use exploration findings as-is |
|
||||
| Confirmation timeout | Save context, display resume instructions |
|
||||
| Modify loop > 3 times | Suggest breaking task or using /workflow:plan |
|
||||
|
||||
## Next Phase
|
||||
|
||||
After Phase 5 handoff, execution continues in [Phase 2: Lite-Execute](02-lite-execute.md).
|
||||
776
.claude/skills/workflow-lite-plan copy/phases/02-lite-execute.md
Normal file
776
.claude/skills/workflow-lite-plan copy/phases/02-lite-execute.md
Normal file
@@ -0,0 +1,776 @@
|
||||
# Phase 2: Lite-Execute
|
||||
|
||||
Complete execution engine: multi-mode input, task grouping, batch execution, code review, and development index update.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Flexible task execution command supporting three input modes: in-memory plan (from lite-plan), direct prompt description, or file content. Handles execution orchestration, progress tracking, and optional code review.
|
||||
|
||||
**Core capabilities:**
|
||||
- Multi-mode input (in-memory plan, prompt description, or file path)
|
||||
- Execution orchestration (Agent or Codex) with full context
|
||||
- Live progress tracking via TodoWrite at execution call level
|
||||
- Optional code review with selected tool (Gemini, Agent, or custom)
|
||||
- Context continuity across multiple executions
|
||||
- Intelligent format detection (Enhanced Task JSON vs plain text)
|
||||
|
||||
## Usage
|
||||
|
||||
### Input
|
||||
```
|
||||
<input> Task description string, or path to file (required)
|
||||
```
|
||||
|
||||
Mode 1 (In-Memory) is triggered by lite-plan direct handoff when `executionContext` is available.
|
||||
Workflow preferences (`autoYes`) are passed from SKILL.md via `workflowPreferences` context variable.
|
||||
|
||||
## Input Modes
|
||||
|
||||
### Mode 1: In-Memory Plan
|
||||
|
||||
**Trigger**: Called by lite-plan direct handoff after Phase 4 approval (executionContext available)
|
||||
|
||||
**Input Source**: `executionContext` global variable set by lite-plan
|
||||
|
||||
**Content**: Complete execution context (see Data Structures section)
|
||||
|
||||
**Behavior**:
|
||||
- Skip execution method selection (already set by lite-plan)
|
||||
- Directly proceed to execution with full context
|
||||
- All planning artifacts available (exploration, clarifications, plan)
|
||||
|
||||
### Mode 2: Prompt Description
|
||||
|
||||
**Trigger**: User calls with task description string
|
||||
|
||||
**Input**: Simple task description (e.g., "Add unit tests for auth module")
|
||||
|
||||
**Behavior**:
|
||||
- Store prompt as `originalUserInput`
|
||||
- Create simple execution plan from prompt
|
||||
- AskUserQuestion: Select execution method (Agent/Codex/Auto)
|
||||
- AskUserQuestion: Select code review tool (Skip/Gemini/Agent/Other)
|
||||
- Proceed to execution with `originalUserInput` included
|
||||
|
||||
**User Interaction**:
|
||||
```javascript
|
||||
const autoYes = workflowPreferences.autoYes
|
||||
|
||||
let userSelection
|
||||
|
||||
if (autoYes) {
|
||||
// Auto mode: Use defaults
|
||||
console.log(`[Auto] Auto-confirming execution:`)
|
||||
console.log(` - Execution method: Auto`)
|
||||
console.log(` - Code review: Skip`)
|
||||
|
||||
userSelection = {
|
||||
execution_method: "Auto",
|
||||
code_review_tool: "Skip"
|
||||
}
|
||||
} else {
|
||||
// Interactive mode: Ask user
|
||||
userSelection = AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "Select execution method:",
|
||||
header: "Execution",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "@code-developer agent" },
|
||||
{ label: "Codex", description: "codex CLI tool" },
|
||||
{ label: "Auto", description: "Auto-select based on complexity" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "Enable code review after execution?",
|
||||
header: "Code Review",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Skip", description: "No review" },
|
||||
{ label: "Gemini Review", description: "Gemini CLI tool" },
|
||||
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
|
||||
{ label: "Agent Review", description: "Current agent review" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Mode 3: File Content
|
||||
|
||||
**Trigger**: User calls with file path
|
||||
|
||||
**Input**: Path to file containing task description or plan.json
|
||||
|
||||
**Step 1: Read and Detect Format**
|
||||
|
||||
```javascript
|
||||
fileContent = Read(filePath)
|
||||
|
||||
// Attempt JSON parsing
|
||||
try {
|
||||
jsonData = JSON.parse(fileContent)
|
||||
|
||||
// Check if plan.json from lite-plan session (two-layer format: task_ids[])
|
||||
if (jsonData.summary && jsonData.approach && jsonData.task_ids) {
|
||||
planObject = jsonData
|
||||
originalUserInput = jsonData.summary
|
||||
isPlanJson = true
|
||||
|
||||
// Load tasks from .task/*.json files
|
||||
const planDir = filePath.replace(/[/\\][^/\\]+$/, '') // parent directory
|
||||
planObject._loadedTasks = loadTaskFiles(planDir, jsonData.task_ids)
|
||||
} else {
|
||||
// Valid JSON but not plan.json - treat as plain text
|
||||
originalUserInput = fileContent
|
||||
isPlanJson = false
|
||||
}
|
||||
} catch {
|
||||
// Not valid JSON - treat as plain text prompt
|
||||
originalUserInput = fileContent
|
||||
isPlanJson = false
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Create Execution Plan**
|
||||
|
||||
If `isPlanJson === true`:
|
||||
- Use `planObject` directly
|
||||
- User selects execution method and code review
|
||||
|
||||
If `isPlanJson === false`:
|
||||
- Treat file content as prompt (same behavior as Mode 2)
|
||||
- Create simple execution plan from content
|
||||
|
||||
**Step 3: User Interaction**
|
||||
|
||||
- AskUserQuestion: Select execution method (Agent/Codex/Auto)
|
||||
- AskUserQuestion: Select code review tool
|
||||
- Proceed to execution with full context
|
||||
|
||||
## Helper Functions
|
||||
|
||||
```javascript
|
||||
// Load task files from .task/ directory (two-layer format)
|
||||
function loadTaskFiles(planDir, taskIds) {
|
||||
return taskIds.map(id => {
|
||||
const taskPath = `${planDir}/.task/${id}.json`
|
||||
return JSON.parse(Read(taskPath))
|
||||
})
|
||||
}
|
||||
|
||||
// Get tasks array from loaded .task/*.json files
|
||||
function getTasks(planObject) {
|
||||
return planObject._loadedTasks || []
|
||||
}
|
||||
```
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Input Parsing:
|
||||
└─ Decision (mode detection):
|
||||
├─ executionContext exists → Mode 1: Load executionContext → Skip user selection
|
||||
├─ Ends with .md/.json/.txt → Mode 3: Read file → Detect format
|
||||
│ ├─ Valid plan.json → Use planObject → User selects method + review
|
||||
│ └─ Not plan.json → Treat as prompt → User selects method + review
|
||||
└─ Other → Mode 2: Prompt description → User selects method + review
|
||||
|
||||
Execution:
|
||||
├─ Step 1: Initialize result tracking (previousExecutionResults = [])
|
||||
├─ Step 2: Task grouping & batch creation
|
||||
│ ├─ Extract explicit depends_on (no file/keyword inference)
|
||||
│ ├─ Group: independent tasks → per-executor parallel batches (one CLI per batch)
|
||||
│ ├─ Group: dependent tasks → sequential phases (respect dependencies)
|
||||
│ └─ Create TodoWrite list for batches
|
||||
├─ Step 3: Launch execution
|
||||
│ ├─ Phase 1: Independent tasks (⚡ per-executor batches, multi-CLI concurrent)
|
||||
│ └─ Phase 2+: Dependent tasks by dependency order
|
||||
├─ Step 4: Track progress (TodoWrite updates per batch)
|
||||
└─ Step 5: Code review (if codeReviewTool ≠ "Skip")
|
||||
|
||||
Output:
|
||||
└─ Execution complete with results in previousExecutionResults[]
|
||||
```
|
||||
|
||||
## Detailed Execution Steps
|
||||
|
||||
### Step 1: Initialize Execution Tracking
|
||||
|
||||
**Operations**:
|
||||
- Initialize result tracking for multi-execution scenarios
|
||||
- Set up `previousExecutionResults` array for context continuity
|
||||
- **In-Memory Mode**: Echo execution strategy from lite-plan for transparency
|
||||
|
||||
```javascript
|
||||
// Initialize result tracking
|
||||
previousExecutionResults = []
|
||||
|
||||
// In-Memory Mode: Echo execution strategy (transparency before execution)
|
||||
if (executionContext) {
|
||||
console.log(`
|
||||
📋 Execution Strategy (from lite-plan):
|
||||
Method: ${executionContext.executionMethod}
|
||||
Review: ${executionContext.codeReviewTool}
|
||||
Tasks: ${getTasks(executionContext.planObject).length}
|
||||
Complexity: ${executionContext.planObject.complexity}
|
||||
${executionContext.executorAssignments ? ` Assignments: ${JSON.stringify(executionContext.executorAssignments)}` : ''}
|
||||
`)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Task Grouping & Batch Creation
|
||||
|
||||
**Dependency Analysis & Grouping Algorithm**:
|
||||
```javascript
|
||||
// Use explicit depends_on from plan.json (no inference from file/keywords)
|
||||
function extractDependencies(tasks) {
|
||||
const taskIdToIndex = {}
|
||||
tasks.forEach((t, i) => { taskIdToIndex[t.id] = i })
|
||||
|
||||
return tasks.map((task, i) => {
|
||||
// Only use explicit depends_on from plan.json
|
||||
const deps = (task.depends_on || [])
|
||||
.map(depId => taskIdToIndex[depId])
|
||||
.filter(idx => idx !== undefined && idx < i)
|
||||
return { ...task, taskIndex: i, dependencies: deps }
|
||||
})
|
||||
}
|
||||
|
||||
// Executor Resolution (used by task grouping below)
|
||||
// 获取任务的 executor(优先使用 executorAssignments,fallback 到全局 executionMethod)
|
||||
function getTaskExecutor(task) {
|
||||
const assignments = executionContext?.executorAssignments || {}
|
||||
if (assignments[task.id]) {
|
||||
return assignments[task.id].executor // 'gemini' | 'codex' | 'agent'
|
||||
}
|
||||
// Fallback: 全局 executionMethod 映射
|
||||
const method = executionContext?.executionMethod || 'Auto'
|
||||
if (method === 'Agent') return 'agent'
|
||||
if (method === 'Codex') return 'codex'
|
||||
// Auto: 根据复杂度
|
||||
return planObject.complexity === 'Low' ? 'agent' : 'codex'
|
||||
}
|
||||
|
||||
// 按 executor 分组任务(核心分组组件)
|
||||
function groupTasksByExecutor(tasks) {
|
||||
const groups = { gemini: [], codex: [], agent: [] }
|
||||
tasks.forEach(task => {
|
||||
const executor = getTaskExecutor(task)
|
||||
groups[executor].push(task)
|
||||
})
|
||||
return groups
|
||||
}
|
||||
|
||||
// Group into batches: per-executor parallel batches (one CLI per batch)
|
||||
function createExecutionCalls(tasks, executionMethod) {
|
||||
const tasksWithDeps = extractDependencies(tasks)
|
||||
const processed = new Set()
|
||||
const calls = []
|
||||
|
||||
// Phase 1: Independent tasks → per-executor batches (multi-CLI concurrent)
|
||||
const independentTasks = tasksWithDeps.filter(t => t.dependencies.length === 0)
|
||||
if (independentTasks.length > 0) {
|
||||
const executorGroups = groupTasksByExecutor(independentTasks)
|
||||
let parallelIndex = 1
|
||||
|
||||
for (const [executor, tasks] of Object.entries(executorGroups)) {
|
||||
if (tasks.length === 0) continue
|
||||
tasks.forEach(t => processed.add(t.taskIndex))
|
||||
calls.push({
|
||||
method: executionMethod,
|
||||
executor: executor, // 明确指定 executor
|
||||
executionType: "parallel",
|
||||
groupId: `P${parallelIndex++}`,
|
||||
taskSummary: tasks.map(t => t.title).join(' | '),
|
||||
tasks: tasks
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: Dependent tasks → sequential/parallel batches (respect dependencies)
|
||||
let sequentialIndex = 1
|
||||
let remaining = tasksWithDeps.filter(t => !processed.has(t.taskIndex))
|
||||
|
||||
while (remaining.length > 0) {
|
||||
// Find tasks whose dependencies are all satisfied
|
||||
const ready = remaining.filter(t =>
|
||||
t.dependencies.every(d => processed.has(d))
|
||||
)
|
||||
|
||||
if (ready.length === 0) {
|
||||
console.warn('Circular dependency detected, forcing remaining tasks')
|
||||
ready.push(...remaining)
|
||||
}
|
||||
|
||||
if (ready.length > 1) {
|
||||
// Multiple ready tasks → per-executor batches (parallel within this phase)
|
||||
const executorGroups = groupTasksByExecutor(ready)
|
||||
for (const [executor, tasks] of Object.entries(executorGroups)) {
|
||||
if (tasks.length === 0) continue
|
||||
tasks.forEach(t => processed.add(t.taskIndex))
|
||||
calls.push({
|
||||
method: executionMethod,
|
||||
executor: executor,
|
||||
executionType: "parallel",
|
||||
groupId: `P${calls.length + 1}`,
|
||||
taskSummary: tasks.map(t => t.title).join(' | '),
|
||||
tasks: tasks
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Single ready task → sequential batch
|
||||
ready.forEach(t => processed.add(t.taskIndex))
|
||||
calls.push({
|
||||
method: executionMethod,
|
||||
executor: getTaskExecutor(ready[0]),
|
||||
executionType: "sequential",
|
||||
groupId: `S${sequentialIndex++}`,
|
||||
taskSummary: ready[0].title,
|
||||
tasks: ready
|
||||
})
|
||||
}
|
||||
|
||||
remaining = remaining.filter(t => !processed.has(t.taskIndex))
|
||||
}
|
||||
|
||||
return calls
|
||||
}
|
||||
|
||||
executionCalls = createExecutionCalls(getTasks(planObject), executionMethod).map(c => ({ ...c, id: `[${c.groupId}]` }))
|
||||
|
||||
TodoWrite({
|
||||
todos: executionCalls.map(c => ({
|
||||
content: `${c.executionType === "parallel" ? "⚡" : "→"} ${c.id} (${c.tasks.length} tasks)`,
|
||||
status: "pending",
|
||||
activeForm: `Executing ${c.id}`
|
||||
}))
|
||||
})
|
||||
```
|
||||
|
||||
### Step 3: Launch Execution
|
||||
|
||||
**Executor Resolution**: `getTaskExecutor()` and `groupTasksByExecutor()` defined in Step 2 (Task Grouping).
|
||||
|
||||
**Batch Execution Routing** (根据 batch.executor 字段路由):
|
||||
```javascript
|
||||
// executeBatch 根据 batch 自身的 executor 字段决定调用哪个 CLI
|
||||
function executeBatch(batch) {
|
||||
const executor = batch.executor || getTaskExecutor(batch.tasks[0])
|
||||
const sessionId = executionContext?.session?.id || 'standalone'
|
||||
const fixedId = `${sessionId}-${batch.groupId}`
|
||||
|
||||
if (executor === 'agent') {
|
||||
// Agent execution (synchronous)
|
||||
return Task({
|
||||
subagent_type: "code-developer",
|
||||
run_in_background: false,
|
||||
description: batch.taskSummary,
|
||||
prompt: buildExecutionPrompt(batch)
|
||||
})
|
||||
} else if (executor === 'codex') {
|
||||
// Codex CLI (background)
|
||||
return Bash(`ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write --id ${fixedId}`, { run_in_background: true })
|
||||
} else if (executor === 'gemini') {
|
||||
// Gemini CLI (background)
|
||||
return Bash(`ccw cli -p "${buildExecutionPrompt(batch)}" --tool gemini --mode write --id ${fixedId}`, { run_in_background: true })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**并行执行原则**:
|
||||
- 每个 batch 对应一个独立的 CLI 实例或 Agent 调用
|
||||
- 并行 = 多个 Bash(run_in_background=true) 或多个 Task() 同时发出
|
||||
- 绝不将多个独立任务合并到同一个 CLI prompt 中
|
||||
- Agent 任务不可后台执行(run_in_background=false),但多个 Agent 任务可通过单条消息中的多个 Task() 调用并发
|
||||
|
||||
**Execution Flow**: Parallel batches concurrently → Sequential batches in order
|
||||
```javascript
|
||||
const parallel = executionCalls.filter(c => c.executionType === "parallel")
|
||||
const sequential = executionCalls.filter(c => c.executionType === "sequential")
|
||||
|
||||
// Phase 1: Launch all parallel batches (single message with multiple tool calls)
|
||||
if (parallel.length > 0) {
|
||||
TodoWrite({ todos: executionCalls.map(c => ({ status: c.executionType === "parallel" ? "in_progress" : "pending" })) })
|
||||
parallelResults = await Promise.all(parallel.map(c => executeBatch(c)))
|
||||
previousExecutionResults.push(...parallelResults)
|
||||
TodoWrite({ todos: executionCalls.map(c => ({ status: parallel.includes(c) ? "completed" : "pending" })) })
|
||||
}
|
||||
|
||||
// Phase 2: Execute sequential batches one by one
|
||||
for (const call of sequential) {
|
||||
TodoWrite({ todos: executionCalls.map(c => ({ status: c === call ? "in_progress" : "..." })) })
|
||||
result = await executeBatch(call)
|
||||
previousExecutionResults.push(result)
|
||||
TodoWrite({ todos: executionCalls.map(c => ({ status: "completed" or "pending" })) })
|
||||
}
|
||||
```
|
||||
|
||||
### Unified Task Prompt Builder
|
||||
|
||||
**Task Formatting Principle**: Each task is a self-contained checklist. The executor only needs to know what THIS task requires. Same template for Agent and CLI.
|
||||
|
||||
```javascript
|
||||
function buildExecutionPrompt(batch) {
|
||||
// Task template (6 parts: Files → Why → How → Reference → Risks → Done)
|
||||
const formatTask = (t) => `
|
||||
## ${t.title}
|
||||
|
||||
**Scope**: \`${t.scope}\` | **Action**: ${t.action}
|
||||
|
||||
### Files
|
||||
${(t.files || []).map(f => `- **${f.path}** → \`${f.target || ''}\`: ${f.change || (f.changes || []).join(', ') || ''}`).join('\n')}
|
||||
|
||||
${t.rationale ? `
|
||||
### Why this approach (Medium/High)
|
||||
${t.rationale.chosen_approach}
|
||||
${t.rationale.decision_factors?.length > 0 ? `\nKey factors: ${t.rationale.decision_factors.join(', ')}` : ''}
|
||||
${t.rationale.tradeoffs ? `\nTradeoffs: ${t.rationale.tradeoffs}` : ''}
|
||||
` : ''}
|
||||
|
||||
### How to do it
|
||||
${t.description}
|
||||
|
||||
${t.implementation.map(step => `- ${step}`).join('\n')}
|
||||
|
||||
${t.code_skeleton ? `
|
||||
### Code skeleton (High)
|
||||
${t.code_skeleton.interfaces?.length > 0 ? `**Interfaces**: ${t.code_skeleton.interfaces.map(i => `\`${i.name}\` - ${i.purpose}`).join(', ')}` : ''}
|
||||
${t.code_skeleton.key_functions?.length > 0 ? `\n**Functions**: ${t.code_skeleton.key_functions.map(f => `\`${f.signature}\` - ${f.purpose}`).join(', ')}` : ''}
|
||||
${t.code_skeleton.classes?.length > 0 ? `\n**Classes**: ${t.code_skeleton.classes.map(c => `\`${c.name}\` - ${c.purpose}`).join(', ')}` : ''}
|
||||
` : ''}
|
||||
|
||||
### Reference
|
||||
- Pattern: ${t.reference?.pattern || 'N/A'}
|
||||
- Files: ${t.reference?.files?.join(', ') || 'N/A'}
|
||||
${t.reference?.examples ? `- Notes: ${t.reference.examples}` : ''}
|
||||
|
||||
${t.risks?.length > 0 ? `
|
||||
### Risk mitigations (High)
|
||||
${t.risks.map(r => `- ${r.description} → **${r.mitigation}**`).join('\n')}
|
||||
` : ''}
|
||||
|
||||
### Done when
|
||||
${(t.convergence?.criteria || []).map(c => `- [ ] ${c}`).join('\n')}
|
||||
${(t.test?.success_metrics || []).length > 0 ? `\n**Success metrics**: ${t.test.success_metrics.join(', ')}` : ''}`
|
||||
|
||||
// Build prompt
|
||||
const sections = []
|
||||
|
||||
if (originalUserInput) sections.push(`## Goal\n${originalUserInput}`)
|
||||
|
||||
sections.push(`## Tasks\n${batch.tasks.map(formatTask).join('\n\n---\n')}`)
|
||||
|
||||
// Context (reference only)
|
||||
const context = []
|
||||
if (previousExecutionResults.length > 0) {
|
||||
context.push(`### Previous Work\n${previousExecutionResults.map(r => `- ${r.tasksSummary}: ${r.status}`).join('\n')}`)
|
||||
}
|
||||
if (clarificationContext) {
|
||||
context.push(`### Clarifications\n${Object.entries(clarificationContext).map(([q, a]) => `- ${q}: ${a}`).join('\n')}`)
|
||||
}
|
||||
if (executionContext?.planObject?.data_flow?.diagram) {
|
||||
context.push(`### Data Flow\n${executionContext.planObject.data_flow.diagram}`)
|
||||
}
|
||||
if (executionContext?.session?.artifacts?.plan) {
|
||||
context.push(`### Artifacts\nPlan: ${executionContext.session.artifacts.plan}`)
|
||||
}
|
||||
// Project guidelines (user-defined constraints from /workflow:session:solidify)
|
||||
context.push(`### Project Guidelines\n@.workflow/project-guidelines.json`)
|
||||
if (context.length > 0) sections.push(`## Context\n${context.join('\n\n')}`)
|
||||
|
||||
sections.push(`Complete each task according to its "Done when" checklist.`)
|
||||
|
||||
return sections.join('\n\n')
|
||||
}
|
||||
```
|
||||
|
||||
**Option A: Agent Execution**
|
||||
|
||||
When to use:
|
||||
- `getTaskExecutor(task) === "agent"`
|
||||
- 或 `executionMethod = "Agent"` (全局 fallback)
|
||||
- 或 `executionMethod = "Auto" AND complexity = "Low"` (全局 fallback)
|
||||
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="code-developer",
|
||||
run_in_background=false,
|
||||
description=batch.taskSummary,
|
||||
prompt=buildExecutionPrompt(batch)
|
||||
)
|
||||
```
|
||||
|
||||
**Result Collection**: After completion, collect result following `executionResult` structure (see Data Structures section)
|
||||
|
||||
**Option B: CLI Execution (Codex)**
|
||||
|
||||
When to use:
|
||||
- `getTaskExecutor(task) === "codex"`
|
||||
- 或 `executionMethod = "Codex"` (全局 fallback)
|
||||
- 或 `executionMethod = "Auto" AND complexity = "Medium/High"` (全局 fallback)
|
||||
|
||||
```bash
|
||||
ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write
|
||||
```
|
||||
|
||||
**Execution with fixed IDs** (predictable ID pattern):
|
||||
```javascript
|
||||
// Launch CLI in background, wait for task hook callback
|
||||
// Generate fixed execution ID: ${sessionId}-${groupId}
|
||||
const sessionId = executionContext?.session?.id || 'standalone'
|
||||
const fixedExecutionId = `${sessionId}-${batch.groupId}` // e.g., "implement-auth-2025-12-13-P1"
|
||||
|
||||
// Check if resuming from previous failed execution
|
||||
const previousCliId = batch.resumeFromCliId || null
|
||||
|
||||
// Build command with fixed ID (and optional resume for continuation)
|
||||
const cli_command = previousCliId
|
||||
? `ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write --id ${fixedExecutionId} --resume ${previousCliId}`
|
||||
: `ccw cli -p "${buildExecutionPrompt(batch)}" --tool codex --mode write --id ${fixedExecutionId}`
|
||||
|
||||
// Execute in background, stop output and wait for task hook callback
|
||||
Bash(
|
||||
command=cli_command,
|
||||
run_in_background=true
|
||||
)
|
||||
// STOP HERE - CLI executes in background, task hook will notify on completion
|
||||
```
|
||||
|
||||
**Resume on Failure** (with fixed ID):
|
||||
```javascript
|
||||
// If execution failed or timed out, offer resume option
|
||||
if (bash_result.status === 'failed' || bash_result.status === 'timeout') {
|
||||
console.log(`
|
||||
⚠️ Execution incomplete. Resume available:
|
||||
Fixed ID: ${fixedExecutionId}
|
||||
Lookup: ccw cli detail ${fixedExecutionId}
|
||||
Resume: ccw cli -p "Continue tasks" --resume ${fixedExecutionId} --tool codex --mode write --id ${fixedExecutionId}-retry
|
||||
`)
|
||||
|
||||
// Store for potential retry in same session
|
||||
batch.resumeFromCliId = fixedExecutionId
|
||||
}
|
||||
```
|
||||
|
||||
**Result Collection**: After completion, analyze output and collect result following `executionResult` structure (include `cliExecutionId` for resume capability)
|
||||
|
||||
**Option C: CLI Execution (Gemini)**
|
||||
|
||||
When to use: `getTaskExecutor(task) === "gemini"` (分析类任务)
|
||||
|
||||
```bash
|
||||
# 使用统一的 buildExecutionPrompt,切换 tool 和 mode
|
||||
ccw cli -p "${buildExecutionPrompt(batch)}" --tool gemini --mode analysis --id ${sessionId}-${batch.groupId}
|
||||
```
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
Progress tracked at batch level (not individual task level). Icons: ⚡ (parallel, concurrent), → (sequential, one-by-one)
|
||||
|
||||
### Step 5: Code Review (Optional)
|
||||
|
||||
**Skip Condition**: Only run if `codeReviewTool ≠ "Skip"`
|
||||
|
||||
**Review Focus**: Verify implementation against plan convergence criteria and test requirements
|
||||
- Read plan.json + .task/*.json for task convergence criteria and test checklist
|
||||
- Check each convergence criterion is fulfilled
|
||||
- Verify success metrics from test field (Medium/High complexity)
|
||||
- Run unit/integration tests specified in test field
|
||||
- Validate code quality and identify issues
|
||||
- Ensure alignment with planned approach and risk mitigations
|
||||
|
||||
**Operations**:
|
||||
- Agent Review: Current agent performs direct review
|
||||
- Gemini Review: Execute gemini CLI with review prompt
|
||||
- Codex Review: Two options - (A) with prompt for complex reviews, (B) `--uncommitted` flag only for quick reviews
|
||||
- Custom tool: Execute specified CLI tool (qwen, etc.)
|
||||
|
||||
**Unified Review Template** (All tools use same standard):
|
||||
|
||||
**Review Criteria**:
|
||||
- **Convergence Criteria**: Verify each criterion from task convergence.criteria
|
||||
- **Test Checklist** (Medium/High): Check unit, integration, success_metrics from task test
|
||||
- **Code Quality**: Analyze quality, identify issues, suggest improvements
|
||||
- **Plan Alignment**: Validate implementation matches planned approach and risk mitigations
|
||||
|
||||
**Shared Prompt Template** (used by all CLI tools):
|
||||
```
|
||||
PURPOSE: Code review for implemented changes against plan convergence criteria and test requirements
|
||||
TASK: • Verify plan convergence criteria fulfillment • Check test requirements (unit, integration, success_metrics) • Analyze code quality • Identify issues • Suggest improvements • Validate plan adherence and risk mitigations
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* @{plan.json} @{.task/*.json} [@{exploration.json}] | Memory: Review lite-execute changes against plan requirements including test checklist
|
||||
EXPECTED: Quality assessment with:
|
||||
- Convergence criteria verification (all tasks from .task/*.json)
|
||||
- Test checklist validation (Medium/High: unit, integration, success_metrics)
|
||||
- Issue identification
|
||||
- Recommendations
|
||||
Explicitly check each convergence criterion and test item from .task/*.json files.
|
||||
CONSTRAINTS: Focus on plan convergence criteria, test requirements, and plan adherence | analysis=READ-ONLY
|
||||
```
|
||||
|
||||
**Tool-Specific Execution** (Apply shared prompt template above):
|
||||
|
||||
```bash
|
||||
# Method 1: Agent Review (current agent)
|
||||
# - Read plan.json: ${executionContext.session.artifacts.plan}
|
||||
# - Apply unified review criteria (see Shared Prompt Template)
|
||||
# - Report findings directly
|
||||
|
||||
# Method 2: Gemini Review (recommended)
|
||||
ccw cli -p "[Shared Prompt Template with artifacts]" --tool gemini --mode analysis
|
||||
# CONTEXT includes: @**/* @${plan.json} [@${exploration.json}]
|
||||
|
||||
# Method 3: Qwen Review (alternative)
|
||||
ccw cli -p "[Shared Prompt Template with artifacts]" --tool qwen --mode analysis
|
||||
# Same prompt as Gemini, different execution engine
|
||||
|
||||
# Method 4: Codex Review (git-aware) - Two mutually exclusive options:
|
||||
|
||||
# Option A: With custom prompt (reviews uncommitted by default)
|
||||
ccw cli -p "[Shared Prompt Template with artifacts]" --tool codex --mode review
|
||||
# Use for complex reviews with specific focus areas
|
||||
|
||||
# Option B: Target flag only (no prompt allowed)
|
||||
ccw cli --tool codex --mode review --uncommitted
|
||||
# Quick review of uncommitted changes without custom instructions
|
||||
|
||||
# ⚠️ IMPORTANT: -p prompt and target flags (--uncommitted/--base/--commit) are MUTUALLY EXCLUSIVE
|
||||
```
|
||||
|
||||
**Multi-Round Review with Fixed IDs**:
|
||||
```javascript
|
||||
// Generate fixed review ID
|
||||
const reviewId = `${sessionId}-review`
|
||||
|
||||
// First review pass with fixed ID
|
||||
const reviewResult = Bash(`ccw cli -p "[Review prompt]" --tool gemini --mode analysis --id ${reviewId}`)
|
||||
|
||||
// If issues found, continue review dialog with fixed ID chain
|
||||
if (hasUnresolvedIssues(reviewResult)) {
|
||||
// Resume with follow-up questions
|
||||
Bash(`ccw cli -p "Clarify the security concerns you mentioned" --resume ${reviewId} --tool gemini --mode analysis --id ${reviewId}-followup`)
|
||||
}
|
||||
```
|
||||
|
||||
**Implementation Note**: Replace `[Shared Prompt Template with artifacts]` placeholder with actual template content, substituting:
|
||||
- `@{plan.json}` → `@${executionContext.session.artifacts.plan}`
|
||||
- `[@{exploration.json}]` → exploration files from artifacts (if exists)
|
||||
|
||||
### Step 6: Auto-Sync Project State
|
||||
|
||||
**Trigger**: After all executions complete (regardless of code review)
|
||||
|
||||
**Operation**: Execute `/workflow:session:sync -y "{summary}"` to update both `project-guidelines.json` and `project-tech.json` in one shot.
|
||||
|
||||
Summary 取值优先级:`originalUserInput` → `planObject.summary` → git log 自动推断。
|
||||
|
||||
## Best Practices
|
||||
|
||||
**Input Modes**: In-memory (lite-plan), prompt (standalone), file (JSON/text)
|
||||
**Task Grouping**: Based on explicit depends_on only; independent tasks split by executor, each batch runs as separate CLI instance
|
||||
**Execution**: Independent task batches launch concurrently via single Claude message with multiple tool calls (one tool call per batch)
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Cause | Resolution |
|
||||
|-------|-------|------------|
|
||||
| Missing executionContext | In-memory mode without context | Error: "No execution context found. Only available when called by lite-plan." |
|
||||
| File not found | File path doesn't exist | Error: "File not found: {path}. Check file path." |
|
||||
| Empty file | File exists but no content | Error: "File is empty: {path}. Provide task description." |
|
||||
| Invalid Enhanced Task JSON | JSON missing required fields | Warning: "Missing required fields. Treating as plain text." |
|
||||
| Malformed JSON | JSON parsing fails | Treat as plain text (expected for non-JSON files) |
|
||||
| Execution failure | Agent/Codex crashes | Display error, use fixed ID `${sessionId}-${groupId}` for resume: `ccw cli -p "Continue" --resume <fixed-id> --id <fixed-id>-retry` |
|
||||
| Execution timeout | CLI exceeded timeout | Use fixed ID for resume with extended timeout |
|
||||
| Codex unavailable | Codex not installed | Show installation instructions, offer Agent execution |
|
||||
| Fixed ID not found | Custom ID lookup failed | Check `ccw cli history`, verify date directories |
|
||||
|
||||
## Data Structures
|
||||
|
||||
### executionContext (Input - Mode 1)
|
||||
|
||||
Passed from lite-plan via global variable:
|
||||
|
||||
```javascript
|
||||
{
|
||||
planObject: {
|
||||
summary: string,
|
||||
approach: string,
|
||||
task_ids: string[], // Task IDs referencing .task/*.json files
|
||||
task_count: number, // Number of tasks
|
||||
_loadedTasks: [...], // Populated at runtime from .task/*.json files
|
||||
estimated_time: string,
|
||||
recommended_execution: string,
|
||||
complexity: string
|
||||
},
|
||||
// Task file paths (populated for two-layer format)
|
||||
taskFiles: [{id: string, path: string}] | null,
|
||||
explorationsContext: {...} | null, // Multi-angle explorations
|
||||
explorationAngles: string[], // List of exploration angles
|
||||
explorationManifest: {...} | null, // Exploration manifest
|
||||
clarificationContext: {...} | null,
|
||||
executionMethod: "Agent" | "Codex" | "Auto", // 全局默认
|
||||
codeReviewTool: "Skip" | "Gemini Review" | "Agent Review" | string,
|
||||
originalUserInput: string,
|
||||
|
||||
// 任务级 executor 分配(优先于 executionMethod)
|
||||
executorAssignments: {
|
||||
[taskId]: { executor: "gemini" | "codex" | "agent", reason: string }
|
||||
},
|
||||
|
||||
// Session artifacts location (saved by lite-plan)
|
||||
session: {
|
||||
id: string, // Session identifier: {taskSlug}-{shortTimestamp}
|
||||
folder: string, // Session folder path: .workflow/.lite-plan/{session-id}
|
||||
artifacts: {
|
||||
explorations: [{angle, path}], // exploration-{angle}.json paths
|
||||
explorations_manifest: string, // explorations-manifest.json path
|
||||
plan: string // plan.json path (always present)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Artifact Usage**:
|
||||
- Artifact files contain detailed planning context
|
||||
- Pass artifact paths to CLI tools and agents for enhanced context
|
||||
- See execution options below for usage examples
|
||||
|
||||
### executionResult (Output)
|
||||
|
||||
Collected after each execution call completes:
|
||||
|
||||
```javascript
|
||||
{
|
||||
executionId: string, // e.g., "[Agent-1]", "[Codex-1]"
|
||||
status: "completed" | "partial" | "failed",
|
||||
tasksSummary: string, // Brief description of tasks handled
|
||||
completionSummary: string, // What was completed
|
||||
keyOutputs: string, // Files created/modified, key changes
|
||||
notes: string, // Important context for next execution
|
||||
fixedCliId: string | null // Fixed CLI execution ID (e.g., "implement-auth-2025-12-13-P1")
|
||||
}
|
||||
```
|
||||
|
||||
Appended to `previousExecutionResults` array for context continuity in multi-execution scenarios.
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 project-guidelines + project-tech(Step 6 已触发,此处不重复)。
|
||||
|
||||
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
|
||||
|
||||
**Fixed ID Pattern**: `${sessionId}-${groupId}` enables predictable lookup without auto-generated timestamps.
|
||||
|
||||
**Resume Usage**: If `status` is "partial" or "failed", use `fixedCliId` to resume:
|
||||
```bash
|
||||
# Lookup previous execution
|
||||
ccw cli detail ${fixedCliId}
|
||||
|
||||
# Resume with new fixed ID for retry
|
||||
ccw cli -p "Continue from where we left off" --resume ${fixedCliId} --tool codex --mode write --id ${fixedCliId}-retry
|
||||
```
|
||||
@@ -714,13 +714,55 @@ executionContext = {
|
||||
}
|
||||
```
|
||||
|
||||
**Step 5.2: Handoff**
|
||||
**Step 5.2: Serialize & Agent Handoff**
|
||||
|
||||
> **Why agent handoff**: Phase 1 history consumes significant context. Direct `Read("phases/02-lite-execute.md")` in the same context risks compact compressing Phase 2 instructions mid-execution. Spawning a fresh agent gives Phase 2 a clean context window.
|
||||
|
||||
```javascript
|
||||
// Direct phase handoff: Read and execute Phase 2 (lite-execute) with in-memory context
|
||||
// No Skill routing needed - executionContext is already set in Step 5.1
|
||||
Read("phases/02-lite-execute.md")
|
||||
// Execute Phase 2 with executionContext (Mode 1: In-Memory Plan)
|
||||
// Pre-populate _loadedTasks so serialized context is self-contained
|
||||
executionContext.planObject._loadedTasks = (executionContext.planObject.task_ids || []).map(id =>
|
||||
JSON.parse(Read(`${sessionFolder}/.task/${id}.json`))
|
||||
)
|
||||
|
||||
// Save executionContext to file for agent handoff
|
||||
Write(`${sessionFolder}/execution-context.json`, JSON.stringify(executionContext, null, 2))
|
||||
|
||||
// Resolve absolute path to Phase 2 instructions
|
||||
const phaseFile = Bash(`cd "${Bash('pwd').trim()}/.claude/skills/workflow-lite-plan/phases" && pwd`).trim()
|
||||
+ '/02-lite-execute.md'
|
||||
|
||||
// Agent handoff: fresh context prevents compact from losing Phase 2 instructions
|
||||
Task(
|
||||
subagent_type="universal-executor",
|
||||
run_in_background=false,
|
||||
description=`Execute: ${taskSlug}`,
|
||||
prompt=`
|
||||
Execute implementation plan following lite-execute protocol.
|
||||
|
||||
## Phase Instructions (MUST read first)
|
||||
Read and follow: ${phaseFile}
|
||||
|
||||
## Execution Context (Mode 1: In-Memory Plan)
|
||||
Read and parse as JSON: ${sessionFolder}/execution-context.json
|
||||
This is the executionContext variable referenced throughout Phase 2.
|
||||
The planObject._loadedTasks array is pre-populated — getTasks(planObject) works directly.
|
||||
|
||||
## Key References
|
||||
- Session ID: ${sessionId}
|
||||
- Session folder: ${sessionFolder}
|
||||
- Plan: ${sessionFolder}/plan.json
|
||||
- Task files: ${sessionFolder}/.task/TASK-*.json
|
||||
- Original task: ${task_description}
|
||||
|
||||
## Execution Steps
|
||||
1. Read phase instructions file (full protocol)
|
||||
2. Read execution-context.json → parse as executionContext
|
||||
3. Follow Phase 2 Mode 1 (In-Memory Plan) — executionContext exists, skip user selection
|
||||
4. Execute all tasks (Step 1-4 in Phase 2)
|
||||
5. Run code review if codeReviewTool ≠ "Skip" (Step 5)
|
||||
6. Run auto-sync (Step 6)
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
## Session Folder Structure
|
||||
|
||||
Reference in New Issue
Block a user