From 29a1fea4678c9cfe67a638af2021d895c04a4914 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Sat, 7 Mar 2026 13:32:04 +0800 Subject: [PATCH] feat: Add templates for epics, product brief, and requirements documentation - Introduced a comprehensive template for generating epics and stories in Phase 5, including an index and individual epic files. - Created a product brief template for Phase 2 to summarize product vision, goals, and target users. - Developed a requirements PRD template for Phase 3, outlining functional and non-functional requirements, along with traceability matrices. feat: Implement tech debt roles for assessment, execution, planning, scanning, validation, and analysis - Added roles for tech debt assessment, executor, planner, scanner, validator, and analyst, each with defined phases and processes for managing technical debt. - Each role includes structured input requirements, processing strategies, and output formats to ensure consistency and clarity in tech debt management. --- .claude/commands/ddd/execute.md | 11 + .claude/commands/ddd/plan.md | 37 +- .claude/commands/ddd/scan.md | 31 +- .claude/commands/ddd/sync.md | 49 ++ .../commands/workflow/analyze-with-file.md | 57 +- .../commands/workflow/brainstorm-with-file.md | 64 +- .claude/skills/team-arch-opt/SKILL.md | 510 +++----------- .../team-arch-opt/roles/analyzer/role.md | 78 +++ .../roles/coordinator/commands/analyze.md | 57 ++ .../roles/coordinator/commands/monitor.md | 376 ++++------ .../team-arch-opt/roles/coordinator/role.md | 304 ++------- .../team-arch-opt/roles/designer/role.md | 115 ++++ .../team-arch-opt/roles/refactorer/role.md | 102 +++ .../team-arch-opt/roles/reviewer/role.md | 111 +++ .../team-arch-opt/roles/validator/role.md | 115 ++++ .../skills/team-arch-opt/specs/pipelines.md | 102 +++ .claude/skills/team-brainstorm/SKILL.md | 411 ++--------- .../team-brainstorm/roles/challenger/role.md | 61 ++ .../roles/coordinator/commands/analyze.md | 58 ++ .../roles/coordinator/commands/monitor.md | 198 +++--- .../team-brainstorm/roles/coordinator/role.md | 312 ++------- .../team-brainstorm/roles/evaluator/role.md | 56 ++ .../team-brainstorm/roles/ideator/role.md | 69 ++ .../team-brainstorm/roles/synthesizer/role.md | 57 ++ .../skills/team-brainstorm/specs/pipelines.md | 72 ++ .claude/skills/team-coordinate/SKILL.md | 34 - .../skills/team-coordinate/specs/pipelines.md | 83 +++ .claude/skills/team-designer/SKILL.md | 153 +++++ .../phases/01-requirements-analysis.md | 265 ++++++++ .../phases/02-scaffold-generation.md | 236 +++++++ .../phases/03-content-generation.md | 330 +++++++++ .../team-designer/phases/04-validation.md | 329 +++++++++ .claude/skills/team-executor/SKILL.md | 32 - .claude/skills/team-frontend/SKILL.md | 281 ++------ .../team-frontend/roles/analyst/role.md | 92 +++ .../team-frontend/roles/architect/role.md | 86 +++ .../roles/coordinator/commands/analyze.md | 52 ++ .../roles/coordinator/commands/monitor.md | 22 +- .../team-frontend/roles/coordinator/role.md | 249 ++----- .../team-frontend/roles/developer/role.md | 93 +++ .claude/skills/team-frontend/roles/qa/role.md | 79 +++ .../skills/team-frontend/specs/pipelines.md | 76 +++ .claude/skills/team-issue/SKILL.md | 424 ++---------- .../roles/coordinator/commands/analyze.md | 64 ++ .../roles/coordinator/commands/dispatch.md | 54 +- .../roles/coordinator/commands/monitor.md | 215 +++--- .../team-issue/roles/coordinator/role.md | 306 +++------ .../skills/team-issue/roles/explorer/role.md | 94 +++ .../team-issue/roles/implementer/role.md | 87 +++ .../team-issue/roles/integrator/role.md | 84 +++ .../skills/team-issue/roles/planner/role.md | 81 +++ .../skills/team-issue/roles/reviewer/role.md | 86 +++ .claude/skills/team-issue/specs/pipelines.md | 124 ++++ .claude/skills/team-iterdev/SKILL.md | 532 ++------------- .../team-iterdev/roles/architect/role.md | 65 ++ .../roles/coordinator/commands/analyze.md | 62 ++ .../roles/coordinator/commands/monitor.md | 26 +- .../team-iterdev/roles/coordinator/role.md | 241 ++----- .../team-iterdev/roles/developer/role.md | 74 ++ .../team-iterdev/roles/reviewer/role.md | 66 ++ .../skills/team-iterdev/roles/tester/role.md | 88 +++ .../skills/team-iterdev/specs/pipelines.md | 94 +++ .claude/skills/team-lifecycle-v2/CHANGELOG.md | 46 -- .claude/skills/team-lifecycle-v2/SKILL.md | 295 -------- .../team-lifecycle-v2/role-specs/analyst.md | 107 --- .../team-lifecycle-v2/role-specs/architect.md | 75 -- .../team-lifecycle-v2/role-specs/executor.md | 66 -- .../role-specs/fe-developer.md | 78 --- .../team-lifecycle-v2/role-specs/fe-qa.md | 78 --- .../team-lifecycle-v2/role-specs/planner.md | 97 --- .../team-lifecycle-v2/role-specs/reviewer.md | 122 ---- .../team-lifecycle-v2/role-specs/tester.md | 75 -- .../team-lifecycle-v2/role-specs/writer.md | 117 ---- .../roles/coordinator/commands/dispatch.md | 134 ---- .../roles/coordinator/commands/monitor.md | 134 ---- .../roles/coordinator/role.md | 139 ---- .../specs/document-standards.md | 192 ------ .../team-lifecycle-v2/specs/quality-gates.md | 207 ------ .../team-lifecycle-v2/specs/team-config.json | 246 ------- .claude/skills/team-lifecycle-v3/SKILL.md | 223 ------ .../skills/team-lifecycle-v3/roles/README.md | 232 ------- .../roles/coordinator/commands/dispatch.md | 236 ------- .../roles/coordinator/commands/execute.md | 68 -- .../roles/coordinator/commands/monitor.md | 275 -------- .../roles/coordinator/role.md | 270 -------- .../roles/pipeline/analyst.md | 108 --- .../roles/pipeline/architect.md | 76 --- .../roles/pipeline/executor.md | 171 ----- .../roles/pipeline/fe-developer.md | 79 --- .../team-lifecycle-v3/roles/pipeline/fe-qa.md | 79 --- .../roles/pipeline/orchestrator.md | 145 ---- .../roles/pipeline/planner.md | 98 --- .../roles/pipeline/reviewer.md | 94 --- .../roles/pipeline/tester.md | 76 --- .../roles/pipeline/writer.md | 139 ---- .../roles/specialists/README.md | 65 -- .../roles/specialists/data-engineer.role.md | 37 - .../roles/specialists/devops-engineer.role.md | 37 - .../roles/specialists/ml-engineer.role.md | 37 - .../roles/specialists/orchestrator.role.md | 39 -- .../specialists/performance-optimizer.role.md | 37 - .../roles/specialists/security-expert.role.md | 37 - .../skills/team-lifecycle-v3/specs/README.md | 61 -- .../specs/artifact-contract-spec.md | 101 --- .../team-lifecycle-v3/specs/core-concepts.md | 264 ------- .../specs/document-standards.md | 192 ------ .../team-lifecycle-v3/specs/domain-model.md | 619 ----------------- .../team-lifecycle-v3/specs/execution-flow.md | 643 ------------------ .../team-lifecycle-v3/specs/quality-gates.md | 207 ------ .../team-lifecycle-v3/templates/README.md | 78 --- .../templates/architecture-doc.md | 254 ------- .../templates/epics-template.md | 196 ------ .../templates/product-brief.md | 133 ---- .../templates/requirements-prd.md | 224 ------ .claude/skills/team-lifecycle-v4/SKILL.md | 140 ++++ .../team-lifecycle-v4/roles/analyst/role.md | 78 +++ .../roles/coordinator/commands/analyze.md | 56 ++ .../roles/coordinator/commands/dispatch.md | 46 ++ .../roles/coordinator/commands/monitor.md | 98 +++ .../roles/coordinator/role.md | 116 ++++ .../roles/executor/commands/fix.md | 35 + .../roles/executor/commands/implement.md | 62 ++ .../team-lifecycle-v4/roles/executor/role.md | 67 ++ .../team-lifecycle-v4/roles/planner/role.md | 76 +++ .../roles/reviewer/commands/review-code.md | 34 + .../roles/reviewer/commands/review-spec.md | 44 ++ .../team-lifecycle-v4/roles/reviewer/role.md | 69 ++ .../team-lifecycle-v4/roles/tester/role.md | 87 +++ .../team-lifecycle-v4/roles/writer/role.md | 95 +++ .../specs/knowledge-transfer.md | 96 +++ .../team-lifecycle-v4/specs/pipelines.md | 113 +++ .../team-lifecycle-v4/specs/quality-gates.md | 130 ++++ .../templates/architecture.md} | 0 .../templates/epics.md} | 0 .../templates/product-brief.md | 0 .../templates/requirements.md} | 0 .claude/skills/team-lifecycle/SKILL.md | 319 --------- .../team-lifecycle/role-specs/analyst.md | 96 --- .../team-lifecycle/role-specs/architect.md | 76 --- .../team-lifecycle/role-specs/executor.md | 67 -- .../team-lifecycle/role-specs/fe-developer.md | 79 --- .../skills/team-lifecycle/role-specs/fe-qa.md | 79 --- .../team-lifecycle/role-specs/planner.md | 98 --- .../team-lifecycle/role-specs/reviewer.md | 102 --- .../team-lifecycle/role-specs/tester.md | 76 --- .../team-lifecycle/role-specs/writer.md | 115 ---- .../roles/coordinator/commands/dispatch.md | 218 ------ .../roles/coordinator/commands/monitor.md | 249 ------- .../team-lifecycle/roles/coordinator/role.md | 213 ------ .../specs/document-standards.md | 192 ------ .../team-lifecycle/specs/quality-gates.md | 207 ------ .../team-lifecycle/specs/team-config.json | 216 ------ .../templates/architecture-doc.md | 254 ------- .../templates/epics-template.md | 196 ------ .../team-lifecycle/templates/product-brief.md | 133 ---- .../templates/requirements-prd.md | 224 ------ .claude/skills/team-perf-opt/SKILL.md | 495 +++----------- .../team-perf-opt/roles/benchmarker/role.md | 89 +++ .../roles/coordinator/commands/analyze.md | 61 ++ .../team-perf-opt/roles/coordinator/role.md | 241 ++----- .../team-perf-opt/roles/optimizer/role.md | 97 +++ .../team-perf-opt/roles/profiler/role.md | 73 ++ .../team-perf-opt/roles/reviewer/role.md | 75 ++ .../team-perf-opt/roles/strategist/role.md | 94 +++ .../skills/team-perf-opt/specs/pipelines.md | 65 ++ .claude/skills/team-planex/SKILL.md | 319 ++------- .../roles/coordinator/commands/analyze.md | 52 ++ .../roles/coordinator/commands/monitor.md | 4 +- .../team-planex/roles/coordinator/role.md | 81 +-- .../skills/team-planex/roles/executor/role.md | 91 +++ .../skills/team-planex/roles/planner/role.md | 111 +++ .claude/skills/team-planex/specs/pipelines.md | 93 +++ .../skills/team-quality-assurance/SKILL.md | 490 ++----------- .../roles/analyst/role.md | 80 +++ .../roles/coordinator/commands/analyze.md | 72 ++ .../roles/coordinator/commands/dispatch.md | 260 +++---- .../roles/coordinator/commands/monitor.md | 270 ++++---- .../roles/coordinator/role.md | 282 +++----- .../roles/executor/role.md | 65 ++ .../roles/generator/role.md | 68 ++ .../roles/scout/role.md | 67 ++ .../roles/strategist/role.md | 71 ++ .../team-quality-assurance/specs/pipelines.md | 115 ++++ .claude/skills/team-review/SKILL.md | 345 ++-------- .../roles/coordinator/commands/analyze.md | 71 ++ .../roles/coordinator/commands/dispatch.md | 198 ++---- .../roles/coordinator/commands/monitor.md | 366 ++++------ .../team-review/roles/coordinator/role.md | 336 +++------ .../skills/team-review/roles/fixer/role.md | 76 +++ .../skills/team-review/roles/reviewer/role.md | 67 ++ .../skills/team-review/roles/scanner/role.md | 71 ++ .claude/skills/team-review/specs/pipelines.md | 102 +++ .claude/skills/team-roadmap-dev/SKILL.md | 423 +++--------- .../roles/coordinator/commands/analyze.md | 61 ++ .../roles/coordinator/commands/monitor.md | 8 +- .../roles/coordinator/role.md | 1 + .../team-roadmap-dev/roles/executor/role.md | 72 ++ .../team-roadmap-dev/roles/planner/role.md | 78 +++ .../team-roadmap-dev/roles/verifier/role.md | 74 ++ .../team-roadmap-dev/specs/pipelines.md | 93 +++ .claude/skills/team-tech-debt/SKILL.md | 519 ++------------ .../team-tech-debt/roles/assessor/role.md | 69 ++ .../roles/coordinator/commands/analyze.md | 47 ++ .../roles/coordinator/commands/monitor.md | 314 ++++----- .../team-tech-debt/roles/coordinator/role.md | 402 ++--------- .../team-tech-debt/roles/executor/role.md | 76 +++ .../team-tech-debt/roles/planner/role.md | 69 ++ .../team-tech-debt/roles/scanner/role.md | 81 +++ .../team-tech-debt/roles/validator/role.md | 78 +++ .../skills/team-tech-debt/specs/pipelines.md | 47 ++ .claude/skills/team-testing/SKILL.md | 393 ++--------- .../skills/team-testing/roles/analyst/role.md | 95 +++ .../roles/coordinator/commands/analyze.md | 70 ++ .../roles/coordinator/commands/dispatch.md | 181 ++--- .../roles/coordinator/commands/monitor.md | 267 ++++---- .../team-testing/roles/coordinator/role.md | 307 ++------- .../team-testing/roles/executor/role.md | 98 +++ .../team-testing/roles/generator/role.md | 97 +++ .../team-testing/roles/strategist/role.md | 83 +++ .../skills/team-testing/specs/pipelines.md | 101 +++ .claude/skills/team-uidesign/SKILL.md | 458 ++----------- .../roles/coordinator/commands/analyze.md | 59 ++ .../roles/coordinator/commands/dispatch.md | 2 +- .../roles/coordinator/commands/monitor.md | 262 ++++--- .../team-uidesign/roles/coordinator/role.md | 335 +++------ .../team-uidesign/roles/designer/role.md | 69 ++ .../team-uidesign/roles/implementer/role.md | 72 ++ .../team-uidesign/roles/researcher/role.md | 82 +++ .../team-uidesign/roles/reviewer/role.md | 67 ++ .../skills/team-uidesign/specs/pipelines.md | 76 +++ .claude/skills/team-ultra-analyze/SKILL.md | 433 ++---------- .../team-ultra-analyze/roles/analyst/role.md | 90 +++ .../roles/coordinator/commands/analyze.md | 73 ++ .../roles/coordinator/role.md | 109 +-- .../roles/discussant/role.md | 107 +++ .../team-ultra-analyze/roles/explorer/role.md | 74 ++ .../roles/synthesizer/role.md | 78 +++ .../team-ultra-analyze/specs/pipelines.md | 64 ++ .claude/skills/team-ux-improve/SKILL.md | 316 +++------ .../roles/coordinator/commands/analyze.md | 62 ++ .../roles/coordinator/commands/dispatch.md | 3 +- .../roles/coordinator/commands/monitor.md | 219 +++--- .../team-ux-improve/roles/coordinator/role.md | 300 +++----- .../team-ux-improve/roles/designer/role.md | 122 ++++ .../team-ux-improve/roles/diagnoser/role.md | 93 +++ .../team-ux-improve/roles/explorer/role.md | 77 +++ .../team-ux-improve/roles/implementer/role.md | 102 +++ .../team-ux-improve/roles/scanner/role.md | 93 +++ .../team-ux-improve/roles/tester/role.md | 84 +++ .../skills/team-ux-improve/specs/pipelines.md | 54 ++ ccw/src/services/deepwiki-service.ts | 173 ++++- ccw/src/tools/cli-executor-core.ts | 81 +-- .../src/codexlens/storage/deepwiki_models.py | 10 +- .../src/codexlens/storage/deepwiki_store.py | 236 ++++++- .../src/codexlens/tools/deepwiki_generator.py | 14 +- 255 files changed, 14407 insertions(+), 21120 deletions(-) create mode 100644 .claude/skills/team-arch-opt/roles/analyzer/role.md create mode 100644 .claude/skills/team-arch-opt/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-arch-opt/roles/designer/role.md create mode 100644 .claude/skills/team-arch-opt/roles/refactorer/role.md create mode 100644 .claude/skills/team-arch-opt/roles/reviewer/role.md create mode 100644 .claude/skills/team-arch-opt/roles/validator/role.md create mode 100644 .claude/skills/team-arch-opt/specs/pipelines.md create mode 100644 .claude/skills/team-brainstorm/roles/challenger/role.md create mode 100644 .claude/skills/team-brainstorm/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-brainstorm/roles/evaluator/role.md create mode 100644 .claude/skills/team-brainstorm/roles/ideator/role.md create mode 100644 .claude/skills/team-brainstorm/roles/synthesizer/role.md create mode 100644 .claude/skills/team-brainstorm/specs/pipelines.md create mode 100644 .claude/skills/team-coordinate/specs/pipelines.md create mode 100644 .claude/skills/team-designer/SKILL.md create mode 100644 .claude/skills/team-designer/phases/01-requirements-analysis.md create mode 100644 .claude/skills/team-designer/phases/02-scaffold-generation.md create mode 100644 .claude/skills/team-designer/phases/03-content-generation.md create mode 100644 .claude/skills/team-designer/phases/04-validation.md create mode 100644 .claude/skills/team-frontend/roles/analyst/role.md create mode 100644 .claude/skills/team-frontend/roles/architect/role.md create mode 100644 .claude/skills/team-frontend/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-frontend/roles/developer/role.md create mode 100644 .claude/skills/team-frontend/roles/qa/role.md create mode 100644 .claude/skills/team-frontend/specs/pipelines.md create mode 100644 .claude/skills/team-issue/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-issue/roles/explorer/role.md create mode 100644 .claude/skills/team-issue/roles/implementer/role.md create mode 100644 .claude/skills/team-issue/roles/integrator/role.md create mode 100644 .claude/skills/team-issue/roles/planner/role.md create mode 100644 .claude/skills/team-issue/roles/reviewer/role.md create mode 100644 .claude/skills/team-issue/specs/pipelines.md create mode 100644 .claude/skills/team-iterdev/roles/architect/role.md create mode 100644 .claude/skills/team-iterdev/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-iterdev/roles/developer/role.md create mode 100644 .claude/skills/team-iterdev/roles/reviewer/role.md create mode 100644 .claude/skills/team-iterdev/roles/tester/role.md create mode 100644 .claude/skills/team-iterdev/specs/pipelines.md delete mode 100644 .claude/skills/team-lifecycle-v2/CHANGELOG.md delete mode 100644 .claude/skills/team-lifecycle-v2/SKILL.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/analyst.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/architect.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/executor.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/fe-developer.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/fe-qa.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/planner.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/reviewer.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/tester.md delete mode 100644 .claude/skills/team-lifecycle-v2/role-specs/writer.md delete mode 100644 .claude/skills/team-lifecycle-v2/roles/coordinator/commands/dispatch.md delete mode 100644 .claude/skills/team-lifecycle-v2/roles/coordinator/commands/monitor.md delete mode 100644 .claude/skills/team-lifecycle-v2/roles/coordinator/role.md delete mode 100644 .claude/skills/team-lifecycle-v2/specs/document-standards.md delete mode 100644 .claude/skills/team-lifecycle-v2/specs/quality-gates.md delete mode 100644 .claude/skills/team-lifecycle-v2/specs/team-config.json delete mode 100644 .claude/skills/team-lifecycle-v3/SKILL.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/README.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/coordinator/commands/dispatch.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/coordinator/commands/execute.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/coordinator/commands/monitor.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/coordinator/role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/analyst.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/architect.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/executor.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/fe-developer.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/fe-qa.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/orchestrator.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/planner.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/reviewer.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/tester.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/pipeline/writer.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/README.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/data-engineer.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/devops-engineer.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/ml-engineer.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/orchestrator.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/performance-optimizer.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/roles/specialists/security-expert.role.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/README.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/artifact-contract-spec.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/core-concepts.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/document-standards.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/domain-model.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/execution-flow.md delete mode 100644 .claude/skills/team-lifecycle-v3/specs/quality-gates.md delete mode 100644 .claude/skills/team-lifecycle-v3/templates/README.md delete mode 100644 .claude/skills/team-lifecycle-v3/templates/architecture-doc.md delete mode 100644 .claude/skills/team-lifecycle-v3/templates/epics-template.md delete mode 100644 .claude/skills/team-lifecycle-v3/templates/product-brief.md delete mode 100644 .claude/skills/team-lifecycle-v3/templates/requirements-prd.md create mode 100644 .claude/skills/team-lifecycle-v4/SKILL.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/analyst/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/coordinator/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/executor/commands/fix.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/executor/commands/implement.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/executor/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/planner/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-code.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-spec.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/reviewer/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/tester/role.md create mode 100644 .claude/skills/team-lifecycle-v4/roles/writer/role.md create mode 100644 .claude/skills/team-lifecycle-v4/specs/knowledge-transfer.md create mode 100644 .claude/skills/team-lifecycle-v4/specs/pipelines.md create mode 100644 .claude/skills/team-lifecycle-v4/specs/quality-gates.md rename .claude/skills/{team-lifecycle-v2/templates/architecture-doc.md => team-lifecycle-v4/templates/architecture.md} (100%) rename .claude/skills/{team-lifecycle-v2/templates/epics-template.md => team-lifecycle-v4/templates/epics.md} (100%) rename .claude/skills/{team-lifecycle-v2 => team-lifecycle-v4}/templates/product-brief.md (100%) rename .claude/skills/{team-lifecycle-v2/templates/requirements-prd.md => team-lifecycle-v4/templates/requirements.md} (100%) delete mode 100644 .claude/skills/team-lifecycle/SKILL.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/analyst.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/architect.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/executor.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/fe-developer.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/fe-qa.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/planner.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/reviewer.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/tester.md delete mode 100644 .claude/skills/team-lifecycle/role-specs/writer.md delete mode 100644 .claude/skills/team-lifecycle/roles/coordinator/commands/dispatch.md delete mode 100644 .claude/skills/team-lifecycle/roles/coordinator/commands/monitor.md delete mode 100644 .claude/skills/team-lifecycle/roles/coordinator/role.md delete mode 100644 .claude/skills/team-lifecycle/specs/document-standards.md delete mode 100644 .claude/skills/team-lifecycle/specs/quality-gates.md delete mode 100644 .claude/skills/team-lifecycle/specs/team-config.json delete mode 100644 .claude/skills/team-lifecycle/templates/architecture-doc.md delete mode 100644 .claude/skills/team-lifecycle/templates/epics-template.md delete mode 100644 .claude/skills/team-lifecycle/templates/product-brief.md delete mode 100644 .claude/skills/team-lifecycle/templates/requirements-prd.md create mode 100644 .claude/skills/team-perf-opt/roles/benchmarker/role.md create mode 100644 .claude/skills/team-perf-opt/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-perf-opt/roles/optimizer/role.md create mode 100644 .claude/skills/team-perf-opt/roles/profiler/role.md create mode 100644 .claude/skills/team-perf-opt/roles/reviewer/role.md create mode 100644 .claude/skills/team-perf-opt/roles/strategist/role.md create mode 100644 .claude/skills/team-perf-opt/specs/pipelines.md create mode 100644 .claude/skills/team-planex/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-planex/roles/executor/role.md create mode 100644 .claude/skills/team-planex/roles/planner/role.md create mode 100644 .claude/skills/team-planex/specs/pipelines.md create mode 100644 .claude/skills/team-quality-assurance/roles/analyst/role.md create mode 100644 .claude/skills/team-quality-assurance/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-quality-assurance/roles/executor/role.md create mode 100644 .claude/skills/team-quality-assurance/roles/generator/role.md create mode 100644 .claude/skills/team-quality-assurance/roles/scout/role.md create mode 100644 .claude/skills/team-quality-assurance/roles/strategist/role.md create mode 100644 .claude/skills/team-quality-assurance/specs/pipelines.md create mode 100644 .claude/skills/team-review/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-review/roles/fixer/role.md create mode 100644 .claude/skills/team-review/roles/reviewer/role.md create mode 100644 .claude/skills/team-review/roles/scanner/role.md create mode 100644 .claude/skills/team-review/specs/pipelines.md create mode 100644 .claude/skills/team-roadmap-dev/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-roadmap-dev/roles/executor/role.md create mode 100644 .claude/skills/team-roadmap-dev/roles/planner/role.md create mode 100644 .claude/skills/team-roadmap-dev/roles/verifier/role.md create mode 100644 .claude/skills/team-roadmap-dev/specs/pipelines.md create mode 100644 .claude/skills/team-tech-debt/roles/assessor/role.md create mode 100644 .claude/skills/team-tech-debt/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-tech-debt/roles/executor/role.md create mode 100644 .claude/skills/team-tech-debt/roles/planner/role.md create mode 100644 .claude/skills/team-tech-debt/roles/scanner/role.md create mode 100644 .claude/skills/team-tech-debt/roles/validator/role.md create mode 100644 .claude/skills/team-tech-debt/specs/pipelines.md create mode 100644 .claude/skills/team-testing/roles/analyst/role.md create mode 100644 .claude/skills/team-testing/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-testing/roles/executor/role.md create mode 100644 .claude/skills/team-testing/roles/generator/role.md create mode 100644 .claude/skills/team-testing/roles/strategist/role.md create mode 100644 .claude/skills/team-testing/specs/pipelines.md create mode 100644 .claude/skills/team-uidesign/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-uidesign/roles/designer/role.md create mode 100644 .claude/skills/team-uidesign/roles/implementer/role.md create mode 100644 .claude/skills/team-uidesign/roles/researcher/role.md create mode 100644 .claude/skills/team-uidesign/roles/reviewer/role.md create mode 100644 .claude/skills/team-uidesign/specs/pipelines.md create mode 100644 .claude/skills/team-ultra-analyze/roles/analyst/role.md create mode 100644 .claude/skills/team-ultra-analyze/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-ultra-analyze/roles/discussant/role.md create mode 100644 .claude/skills/team-ultra-analyze/roles/explorer/role.md create mode 100644 .claude/skills/team-ultra-analyze/roles/synthesizer/role.md create mode 100644 .claude/skills/team-ultra-analyze/specs/pipelines.md create mode 100644 .claude/skills/team-ux-improve/roles/coordinator/commands/analyze.md create mode 100644 .claude/skills/team-ux-improve/roles/designer/role.md create mode 100644 .claude/skills/team-ux-improve/roles/diagnoser/role.md create mode 100644 .claude/skills/team-ux-improve/roles/explorer/role.md create mode 100644 .claude/skills/team-ux-improve/roles/implementer/role.md create mode 100644 .claude/skills/team-ux-improve/roles/scanner/role.md create mode 100644 .claude/skills/team-ux-improve/roles/tester/role.md create mode 100644 .claude/skills/team-ux-improve/specs/pipelines.md diff --git a/.claude/commands/ddd/execute.md b/.claude/commands/ddd/execute.md index f4a81647..81134e8e 100644 --- a/.claude/commands/ddd/execute.md +++ b/.claude/commands/ddd/execute.md @@ -64,6 +64,7 @@ For each task with `doc_context`: - Load referenced `component_docs` (tech-registry/{slug}.md) - Load ADR excerpts from doc-index `architectureDecisions[]` - Extract requirement acceptance criteria from doc-index `requirements[]` +- Load `doc_context.symbol_docs[]` documentation content (if present) ### 1.4 Echo Strategy @@ -131,6 +132,16 @@ ${feature-map content excerpt — overview + requirements section} ${for each component in task.doc_context.component_ids: tech-registry excerpt — responsibility + code locations + key patterns} +### Symbol Documentation +${if doc_context.symbol_docs is non-empty: + for each component in doc_context.component_ids: + #### ${component.name} Symbols (Top-5) + ${for each symbol in component.symbol_docs.slice(0, 5): + - **${symbol.name}** (${symbol.type}): ${symbol.doc_summary} + Source: `${symbol.source_path}` | Freshness: ${symbol.freshness} + } +} + ### Architecture Constraints ${for each ADR in task.doc_context.adr_ids: ADR title + decision + rationale from doc-index} diff --git a/.claude/commands/ddd/plan.md b/.claude/commands/ddd/plan.md index 714c2dac..6cfff061 100644 --- a/.claude/commands/ddd/plan.md +++ b/.claude/commands/ddd/plan.md @@ -142,6 +142,17 @@ Assemble all found references into a structured impact map: Save as `planning-context.md` (legacy format for backward compatibility). +### Phase 1.7: Symbol Query (DeepWiki Bridge) + +If DeepWiki is available (`deepwiki_feature_to_symbol_index` exists in doc-index.json): + +1. Collect all `codeLocations[].path` from matched `technicalComponents[]` +2. Query DeepWiki: `POST /api/deepwiki/symbols-for-paths { paths: unique_paths }` +3. Build symbol_docs by component, sorted by type priority (class > function > method) +4. Populate `doc_context.symbol_docs[]` with Top-5 symbols per component + +**Graceful degradation**: If DeepWiki unavailable → log warning → skip symbol injection → continue flow. + --- ## Phase 2: Doc-Index-Guided Exploration (NEW) @@ -323,7 +334,18 @@ Follows `plan-overview-base-schema` with ddd-specific `doc_context` extension: "affected_requirements": ["REQ-001", "REQ-002"], "affected_components": ["tech-auth-service"], "architecture_constraints": ["ADR-001"], - "index_path": ".workflow/.doc-index/doc-index.json" + "index_path": ".workflow/.doc-index/doc-index.json", + "symbol_docs": [ + { + "symbol_urn": "deepwiki:symbol:#L-L", + "name": "SymbolName", + "type": "class|function|method", + "doc_summary": "Generated documentation summary...", + "source_path": "src/path/to/file.ts", + "doc_path": ".deepwiki/file.md", + "freshness": "fresh|stale|unknown" + } + ] }, "_metadata": { "timestamp": "ISO8601", @@ -356,7 +378,18 @@ Follows `task-schema` with ddd-specific `doc_context` extension: "component_ids": ["tech-auth-service"], "adr_ids": ["ADR-001"], "feature_docs": ["feature-maps/auth.md"], - "component_docs": ["tech-registry/auth-service.md"] + "component_docs": ["tech-registry/auth-service.md"], + "symbol_docs": [ + { + "symbol_urn": "deepwiki:symbol:#L-L", + "name": "SymbolName", + "type": "class|function|method", + "doc_summary": "Generated documentation summary...", + "source_path": "src/path/to/file.ts", + "doc_path": ".deepwiki/file.md", + "freshness": "fresh|stale|unknown" + } + ] }, "files": [...], "implementation": [...] diff --git a/.claude/commands/ddd/scan.md b/.claude/commands/ddd/scan.md index d073153e..6694bfd2 100644 --- a/.claude/commands/ddd/scan.md +++ b/.claude/commands/ddd/scan.md @@ -266,10 +266,39 @@ Write the index with code-first markers: "affectedComponents": ["tech-{slug}"], "relatedCommit": "full-hash", "timestamp": "ISO8601" - }] + }], + "freshness": { + "thresholds": { "warning": 0.3, "stale": 0.7 }, + "weights": { "time": 0.1, "churn": 0.4, "symbol": 0.5 }, + "time_decay_k": 0.05, + "auto_regenerate": false + }, + "deepwiki_feature_to_symbol_index": {} } ``` +## Phase 6.5: Build DeepWiki Feature-to-Symbol Index + +If DeepWiki is available (`.codexlens/deepwiki_index.db` exists): + +1. Collect all `codeLocations[].path` from `technicalComponents[]` +2. Query DeepWiki: `POST /api/deepwiki/symbols-for-paths { paths: [...] }` +3. Build `deepwiki_feature_to_symbol_index` by traversing: + `feature → requirementIds → techComponentIds → codeLocations → symbols` + +```json +"deepwiki_feature_to_symbol_index": { + "feat-auth": [ + "deepwiki:symbol:src/auth/jwt.ts#L30-L55", + "deepwiki:symbol:src/models/user.ts#L12-L40" + ] +} +``` + +**Symbol URN format**: `deepwiki:symbol:#L-L` + +**Graceful degradation**: If DeepWiki is unavailable, set `deepwiki_feature_to_symbol_index: {}` and log warning. + ## Phase 7: Generate Documents ### 7.1 Feature Maps diff --git a/.claude/commands/ddd/sync.md b/.claude/commands/ddd/sync.md index 968d596a..46e2e46b 100644 --- a/.claude/commands/ddd/sync.md +++ b/.claude/commands/ddd/sync.md @@ -118,6 +118,47 @@ If changed files don't match any existing component: - REQ-002: JWT token generation (implementation updated) ``` +## Phase 2.4: DeepWiki Freshness Check + +If DeepWiki integration is configured (`doc-index.json.freshness` exists): + +### 2.4.1 Identify Modified Files +From `execution-manifest.json` or git diff, collect `files_modified[]` with `action == "modified"`. + +### 2.4.2 Check Staleness +Query DeepWiki: `POST /api/deepwiki/stale-files { files: [{path, hash}] }` + +For each stale file's symbols, calculate staleness score: +``` +S(symbol) = min(1.0, w_t × T + w_c × C + w_s × M) +``` +Where weights come from `doc-index.json.freshness.weights`. + +### 2.4.3 Score Propagation (max aggregation) +``` +S_file = max(S_symbol_1, S_symbol_2, ...) +S_component = max(S_file_1, S_file_2, ...) +S_feature = max(S_component_1, S_component_2, ...) +``` + +### 2.4.4 Status Assignment +Using thresholds from `doc-index.json.freshness.thresholds`: +- `fresh`: score in [0, warning_threshold) +- `warning`: score in [warning_threshold, stale_threshold) +- `stale`: score in [stale_threshold, 1.0] + +### 2.4.5 Update Records +- Update `deepwiki_symbols.staleness_score` and `deepwiki_files.staleness_score` in DeepWiki SQLite +- Update `tech-registry/{slug}.md` YAML frontmatter with freshness block +- Update `feature-maps/{slug}.md` YAML frontmatter with freshness block +- Update `deepwiki_feature_to_symbol_index` in doc-index.json + +### 2.4.6 Staleness Report +Add to action-log: +- Number of stale symbols/files/components +- Top-5 most stale items with scores +- Auto-regeneration candidates (if `auto_regenerate: true` and score >= stale threshold) + ## Phase 3: Update Index ### 3.0 Dry-Run Gate @@ -229,6 +270,14 @@ timestamp: ISO8601 - Features affected: feat-auth - Requirements addressed: REQ-001, REQ-002 +## Staleness (if DeepWiki freshness enabled) +| Item | Type | Score | Status | +|------|------|-------|--------| +| {symbol/file/component} | {type} | {score} | {fresh/warning/stale} | + +- Stale counts: {N} symbols, {N} files, {N} components +- Auto-regeneration candidates: {list of items with auto_regenerate and score >= stale} + ## Notes {any user-provided notes} ``` diff --git a/.claude/commands/workflow/analyze-with-file.md b/.claude/commands/workflow/analyze-with-file.md index 396b6f7c..2dbdf606 100644 --- a/.claude/commands/workflow/analyze-with-file.md +++ b/.claude/commands/workflow/analyze-with-file.md @@ -81,6 +81,18 @@ All `AskUserQuestion` calls MUST comply: 4. Parse options: `-c`/`--continue` for continuation, `-y`/`--yes` for auto-approval 5. Auto-detect: If session folder + discussion.md exist → continue mode 6. Create directory structure +7. **Create Progress Tracking** (TodoWrite — MANDATORY): + ``` + TodoWrite([ + { id: "phase-1", title: "Phase 1: Topic Understanding", status: "in_progress" }, + { id: "phase-2", title: "Phase 2: CLI Exploration", status: "pending" }, + { id: "phase-3", title: "Phase 3: Interactive Discussion", status: "pending" }, + { id: "phase-4", title: "Phase 4: Synthesis & Conclusion", status: "pending" }, + { id: "next-step", title: "GATE: Post-Completion Next Step", status: "pending" } + ]) + ``` + - Update status to `"in_progress"` when entering each phase, `"completed"` when done + - **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"` **Session Variables**: `sessionId`, `sessionFolder`, `autoMode` (boolean), `mode` (new|continue) @@ -98,6 +110,7 @@ All `AskUserQuestion` calls MUST comply: 4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments **Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded +**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"` ### Phase 2: CLI Exploration @@ -218,6 +231,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} - code_anchors/call_chains include `perspective` field **Success**: Exploration + CLI artifacts created, discussion.md Round 1, key findings and exploration decisions recorded +**TodoWrite**: Update `phase-2` → `"completed"`, `phase-3` → `"in_progress"` ### Phase 3: Interactive Discussion @@ -280,6 +294,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} - If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?" **Success**: All rounds documented with narrative synthesis, assumptions corrected, all decisions recorded with rejection reasoning, direction changes with before/after +**TodoWrite**: Update `phase-3` → `"completed"`, `phase-4` → `"in_progress"` ### Phase 4: Synthesis & Conclusion @@ -335,30 +350,38 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} - Accepted: N items | Modified: N items | Rejected: N items - Only accepted/modified recommendations proceed to next step -6. **Post-Completion Options** (analyze-with-file transitions based on user selection): +6. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step. - > **WORKFLOW TRANSITION**: "执行任务" MUST invoke `Skill(skill="workflow-lite-plan")` — do NOT end without calling it. + **TodoWrite**: Update `phase-4` → `"completed"`, `next-step` → `"in_progress"` - AskUserQuestion (single-select, header: "Next Step"): - - **执行任务** (Recommended if high/medium priority recs exist): Launch workflow-lite-plan - - **产出Issue**: Convert recommendations to issues via /issue:new - - **完成**: No further action + > **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying conclusions (step 4) and recommendation review (step 5), you MUST immediately proceed here. - **Handle "产出Issue"**: + Call AskUserQuestion (single-select, header: "Next Step"): + - **执行任务** (Recommended if high/medium priority recs exist): "基于分析结论启动 workflow-lite-plan 制定执行计划" + - **产出Issue**: "将建议转化为 issue 进行跟踪管理" + - **完成**: "分析已足够,无需进一步操作" + + **Handle user selection**: + + **"执行任务"** → MUST invoke Skill tool (do NOT just display a summary and stop): + 1. Build `taskDescription` from high/medium priority recommendations (fallback: summary) + 2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json + 3. **Invoke Skill tool immediately**: + ```javascript + Skill({ skill: "workflow-lite-plan", args: `${taskDescription}\n\n${contextLines}` }) + ``` + If Skill invocation is omitted, the workflow is BROKEN. + 4. After Skill invocation, analyze-with-file is complete — do not output any additional content + + **"产出Issue"** → Convert recommendations to issues: 1. For each recommendation in conclusions.recommendations (priority high/medium): - Build issue JSON: `{title, context: rec.action + rec.rationale, priority: rec.priority == 'high' ? 2 : 3, source: 'discovery', labels: dimensions}` - Create via pipe: `echo '' | ccw issue create` 2. Display created issue IDs with next step hint: `/issue:plan ` - **Handle "执行任务"** — MUST invoke Skill tool (do NOT just display a summary and stop): - 1. Build `taskDescription` from high/medium priority recommendations (fallback: summary) - 2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json - 3. **MANDATORY — Invoke Skill tool immediately** (this is the ONLY correct action, do NOT skip): - ```javascript - Skill({ skill: "workflow-lite-plan", args: `${taskDescription}\n\n${contextLines}` }) - ``` - If Skill invocation is omitted, the workflow is BROKEN — user selected "执行任务" specifically to launch lite-plan. - 4. After Skill invocation, analyze-with-file is complete — do not output any additional content + **"完成"** → No further action needed. + + **TodoWrite**: Update `next-step` → `"completed"` after user selection is handled **conclusions.json Schema**: - `session_id`, `topic`, `completed`, `total_rounds`, `summary` @@ -370,7 +393,7 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} - `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions} - `intent_coverage[]`: {intent, status, where_addressed, notes} -**Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented +**Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented, `next-step` gate completed ## Configuration diff --git a/.claude/commands/workflow/brainstorm-with-file.md b/.claude/commands/workflow/brainstorm-with-file.md index 33e919a3..a725e0e4 100644 --- a/.claude/commands/workflow/brainstorm-with-file.md +++ b/.claude/commands/workflow/brainstorm-with-file.md @@ -107,6 +107,19 @@ When `--yes` or `-y`: Auto-confirm decisions, use recommended roles, balanced ex 5. Auto-detect mode: If session folder + brainstorm.md exist → continue mode 6. Create directory structure: `{session-folder}/ideas/` +7. **Create Progress Tracking** (TodoWrite — MANDATORY): + ``` + TodoWrite([ + { id: "phase-1", title: "Phase 1: Seed Understanding", status: "in_progress" }, + { id: "phase-2", title: "Phase 2: Divergent Exploration", status: "pending" }, + { id: "phase-3", title: "Phase 3: Interactive Refinement", status: "pending" }, + { id: "phase-4", title: "Phase 4: Convergence & Crystallization", status: "pending" }, + { id: "next-step", title: "GATE: Post-Completion Next Step", status: "pending" } + ]) + ``` + - Update status to `"in_progress"` when entering each phase, `"completed"` when done + - **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"` + **Session Variables**: `sessionId`, `sessionFolder`, `brainstormMode` (creative|structured|balanced), `autoMode` (boolean), `mode` (new|continue) ### Phase 1: Seed Understanding @@ -153,6 +166,8 @@ Output as structured exploration vectors for multi-perspective analysis. 5. **Initialize brainstorm.md** with session metadata, initial context (user focus, depth, constraints), seed expansion (original idea + exploration vectors), empty thought evolution timeline sections +**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"` + ### Phase 2: Divergent Exploration 1. **Primary Codebase Exploration via cli-explore-agent** (⚠️ FIRST) @@ -353,6 +368,9 @@ CONSTRAINTS: Don't force incompatible ideas together 4. **Update brainstorm.md** with Round N findings 5. **Repeat or Converge**: Continue loop (max 6 rounds) or exit to Phase 4 +**TodoWrite**: Update `phase-2` → `"completed"` (after first round enters Phase 3), `phase-3` → `"in_progress"` +**TodoWrite** (on exit loop): Update `phase-3` → `"completed"`, `phase-4` → `"in_progress"` + ### Phase 4: Convergence & Crystallization 1. **Generate Final Synthesis** → Write to synthesis.json @@ -366,12 +384,46 @@ CONSTRAINTS: Don't force incompatible ideas together 2. **Final brainstorm.md Update**: Executive summary, top ideas ranked, primary recommendation with rationale, alternative approaches, parked ideas, key insights, session statistics (rounds, ideas generated/survived, duration) -3. **Post-Completion Options** (AskUserQuestion) - - **创建实施计划**: Launch workflow-plan with top idea - - **创建Issue**: Launch issue-discover for top 3 ideas - - **深入分析**: Launch workflow:analyze-with-file for top idea - - **导出分享**: Generate shareable report - - **完成**: No further action +3. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step. + + **TodoWrite**: Update `phase-4` → `"completed"`, `next-step` → `"in_progress"` + + > **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying synthesis (step 2), you MUST immediately proceed here. + + Call AskUserQuestion (single-select, header: "Next Step"): + - **创建实施计划** (Recommended if top idea has high feasibility): "基于最佳创意启动 workflow-plan 制定实施计划" + - **创建Issue**: "将 Top 3 创意转化为 issue 进行跟踪管理" + - **深入分析**: "对最佳创意启动 analyze-with-file 深入技术分析" + - **完成**: "头脑风暴已足够,无需进一步操作" + + **Handle user selection**: + + **"创建实施计划"** → MUST invoke Skill tool: + 1. Build `taskDescription` from top idea in synthesis.json (title + description + next_steps) + 2. Assemble context: `## Prior Brainstorm ({sessionId})` + summary + top idea details + key insights (up to 5) + 3. **Invoke Skill tool immediately**: + ```javascript + Skill({ skill: "workflow-plan", args: `${taskDescription}\n\n${contextLines}` }) + ``` + If Skill invocation is omitted, the workflow is BROKEN. + 4. After Skill invocation, brainstorm-with-file is complete + + **"创建Issue"** → Convert top ideas to issues: + 1. For each idea in synthesis.top_ideas (top 3): + - Build issue JSON: `{title: idea.title, context: idea.description + '\n' + idea.next_steps.join('\n'), priority: idea.score >= 8 ? 2 : 3, source: 'brainstorm', labels: dimensions}` + - Create via: `Skill({ skill: "issue:from-brainstorm", args: "${sessionFolder}/synthesis.json" })` + 2. Display created issue IDs + + **"深入分析"** → Launch analysis on top idea: + 1. Build analysis topic from top idea title + description + 2. **Invoke Skill tool immediately**: + ```javascript + Skill({ skill: "workflow:analyze-with-file", args: `${topIdea.title}: ${topIdea.description}` }) + ``` + + **"完成"** → No further action needed. + + **TodoWrite**: Update `next-step` → `"completed"` after user selection is handled ## Configuration diff --git a/.claude/skills/team-arch-opt/SKILL.md b/.claude/skills/team-arch-opt/SKILL.md index bf3f7ea0..ba91a44e 100644 --- a/.claude/skills/team-arch-opt/SKILL.md +++ b/.claude/skills/team-arch-opt/SKILL.md @@ -1,476 +1,144 @@ --- name: team-arch-opt -description: Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team arch-opt". +description: Unified team skill for architecture optimization. Uses team-worker agent architecture with role directories for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team arch-opt". allowed-tools: Agent, TaskCreate, TaskList, TaskGet, TaskUpdate, TeamCreate, TeamDelete, SendMessage, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context --- # Team Architecture Optimization -Unified team skill: Analyze codebase architecture, identify structural issues (dependency cycles, coupling/cohesion, layering violations, God Classes, dead code), design refactoring strategies, implement changes, validate improvements, and review code quality. Built on **team-worker agent architecture** -- all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. +Orchestrate multi-agent architecture optimization: analyze codebase → design refactoring plan → implement changes → validate improvements → review code quality. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-arch-opt") | -| args="" | -+-------------------+-------------------------------+ +Skill(skill="team-arch-opt", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+-------+ - v v v v v - [tw] [tw] [tw] [tw] [tw] -analyzer desig- refact- valid- review- - ner orer ator er - - CLI Tools (callable by workers inline): - [explore] [discuss] - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role + | | + Coordinator Worker + roles/coordinator/role.md roles//role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+-------+ + v v v v v + [analyzer][designer][refactorer][validator][reviewer] ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| analyzer | [roles/analyzer/role.md](roles/analyzer/role.md) | ANALYZE-* | false | +| designer | [roles/designer/role.md](roles/designer/role.md) | DESIGN-* | false | +| refactorer | [roles/refactorer/role.md](roles/refactorer/role.md) | REFACTOR-*, FIX-* | true | +| validator | [roles/validator/role.md](roles/validator/role.md) | VALIDATE-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REVIEW-*, QUALITY-* | false | + ## Role Router -This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. +Parse `$ARGUMENTS`: +- Has `--role ` → Read `roles//role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -### Input Parsing +## Shared Constants -Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. +- **Session prefix**: `TAO` +- **Session path**: `.workflow/.team/TAO--/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=, ...)` -### Role Registry +## Worker Spawn Template -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| analyzer | [role-specs/analyzer.md](role-specs/analyzer.md) | ANALYZE-* | orchestration | false | -| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | orchestration | false | -| refactorer | [role-specs/refactorer.md](role-specs/refactorer.md) | REFACTOR-* / FIX-* | code_generation | true | -| validator | [role-specs/validator.md](role-specs/validator.md) | VALIDATE-* | validation | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* / QUALITY-* | read_only_analysis | false | - -### CLI Tool Registry - -| Tool | Spec | Used By | Purpose | -|------|------|---------|---------| -| explore | [cli-tools/explore.md](cli-tools/explore.md) | analyzer, refactorer | Shared codebase exploration for architecture-critical structures and dependency graphs | -| discuss | [cli-tools/discuss.md](cli-tools/discuss.md) | designer, reviewer | Multi-perspective discussion for refactoring approaches and review findings | - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User just provides task description. - -**Invocation**: -```bash -Skill(skill="team-arch-opt", args="") # auto mode -Skill(skill="team-arch-opt", args="--parallel-mode=fan-out ") # force fan-out -Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent -Skill(skill="team-arch-opt", args="--max-branches=3 ") # limit branches -``` - -**Parallel Modes**: - -| Mode | Description | When to Use | -|------|-------------|------------| -| `auto` (default) | count <= 2 -> single, count >= 3 -> fan-out | General refactoring requests | -| `single` | Linear pipeline, no branching | Simple or tightly coupled refactorings | -| `fan-out` | Shared ANALYZE+DESIGN, then N parallel REFACTOR->VALIDATE+REVIEW branches | Multiple independent architecture issues | -| `independent` | M fully independent pipelines from analysis to review | Separate refactoring targets | - -**Lifecycle**: -``` -User provides task description + optional --parallel-mode / --max-branches - -> coordinator Phase 1-3: Parse flags -> TeamCreate -> Create task chain (mode-aware) - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances - -> [auto/fan-out] CP-2.5: Design complete -> create N branch tasks -> spawn all REFACTOR-B* in parallel - -> [independent] All pipelines run in parallel from the start - -> Per-branch/pipeline fix cycles run independently - -> All branches/pipelines complete -> AGGREGATE -> Phase 5 report + completion action -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph (branch-grouped), no advancement | -| `resume` / `continue` | Check worker states, advance next step | -| `revise [feedback]` | Create revision task + cascade downstream (scoped to branch) | -| `feedback ` | Analyze feedback impact, create targeted revision chain | -| `recheck` | Re-run quality check | -| `improve [dimension]` | Auto-improve weakest dimension | - ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ subagent_type: "team-worker", description: "Spawn worker", - team_name: , + team_name: "arch-opt", name: "", run_in_background: true, prompt: `## Role Assignment role: -role_spec: .claude/skills/team-arch-opt/role-specs/.md +role_spec: .claude/skills/team-arch-opt/roles//role.md session: session_id: -team_name: +team_name: arch-opt requirement: inner_loop: Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (refactorer): Set `inner_loop: true`. The team-worker agent handles the loop internally. - +**Inner Loop roles** (refactorer): Set `inner_loop: true`. **Single-task roles** (analyzer, designer, validator, reviewer): Set `inner_loop: false`. ---- +## User Commands -## Pipeline Definitions - -### Pipeline Diagrams - -**Single Mode** (linear, backward compatible): -``` -Pipeline: Single (Linear with Review-Fix Cycle) -===================================================================== -Stage 1 Stage 2 Stage 3 Stage 4 -ANALYZE-001 --> DESIGN-001 --> REFACTOR-001 --> VALIDATE-001 -[analyzer] [designer] [refactorer] [validator] - ^ | - +<--FIX-001---->+ - | REVIEW-001 - +<--------> [reviewer] - (max 3 iterations) | - COMPLETE -===================================================================== -``` - -**Fan-out Mode** (shared stages 1-2, parallel branches 3-4): -``` -Pipeline: Fan-out (N parallel refactoring branches) -===================================================================== -Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch) - (branch creation) -ANALYZE-001 --> DESIGN-001 --+-> REFACTOR-B01 --> VALIDATE-B01 + REVIEW-B01 (fix cycle) -[analyzer] [designer] | [refactorer] [validator] [reviewer] - +-> REFACTOR-B02 --> VALIDATE-B02 + REVIEW-B02 (fix cycle) - | [refactorer] [validator] [reviewer] - +-> REFACTOR-B0N --> VALIDATE-B0N + REVIEW-B0N (fix cycle) - | - AGGREGATE -> Phase 5 -===================================================================== -``` - -**Independent Mode** (M fully independent pipelines): -``` -Pipeline: Independent (M complete pipelines) -===================================================================== -Pipeline A: ANALYZE-A01 --> DESIGN-A01 --> REFACTOR-A01 --> VALIDATE-A01 + REVIEW-A01 -Pipeline B: ANALYZE-B01 --> DESIGN-B01 --> REFACTOR-B01 --> VALIDATE-B01 + REVIEW-B01 -Pipeline C: ANALYZE-C01 --> DESIGN-C01 --> REFACTOR-C01 --> VALIDATE-C01 + REVIEW-C01 - | - AGGREGATE -> Phase 5 -===================================================================== -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker A] Phase 1-5 - | (parallel OK) --+--> [team-worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker B directly - | --> log fast_advance to message bus (coordinator syncs on next wake) - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -``` -Beat View: Architecture Optimization Pipeline -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - new task --> +- Phase 1-3: clarify -+ - | TeamCreate | - | create ANALYZE-001 | - +- Phase 4: spawn ------+--> [analyzer] Phase 1-5 - +- STOP (idle) ---------+ | - | - callback <----------------------------------------------+ - (analyzer done) --> +- handleCallback ------+ analyze_complete - | mark ANALYZE done | - | spawn designer ------+--> [designer] Phase 1-5 - +- STOP ----------------+ | - | - callback <----------------------------------------------+ - (designer done) --> +- handleCallback ------+ design_complete - | mark DESIGN done | - | spawn refactorer ----+--> [refactorer] Phase 1-5 - +- STOP ----------------+ | - | - callback <----------------------------------------------+ - (refactorer done)--> +- handleCallback ------+ refactor_complete - | mark REFACTOR done | - | spawn valid+reviewer-+--> [validator] Phase 1-5 - | (parallel) -------+--> [reviewer] Phase 1-5 - +- STOP ----------------+ | | - | | - callback x2 <--------------------------------------+-----------+ - --> +- handleCallback ------+ - | both done? | - | YES + pass -> Phase 5| - | NO / fail -> FIX task| - | spawn refactorer ----+--> [refactorer] FIX-001 - +- STOP or Phase 5 -----+ -====================================================================== -``` - -**Checkpoints**: - -| Checkpoint | Trigger | Location | Behavior | -|------------|---------|----------|----------| -| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope | -| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities | -| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks from refactoring plan, spawn all REFACTOR-B* in parallel | -| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) | -| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action | - -### Task Metadata Registry - -**Single mode** (backward compatible): - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues | -| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report | -| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings | -| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility | -| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness | -| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation | - -**Fan-out mode** (branch tasks created at CP-2.5): - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture | -| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs | -| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only | -| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} | -| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} | -| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} | -| VALIDATE-B{NN}-R{cycle} | validator | Retry (branch) | FIX-B{NN}-{cycle} | Re-validate after fix | -| REVIEW-B{NN}-R{cycle} | reviewer | Retry (branch) | FIX-B{NN}-{cycle} | Re-review after fix | - -**Independent mode**: - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target | -| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} | -| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings | -| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} | -| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} | -| FIX-{P}01-{cycle} | refactorer | Fix | (none) | Fix issues in pipeline {P} | - -### Task Naming Rules - -| Mode | Stage 3 | Stage 4 | Fix | Retry | -|------|---------|---------|-----|-------| -| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 | -| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 | -| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 | - ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-arch-opt", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph (branch-grouped), no advancement | +| `resume` / `continue` | Check worker states, advance next step | +| `revise [feedback]` | Revise specific task + cascade downstream | +| `feedback ` | Analyze feedback impact, create targeted revision chain | +| `recheck` | Re-run quality check | +| `improve [dimension]` | Auto-improve weakest dimension | ## Session Directory -**Single mode**: ``` -.workflow// -+-- session.json # Session metadata + status + parallel_mode -+-- artifacts/ -| +-- architecture-baseline.json # Analyzer: pre-refactoring metrics -| +-- architecture-report.md # Analyzer: ranked structural issue findings -| +-- refactoring-plan.md # Designer: prioritized refactoring plan -| +-- validation-results.json # Validator: post-refactoring validation -| +-- review-report.md # Reviewer: code review findings -+-- explorations/ -| +-- cache-index.json # Shared explore cache -| +-- .md # Cached exploration results -+-- wisdom/ -| +-- patterns.md # Discovered patterns and conventions -+-- .msg/ -| +-- messages.jsonl # Message bus log -| +-- meta.json # Session state + cross-role state -+-- discussions/ -| +-- DISCUSS-REFACTOR.md # Refactoring design discussion record -| +-- DISCUSS-REVIEW.md # Review discussion record +.workflow/.team/TAO--/ +├── session.json # Session metadata + status + parallel_mode +├── task-analysis.json # Coordinator analyze output +├── artifacts/ +│ ├── architecture-baseline.json # Analyzer: pre-refactoring metrics +│ ├── architecture-report.md # Analyzer: ranked structural issue findings +│ ├── refactoring-plan.md # Designer: prioritized refactoring plan +│ ├── validation-results.json # Validator: post-refactoring validation +│ ├── review-report.md # Reviewer: code review findings +│ ├── aggregate-results.json # Fan-out/independent: aggregated results +│ ├── branches/ # Fan-out mode branch artifacts +│ │ └── B{NN}/ +│ │ ├── refactoring-detail.md +│ │ ├── validation-results.json +│ │ └── review-report.md +│ └── pipelines/ # Independent mode pipeline artifacts +│ └── {P}/ +│ └── ... +├── explorations/ +│ ├── cache-index.json # Shared explore cache +│ └── .md +├── wisdom/ +│ └── patterns.md # Discovered patterns and conventions +├── discussions/ +│ ├── DISCUSS-REFACTOR.md +│ └── DISCUSS-REVIEW.md +└── .msg/ + ├── messages.jsonl # Message bus log + └── meta.json # Session state + cross-role state ``` -**Fan-out mode** (adds branches/ directory): -``` -.workflow// -+-- session.json # + parallel_mode, branches, fix_cycles -+-- artifacts/ -| +-- architecture-baseline.json # Shared baseline (all branches use this) -| +-- architecture-report.md # Shared architecture report -| +-- refactoring-plan.md # Shared plan with discrete REFACTOR-IDs -| +-- aggregate-results.json # Aggregated results from all branches -| +-- branches/ -| +-- B01/ -| | +-- refactoring-detail.md # Extracted REFACTOR-001 detail -| | +-- validation-results.json # Branch B01 validation -| | +-- review-report.md # Branch B01 review -| +-- B02/ -| | +-- refactoring-detail.md -| | +-- validation-results.json -| | +-- review-report.md -| +-- B0N/ -+-- explorations/ wisdom/ discussions/ # Same as single -``` +## Specs Reference -**Independent mode** (adds pipelines/ directory): -``` -.workflow// -+-- session.json # + parallel_mode, independent_targets, fix_cycles -+-- artifacts/ -| +-- aggregate-results.json # Aggregated results from all pipelines -| +-- pipelines/ -| +-- A/ -| | +-- architecture-baseline.json -| | +-- architecture-report.md -| | +-- refactoring-plan.md -| | +-- validation-results.json -| | +-- review-report.md -| +-- B/ -| +-- architecture-baseline.json -| +-- ... -+-- explorations/ wisdom/ discussions/ # Same as single -``` - -## Session Resume - -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan session directory for sessions with status "active" or "paused" -2. Multiple matches -> AskUserQuestion for selection -3. Audit TaskList -> reconcile session state <-> task status -4. Reset in_progress -> pending (interrupted tasks) -5. Rebuild team and spawn needed workers only -6. Create missing tasks with correct blockedBy -7. Kick first executable task -> Phase 4 coordination loop - -## Shared Resources - -| Resource | Path | Usage | -|----------|------|-------| -| Architecture Baseline | [/artifacts/architecture-baseline.json](/artifacts/architecture-baseline.json) | Pre-refactoring metrics for comparison | -| Architecture Report | [/artifacts/architecture-report.md](/artifacts/architecture-report.md) | Analyzer output consumed by designer | -| Refactoring Plan | [/artifacts/refactoring-plan.md](/artifacts/refactoring-plan.md) | Designer output consumed by refactorer | -| Validation Results | [/artifacts/validation-results.json](/artifacts/validation-results.json) | Validator output consumed by reviewer | +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions, task registry, parallel modes ## Error Handling | Scenario | Resolution | |----------|------------| -| Role spec file not found | Error with expected path (role-specs/.md) | -| Command file not found | Fallback to inline execution in coordinator role.md | -| CLI tool spec not found | Error with expected path (cli-tools/.md) | -| Fast-advance orphan detected | Coordinator resets task to pending on next check | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| CLI tool fails | Worker fallback to direct implementation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | | consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline | -| team-worker agent unavailable | Error: requires .claude/agents/team-worker.md | -| Completion action timeout | Default to Keep Active | -| Analysis tool not available | Fallback to static analysis methods | -| Validation regression detected | Auto-create FIX task with regression details (scoped to branch/pipeline) | -| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues (per-branch/pipeline scope) | -| One branch REFACTOR fails | Mark that branch failed, other branches continue to completion | -| Branch scope overlap detected | Designer constrains non-overlapping target files; REFACTOR logs warning on detection | -| Meta.json concurrent writes | Each worker writes only its own namespace key (e.g., `refactorer.B01`) | -| Branch fix cycle >= 3 | Escalate only that branch to user, other branches continue independently | -| max_branches exceeded | Coordinator truncates to top N refactorings by priority at CP-2.5 | -| Independent pipeline partial failure | Failed pipeline marked, others continue; aggregate reports partial results | +| Branch fix cycle >= 3 | Escalate only that branch to user, others continue | +| max_branches exceeded | Coordinator truncates to top N at CP-2.5 | diff --git a/.claude/skills/team-arch-opt/roles/analyzer/role.md b/.claude/skills/team-arch-opt/roles/analyzer/role.md new file mode 100644 index 00000000..0c59dee2 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/analyzer/role.md @@ -0,0 +1,78 @@ +--- +role: analyzer +prefix: ANALYZE +inner_loop: false +message_types: [state_update] +--- + +# Architecture Analyzer + +Analyze codebase architecture to identify structural issues: dependency cycles, coupling/cohesion problems, layering violations, God Classes, code duplication, dead code, and API surface bloat. Produce quantified baseline metrics and a ranked architecture report. + +## Phase 2: Context & Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | /wisdom/.msg/meta.json | No | + +1. Extract session path and target scope from task description +2. Detect project type by scanning for framework markers: + +| Signal File | Project Type | Analysis Focus | +|-------------|-------------|----------------| +| package.json + React/Vue/Angular | Frontend | Component tree, prop drilling, state management, barrel exports | +| package.json + Express/Fastify/NestJS | Backend Node | Service layer boundaries, middleware chains, DB access patterns | +| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | Module boundaries, trait/interface usage, dependency injection | +| Mixed framework markers | Full-stack / Monorepo | Cross-package dependencies, shared types, API contracts | +| CLI entry / bin/ directory | CLI Tool | Command structure, plugin architecture, configuration layering | +| No detection | Generic | All architecture dimensions | + +3. Use `explore` CLI tool to map module structure, dependency graph, and layer boundaries within target scope +4. Detect available analysis tools (linters, dependency analyzers, build tools) + +## Phase 3: Architecture Analysis + +Execute analysis based on detected project type: + +**Dependency analysis**: +- Build import/require graph across modules +- Detect circular dependencies (direct and transitive cycles) +- Identify layering violations (e.g., UI importing from data layer, utils importing from domain) +- Calculate fan-in/fan-out per module (high fan-out = fragile hub, high fan-in = tightly coupled) + +**Structural analysis**: +- Identify God Classes / God Modules (> 500 LOC, > 10 public methods, too many responsibilities) +- Calculate coupling metrics (afferent/efferent coupling per module) +- Calculate cohesion metrics (LCOM -- Lack of Cohesion of Methods) +- Detect code duplication (repeated logic blocks, copy-paste patterns) +- Identify missing abstractions (repeated conditionals, switch-on-type patterns) + +**API surface analysis**: +- Count exported symbols per module (export bloat detection) +- Identify dead exports (exported but never imported elsewhere) +- Detect dead code (unreachable functions, unused variables, orphan files) +- Check for pattern inconsistencies (mixed naming conventions, inconsistent error handling) + +**All project types**: +- Collect quantified architecture baseline metrics (dependency count, cycle count, coupling scores, LOC distribution) +- Rank top 3-7 architecture issues by severity (Critical / High / Medium) +- Record evidence: file paths, line numbers, measured values + +## Phase 4: Report Generation + +1. Write architecture baseline to `/artifacts/architecture-baseline.json`: + - Module count, dependency count, cycle count, average coupling, average cohesion + - God Class candidates with LOC and method count + - Dead code file count, dead export count + - Timestamp and project type details + +2. Write architecture report to `/artifacts/architecture-report.md`: + - Ranked list of architecture issues with severity, location (file:line or module), measured impact + - Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT + - Evidence summary per issue + - Detected project type and analysis methods used + +3. Update `/wisdom/.msg/meta.json` under `analyzer` namespace: + - Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back diff --git a/.claude/skills/team-arch-opt/roles/coordinator/commands/analyze.md b/.claude/skills/team-arch-opt/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..f4f53552 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/analyze.md @@ -0,0 +1,57 @@ +# Analyze Task + +Parse user task -> detect architecture capabilities -> build dependency graph -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| analyze, scan, audit, map, identify | analyzer | ANALYZE | +| design, plan, strategy, refactoring-plan | designer | DESIGN | +| refactor, implement, fix, apply | refactorer | REFACTOR | +| validate, build, test, verify, compile | validator | VALIDATE | +| review, audit-code, quality, check-code | reviewer | REVIEW | + +## Dependency Graph + +Natural ordering tiers: +- Tier 0: analyzer (knowledge gathering -- no dependencies) +- Tier 1: designer (requires analyzer output) +- Tier 2: refactorer (requires designer output) +- Tier 3: validator, reviewer (validation requires refactored artifacts, can run in parallel) + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per capability | +1 | +| Cross-domain refactoring | +2 | +| Parallel branches requested | +1 per branch | +| Serial depth > 3 | +1 | +| Multiple targets (independent mode) | +2 | + +Results: 1-3 Low, 4-6 Medium, 7+ High + +## Role Minimization + +- Cap at 5 roles +- Merge overlapping capabilities +- Absorb trivial single-step roles + +## Output + +Write /task-analysis.json: +```json +{ + "task_description": "", + "pipeline_type": "", + "capabilities": [{ "name": "", "prefix": "", "keywords": ["..."] }], + "dependency_graph": { "": { "role": "", "blockedBy": ["..."], "priority": "P0|P1|P2" } }, + "roles": [{ "name": "", "prefix": "", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "parallel_mode": "", + "max_branches": 5 +} +``` diff --git a/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md b/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md index 37239192..b38487aa 100644 --- a/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md @@ -1,27 +1,33 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, and completion. Supports single, fan-out, and independent parallel modes with per-branch/pipeline tracking. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. -## Phase 2: Context Loading +## Constants -| Input | Source | Required | -|-------|--------|----------| -| Session state | /session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Pipeline definition | From SKILL.md | Yes | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker -1. Load session.json for current state, `parallel_mode`, `branches`, `fix_cycles` -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## Handler Router -## Phase 3: Event Handlers +| Source | Handler | +|--------|---------| +| Message contains [analyzer], [designer], [refactorer], [validator], [reviewer] | handleCallback | +| Message contains branch tag [refactorer-B01], etc. | handleCallback (branch-aware) | +| Message contains pipeline tag [analyzer-A], etc. | handleCallback (pipeline-aware) | +| "consensus_blocked" | handleConsensus | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -### handleCallback +## handleCallback -Triggered when a worker sends completion message. +Worker completed. Process and advance. -1. Parse message to identify role, task ID, and **branch/pipeline label**: +1. Parse message to identify role, task ID, and branch/pipeline label: | Message Pattern | Branch Detection | |----------------|-----------------| @@ -29,238 +35,126 @@ Triggered when a worker sends completion message. | `[analyzer-A]` or task ID `ANALYZE-A01` | Pipeline `A` (independent) | | `[analyzer]` or task ID `ANALYZE-001` | No branch (single) | -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "", status: "completed" }) -``` - +2. Mark task as completed: `TaskUpdate({ taskId: "", status: "completed" })` 3. Record completion in session state - 4. **CP-2.5 check** (auto/fan-out mode only): - - If completed task is DESIGN-001 AND `parallel_mode` is `auto` or `fan-out`: - - Execute **CP-2.5 Branch Creation** subroutine from dispatch.md + - If completed task is DESIGN-001 AND parallel_mode is `auto` or `fan-out`: + - Execute CP-2.5 Branch Creation from dispatch.md - After branch creation, proceed to handleSpawnNext (spawns all REFACTOR-B* in parallel) - STOP after spawning - -5. Check if checkpoint feedback is configured for this stage: +5. Check stage checkpoints: | Completed Task | Checkpoint | Action | |---------------|------------|--------| -| ANALYZE-001 / ANALYZE-{P}01 | CP-1 | Notify user: architecture report ready for review | -| DESIGN-001 / DESIGN-{P}01 | CP-2 | Notify user: refactoring plan ready for review | -| DESIGN-001 (auto/fan-out) | CP-2.5 | Execute branch creation, then notify user with branch count | -| VALIDATE-* or REVIEW-* | CP-3 | Check verdicts per branch (see Review-Fix Cycle below) | +| ANALYZE-001 / ANALYZE-{P}01 | CP-1 | Notify user: architecture report ready | +| DESIGN-001 / DESIGN-{P}01 | CP-2 | Notify user: refactoring plan ready | +| DESIGN-001 (auto/fan-out) | CP-2.5 | Execute branch creation, notify with branch count | +| VALIDATE-* or REVIEW-* | CP-3 | Check verdicts per branch (see Review-Fix Cycle) | 6. Proceed to handleSpawnNext -### handleSpawnNext +## handleCheck -Find and spawn the next ready tasks. - -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" - -2. For each ready task, spawn team-worker: +Read-only status report, then STOP. +Output (single mode): ``` -Agent({ - subagent_type: "team-worker", - description: "Spawn worker for ", - team_name: "arch-opt", - name: "", - run_in_background: true, - prompt: `## Role Assignment -role: -role_spec: .claude/skills/team-arch-opt/role-specs/.md -session: -session_id: -team_name: arch-opt -requirement: -inner_loop: - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) +[coordinator] Pipeline Status +[coordinator] Progress: / (%) +[coordinator] Active: +[coordinator] Ready: +[coordinator] Commands: 'resume' to advance | 'check' to refresh ``` -3. **Parallel spawn rules by mode**: +Fan-out mode adds per-branch grouping. Independent mode adds per-pipeline grouping. + +## handleResume + +1. Audit task list: Tasks stuck in "in_progress" -> reset to "pending" +2. For fan-out/independent: check each branch/pipeline independently +3. Proceed to handleSpawnNext + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect: completedSubjects, inProgressSubjects, readySubjects +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Check if inner loop role with active worker -> skip (worker picks up) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker (see SKILL.md Spawn Template): + ``` + Agent({ + subagent_type: "team-worker", + description: "Spawn worker for ", + team_name: "arch-opt", + name: "", + run_in_background: true, + prompt: `## Role Assignment + role: + role_spec: .claude/skills/team-arch-opt/roles//role.md + session: + session_id: + team_name: arch-opt + requirement: + inner_loop: + + Read role_spec file to load Phase 2-4 domain instructions. + Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` + }) + ``` + e. Add to active_workers +5. Parallel spawn rules by mode: | Mode | Scenario | Spawn Behavior | |------|----------|---------------| | Single | Stage 4 ready | Spawn VALIDATE-001 + REVIEW-001 in parallel | | Fan-out (CP-2.5 done) | All REFACTOR-B* unblocked | Spawn ALL REFACTOR-B* in parallel | -| Fan-out (REFACTOR-B{NN} done) | VALIDATE-B{NN} + REVIEW-B{NN} ready | Spawn both for that branch in parallel | +| Fan-out (REFACTOR-B{NN} done) | VALIDATE + REVIEW ready | Spawn both for that branch in parallel | | Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel | -4. STOP after spawning -- wait for next callback +6. Update session, output summary, STOP -### Review-Fix Cycle (CP-3) +## Review-Fix Cycle (CP-3) **Per-branch/pipeline scoping**: Each branch/pipeline has its own independent fix cycle. -#### Single Mode (unchanged) +When both VALIDATE-* and REVIEW-* are completed for a branch/pipeline: -When both VALIDATE-001 and REVIEW-001 are completed: - -1. Read validation verdict from .msg/meta.json (validator namespace) -2. Read review verdict from .msg/meta.json (reviewer namespace) +1. Read validation verdict from scoped meta.json namespace +2. Read review verdict from scoped meta.json namespace | Validate Verdict | Review Verdict | Action | |-----------------|----------------|--------| -| PASS | APPROVE | -> handleComplete | +| PASS | APPROVE | -> handleComplete check | | PASS | REVISE | Create FIX task with review feedback | | FAIL | APPROVE | Create FIX task with validation feedback | | FAIL | REVISE/REJECT | Create FIX task with combined feedback | | Any | REJECT | Create FIX task + flag for designer re-evaluation | -#### Fan-out Mode (per-branch) +Fix cycle tracking per branch in session.json `fix_cycles`: +- < 3: Create FIX task, increment cycle count +- >= 3: Escalate THIS branch to user. Other branches continue -When both VALIDATE-B{NN} and REVIEW-B{NN} are completed for a specific branch: +## handleComplete -1. Read validation verdict from `validator.B{NN}` namespace -2. Read review verdict from `reviewer.B{NN}` namespace -3. Apply same verdict matrix as single mode, but scoped to this branch only -4. **Other branches are unaffected** -- they continue independently +Pipeline done. Generate report and completion action. -#### Independent Mode (per-pipeline) +Completion check by mode: +| Mode | Completion Condition | +|------|---------------------| +| Single | All 5 tasks (+ any FIX/retry tasks) completed | +| Fan-out | ALL branches have VALIDATE + REVIEW completed (or escalated), shared stages done | +| Independent | ALL pipelines have VALIDATE + REVIEW completed (or escalated) | -When both VALIDATE-{P}01 and REVIEW-{P}01 are completed for a specific pipeline: +1. For fan-out/independent: aggregate per-branch/pipeline results to `/artifacts/aggregate-results.json` +2. If any tasks not completed, return to handleSpawnNext +3. If all completed -> transition to coordinator Phase 5 -1. Read verdicts from `validator.{P}` and `reviewer.{P}` namespaces -2. Apply same verdict matrix, scoped to this pipeline only - -#### Fix Cycle Count Tracking - -Fix cycles are tracked per branch/pipeline in `session.json`: - -```json -// Single mode -{ "fix_cycles": { "main": 0 } } - -// Fan-out mode -{ "fix_cycles": { "B01": 0, "B02": 1, "B03": 0 } } - -// Independent mode -{ "fix_cycles": { "A": 0, "B": 2 } } -``` - -| Cycle Count | Action | -|-------------|--------| -| < 3 | Create FIX task, increment cycle count for this branch/pipeline | -| >= 3 | Escalate THIS branch/pipeline to user. Other branches continue | - -#### FIX Task Creation (branched) - -**Fan-out mode**: -``` -TaskCreate({ - subject: "FIX-B{NN}-{cycle}", - description: "PURPOSE: Fix issues in branch B{NN} from review/validation | Success: All flagged issues resolved -TASK: - - Address review findings: - - Fix validation failures: - - Re-validate after fixes -CONTEXT: - - Session: - - Branch: B{NN} - - Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/validation-results.json - - Shared memory: /wisdom/.msg/meta.json (namespace: refactorer.B{NN}) -EXPECTED: Fixed source files for B{NN} only -CONSTRAINTS: Targeted fixes only | Do not touch other branches ---- -InnerLoop: false -BranchId: B{NN}" -}) -TaskUpdate({ taskId: "FIX-B{NN}-{cycle}", owner: "refactorer" }) -``` - -Create new VALIDATE and REVIEW with retry suffix: -- `VALIDATE-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}` -- `REVIEW-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}` - -**Independent mode**: -``` -TaskCreate({ - subject: "FIX-{P}01-{cycle}", - ...same pattern with pipeline prefix... -}) -TaskUpdate({ taskId: "FIX-{P}01-{cycle}", owner: "refactorer" }) -``` - -Create `VALIDATE-{P}01-R{cycle}` and `REVIEW-{P}01-R{cycle}`. - -### handleCheck - -Output current pipeline status grouped by branch/pipeline. - -**Single mode** (unchanged): -``` -Pipeline Status: - [DONE] ANALYZE-001 (analyzer) -> architecture-report.md - [DONE] DESIGN-001 (designer) -> refactoring-plan.md - [RUN] REFACTOR-001 (refactorer) -> refactoring... - [WAIT] VALIDATE-001 (validator) -> blocked by REFACTOR-001 - [WAIT] REVIEW-001 (reviewer) -> blocked by REFACTOR-001 - -Fix Cycles: 0/3 -Session: -``` - -**Fan-out mode**: -``` -Pipeline Status (fan-out, 3 branches): - Shared Stages: - [DONE] ANALYZE-001 (analyzer) -> architecture-report.md - [DONE] DESIGN-001 (designer) -> refactoring-plan.md (4 REFACTOR-IDs) - - Branch B01 (REFACTOR-001: ): - [RUN] REFACTOR-B01 (refactorer) -> refactoring... - [WAIT] VALIDATE-B01 (validator) -> blocked by REFACTOR-B01 - [WAIT] REVIEW-B01 (reviewer) -> blocked by REFACTOR-B01 - Fix Cycles: 0/3 - - Branch B02 (REFACTOR-002: <title>): - [DONE] REFACTOR-B02 (refactorer) -> done - [RUN] VALIDATE-B02 (validator) -> validating... - [RUN] REVIEW-B02 (reviewer) -> reviewing... - Fix Cycles: 0/3 - - Branch B03 (REFACTOR-003: <title>): - [FAIL] REFACTOR-B03 (refactorer) -> failed - Fix Cycles: 0/3 [BRANCH FAILED] - -Session: <session-id> -``` - -**Independent mode**: -``` -Pipeline Status (independent, 2 pipelines): - Pipeline A (target: refactor auth module): - [DONE] ANALYZE-A01 -> [DONE] DESIGN-A01 -> [RUN] REFACTOR-A01 -> ... - Fix Cycles: 0/3 - - Pipeline B (target: refactor API layer): - [DONE] ANALYZE-B01 -> [DONE] DESIGN-B01 -> [DONE] REFACTOR-B01 -> ... - Fix Cycles: 1/3 - -Session: <session-id> -``` - -Output status -- do NOT advance pipeline. - -### handleResume - -Resume pipeline after user pause or interruption. - -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. For fan-out/independent: check each branch/pipeline independently -3. Proceed to handleSpawnNext - -### handleConsensus +## handleConsensus Handle consensus_blocked signals from discuss rounds. @@ -270,61 +164,19 @@ Handle consensus_blocked signals from discuss rounds. | MEDIUM | Create revision task for the blocked role (scoped to branch if applicable) | | LOW | Log finding, continue pipeline | -### handleComplete +## handleAdapt -Triggered when all pipeline tasks are completed and no fix cycles remain. +Capability gap reported mid-pipeline. -**Completion check varies by mode**: +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause -| Mode | Completion Condition | -|------|---------------------| -| Single | All 5 tasks (+ any FIX/retry tasks) have status "completed" | -| Fan-out | ALL branches have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated), shared stages done | -| Independent | ALL pipelines have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated) | +## Fast-Advance Reconciliation -**Aggregate results** before transitioning to Phase 5: - -1. For fan-out mode: collect per-branch validation results into `<session>/artifacts/aggregate-results.json`: - ```json - { - "branches": { - "B01": { "refactor_id": "REFACTOR-001", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." }, - "B02": { "refactor_id": "REFACTOR-002", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." }, - "B03": { "status": "failed", "reason": "REFACTOR failed" } - }, - "overall": { "total_branches": 3, "passed": 2, "failed": 1 } - } - ``` - -2. For independent mode: collect per-pipeline results similarly - -3. If any tasks not completed, return to handleSpawnNext -4. If all completed (allowing for failed branches marked as such), transition to coordinator Phase 5 - -### handleRevise - -Triggered by user "revise <TASK-ID> [feedback]" command. - -1. Parse target task ID and optional feedback -2. Detect branch/pipeline from task ID pattern -3. Create revision task with same role but updated requirements, scoped to branch -4. Set blockedBy to empty (immediate execution) -5. Cascade: create new downstream tasks within same branch only -6. Proceed to handleSpawnNext - -### handleFeedback - -Triggered by user "feedback <text>" command. - -1. Analyze feedback text to determine impact scope -2. Identify which pipeline stage, role, and branch/pipeline should handle the feedback -3. Create targeted revision task (scoped to branch if applicable) -4. Proceed to handleSpawnNext - -## Phase 4: State Persistence - -After every handler execution: - -1. Update session.json with current state (active tasks, fix cycle counts per branch, last event, resolved parallel_mode) -2. Verify task list consistency -3. STOP and wait for next event +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-arch-opt/roles/coordinator/role.md b/.claude/skills/team-arch-opt/roles/coordinator/role.md index 5772a8c3..3c6a3766 100644 --- a/.claude/skills/team-arch-opt/roles/coordinator/role.md +++ b/.claude/skills/team-arch-opt/roles/coordinator/role.md @@ -1,15 +1,14 @@ -# Coordinator - Architecture Optimization Team +# Coordinator -**Role**: coordinator -**Type**: Orchestrator -**Team**: arch-opt +Orchestrate team-arch-opt: analyze -> dispatch -> spawn -> monitor -> report. -Orchestrates the architecture optimization pipeline: manages task chains, spawns team-worker agents, handles review-fix cycles, and drives the pipeline to completion. +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) @@ -18,113 +17,55 @@ Orchestrates the architecture optimization pipeline: manages task chains, spawns - Execute completion action in Phase 5 ### MUST NOT - - Implement domain logic (analyzing, refactoring, reviewing) -- workers handle this - Spawn workers without creating tasks first - Skip checkpoints when configured - Force-advance pipeline past failed review/validation - Modify source code directly -- delegate to refactorer worker ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [analyzer], [designer], [refactorer], [validator], [reviewer] | -> handleCallback | -| Branch callback | Message contains branch tag [refactorer-B01], [validator-B02], etc. | -> handleCallback (branch-aware) | -| Pipeline callback | Message contains pipeline tag [analyzer-A], [refactorer-B], etc. | -> handleCallback (pipeline-aware) | -| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [analyzer], [designer], [refactorer], [validator], [reviewer] | -> handleCallback (monitor.md) | +| Branch callback | Message contains [refactorer-B01], [validator-B02], etc. | -> handleCallback branch-aware (monitor.md) | +| Pipeline callback | Message contains [analyzer-A], [refactorer-B], etc. | -> handleCallback pipeline-aware (monitor.md) | +| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/TAO-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/ARCH-OPT-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and `parallel_mode` - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content (including branch variants like `[refactorer-B01]`) - - Check for "check", "status", "resume", "continue" keywords - - Check for "consensus_blocked" signal - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/consensus/adapt/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "arch-opt" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/TAO-*/session.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -1. Parse user task description from $ARGUMENTS -2. **Parse parallel mode flags**: +TEXT-LEVEL ONLY. No source code reading. + +1. Parse task description from $ARGUMENTS +2. Parse parallel mode flags: | Flag | Value | Default | |------|-------|---------| | `--parallel-mode` | `single`, `fan-out`, `independent`, `auto` | `auto` | -| `--max-branches` | integer 1-10 | 5 (from config) | - - - For `independent` mode: remaining positional arguments after flags are `independent_targets` array - - Example: `--parallel-mode=independent "refactor auth" "refactor API"` -> targets = ["refactor auth", "refactor API"] +| `--max-branches` | integer 1-10 | 5 | 3. Identify architecture optimization target: @@ -132,134 +73,43 @@ TeamCreate({ team_name: "arch-opt" }) |--------|--------| | Specific file/module mentioned | Scoped refactoring | | "coupling", "dependency", "structure", generic | Full architecture analysis | -| Specific issue mentioned (cycles, God Class, duplication) | Targeted issue resolution | +| Specific issue (cycles, God Class, duplication) | Targeted issue resolution | | Multiple quoted targets (independent mode) | Per-target scoped refactoring | -4. If target is unclear, ask for clarification: +4. If target is unclear, AskUserQuestion for scope clarification +5. Record requirement with scope, target issues, parallel_mode, max_branches -``` -AskUserQuestion({ - questions: [{ - question: "What should I analyze and refactor? Provide a target scope or describe the architecture issue.", - header: "Scope" - }] -}) -``` +## Phase 2: Create Team + Initialize Session -5. Record refactoring requirement with scope, target issues, parallel_mode, and max_branches +1. Generate session ID: `TAO-<slug>-<date>` +2. Create session folder structure +3. TeamCreate with team name `arch-opt` +4. Write session.json with parallel_mode, max_branches, branches, independent_targets, fix_cycles +5. Initialize meta.json via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { pipeline_mode: "<mode>", pipeline_stages: ["analyzer","designer","refactorer","validator","reviewer"], team_name: "arch-opt" } + }) + ``` +6. Write session.json ---- +## Phase 3: Create Task Chain -## Phase 2: Session & Team Setup +Delegate to commands/dispatch.md: +1. Read dependency graph and parallel mode from session.json +2. Topological sort tasks +3. Create tasks via TaskCreate with blockedBy +4. Update session.json with task count -1. Create session directory: +## Phase 4: Spawn-and-Stop -``` -Bash("mkdir -p .workflow/<session-id>/artifacts .workflow/<session-id>/explorations .workflow/<session-id>/wisdom .workflow/<session-id>/discussions") -``` - - For independent mode, also create pipeline subdirectories: -``` -// For each target in independent_targets -Bash("mkdir -p .workflow/<session-id>/artifacts/pipelines/A .workflow/<session-id>/artifacts/pipelines/B ...") -``` - -2. Write session.json with extended fields: - -```json -{ - "status": "active", - "team_name": "arch-opt", - "requirement": "<requirement>", - "timestamp": "<ISO-8601>", - "parallel_mode": "<auto|single|fan-out|independent>", - "max_branches": 5, - "branches": [], - "independent_targets": [], - "fix_cycles": {} -} -``` - - - `parallel_mode`: from Phase 1 parsing (default: "auto") - - `max_branches`: from Phase 1 parsing (default: 5) - - `branches`: populated at CP-2.5 for fan-out mode (e.g., ["B01", "B02", "B03"]) - - `independent_targets`: populated for independent mode (e.g., ["refactor auth", "refactor API"]) - - `fix_cycles`: populated per-branch/pipeline as fix cycles occur - -4. Initialize meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<parallel_mode>", - pipeline_stages: ["analyzer", "designer", "refactorer", "validator", "reviewer"], - roles: ["coordinator", "analyzer", "designer", "refactorer", "validator", "reviewer"], - team_name: "arch-opt" - } -}) -``` - -5. Create team: - -``` -TeamCreate({ team_name: "arch-opt" }) -``` - ---- - -## Phase 3: Task Chain Creation - -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies - ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn analyzer worker", - team_name: "arch-opt", - name: "analyzer", - run_in_background: true, - prompt: `## Role Assignment -role: analyzer -role_spec: .claude/skills/team-arch-opt/role-specs/analyzer.md -session: <session-folder> -session_id: <session-id> -team_name: arch-opt -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action @@ -275,29 +125,19 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger | Review Report | <session>/artifacts/review-report.md | 3. Include discussion summaries if discuss rounds were used -4. Output pipeline summary: task count, duration, improvement metrics from validation results +4. Output pipeline summary: task count, duration, improvement metrics -5. **Completion Action** (interactive): +5. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` +## Error Handling -6. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-arch-opt', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Dependency cycle | Detect in analysis, halt | +| Role limit exceeded | Merge overlapping roles | diff --git a/.claude/skills/team-arch-opt/roles/designer/role.md b/.claude/skills/team-arch-opt/roles/designer/role.md new file mode 100644 index 00000000..5a8f37f1 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/designer/role.md @@ -0,0 +1,115 @@ +--- +role: designer +prefix: DESIGN +inner_loop: false +message_types: [state_update] +--- + +# Refactoring Designer + +Analyze architecture reports and baseline metrics to design a prioritized refactoring plan with concrete strategies, expected structural improvements, and risk assessments. + +## Phase 2: Analysis Loading + +| Input | Source | Required | +|-------|--------|----------| +| Architecture report | <session>/artifacts/architecture-report.md | Yes | +| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Wisdom files | <session>/wisdom/patterns.md | No | + +1. Extract session path from task description +2. Read architecture report -- extract ranked issue list with severities and categories +3. Read architecture baseline -- extract current structural metrics +4. Load .msg/meta.json for analyzer findings (project_type, scope) +5. Assess overall refactoring complexity: + +| Issue Count | Severity Mix | Complexity | +|-------------|-------------|------------| +| 1-2 | All Medium | Low | +| 2-3 | Mix of High/Medium | Medium | +| 3+ or any Critical | Any Critical present | High | + +## Phase 3: Strategy Formulation + +For each architecture issue, select refactoring approach by type: + +| Issue Type | Strategies | Risk Level | +|------------|-----------|------------| +| Circular dependency | Interface extraction, dependency inversion, mediator pattern | High | +| God Class/Module | SRP decomposition, extract class/module, delegate pattern | High | +| Layering violation | Move to correct layer, introduce Facade, add anti-corruption layer | Medium | +| Code duplication | Extract shared utility/base class, template method pattern | Low | +| High coupling | Introduce interface/abstraction, dependency injection, event-driven | Medium | +| API bloat / dead exports | Privatize internals, re-export only public API, barrel file cleanup | Low | +| Dead code | Safe removal with reference verification | Low | +| Missing abstraction | Extract interface/type, introduce strategy/factory pattern | Medium | + +Prioritize refactorings by impact/effort ratio: + +| Priority | Criteria | +|----------|----------| +| P0 (Critical) | High impact + Low effort -- quick wins (dead code removal, simple moves) | +| P1 (High) | High impact + Medium effort (cycle breaking, layer fixes) | +| P2 (Medium) | Medium impact + Low effort (duplication extraction) | +| P3 (Low) | Low impact or High effort -- defer (large God Class decomposition) | + +If complexity is High, invoke `discuss` CLI tool (DISCUSS-REFACTOR round) to evaluate trade-offs between competing strategies before finalizing the plan. + +Define measurable success criteria per refactoring (target metric improvement or structural change). + +## Phase 4: Plan Output + +1. Write refactoring plan to `<session>/artifacts/refactoring-plan.md`: + + Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block: + + ```markdown + ### REFACTOR-001: <title> + - Priority: P0 + - Target issue: <issue from report> + - Issue type: <CYCLE|COUPLING|GOD_CLASS|DUPLICATION|LAYER_VIOLATION|DEAD_CODE|API_BLOAT> + - Target files: <file-list> + - Strategy: <selected approach> + - Expected improvement: <metric> by <description> + - Risk level: <Low/Medium/High> + - Success criteria: <specific structural change to verify> + - Implementation guidance: + 1. <step 1> + 2. <step 2> + 3. <step 3> + + ### REFACTOR-002: <title> + ... + ``` + + Requirements: + - Each REFACTOR-ID is sequentially numbered (REFACTOR-001, REFACTOR-002, ...) + - Each refactoring must be **non-overlapping** in target files (no two REFACTOR-IDs modify the same file unless explicitly noted with conflict resolution) + - Implementation guidance must be self-contained -- a branch refactorer should be able to work from a single REFACTOR block without reading others + +2. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace: + - Read existing -> merge -> write back: + ```json + { + "designer": { + "complexity": "<Low|Medium|High>", + "refactoring_count": 4, + "priorities": ["P0", "P0", "P1", "P2"], + "discuss_used": false, + "refactorings": [ + { + "id": "REFACTOR-001", + "title": "<title>", + "issue_type": "<CYCLE|COUPLING|...>", + "priority": "P0", + "target_files": ["src/a.ts", "src/b.ts"], + "expected_improvement": "<metric> by <description>", + "success_criteria": "<threshold>" + } + ] + } + } + ``` + +3. If DISCUSS-REFACTOR was triggered, record discussion summary in `<session>/discussions/DISCUSS-REFACTOR.md` diff --git a/.claude/skills/team-arch-opt/roles/refactorer/role.md b/.claude/skills/team-arch-opt/roles/refactorer/role.md new file mode 100644 index 00000000..9a5c0cb6 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/refactorer/role.md @@ -0,0 +1,102 @@ +--- +role: refactorer +prefix: REFACTOR +inner_loop: true +message_types: [state_update] +--- + +# Code Refactorer + +Implement architecture refactoring changes following the design plan. For FIX tasks, apply targeted corrections based on review/validation feedback. + +## Modes + +| Mode | Task Prefix | Trigger | Focus | +|------|-------------|---------|-------| +| Refactor | REFACTOR | Design plan ready | Apply refactorings per plan priority | +| Fix | FIX | Review/validation feedback | Targeted fixes for identified issues | + +## Phase 2: Plan & Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Refactoring plan | <session>/artifacts/refactoring-plan.md | Yes (REFACTOR, no branch) | +| Branch refactoring detail | <session>/artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) | +| Pipeline refactoring plan | <session>/artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) | +| Review/validation feedback | From task description | Yes (FIX) | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Wisdom files | <session>/wisdom/patterns.md | No | +| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) | + +1. Extract session path and task mode (REFACTOR or FIX) from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- load single refactoring detail | +| `PipelineId: {P}` | Present | Independent pipeline -- load pipeline-scoped plan | +| Neither present | - | Single mode -- load full refactoring plan | + +3. **Load refactoring context by mode**: + - **Single mode (no branch)**: Read `<session>/artifacts/refactoring-plan.md` -- extract ALL priority-ordered changes + - **Fan-out branch**: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- extract ONLY this branch's refactoring (single REFACTOR-ID) + - **Independent pipeline**: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` -- extract this pipeline's plan + +4. For FIX: parse review/validation feedback for specific issues to address +5. Use `explore` CLI tool to load implementation context for target files +6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks + +**Meta.json namespace**: +- Single: write to `refactorer` namespace +- Fan-out: write to `refactorer.B{NN}` namespace +- Independent: write to `refactorer.{P}` namespace + +## Phase 3: Code Implementation + +Implementation backend selection: + +| Backend | Condition | Method | +|---------|-----------|--------| +| CLI | Multi-file refactoring with clear plan | ccw cli --tool gemini --mode write | +| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools | + +For REFACTOR tasks: +- **Single mode**: Apply refactorings in plan priority order (P0 first, then P1, etc.) +- **Fan-out branch**: Apply ONLY this branch's single refactoring (from refactoring-detail.md) +- **Independent pipeline**: Apply this pipeline's refactorings in priority order +- Follow implementation guidance from plan (target files, patterns) +- **Preserve existing behavior -- refactoring must not change functionality** +- **Update ALL import references** when moving/renaming modules +- **Update ALL test files** that reference moved/renamed symbols + +For FIX tasks: +- Read specific issues from review/validation feedback +- Apply targeted corrections to flagged code locations +- Verify the fix addresses the exact concern raised + +General rules: +- Make minimal, focused changes per refactoring +- Add comments only where refactoring logic is non-obvious +- Preserve existing code style and conventions +- Verify no dangling imports after module moves + +## Phase 4: Self-Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Syntax | IDE diagnostics or build check | No new errors | +| File integrity | Verify all planned files exist and are modified | All present | +| Import integrity | Verify no broken imports after moves | All imports resolve | +| Acceptance | Match refactoring plan success criteria | All structural changes applied | +| No regression | Run existing tests if available | No new failures | + +If validation fails, attempt auto-fix (max 2 attempts) before reporting error. + +Append to context_accumulator for next REFACTOR/FIX task (single/inner-loop mode only): +- Files modified, refactorings applied, validation results +- Any discovered patterns or caveats for subsequent iterations + +**Branch output paths**: +- Single: write artifacts to `<session>/artifacts/` +- Fan-out: write artifacts to `<session>/artifacts/branches/B{NN}/` +- Independent: write artifacts to `<session>/artifacts/pipelines/{P}/` diff --git a/.claude/skills/team-arch-opt/roles/reviewer/role.md b/.claude/skills/team-arch-opt/roles/reviewer/role.md new file mode 100644 index 00000000..c6506454 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/reviewer/role.md @@ -0,0 +1,111 @@ +--- +role: reviewer +prefix: REVIEW +inner_loop: false +message_types: [state_update] +--- + +# Architecture Reviewer + +Review refactoring code changes for correctness, pattern consistency, completeness, migration safety, and adherence to best practices. Provide structured verdicts with actionable feedback. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Refactoring code changes | From REFACTOR task artifacts / git diff | Yes | +| Refactoring plan / detail | Varies by mode (see below) | Yes | +| Validation results | Varies by mode (see below) | No | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | + +1. Extract session path from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- review only this branch's changes | +| `PipelineId: {P}` | Present | Independent pipeline -- review pipeline-scoped changes | +| Neither present | - | Single mode -- review all refactoring changes | + +3. **Load refactoring context by mode**: + - Single: Read `<session>/artifacts/refactoring-plan.md` + - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` + - Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` + +4. Load .msg/meta.json for scoped refactorer namespace: + - Single: `refactorer` namespace + - Fan-out: `refactorer.B{NN}` namespace + - Independent: `refactorer.{P}` namespace + +5. Identify changed files from refactorer context -- read ONLY files modified by this branch/pipeline +6. If validation results available, read from scoped path: + - Single: `<session>/artifacts/validation-results.json` + - Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json` + - Independent: `<session>/artifacts/pipelines/{P}/validation-results.json` + +## Phase 3: Multi-Dimension Review + +Analyze refactoring changes across five dimensions: + +| Dimension | Focus | Severity | +|-----------|-------|----------| +| Correctness | No behavior changes, all references updated, no dangling imports | Critical | +| Pattern consistency | Follows existing patterns, naming consistent, language-idiomatic | High | +| Completeness | All related code updated (imports, tests, config, documentation) | High | +| Migration safety | No dangling references, backward compatible, public API preserved | Critical | +| Best practices | Clean Architecture / SOLID principles, appropriate abstraction level | Medium | + +Per-dimension review process: +- Scan modified files for patterns matching each dimension +- Record findings with severity (Critical / High / Medium / Low) +- Include specific file:line references and suggested fixes + +**Correctness checks**: +- Verify moved code preserves original behavior (no logic changes mixed with structural changes) +- Check all import/require statements updated to new paths +- Verify no orphaned files left behind after moves + +**Pattern consistency checks**: +- New module names follow existing naming conventions +- Extracted interfaces/classes use consistent patterns with existing codebase +- File organization matches project conventions (e.g., index files, barrel exports) + +**Completeness checks**: +- All test files updated for moved/renamed modules +- Configuration files updated if needed (e.g., path aliases, build configs) +- Type definitions updated for extracted interfaces + +**Migration safety checks**: +- Public API surface unchanged (same exports available to consumers) +- No circular dependencies introduced by the refactoring +- Re-exports in place if module paths changed for backward compatibility + +**Best practices checks**: +- Extracted modules have clear single responsibility +- Dependency direction follows layer conventions (dependencies flow inward) +- Appropriate abstraction level (not over-engineered, not under-abstracted) + +If any Critical findings detected, invoke `discuss` CLI tool (DISCUSS-REVIEW round) to validate the assessment before issuing verdict. + +## Phase 4: Verdict & Feedback + +Classify overall verdict based on findings: + +| Verdict | Condition | Action | +|---------|-----------|--------| +| APPROVE | No Critical or High findings | Send review_complete | +| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback | +| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for designer escalation | + +1. Write review report to scoped output path: + - Single: `<session>/artifacts/review-report.md` + - Fan-out: `<session>/artifacts/branches/B{NN}/review-report.md` + - Independent: `<session>/artifacts/pipelines/{P}/review-report.md` + - Content: Per-dimension findings with severity, file:line, description; Overall verdict with rationale; Specific fix instructions for REVISE/REJECT verdicts + +2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace: + - Single: merge `{ "reviewer": { verdict, finding_count, critical_count, dimensions_reviewed } }` + - Fan-out: merge `{ "reviewer.B{NN}": { verdict, finding_count, critical_count, dimensions_reviewed } }` + - Independent: merge `{ "reviewer.{P}": { verdict, finding_count, critical_count, dimensions_reviewed } }` + +3. If DISCUSS-REVIEW was triggered, record discussion summary in `<session>/discussions/DISCUSS-REVIEW.md` (or `DISCUSS-REVIEW-B{NN}.md` for branch-scoped discussions) diff --git a/.claude/skills/team-arch-opt/roles/validator/role.md b/.claude/skills/team-arch-opt/roles/validator/role.md new file mode 100644 index 00000000..70251a3d --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/validator/role.md @@ -0,0 +1,115 @@ +--- +role: validator +prefix: VALIDATE +inner_loop: false +message_types: [state_update] +--- + +# Architecture Validator + +Validate refactoring changes by running build checks, test suites, dependency metric comparisons, and API compatibility verification. Ensure refactoring improves architecture without breaking functionality. + +## Phase 2: Environment & Baseline Loading + +| Input | Source | Required | +|-------|--------|----------| +| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes | +| Refactoring plan / detail | Varies by mode (see below) | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | + +1. Extract session path from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- validate only this branch's changes | +| `PipelineId: {P}` | Present | Independent pipeline -- use pipeline-scoped baseline | +| Neither present | - | Single mode -- full validation | + +3. **Load architecture baseline**: + - Single / Fan-out: Read `<session>/artifacts/architecture-baseline.json` (shared baseline) + - Independent: Read `<session>/artifacts/pipelines/{P}/architecture-baseline.json` + +4. **Load refactoring context**: + - Single: Read `<session>/artifacts/refactoring-plan.md` -- all success criteria + - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria + - Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` + +5. Load .msg/meta.json for project type and refactoring scope +6. Detect available validation tools from project: + +| Signal | Validation Tool | Method | +|--------|----------------|--------| +| package.json + tsc | TypeScript compiler | Type-check entire project | +| package.json + vitest/jest | Test runner | Run existing test suite | +| package.json + eslint | Linter | Run lint checks for import/export issues | +| Cargo.toml | Rust compiler | cargo check + cargo test | +| go.mod | Go tools | go build + go test | +| Makefile with test target | Custom tests | make test | +| No tooling detected | Manual validation | File existence + import grep checks | + +7. Get changed files scope from .msg/meta.json: + - Single: `refactorer` namespace + - Fan-out: `refactorer.B{NN}` namespace + - Independent: `refactorer.{P}` namespace + +## Phase 3: Validation Execution + +Run validations across four dimensions: + +**Build validation**: +- Compile/type-check the project -- zero new errors allowed +- Verify all moved/renamed files are correctly referenced +- Check for missing imports or unresolved modules + +**Test validation**: +- Run existing test suite -- all previously passing tests must still pass +- Identify any tests that need updating due to module moves (update, don't skip) +- Check for test file imports that reference old paths + +**Dependency metric validation**: +- Recalculate architecture metrics post-refactoring +- Compare coupling scores against baseline (must improve or stay neutral) +- Verify no new circular dependencies introduced +- Check cohesion metrics for affected modules + +**API compatibility validation**: +- Verify public API signatures are preserved (exported function/class/type names) +- Check for dangling references (imports pointing to removed/moved files) +- Verify no new dead exports introduced by the refactoring +- Check that re-exports maintain backward compatibility where needed + +**Branch-scoped validation** (fan-out mode): +- Only validate metrics relevant to this branch's refactoring (from refactoring-detail.md) +- Still check for regressions across all metrics (not just branch-specific ones) + +## Phase 4: Result Analysis + +Compare against baseline and plan criteria: + +| Metric | Threshold | Verdict | +|--------|-----------|---------| +| Build passes | Zero compilation errors | PASS | +| All tests pass | No new test failures | PASS | +| Coupling improved or neutral | No metric degradation > 5% | PASS | +| No new cycles introduced | Cycle count <= baseline | PASS | +| All plan success criteria met | Every criterion satisfied | PASS | +| Partial improvement | Some metrics improved, none degraded | WARN | +| Build fails | Compilation errors detected | FAIL -> fix_required | +| Test failures | Previously passing tests now fail | FAIL -> fix_required | +| New cycles introduced | Cycle count > baseline | FAIL -> fix_required | +| Dangling references | Unresolved imports detected | FAIL -> fix_required | + +1. Write validation results to output path: + - Single: `<session>/artifacts/validation-results.json` + - Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json` + - Independent: `<session>/artifacts/pipelines/{P}/validation-results.json` + - Content: Per-dimension: name, baseline value, current value, improvement/regression, verdict; Overall verdict: PASS / WARN / FAIL; Failure details (if any) + +2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace: + - Single: merge `{ "validator": { verdict, improvements, regressions, build_pass, test_pass } }` + - Fan-out: merge `{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } }` + - Independent: merge `{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }` + +3. If verdict is FAIL, include detailed feedback in message for FIX task creation: + - Which validations failed, specific errors, suggested investigation areas diff --git a/.claude/skills/team-arch-opt/specs/pipelines.md b/.claude/skills/team-arch-opt/specs/pipelines.md new file mode 100644 index 00000000..8ae0e4c1 --- /dev/null +++ b/.claude/skills/team-arch-opt/specs/pipelines.md @@ -0,0 +1,102 @@ +# Pipeline Definitions — team-arch-opt + +## Available Pipelines + +### Single Mode (Linear) + +``` +ANALYZE-001 → DESIGN-001 → REFACTOR-001 → VALIDATE-001 + REVIEW-001 +[analyzer] [designer] [refactorer] [validator] [reviewer] + ^ | + +<-- FIX-001 ----+ + (max 3 iterations) +``` + +### Fan-out Mode (Shared Stages + Parallel Branches) + +``` +ANALYZE-001 → DESIGN-001 --+→ REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01 +[analyzer] [designer] | [refactorer] [validator] [reviewer] + +→ REFACTOR-B02 → VALIDATE-B02 + REVIEW-B02 + +→ REFACTOR-B0N → VALIDATE-B0N + REVIEW-B0N + | + AGGREGATE → Phase 5 +``` + +Branch tasks created at CP-2.5 after DESIGN-001 completes. + +### Independent Mode (M Complete Pipelines) + +``` +Pipeline A: ANALYZE-A01 → DESIGN-A01 → REFACTOR-A01 → VALIDATE-A01 + REVIEW-A01 +Pipeline B: ANALYZE-B01 → DESIGN-B01 → REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01 +... | + AGGREGATE → Phase 5 +``` + +### Auto Mode + +Auto-detects based on refactoring count at CP-2.5: +- count <= 2 → switch to single mode +- count >= 3 → switch to fan-out mode + +## Task Metadata Registry + +### Single Mode + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues | +| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report | +| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings | +| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility | +| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness | +| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation | + +### Fan-out Mode (Branch Tasks at CP-2.5) + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture | +| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs | +| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only | +| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} | +| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} | +| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} | + +### Independent Mode + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target | +| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} | +| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings | +| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} | +| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} | + +## Checkpoints + +| Checkpoint | Trigger | Location | Behavior | +|------------|---------|----------|----------| +| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope | +| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities | +| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks, spawn all REFACTOR-B* in parallel | +| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) | +| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action | + +## Task Naming Rules + +| Mode | Stage 3 | Stage 4 | Fix | Retry | +|------|---------|---------|-----|-------| +| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 | +| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 | +| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 | + +## Parallel Mode Invocation + +```bash +Skill(skill="team-arch-opt", args="<task-description>") # auto mode +Skill(skill="team-arch-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out +Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent +Skill(skill="team-arch-opt", args="--max-branches=3 <task-description>") # limit branches +``` diff --git a/.claude/skills/team-brainstorm/SKILL.md b/.claude/skills/team-brainstorm/SKILL.md index e4266cbf..95d88538 100644 --- a/.claude/skills/team-brainstorm/SKILL.md +++ b/.claude/skills/team-brainstorm/SKILL.md @@ -1,309 +1,60 @@ --- name: team-brainstorm -description: Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team brainstorm". +description: Unified team skill for brainstorming team. Uses team-worker agent architecture with role directories for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team brainstorm". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) --- # Team Brainstorm -Unified team skill: multi-angle brainstorming via Generator-Critic loops, shared memory, and dynamic pipeline selection. All team members invoke with `--role=xxx` to route to role-specific execution. +Orchestrate multi-agent brainstorming: generate ideas → challenge assumptions → synthesize → evaluate. Supports Quick, Deep, and Full pipelines with Generator-Critic loop. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-brainstorm") | -| args="<topic-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-brainstorm", args="topic description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -ideator chall- synthe- evalua- - enger sizer tor - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+ + v v v v + [ideator][challenger][synthesizer][evaluator] ``` -## Command Execution Protocol +## Role Registry -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| ideator | [roles/ideator/role.md](roles/ideator/role.md) | IDEA-* | false | +| challenger | [roles/challenger/role.md](roles/challenger/role.md) | CHALLENGE-* | false | +| synthesizer | [roles/synthesizer/role.md](roles/synthesizer/role.md) | SYNTH-* | false | +| evaluator | [roles/evaluator/role.md](roles/evaluator/role.md) | EVAL-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `BRS` +- **Session path**: `.workflow/.team/BRS-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| ideator | [role-specs/ideator.md](role-specs/ideator.md) | IDEA-* | false | -| challenger | [role-specs/challenger.md](role-specs/challenger.md) | CHALLENGE-* | false | -| synthesizer | [role-specs/synthesizer.md](role-specs/synthesizer.md) | SYNTH-* | false | -| evaluator | [role-specs/evaluator.md](role-specs/evaluator.md) | EVAL-* | false | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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 topic description. - -**Invocation**: `Skill(skill="team-brainstorm", args="<topic-description>")` - -**Lifecycle**: -``` -User provides topic description - → coordinator Phase 1-3: Topic clarification → TeamCreate → Create task chain - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until pipeline complete → Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Share state via team_msg(type="state_update") | Create tasks for other roles | -| Delegate to commands/ files | Modify resources outside own responsibility | - -Coordinator additional restrictions: Do not generate ideas directly, do not evaluate/challenge ideas, do not execute analysis/synthesis, do not bypass workers. - -### Output Tagging - -All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary. - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: - -**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - -`to` and `summary` auto-defaulted -- do NOT specify explicitly. - -**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` - - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `pipeline_selected`, `gc_loop_trigger`, `task_unblocked`, `error`, `shutdown` | -| ideator | `ideas_ready`, `ideas_revised`, `error` | -| challenger | `critique_ready`, `error` | -| synthesizer | `synthesis_ready`, `error` | -| evaluator | `evaluation_ready`, `error` | - -### Shared State - -Cross-role state is shared via `team_msg(type="state_update")` messages, persisted in `.msg/meta.json`: - -| Role | State Key | -|------|-----------| -| ideator | `generated_ideas` | -| challenger | `critique_insights` | -| synthesizer | `synthesis_themes` | -| evaluator | `evaluation_scores` | - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | brainstorm | -| Session directory | `.workflow/.team/BRS-<slug>-<date>/` | -| Message store | `.msg/messages.jsonl` + `.msg/meta.json` in session dir | - ---- - -## Three-Pipeline Architecture - -``` -Quick: - IDEA-001 → CHALLENGE-001 → SYNTH-001 - -Deep (Generator-Critic Loop): - IDEA-001 → CHALLENGE-001 → IDEA-002(fix) → CHALLENGE-002 → SYNTH-001 → EVAL-001 - -Full (Fan-out + Generator-Critic): - [IDEA-001 + IDEA-002 + IDEA-003](parallel) → CHALLENGE-001(batch) → IDEA-004(fix) → SYNTH-001 → EVAL-001 -``` - -### Generator-Critic Loop - -ideator <-> challenger loop, max 2 rounds: - -``` -IDEA → CHALLENGE → (if critique.severity >= HIGH) → IDEA-fix → CHALLENGE-2 → SYNTH - (if critique.severity < HIGH) → SYNTH -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. Brainstorm beat: generate → challenge → synthesize → evaluate. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - │ (parallel OK) ──┼──→ [Worker B] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat views**: - -``` -Quick (3 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 - │ │ │ - IDEA → CHALLENGE ──→ SYNTH - ▲ ▲ - pipeline pipeline - start done - -IDEA=ideator CHALLENGE=challenger SYNTH=synthesizer - -Deep (5-6 beats, with Generator-Critic loop) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 - │ │ │ │ │ │ - IDEA → CHALLENGE → (GC loop?) → IDEA-fix → SYNTH → EVAL - │ - severity check - (< HIGH → skip to SYNTH) - -Full (4-7 beats, fan-out + Generator-Critic) -────────────────────────────────────────────────────────── -Beat 1 2 3-4 5 6 - ┌────┴────┐ │ │ │ │ - IDEA-1 ∥ IDEA-2 ∥ IDEA-3 → CHALLENGE → (GC loop) → SYNTH → EVAL - ▲ ▲ - parallel pipeline - window done -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Generator-Critic loop | After CHALLENGE-* | If severity >= HIGH → create IDEA-fix task; else proceed to SYNTH | -| GC loop limit | Max 2 rounds | Exceeds limit → force convergence to SYNTH | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| GC loop exceeded | ideator/challenger iteration > 2 rounds | Terminate loop, force convergence to synthesizer | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| IDEA-001 | ideator | generate | (none) | Multi-angle idea generation | -| IDEA-002 | ideator | generate | (none) | Parallel angle (Full pipeline only) | -| IDEA-003 | ideator | generate | (none) | Parallel angle (Full pipeline only) | -| CHALLENGE-001 | challenger | challenge | IDEA-001 (or all IDEA-*) | Devil's advocate critique and feasibility challenge | -| IDEA-004 | ideator | gc-fix | CHALLENGE-001 | Revision based on critique (GC loop, if triggered) | -| CHALLENGE-002 | challenger | gc-fix | IDEA-004 | Re-critique of revised ideas (GC loop round 2) | -| SYNTH-001 | synthesizer | synthesize | last CHALLENGE-* | Cross-idea integration, theme extraction, conflict resolution | -| EVAL-001 | evaluator | evaluate | SYNTH-001 | Scoring, ranking, priority recommendation, final selection | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -314,39 +65,31 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md +role_spec: .claude/skills/team-brainstorm/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: brainstorm requirement: <topic-description> -inner_loop: <true|false> +inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**All roles** (ideator, challenger, synthesizer, evaluator): Set `inner_loop: false`. - **Parallel ideator spawn** (Full pipeline with N angles): -> When Full pipeline has N parallel IDEA tasks assigned to ideator role, spawn N distinct team-worker agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name. - -| Condition | Action | -|-----------|--------| -| Full pipeline with N idea angles (N > 1) | Spawn N team-worker agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` | -| Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` team-worker agent | +When Full pipeline has N parallel IDEA tasks, spawn N distinct team-worker agents named `ideator-1`, `ideator-2`, etc. ``` Agent({ subagent_type: "team-worker", - description: "Spawn ideator-<N> worker", - team_name: "brainstorm", name: "ideator-<N>", + team_name: "brainstorm", run_in_background: true, prompt: `## Role Assignment role: ideator -role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md +role_spec: .claude/skills/team-brainstorm/roles/ideator/role.md session: <session-folder> session_id: <session-id> team_name: brainstorm @@ -355,73 +98,55 @@ agent_name: ideator-<N> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery, owner=ideator-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery, owner=ideator-<N>) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Dispatch must match agent names**: When dispatching parallel IDEA tasks, coordinator sets each task's owner to the corresponding instance name (`ideator-1`, `ideator-2`, etc.). In role.md, task discovery uses `--agent-name` for owner matching. +## User Commands ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph, no advancement | +| `resume` / `continue` | Check worker states, advance next step | -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): +## Session Directory ``` -AskUserQuestion({ - questions: [{ - question: "Brainstorm pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-brainstorm", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- - -## Unified Session Directory - -``` -.workflow/.team/BRS-<slug>-<YYYY-MM-DD>/ +.workflow/.team/BRS-<slug>-<date>/ +├── session.json # Session metadata + pipeline + gc_round +├── task-analysis.json # Coordinator analyze output ├── .msg/ -│ ├── messages.jsonl # Message bus log -│ └── meta.json # Session state + cross-role state -├── wisdom/ # Cross-task knowledge +│ ├── messages.jsonl # Message bus log +│ └── meta.json # Session state + cross-role state +├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md │ ├── conventions.md │ └── issues.md -├── ideas/ # Ideator output +├── ideas/ # Ideator output │ ├── idea-001.md -│ ├── idea-002.md -│ └── idea-003.md -├── critiques/ # Challenger output +│ └── idea-002.md +├── critiques/ # Challenger output │ ├── critique-001.md │ └── critique-002.md -├── synthesis/ # Synthesizer output +├── synthesis/ # Synthesizer output │ └── synthesis-001.md -└── evaluation/ # Evaluator output +└── evaluation/ # Evaluator output └── evaluation-001.md ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry + ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>.md) | -| Task prefix conflict | Log warning, proceed | -| Generator-Critic loop exceeds 2 rounds | Force convergence → SYNTH | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| CLI tool fails | Worker fallback to direct implementation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | +| Generator-Critic loop exceeds 2 rounds | Force convergence to synthesizer | | No ideas generated | Coordinator prompts with seed questions | diff --git a/.claude/skills/team-brainstorm/roles/challenger/role.md b/.claude/skills/team-brainstorm/roles/challenger/role.md new file mode 100644 index 00000000..49966feb --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/challenger/role.md @@ -0,0 +1,61 @@ +--- +role: challenger +prefix: CHALLENGE +inner_loop: false +message_types: [state_update] +--- + +# Challenger + +Devil's advocate role. Assumption challenging, feasibility questioning, risk identification. Acts as the Critic in the Generator-Critic loop. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session folder | Task description (Session: line) | Yes | +| Ideas | <session>/ideas/*.md files | Yes | +| Previous critiques | <session>/.msg/meta.json critique_insights | No | + +1. Extract session path from task description (match "Session: <path>") +2. Glob idea files from <session>/ideas/ +3. Read all idea files for analysis +4. Read .msg/meta.json critique_insights to avoid repeating past challenges + +## Phase 3: Critical Analysis + +**Challenge Dimensions** (apply to each idea): + +| Dimension | Focus | +|-----------|-------| +| Assumption Validity | Does the core assumption hold? Counter-examples? | +| Feasibility | Technical/resource/time feasibility? | +| Risk Assessment | Worst case scenario? Hidden risks? | +| Competitive Analysis | Better alternatives already exist? | + +**Severity Classification**: + +| Severity | Criteria | +|----------|----------| +| CRITICAL | Fundamental issue, idea may need replacement | +| HIGH | Significant flaw, requires revision | +| MEDIUM | Notable weakness, needs consideration | +| LOW | Minor concern, does not invalidate the idea | + +**Generator-Critic Signal**: + +| Condition | Signal | +|-----------|--------| +| Any CRITICAL or HIGH severity | REVISION_NEEDED | +| All MEDIUM or lower | CONVERGED | + +**Output**: Write to `<session>/critiques/critique-<num>.md` +- Sections: Ideas Reviewed, Per-idea challenges with severity, Summary table with counts, GC Signal + +## Phase 4: Severity Summary + +1. Count challenges by severity level +2. Determine signal: REVISION_NEEDED if critical+high > 0, else CONVERGED +3. Update shared state: + - Append challenges to .msg/meta.json critique_insights + - Each entry: idea, severity, key_challenge, round diff --git a/.claude/skills/team-brainstorm/roles/coordinator/commands/analyze.md b/.claude/skills/team-brainstorm/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..d269a59a --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/coordinator/commands/analyze.md @@ -0,0 +1,58 @@ +# Analyze Task + +Parse user topic -> detect brainstorming capabilities -> assess complexity -> select pipeline. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| generate, create, brainstorm, ideas, explore | ideator | IDEA | +| challenge, critique, argue, devil, risk | challenger | CHALLENGE | +| synthesize, integrate, combine, merge, themes | synthesizer | SYNTH | +| evaluate, score, rank, prioritize, select | evaluator | EVAL | + +## Dependency Graph + +Natural ordering tiers: +- Tier 0: ideator (divergent generation -- no dependencies) +- Tier 1: challenger (requires ideator output) +- Tier 2: ideator-revision (requires challenger output, GC loop) +- Tier 3: synthesizer (requires last challenger output) +- Tier 4: evaluator (requires synthesizer output, deep/full only) + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per capability needed | +1 | +| Strategic/systemic topic | +3 | +| Multi-dimensional analysis | +2 | +| Innovation-focused request | +2 | +| Simple/basic topic | -2 | + +Results: 0-1 Low (quick), 2-3 Medium (deep), 4+ High (full) + +## Pipeline Selection + +| Complexity | Pipeline | Tasks | +|------------|----------|-------| +| Low | quick | IDEA → CHALLENGE → SYNTH | +| Medium | deep | IDEA → CHALLENGE → IDEA-fix → CHALLENGE-2 → SYNTH → EVAL | +| High | full | 3x IDEA (parallel) → CHALLENGE → IDEA-fix → SYNTH → EVAL | + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_type": "<quick|deep|full>", + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "angles": ["Technical", "Product", "Innovation", "Risk"] +} +``` diff --git a/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md b/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md index 6d93ecf8..07a2e592 100644 --- a/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md @@ -1,34 +1,30 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | -|-----|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| WORKER_AGENT | team-worker | -| MAX_GC_ROUNDS | 2 | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 2 -## Phase 2: Context Loading +## Handler Router -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Meta state | <session>/.msg/meta.json | Yes | +| Source | Handler | +|--------|---------| +| Message contains [ideator], [challenger], [synthesizer], [evaluator] | handleCallback | +| "consensus_blocked" | handleConsensus | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -1. Load session.json for current state, pipeline mode, gc_round -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## handleCallback -## Phase 3: Event Handlers - -### handleCallback - -Triggered when a worker sends completion message. +Worker completed. Process and advance. 1. Parse message to identify role and task ID: @@ -39,14 +35,8 @@ Triggered when a worker sends completion message. | `[synthesizer]` or task ID `SYNTH-*` | synthesizer | | `[evaluator]` or task ID `EVAL-*` | evaluator | -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` - +2. Mark task as completed: `TaskUpdate({ taskId: "<task-id>", status: "completed" })` 3. Record completion in session state - 4. **Generator-Critic check** (when challenger completes): - If completed task is CHALLENGE-* AND pipeline is deep or full: - Read critique file for GC signal @@ -63,38 +53,57 @@ TaskUpdate({ taskId: "<task-id>", status: "completed" }) 5. Proceed to handleSpawnNext -### handleSpawnNext +## handleCheck -Find and spawn the next ready tasks. - -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" - -2. For each ready task, spawn team-worker: +Read-only status report, then STOP. ``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker for <task-id>", - team_name: "brainstorm", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: brainstorm -requirement: <task-description> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) +[coordinator] Pipeline Status (<pipeline-mode>) +[coordinator] Progress: <done>/<total> (<pct>%) +[coordinator] Active: <workers with elapsed time> +[coordinator] Ready: <pending tasks with resolved deps> +[coordinator] GC Rounds: <gc_round>/<max_gc_rounds> +[coordinator] Commands: 'resume' to advance | 'check' to refresh ``` -3. **Parallel spawn rules**: +## handleResume + +1. Audit task list: Tasks stuck in "in_progress" -> reset to "pending" +2. Proceed to handleSpawnNext + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect: completedSubjects, inProgressSubjects, readySubjects +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. TaskUpdate -> in_progress + b. team_msg log -> task_unblocked + c. Spawn team-worker (see SKILL.md Spawn Template): + ``` + Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <task-id>", + team_name: "brainstorm", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment + role: <role> + role_spec: .claude/skills/team-brainstorm/roles/<role>/role.md + session: <session-folder> + session_id: <session-id> + team_name: brainstorm + requirement: <task-description> + inner_loop: false + + Read role_spec file to load Phase 2-4 domain instructions. + Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` + }) + ``` + d. Add to active_workers +5. Parallel spawn rules: | Pipeline | Scenario | Spawn Behavior | |----------|----------|---------------| @@ -103,33 +112,34 @@ Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` | Full | IDEA-001/002/003 unblocked | Spawn ALL 3 ideator workers in parallel | | Full | Other stages | One worker at a time | -4. STOP after spawning -- wait for next callback - -### handleCheck - -Output current pipeline status. Do NOT advance pipeline. - +**Parallel ideator spawn** (Full pipeline): ``` -Pipeline Status (<pipeline-mode>): - [DONE] IDEA-001 (ideator) -> ideas/idea-001.md - [DONE] CHALLENGE-001 (challenger) -> critiques/critique-001.md - [RUN] SYNTH-001 (synthesizer) -> synthesizing... - [WAIT] EVAL-001 (evaluator) -> blocked by SYNTH-001 - -GC Rounds: <gc_round>/<max_gc_rounds> -Session: <session-id> +Agent({ + subagent_type: "team-worker", + name: "ideator-<N>", + ... + prompt: `...agent_name: ideator-<N>...` +}) ``` -### handleResume +6. Update session, output summary, STOP -Resume pipeline after user pause or interruption. +## handleComplete -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext +Pipeline done. Generate report and completion action. -### handleConsensus +Completion check by mode: +| Mode | Completion Condition | +|------|---------------------| +| quick | All 3 tasks completed | +| deep | All 6 tasks (+ any skipped GC tasks) completed | +| full | All 7 tasks (+ any skipped GC tasks) completed | + +1. Verify all tasks completed via TaskList() +2. If any tasks not completed, return to handleSpawnNext +3. If all completed -> transition to coordinator Phase 5 + +## handleConsensus Handle consensus_blocked signals. @@ -139,27 +149,19 @@ Handle consensus_blocked signals. | MEDIUM | Log finding, attempt to continue | | LOW | Log finding, continue pipeline | -### handleComplete +## handleAdapt -Triggered when all pipeline tasks are completed. +Capability gap reported mid-pipeline. -**Completion check by mode**: +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause -| Mode | Completion Condition | -|------|---------------------| -| quick | All 3 tasks completed | -| deep | All 6 tasks (+ any skipped GC tasks) completed | -| full | All 7 tasks (+ any skipped GC tasks) completed | +## Fast-Advance Reconciliation -1. Verify all tasks completed via TaskList() -2. If any tasks not completed, return to handleSpawnNext -3. If all completed, transition to coordinator Phase 5 (Report + Completion Action) - -## Phase 4: State Persistence - -After every handler execution: - -1. Update session.json with current state (gc_round, last event, active tasks) -2. Update .msg/meta.json gc_round if changed -3. Verify task list consistency -4. STOP and wait for next event +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-brainstorm/roles/coordinator/role.md b/.claude/skills/team-brainstorm/roles/coordinator/role.md index 92daacc6..7782fa80 100644 --- a/.claude/skills/team-brainstorm/roles/coordinator/role.md +++ b/.claude/skills/team-brainstorm/roles/coordinator/role.md @@ -1,15 +1,14 @@ -# Coordinator - Brainstorm Team +# Coordinator -**Role**: coordinator -**Type**: Orchestrator -**Team**: brainstorm +Orchestrate team-brainstorm: topic clarify -> dispatch -> spawn -> monitor -> report. -Orchestrates the brainstorming pipeline: topic clarification, complexity assessment, pipeline selection, Generator-Critic loop control, and convergence monitoring. Spawns team-worker agents for all worker roles. +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Topic clarification -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) @@ -18,105 +17,48 @@ Orchestrates the brainstorming pipeline: topic clarification, complexity assessm - Execute completion action in Phase 5 ### MUST NOT - - Generate ideas, challenge assumptions, synthesize, or evaluate -- workers handle this - Spawn workers without creating tasks first - Force-advance pipeline past GC loop decisions - Modify artifact files (ideas/*.md, critiques/*.md, etc.) -- delegate to workers - Skip GC severity check when critique arrives ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [ideator], [challenger], [synthesizer], [evaluator] | -> handleCallback | -| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Topic Clarification) | +| Worker callback | Message contains [ideator], [challenger], [synthesizer], [evaluator] | -> handleCallback (monitor.md) | +| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/BRS-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/BRS-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - - Check for "consensus_blocked" signal - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Topic Clarification below - ---- +For callback/check/resume/consensus/adapt/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "brainstorm" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/BRS-*/session.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Topic Clarification + Complexity Assessment -1. Parse user task description from $ARGUMENTS -2. Parse optional `--team-name` flag (default: "brainstorm") +TEXT-LEVEL ONLY. No source code reading. -3. Assess topic complexity: +1. Parse topic from $ARGUMENTS +2. Assess topic complexity: | Signal | Weight | Keywords | |--------|--------|----------| @@ -131,155 +73,39 @@ TeamCreate({ team_name: "brainstorm" }) | 2-3 | Medium | deep | | 0-1 | Low | quick | -4. Ask for missing parameters: +3. AskUserQuestion for pipeline mode and divergence angles +4. Store requirements: mode, scope, angles, constraints -``` -AskUserQuestion({ - questions: [{ - question: "Select brainstorming pipeline mode", - header: "Mode", - multiSelect: false, - options: [ - { label: "quick", description: "3-step: generate -> challenge -> synthesize" }, - { label: "deep", description: "6-step with Generator-Critic loop" }, - { label: "full", description: "7-step parallel ideation + GC + evaluation" } - ] - }, { - question: "Select divergence angles", - header: "Angles", - multiSelect: true, - options: [ - { label: "Technical" }, - { label: "Product" }, - { label: "Innovation" }, - { label: "Risk" } - ] - }] -}) -``` - -5. Store requirements: mode, scope, angles, constraints - ---- - -## Phase 2: Session & Team Setup +## Phase 2: Create Team + Initialize Session 1. Generate session ID: `BRS-<topic-slug>-<date>` -2. Create session folder structure: +2. Create session folder structure: ideas/, critiques/, synthesis/, evaluation/, wisdom/, .msg/ +3. TeamCreate with team name `brainstorm` +4. Write session.json with pipeline, angles, gc_round=0, max_gc_rounds=2 +5. Initialize meta.json via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { pipeline_mode: "<mode>", pipeline_stages: ["ideator","challenger","synthesizer","evaluator"], team_name: "brainstorm", topic: "<topic>", angles: [...], gc_round: 0 } + }) + ``` +6. Write session.json -``` -Bash("mkdir -p .workflow/.team/<session-id>/ideas .workflow/.team/<session-id>/critiques .workflow/.team/<session-id>/synthesis .workflow/.team/<session-id>/evaluation .workflow/.team/<session-id>/wisdom .workflow/.team/<session-id>/.msg") -``` +## Phase 3: Create Task Chain -3. Write session.json: +Delegate to commands/dispatch.md: +1. Read pipeline mode and angles from session.json +2. Create tasks for selected pipeline with correct blockedBy +3. Update session.json with task count -```json -{ - "status": "active", - "team_name": "brainstorm", - "topic": "<topic>", - "pipeline": "<quick|deep|full>", - "angles": ["<angle1>", "<angle2>"], - "gc_round": 0, - "max_gc_rounds": 2, - "timestamp": "<ISO-8601>" -} -``` +## Phase 4: Spawn-and-Stop -4. Initialize meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<mode>", - pipeline_stages: ["ideator", "challenger", "synthesizer", "evaluator"], - roles: ["coordinator", "ideator", "challenger", "synthesizer", "evaluator"], - team_name: "brainstorm", - topic: "<topic>", - angles: ["<angle1>", "<angle2>"], - gc_round": 0, - status: "active" - } -}) -``` - -5. Create team: - -``` -TeamCreate({ team_name: "brainstorm" }) -``` - ---- - -## Phase 3: Task Chain Creation - -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies - ---- - -## Phase 4: Spawn First Batch - -Find first unblocked task(s) and spawn worker(s): - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn ideator worker", - team_name: "brainstorm", - name: "ideator", - run_in_background: true, - prompt: `## Role Assignment -role: ideator -role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md -session: <session-folder> -session_id: <session-id> -team_name: brainstorm -requirement: <topic-description> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -For **Full pipeline** with parallel ideators, spawn N team-worker agents: - -``` -// For each parallel IDEA task (IDEA-001, IDEA-002, IDEA-003) -Agent({ - subagent_type: "team-worker", - description: "Spawn ideator worker for IDEA-<N>", - team_name: "brainstorm", - name: "ideator-<N>", - run_in_background: true, - prompt: `## Role Assignment -role: ideator -role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md -session: <session-folder> -session_id: <session-id> -team_name: brainstorm -requirement: <topic-description> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -All subsequent coordination handled by `commands/monitor.md` handlers. - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action @@ -295,27 +121,17 @@ All subsequent coordination handled by `commands/monitor.md` handlers. 3. Output pipeline summary: topic, pipeline mode, GC rounds, total ideas, key themes -4. **Completion Action** (interactive): +4. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -``` -AskUserQuestion({ - questions: [{ - question: "Brainstorm pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up brainstorming" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` +## Error Handling -5. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-brainstorm', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| GC loop exceeded | Force convergence to synthesizer | +| No ideas generated | Coordinator prompts with seed questions | diff --git a/.claude/skills/team-brainstorm/roles/evaluator/role.md b/.claude/skills/team-brainstorm/roles/evaluator/role.md new file mode 100644 index 00000000..53abdb21 --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/evaluator/role.md @@ -0,0 +1,56 @@ +--- +role: evaluator +prefix: EVAL +inner_loop: false +message_types: [state_update] +--- + +# Evaluator + +Scoring, ranking, and final selection. Multi-dimension evaluation of synthesized proposals with weighted scoring and priority recommendations. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session folder | Task description (Session: line) | Yes | +| Synthesis results | <session>/synthesis/*.md files | Yes | +| All ideas | <session>/ideas/*.md files | No (for context) | +| All critiques | <session>/critiques/*.md files | No (for context) | + +1. Extract session path from task description (match "Session: <path>") +2. Glob synthesis files from <session>/synthesis/ +3. Read all synthesis files for evaluation +4. Optionally read ideas and critiques for full context + +## Phase 3: Evaluation and Scoring + +**Scoring Dimensions**: + +| Dimension | Weight | Focus | +|-----------|--------|-------| +| Feasibility | 30% | Technical feasibility, resource needs, timeline | +| Innovation | 25% | Novelty, differentiation, breakthrough potential | +| Impact | 25% | Scope of impact, value creation, problem resolution | +| Cost Efficiency | 20% | Implementation cost, risk cost, opportunity cost | + +**Weighted Score**: `(Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + (Cost * 0.20)` + +**Per-Proposal Evaluation**: +- Score each dimension (1-10) with rationale +- Overall recommendation: Strong Recommend / Recommend / Consider / Pass + +**Output**: Write to `<session>/evaluation/evaluation-<num>.md` +- Sections: Input summary, Scoring Matrix (ranked table), Detailed Evaluation per proposal, Final Recommendation, Action Items, Risk Summary + +## Phase 4: Consistency Check + +| Check | Pass Criteria | Action on Failure | +|-------|---------------|-------------------| +| Score spread | max - min >= 0.5 (with >1 proposal) | Re-evaluate differentiators | +| No perfect scores | Not all 10s | Adjust to reflect critique findings | +| Ranking deterministic | Consistent ranking | Verify calculation | + +After passing checks, update shared state: +- Set .msg/meta.json evaluation_scores +- Each entry: title, weighted_score, rank, recommendation diff --git a/.claude/skills/team-brainstorm/roles/ideator/role.md b/.claude/skills/team-brainstorm/roles/ideator/role.md new file mode 100644 index 00000000..5983d37e --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/ideator/role.md @@ -0,0 +1,69 @@ +--- +role: ideator +prefix: IDEA +inner_loop: false +message_types: [state_update] +--- + +# Ideator + +Multi-angle idea generator. Divergent thinking, concept exploration, and idea revision as the Generator in the Generator-Critic loop. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session folder | Task description (Session: line) | Yes | +| Topic | <session>/.msg/meta.json | Yes | +| Angles | <session>/.msg/meta.json | Yes | +| GC Round | <session>/.msg/meta.json | Yes | +| Previous critique | <session>/critiques/*.md | For revision tasks only | +| Previous ideas | <session>/.msg/meta.json generated_ideas | No | + +1. Extract session path from task description (match "Session: <path>") +2. Read .msg/meta.json for topic, angles, gc_round +3. Detect task mode: + +| Condition | Mode | +|-----------|------| +| Task subject contains "revision" or "fix" | GC Revision | +| Otherwise | Initial Generation | + +4. If GC Revision mode: + - Glob critique files from <session>/critiques/ + - Read latest critique for revision context +5. Read previous ideas from .msg/meta.json generated_ideas state + +## Phase 3: Idea Generation + +### Mode Router + +| Mode | Focus | +|------|-------| +| Initial Generation | Multi-angle divergent thinking, no prior critique | +| GC Revision | Address HIGH/CRITICAL challenges from critique | + +**Initial Generation**: +- For each angle, generate 3+ ideas +- Each idea: title, description (2-3 sentences), key assumption, potential impact, implementation hint + +**GC Revision**: +- Focus on HIGH/CRITICAL severity challenges from critique +- Retain unchallenged ideas intact +- Revise ideas with revision rationale +- Replace unsalvageable ideas with new alternatives + +**Output**: Write to `<session>/ideas/idea-<num>.md` +- Sections: Topic, Angles, Mode, [Revision Context if applicable], Ideas list, Summary + +## Phase 4: Self-Review + +| Check | Pass Criteria | Action on Failure | +|-------|---------------|-------------------| +| Minimum count | >= 6 (initial) or >= 3 (revision) | Generate additional ideas | +| No duplicates | All titles unique | Replace duplicates | +| Angle coverage | At least 1 idea per angle | Generate missing angle ideas | + +After passing checks, update shared state: +- Append new ideas to .msg/meta.json generated_ideas +- Each entry: id, title, round, revised flag diff --git a/.claude/skills/team-brainstorm/roles/synthesizer/role.md b/.claude/skills/team-brainstorm/roles/synthesizer/role.md new file mode 100644 index 00000000..458d24cd --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/synthesizer/role.md @@ -0,0 +1,57 @@ +--- +role: synthesizer +prefix: SYNTH +inner_loop: false +message_types: [state_update] +--- + +# Synthesizer + +Cross-idea integrator. Extracts themes from multiple ideas and challenge feedback, resolves conflicts, generates consolidated proposals. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session folder | Task description (Session: line) | Yes | +| All ideas | <session>/ideas/*.md files | Yes | +| All critiques | <session>/critiques/*.md files | Yes | +| GC rounds completed | <session>/.msg/meta.json gc_round | Yes | + +1. Extract session path from task description (match "Session: <path>") +2. Glob all idea files from <session>/ideas/ +3. Glob all critique files from <session>/critiques/ +4. Read all idea and critique files for synthesis +5. Read .msg/meta.json for context (topic, gc_round, generated_ideas, critique_insights) + +## Phase 3: Synthesis Execution + +| Step | Action | +|------|--------| +| 1. Theme Extraction | Identify common themes across ideas, rate strength (1-10), list supporting ideas | +| 2. Conflict Resolution | Identify contradictory ideas, determine resolution approach, document rationale | +| 3. Complementary Grouping | Group complementary ideas together | +| 4. Gap Identification | Discover uncovered perspectives | +| 5. Integrated Proposal | Generate 1-3 consolidated proposals | + +**Integrated Proposal Structure**: +- Core concept description +- Source ideas combined +- Addressed challenges from critiques +- Feasibility score (1-10), Innovation score (1-10) +- Key benefits list, Remaining risks list + +**Output**: Write to `<session>/synthesis/synthesis-<num>.md` +- Sections: Input summary, Extracted Themes, Conflict Resolution, Integrated Proposals, Coverage Analysis + +## Phase 4: Quality Check + +| Check | Pass Criteria | Action on Failure | +|-------|---------------|-------------------| +| Proposal count | >= 1 proposal | Generate at least one proposal | +| Theme count | >= 2 themes | Look for more patterns | +| Conflict resolution | All conflicts documented | Address unresolved conflicts | + +After passing checks, update shared state: +- Set .msg/meta.json synthesis_themes +- Each entry: name, strength, supporting_ideas diff --git a/.claude/skills/team-brainstorm/specs/pipelines.md b/.claude/skills/team-brainstorm/specs/pipelines.md new file mode 100644 index 00000000..9d6f051d --- /dev/null +++ b/.claude/skills/team-brainstorm/specs/pipelines.md @@ -0,0 +1,72 @@ +# Pipeline Definitions — team-brainstorm + +## Available Pipelines + +### Quick Pipeline (3 beats, strictly serial) + +``` +IDEA-001 → CHALLENGE-001 → SYNTH-001 +[ideator] [challenger] [synthesizer] +``` + +### Deep Pipeline (6 beats, Generator-Critic loop) + +``` +IDEA-001 → CHALLENGE-001 → IDEA-002(fix) → CHALLENGE-002 → SYNTH-001 → EVAL-001 +``` + +GC loop check: if critique.severity >= HIGH → create IDEA-fix → CHALLENGE-2 → SYNTH; else skip to SYNTH + +### Full Pipeline (7 tasks, fan-out parallel ideation + GC) + +``` +[IDEA-001 + IDEA-002 + IDEA-003](parallel) → CHALLENGE-001(batch) → IDEA-004(fix) → SYNTH-001 → EVAL-001 +``` + +## Task Metadata Registry + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| IDEA-001 | ideator | generate | (none) | Multi-angle idea generation | +| IDEA-002 | ideator | generate | (none) | Parallel angle (Full pipeline only) | +| IDEA-003 | ideator | generate | (none) | Parallel angle (Full pipeline only) | +| CHALLENGE-001 | challenger | challenge | IDEA-001 (or all IDEA-*) | Devil's advocate critique and feasibility challenge | +| IDEA-004 | ideator | gc-fix | CHALLENGE-001 | Revision based on critique (GC loop, if triggered) | +| CHALLENGE-002 | challenger | gc-fix | IDEA-004 | Re-critique of revised ideas (GC loop round 2) | +| SYNTH-001 | synthesizer | synthesize | last CHALLENGE-* | Cross-idea integration, theme extraction, conflict resolution | +| EVAL-001 | evaluator | evaluate | SYNTH-001 | Scoring, ranking, priority recommendation, final selection | + +## Checkpoints + +| Trigger | Location | Behavior | +|---------|----------|----------| +| Generator-Critic loop | After CHALLENGE-* | If severity >= HIGH → create IDEA-fix task; else proceed to SYNTH | +| GC loop limit | Max 2 rounds | Exceeds limit → force convergence to SYNTH | +| Pipeline stall | No ready + no running | Check missing tasks, report to user | + +## Completion Conditions + +| Mode | Completion Condition | +|------|---------------------| +| quick | All 3 tasks completed | +| deep | All 6 tasks (+ any skipped GC tasks) completed | +| full | All 7 tasks (+ any skipped GC tasks) completed | + +## Shared State (meta.json) + +| Role | State Key | +|------|-----------| +| ideator | `generated_ideas` | +| challenger | `critique_insights` | +| synthesizer | `synthesis_themes` | +| evaluator | `evaluation_scores` | + +## Message Types + +| Role | Types | +|------|-------| +| coordinator | `pipeline_selected`, `gc_loop_trigger`, `task_unblocked`, `error`, `shutdown` | +| ideator | `ideas_ready`, `ideas_revised`, `error` | +| challenger | `critique_ready`, `error` | +| synthesizer | `synthesis_ready`, `error` | +| evaluator | `evaluation_ready`, `error` | diff --git a/.claude/skills/team-coordinate/SKILL.md b/.claude/skills/team-coordinate/SKILL.md index 0304a209..fbfd9b1e 100644 --- a/.claude/skills/team-coordinate/SKILL.md +++ b/.claude/skills/team-coordinate/SKILL.md @@ -150,40 +150,6 @@ AskUserQuestion({ --- -## Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker A] Phase 1-5 - | (parallel OK) --+--> [team-worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? --> spawn team-worker B directly - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -**Pipelines are dynamic**: Unlike static pipeline definitions, team-coordinate pipelines are generated per-task from the dependency graph. - ---- - ## Session Directory ``` diff --git a/.claude/skills/team-coordinate/specs/pipelines.md b/.claude/skills/team-coordinate/specs/pipelines.md new file mode 100644 index 00000000..2b91cd49 --- /dev/null +++ b/.claude/skills/team-coordinate/specs/pipelines.md @@ -0,0 +1,83 @@ +# Pipeline Definitions — Team Coordinate + +## Dynamic Pipeline Model + +team-coordinate does NOT have a static pipeline. All pipelines are generated at runtime from task-analysis.json based on the user's task description. + +## Pipeline Generation Process + +``` +Phase 1: analyze-task.md + -> Signal detection -> capability mapping -> dependency graph + -> Output: task-analysis.json + +Phase 2: dispatch.md + -> Read task-analysis.json dependency graph + -> Create TaskCreate entries per dependency node + -> Set blockedBy chains from graph edges + -> Output: TaskList with correct DAG + +Phase 3-N: monitor.md + -> handleSpawnNext: spawn ready tasks as team-worker agents + -> handleCallback: mark completed, advance pipeline + -> Repeat until all tasks done +``` + +## Dynamic Task Naming + +| Capability | Prefix | Example | +|------------|--------|---------| +| researcher | RESEARCH | RESEARCH-001 | +| developer | IMPL | IMPL-001 | +| analyst | ANALYSIS | ANALYSIS-001 | +| designer | DESIGN | DESIGN-001 | +| tester | TEST | TEST-001 | +| writer | DRAFT | DRAFT-001 | +| planner | PLAN | PLAN-001 | +| (default) | TASK | TASK-001 | + +## Dependency Graph Structure + +task-analysis.json encodes the pipeline: + +```json +{ + "dependency_graph": { + "RESEARCH-001": { "role": "researcher", "blockedBy": [], "priority": "P0" }, + "IMPL-001": { "role": "developer", "blockedBy": ["RESEARCH-001"], "priority": "P1" }, + "TEST-001": { "role": "tester", "blockedBy": ["IMPL-001"], "priority": "P2" } + } +} +``` + +## Role-Worker Map + +Dynamic — loaded from session role-specs at runtime: + +``` +<session>/role-specs/<role-name>.md -> team-worker agent +``` + +Role-spec files contain YAML frontmatter: +```yaml +--- +role: <role-name> +prefix: <PREFIX> +inner_loop: <true|false> +message_types: + success: <type> + error: error +--- +``` + +## Checkpoint + +| Trigger | Behavior | +|---------|----------| +| capability_gap reported | handleAdapt: generate new role-spec, spawn new worker | +| consensus_blocked HIGH | Create REVISION task or pause for user | +| All tasks complete | handleComplete: interactive completion action | + +## Specs Reference + +- [role-spec-template.md](role-spec-template.md) — Template for generating dynamic role-specs diff --git a/.claude/skills/team-designer/SKILL.md b/.claude/skills/team-designer/SKILL.md new file mode 100644 index 00000000..7d11c5c7 --- /dev/null +++ b/.claude/skills/team-designer/SKILL.md @@ -0,0 +1,153 @@ +--- +name: team-designer +description: Meta-skill for generating team skills following the v4 architecture pattern. Produces complete skill packages with SKILL.md router, coordinator, worker roles, specs, and templates. Triggers on "team-designer", "design team". +allowed-tools: Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +--- + +# Team Skill Designer + +Generate complete team skills following the team-lifecycle-v4 architecture: SKILL.md as universal router, coordinator with beat model, worker roles with optional commands/, shared specs, and templates. + +## Architecture Overview + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Team Skill Designer (SKILL.md) │ +│ → Orchestrator: gather requirements, generate files, validate │ +└───────────────────────────┬──────────────────────────────────────┘ + │ + ┌───────────┬───────────┼───────────┬───────────┐ + ↓ ↓ ↓ ↓ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ Phase 1 │ │ Phase 2 │ │ Phase 3 │ │ Phase 4 │ +│ Require │ │ Scaffold│ │ Content │ │ Valid │ +│ Analysis│ │ Gen │ │ Gen │ │ & Report│ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ + ↓ ↓ ↓ ↓ + teamConfig SKILL.md roles/ Validated + + dirs specs/ skill pkg + templates/ +``` + +## Key Design Principles + +1. **v4 Architecture Compliance**: Generated skills follow team-lifecycle-v4 pattern — SKILL.md = pure router, beat model = coordinator-only, unified structure (roles/ + specs/ + templates/) +2. **Golden Sample Reference**: Uses `team-lifecycle-v4` as reference implementation at `.claude/skills/team-lifecycle-v4/` +3. **Intelligent Commands Distribution**: Auto-determines which roles need `commands/` (2+ commands) vs inline logic (1 command) +4. **team-worker Compatibility**: Role.md files include correct YAML frontmatter for team-worker agent parsing + +## Execution Flow + +``` +Input Parsing: + └─ Parse user requirements (skill name, roles, pipelines, domain) + +Phase 1: Requirements Analysis + └─ Ref: phases/01-requirements-analysis.md + ├─ Tasks: Detect input → Gather roles → Define pipelines → Build teamConfig + └─ Output: teamConfig + +Phase 2: Scaffold Generation + └─ Ref: phases/02-scaffold-generation.md + ├─ Tasks: Create dirs → Generate SKILL.md router → Verify + └─ Output: SKILL.md + directory structure + +Phase 3: Content Generation + └─ Ref: phases/03-content-generation.md + ├─ Tasks: Coordinator → Workers → Specs → Templates + └─ Output: roles/**/*.md, specs/*.md, templates/*.md + +Phase 4: Validation + └─ Ref: phases/04-validation.md + └─ Output: Validation report (PASS/REVIEW/FAIL) + +Return: + └─ Summary with skill location and usage instructions +``` + +**Phase Reference Documents** (read on-demand when phase executes): + +| Phase | Document | Purpose | +|-------|----------|---------| +| 1 | [phases/01-requirements-analysis.md](phases/01-requirements-analysis.md) | Gather team skill requirements, build teamConfig | +| 2 | [phases/02-scaffold-generation.md](phases/02-scaffold-generation.md) | Generate SKILL.md router and directory structure | +| 3 | [phases/03-content-generation.md](phases/03-content-generation.md) | Generate coordinator, workers, specs, templates | +| 4 | [phases/04-validation.md](phases/04-validation.md) | Validate structure, references, and consistency | + +## Golden Sample + +Generated skills follow the architecture of `.claude/skills/team-lifecycle-v4/`: + +``` +.claude/skills/<skill-name>/ +├── SKILL.md # Universal router (all roles read) +├── roles/ +│ ├── coordinator/ +│ │ ├── role.md # Orchestrator + beat model + entry router +│ │ └── commands/ +│ │ ├── analyze.md # Task analysis +│ │ ├── dispatch.md # Task chain creation +│ │ └── monitor.md # Beat control + callbacks +│ ├── <inline-worker>/ +│ │ └── role.md # Phase 2-4 embedded (simple role) +│ └── <command-worker>/ +│ ├── role.md # Phase 2-4 dispatcher +│ └── commands/ +│ ├── <cmd-1>.md +│ └── <cmd-2>.md +├── specs/ +│ ├── pipelines.md # Pipeline definitions + task registry +│ └── <domain-specs>.md # Domain-specific specifications +└── templates/ # Optional document templates +``` + +## Data Flow + +``` +User Input (skill name, roles, pipelines) + ↓ +Phase 1: Requirements Analysis + ↓ Output: teamConfig + ↓ +Phase 2: Scaffold Generation + ↓ Input: teamConfig + ↓ Output: SKILL.md + skillDir + ↓ +Phase 3: Content Generation + ↓ Input: teamConfig + skillDir + ↓ Output: roles/, specs/, templates/ + ↓ +Phase 4: Validation + ↓ Input: teamConfig + all files + ↓ Output: validation report + ↓ +Return summary to user +``` + +## Core Rules + +1. **Start Immediately**: First action is Phase 1 execution +2. **Parse Every Output**: Extract teamConfig from Phase 1 for subsequent phases +3. **Auto-Continue**: After each phase, automatically execute next phase +4. **Progressive Phase Loading**: Read phase docs ONLY when that phase is about to execute +5. **Golden Sample Fidelity**: Generated files must match team-lifecycle-v4 patterns +6. **DO NOT STOP**: Continuous workflow until all 4 phases complete + +## Input Processing + +Convert user input to structured format: + +``` +SKILL_NAME: [kebab-case name, e.g., team-code-review] +DOMAIN: [what this team does, e.g., "multi-stage code review with security analysis"] +ROLES: [worker roles beyond coordinator, e.g., "analyst, reviewer, security-expert"] +PIPELINES: [pipeline types and flows, e.g., "review-only: SCAN-001 → REVIEW-001 → REPORT-001"] +SESSION_PREFIX: [3-4 char, e.g., TCR] +``` + +## Error Handling + +- **Invalid role name**: Must be lowercase alphanumeric with hyphens, max 20 chars +- **Circular dependencies**: Detect and report in pipeline validation +- **Missing golden sample**: Fall back to embedded templates in phase files +- **Directory conflict**: Warn if skill directory already exists, ask user to confirm overwrite diff --git a/.claude/skills/team-designer/phases/01-requirements-analysis.md b/.claude/skills/team-designer/phases/01-requirements-analysis.md new file mode 100644 index 00000000..848d3db0 --- /dev/null +++ b/.claude/skills/team-designer/phases/01-requirements-analysis.md @@ -0,0 +1,265 @@ +# Phase 1: Requirements Analysis + +Gather team skill requirements from user input and build the `teamConfig` data structure that drives all subsequent phases. + +## Objective + +- Parse user input (text description, reference skill, or interactive) +- Determine roles, pipelines, specs, templates +- Auto-decide commands distribution (inline vs commands/ folder) +- Build comprehensive `teamConfig` object +- Confirm with user before proceeding + +## Step 1.1: Detect Input Source + +```javascript +function detectInputSource(userInput) { + // Source A: Reference to existing skill + if (userInput.includes('based on') || userInput.includes('参考') || userInput.includes('like')) { + return { type: 'reference', refSkill: extractSkillName(userInput) }; + } + // Source B: Structured input with roles/pipelines + if (userInput.includes('ROLES:') || userInput.includes('PIPELINES:')) { + return { type: 'structured', data: parseStructuredInput(userInput) }; + } + // Source C: Natural language description + return { type: 'natural', description: userInput }; +} +``` + +**For reference source**: Read the referenced skill's SKILL.md and role files to extract structure. + +**For natural language**: Use AskUserQuestion to gather missing details interactively. + +## Step 1.2: Gather Core Identity + +```javascript +const coreIdentity = AskUserQuestion({ + questions: [ + { + question: "团队技能名称?(kebab-case, e.g., team-code-review)", + header: "Skill Name", + multiSelect: false, + options: [ + { label: suggestedName, description: "Auto-suggested from description" }, + { label: "Custom", description: "Enter custom name" } + ] + }, + { + question: "会话前缀?(3-4字符用于任务ID, e.g., TCR)", + header: "Prefix", + multiSelect: false, + options: [ + { label: suggestedPrefix, description: "Auto-suggested" }, + { label: "Custom", description: "Enter custom prefix" } + ] + } + ] +}); +``` + +If user provided clear name/prefix in input, skip this step. + +## Step 1.3: Determine Roles + +### Role Discovery from Domain + +Analyze domain description to identify required roles: + +```javascript +function discoverRoles(domain) { + const rolePatterns = { + 'analyst': ['分析', 'analyze', 'research', 'explore', 'investigate', 'scan'], + 'planner': ['规划', 'plan', 'design', 'architect', 'decompose'], + 'writer': ['文档', 'write', 'document', 'draft', 'spec', 'report'], + 'executor': ['实现', 'implement', 'execute', 'build', 'code', 'develop'], + 'tester': ['测试', 'test', 'verify', 'validate', 'qa'], + 'reviewer': ['审查', 'review', 'quality', 'check', 'audit', 'inspect'], + 'security-expert': ['安全', 'security', 'vulnerability', 'penetration'], + 'performance-optimizer': ['性能', 'performance', 'optimize', 'benchmark'], + 'data-engineer': ['数据', 'data', 'pipeline', 'etl', 'migration'], + 'devops-engineer': ['部署', 'devops', 'deploy', 'ci/cd', 'infrastructure'], + }; + + const matched = []; + for (const [role, keywords] of Object.entries(rolePatterns)) { + if (keywords.some(kw => domain.toLowerCase().includes(kw))) { + matched.push(role); + } + } + return matched; +} +``` + +### Role Configuration + +For each discovered role, determine: + +```javascript +function configureRole(roleName) { + return { + name: roleName, + prefix: determinePrefix(roleName), + inner_loop: determineInnerLoop(roleName), + hasCommands: false, // determined in Step 1.5 + commands: [], + message_types: determineMessageTypes(roleName), + path: `roles/${roleName}/role.md` + }; +} + +// Standard prefix mapping +const prefixMap = { + 'analyst': 'RESEARCH', + 'writer': 'DRAFT', + 'planner': 'PLAN', + 'executor': 'IMPL', + 'tester': 'TEST', + 'reviewer': 'REVIEW', + // Dynamic roles use uppercase role name +}; + +// Inner loop: roles that process multiple tasks sequentially +const innerLoopRoles = ['executor', 'writer', 'planner']; + +// Message types the role handles +const messageMap = { + 'analyst': ['state_update'], + 'writer': ['state_update', 'discuss_response'], + 'planner': ['state_update'], + 'executor': ['state_update', 'revision_request'], + 'tester': ['state_update'], + 'reviewer': ['state_update', 'discuss_request'], +}; +``` + +## Step 1.4: Define Pipelines + +### Pipeline Types from Role Combination + +```javascript +function definePipelines(roles, domain) { + const has = name => roles.some(r => r.name === name); + + // Full lifecycle: analyst → writer → planner → executor → tester → reviewer + if (has('analyst') && has('writer') && has('planner') && has('executor')) + return [{ name: 'full-lifecycle', tasks: buildFullLifecycleTasks(roles) }]; + + // Spec-only: analyst → writer → reviewer + if (has('analyst') && has('writer') && !has('executor')) + return [{ name: 'spec-only', tasks: buildSpecOnlyTasks(roles) }]; + + // Impl-only: planner → executor → tester → reviewer + if (has('planner') && has('executor') && !has('analyst')) + return [{ name: 'impl-only', tasks: buildImplOnlyTasks(roles) }]; + + // Custom: user-defined + return [{ name: 'custom', tasks: buildCustomTasks(roles, domain) }]; +} +``` + +### Task Schema + +```javascript +const taskSchema = { + id: 'PREFIX-NNN', // e.g., RESEARCH-001 + role: 'analyst', // which role executes + name: 'Seed Analysis', // human-readable name + dependsOn: [], // task IDs that must complete first + isCheckpoint: false, // true for quality gates + isConditional: false, // true for routing decisions + description: '...' +}; +``` + +## Step 1.5: Determine Commands Distribution + +**Rule**: 1 action → inline in role.md. 2+ distinct actions → commands/ folder. + +```javascript +function determineCommandsDistribution(roles) { + // Coordinator: always has commands/ + // coordinator.commands = ['analyze', 'dispatch', 'monitor'] + + // Standard multi-action roles: + // executor → implement + fix → commands/ + // reviewer (if both code & spec review) → review-code + review-spec → commands/ + // All others → typically inline + + for (const role of roles) { + const actions = countDistinctActions(role); + if (actions.length >= 2) { + role.hasCommands = true; + role.commands = actions.map(a => a.name); + } + } +} +``` + +## Step 1.6: Determine Specs and Templates + +```javascript +// Specs: always include pipelines, add domain-specific +const specs = ['pipelines']; +if (hasQualityGates) specs.push('quality-gates'); +if (hasKnowledgeTransfer) specs.push('knowledge-transfer'); + +// Templates: only if writer role exists +const templates = []; +if (has('writer')) { + // Detect from domain keywords + if (domain.includes('product')) templates.push('product-brief'); + if (domain.includes('requirement')) templates.push('requirements'); + if (domain.includes('architecture')) templates.push('architecture'); + if (domain.includes('epic')) templates.push('epics'); +} +``` + +## Step 1.7: Build teamConfig + +```javascript +const teamConfig = { + skillName: string, // e.g., "team-code-review" + sessionPrefix: string, // e.g., "TCR" + domain: string, // domain description + title: string, // e.g., "Code Review Team" + roles: Array<RoleConfig>, // includes coordinator + pipelines: Array<Pipeline>, + specs: Array<string>, // filenames without .md + templates: Array<string>, // filenames without .md + conditionalRouting: boolean, + dynamicSpecialists: Array<string>, +}; +``` + +## Step 1.8: Confirm with User + +``` +╔══════════════════════════════════════════╗ +║ Team Skill Configuration Summary ║ +╠══════════════════════════════════════════╣ + +Skill Name: ${skillName} +Session Prefix: ${sessionPrefix} +Domain: ${domain} + +Roles (N): + ├─ coordinator (commands: analyze, dispatch, monitor) + ├─ role-a [PREFIX-*] (inline) 🔄 + └─ role-b [PREFIX-*] (commands: cmd1, cmd2) + +Pipelines: + └─ pipeline-name: TASK-001 → TASK-002 → TASK-003 + +Specs: pipelines, quality-gates +Templates: (none) + +╚══════════════════════════════════════════╝ +``` + +Use AskUserQuestion to confirm or allow modifications. + +## Output + +- **Variable**: `teamConfig` — complete configuration for all subsequent phases +- **Next**: Phase 2 - Scaffold Generation diff --git a/.claude/skills/team-designer/phases/02-scaffold-generation.md b/.claude/skills/team-designer/phases/02-scaffold-generation.md new file mode 100644 index 00000000..2af0193d --- /dev/null +++ b/.claude/skills/team-designer/phases/02-scaffold-generation.md @@ -0,0 +1,236 @@ +# Phase 2: Scaffold Generation + +Generate the SKILL.md universal router and create the directory structure for the team skill. + +## Objective + +- Create directory structure (roles/, specs/, templates/) +- Generate SKILL.md as universal router following v4 pattern +- SKILL.md must NOT contain beat model, pipeline details, or role Phase 2-4 logic + +## Step 2.1: Create Directory Structure + +```bash +skillDir=".claude/skills/${teamConfig.skillName}" +mkdir -p "${skillDir}" + +# Create role directories +for role in teamConfig.roles: + mkdir -p "${skillDir}/roles/${role.name}" + if role.hasCommands: + mkdir -p "${skillDir}/roles/${role.name}/commands" + +# Create specs directory +mkdir -p "${skillDir}/specs" + +# Create templates directory (if needed) +if teamConfig.templates.length > 0: + mkdir -p "${skillDir}/templates" +``` + +## Step 2.2: Generate SKILL.md + +The SKILL.md follows a strict template. Every generated SKILL.md contains these sections in order: + +### Section 1: Frontmatter + +```yaml +--- +name: ${teamConfig.skillName} +description: ${teamConfig.domain}. Triggers on "${teamConfig.skillName}". +allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +--- +``` + +### Section 2: Title + Architecture Diagram + +```markdown +# ${Title} + +${One-line description} + +## Architecture + +\``` +Skill(skill="${teamConfig.skillName}", args="task description") + | + SKILL.md (this file) = Router + | + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+ + v v v v + [team-worker agents, each loads roles/<role>/role.md] +\``` +``` + +### Section 3: Role Registry + +```markdown +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | roles/coordinator/role.md | — | — | +${teamConfig.roles.filter(r => r.name !== 'coordinator').map(r => + `| ${r.name} | ${r.path} | ${r.prefix}-* | ${r.inner_loop} |` +).join('\n')} +``` + +### Section 4: Role Router + +```markdown +## Role Router + +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router +``` + +### Section 5: Shared Constants + +```markdown +## Shared Constants + +- **Session prefix**: `${teamConfig.sessionPrefix}` +- **Session path**: `.workflow/.team/${teamConfig.sessionPrefix}-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` +``` + +### Section 6: Worker Spawn Template + +```markdown +## Worker Spawn Template + +Coordinator spawns workers using this template: + +\``` +Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker", + team_name: <team-name>, + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/${teamConfig.skillName}/roles/<role>/role.md +session: <session-folder> +session_id: <session-id> +team_name: <team-name> +requirement: <task-description> +inner_loop: <true|false> + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` +}) +\``` +``` + +### Section 7: User Commands + +```markdown +## User Commands + +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | +| `revise <TASK-ID> [feedback]` | Revise specific task | +| `feedback <text>` | Inject feedback for revision | +| `recheck` | Re-run quality check | +| `improve [dimension]` | Auto-improve weakest dimension | +``` + +### Section 8: Completion Action + +```markdown +## Completion Action + +When pipeline completes, coordinator presents: + +\``` +AskUserQuestion({ + questions: [{ + question: "Pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory" } + ] + }] +}) +\``` +``` + +### Section 9: Specs Reference + +```markdown +## Specs Reference + +${teamConfig.specs.map(s => + `- [specs/${s}.md](specs/${s}.md) — ${specDescription(s)}` +).join('\n')} +``` + +### Section 10: Session Directory + +```markdown +## Session Directory + +\``` +.workflow/.team/${teamConfig.sessionPrefix}-<slug>-<date>/ +├── team-session.json # Session state + role registry +├── spec/ # Spec phase outputs +├── plan/ # Implementation plan + TASK-*.json +├── artifacts/ # All deliverables +├── wisdom/ # Cross-task knowledge +├── explorations/ # Shared explore cache +├── discussions/ # Discuss round records +└── .msg/ # Team message bus +\``` +``` + +### Section 11: Error Handling + +```markdown +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| CLI tool fails | Worker fallback to direct implementation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | +``` + +## Step 2.3: Assemble and Write + +Assemble all sections into a single SKILL.md file and write to `${skillDir}/SKILL.md`. + +**Quality Rules**: +1. SKILL.md must NOT contain beat model (ONE_STEP_PER_INVOCATION, spawn-and-stop) +2. SKILL.md must NOT contain pipeline task details (task IDs, dependencies) +3. SKILL.md must NOT contain role Phase 2-4 logic +4. SKILL.md MUST contain role registry table with correct paths +5. SKILL.md MUST contain worker spawn template with correct `role_spec` paths + +## Output + +- **File**: `.claude/skills/${teamConfig.skillName}/SKILL.md` +- **Variable**: `skillDir` (path to skill root directory) +- **Next**: Phase 3 - Content Generation + +## Next Phase + +Return to orchestrator, then auto-continue to [Phase 3: Content Generation](03-content-generation.md). diff --git a/.claude/skills/team-designer/phases/03-content-generation.md b/.claude/skills/team-designer/phases/03-content-generation.md new file mode 100644 index 00000000..b891db51 --- /dev/null +++ b/.claude/skills/team-designer/phases/03-content-generation.md @@ -0,0 +1,330 @@ +# Phase 3: Content Generation + +Generate all role files, specs, and templates based on `teamConfig` and the generated SKILL.md. + +## Objective + +- Generate coordinator role.md + commands/ (analyze, dispatch, monitor) +- Generate each worker role.md (inline or with commands/) +- Generate specs/ files (pipelines.md + domain specs) +- Generate templates/ if needed +- Follow team-lifecycle-v4 golden sample patterns + +## Golden Sample Reference + +Read the golden sample at `.claude/skills/team-lifecycle-v4/` for each file type before generating. This ensures pattern fidelity. + +## Step 3.1: Generate Coordinator + +The coordinator is the most complex role. It always has 3 commands. + +### coordinator/role.md + +```markdown +--- +role: coordinator +--- + +# Coordinator — ${teamConfig.title} + +## Identity + +You are the coordinator for ${teamConfig.title}. You orchestrate the ${teamConfig.domain} pipeline by analyzing requirements, dispatching tasks, and monitoring worker progress. + +## Boundaries + +- **DO**: Analyze, dispatch, monitor, reconcile, report +- **DO NOT**: Implement domain work directly — delegate to workers + +## Command Execution Protocol + +Read command file → Execute ALL steps sequentially → Return to entry router. +Commands: `commands/analyze.md`, `commands/dispatch.md`, `commands/monitor.md`. + +## Entry Router + +On each invocation, detect current state and route: + +| Condition | Handler | +|-----------|---------| +| First invocation (no session) | → Phase 1: Requirement Clarification | +| Session exists, no team | → Phase 2: Team Setup | +| Team exists, no tasks | → Phase 3: Dispatch (analyze.md → dispatch.md) | +| Tasks exist, none started | → Phase 4: Spawn First (monitor.md → handleSpawnNext) | +| Callback received | → monitor.md → handleCallback | +| User says "check"/"status" | → monitor.md → handleCheck | +| User says "resume"/"continue" | → monitor.md → handleResume | +| All tasks completed | → Phase 5: Report & Completion | + +## Phase 0: Session Resume + +If `.workflow/.team/${teamConfig.sessionPrefix}-*/team-session.json` exists: +- Load session state, verify team, reconcile task status +- Route to appropriate handler based on current state + +## Phase 1: Requirement Clarification + +- Parse user's task description at TEXT LEVEL +- Use AskUserQuestion if requirements are ambiguous +- Execute `commands/analyze.md` for signal detection + complexity scoring + +## Phase 2: Team Setup + +- TeamCreate with session ID: `${teamConfig.sessionPrefix}-<slug>-<date>` +- Initialize team_msg message bus +- Create session directory structure + +## Phase 3: Dispatch + +- Execute `commands/dispatch.md` +- Creates TaskCreate calls with blockedBy dependencies + +## Phase 4: Spawn & Monitor + +- Execute `commands/monitor.md` → handleSpawnNext +- Spawn ready workers as team-worker agents +- **STOP after spawning** — wait for callback + +## Phase 5: Report & Completion + +- Aggregate all task artifacts +- Present completion action to user +``` + +### coordinator/commands/analyze.md + +Template based on golden sample — includes: +- Signal detection (keywords → capabilities) +- Dependency graph construction (tiers) +- Complexity scoring (1-3 Low, 4-6 Medium, 7+ High) +- Role minimization (cap at 5) +- Output: task-analysis.json + +```markdown +# Command: Analyze + +## Signal Detection + +Scan requirement text for capability signals: +${teamConfig.roles.filter(r => r.name !== 'coordinator').map(r => + `- **${r.name}**: [domain-specific keywords]` +).join('\n')} + +## Dependency Graph + +Build 4-tier dependency graph: +- Tier 0: Independent tasks (can run in parallel) +- Tier 1: Depends on Tier 0 +- Tier 2: Depends on Tier 1 +- Tier 3: Depends on Tier 2 + +## Complexity Scoring + +| Score | Level | Strategy | +|-------|-------|----------| +| 1-3 | Low | Direct implementation, skip deep planning | +| 4-6 | Medium | Standard pipeline with planning | +| 7+ | High | Full spec → plan → implement cycle | + +## Output + +Write `task-analysis.json` to session directory: +\```json +{ + "signals": [...], + "roles_needed": [...], + "dependency_tiers": [...], + "complexity": { "score": N, "level": "Low|Medium|High" }, + "pipeline": "${teamConfig.pipelines[0].name}" +} +\``` +``` + +### coordinator/commands/dispatch.md + +Template — includes: +- Topological sort from dependency graph +- TaskCreate with blockedBy +- Task description template (PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS) + +### coordinator/commands/monitor.md + +Template — includes: +- Beat model constants (ONE_STEP_PER_INVOCATION, SPAWN_MODE: spawn-and-stop) +- 6 handlers: handleCallback, handleCheck, handleResume, handleSpawnNext, handleComplete, handleAdapt +- Checkpoint detection for quality gates +- Fast-advance reconciliation + +**Critical**: This is the ONLY file that contains beat model logic. + +## Step 3.2: Generate Worker Roles + +For each worker role in `teamConfig.roles`: + +### Inline Role Template (no commands/) + +```markdown +--- +role: ${role.name} +prefix: ${role.prefix} +inner_loop: ${role.inner_loop} +message_types: [${role.message_types.join(', ')}] +--- + +# ${capitalize(role.name)} — ${teamConfig.title} + +## Identity + +You are the ${role.name} for ${teamConfig.title}. +Task prefix: `${role.prefix}-*` + +## Phase 2: Context Loading + +- Read task description from TaskGet +- Load relevant session artifacts from session directory +- Load specs from `specs/` as needed + +## Phase 3: Domain Execution + +[Domain-specific execution logic for this role] + +### Execution Steps + +1. [Step 1 based on role's domain] +2. [Step 2] +3. [Step 3] + +### Tools Available + +- CLI tools: `ccw cli --mode analysis|write` +- Direct tools: Read, Write, Edit, Bash, Grep, Glob +- Message bus: `mcp__ccw-tools__team_msg` +- **Cannot use Agent()** — workers must use CLI or direct tools + +## Phase 4: Output & Report + +- Write artifacts to session directory +- Log state_update via team_msg +- Publish wisdom if cross-task knowledge discovered +``` + +### Command-Based Role Template (has commands/) + +```markdown +--- +role: ${role.name} +prefix: ${role.prefix} +inner_loop: ${role.inner_loop} +message_types: [${role.message_types.join(', ')}] +--- + +# ${capitalize(role.name)} — ${teamConfig.title} + +## Identity + +You are the ${role.name} for ${teamConfig.title}. +Task prefix: `${role.prefix}-*` + +## Phase 2: Context Loading + +Load task description, detect mode/command. + +## Phase 3: Command Router + +| Condition | Command | +|-----------|---------| +${role.commands.map(cmd => + `| [condition for ${cmd}] | → commands/${cmd}.md |` +).join('\n')} + +Read command file → Execute ALL steps → Return to Phase 4. + +## Phase 4: Output & Report + +Write artifacts, log state_update. +``` + +Then generate each `commands/<cmd>.md` with domain-specific logic. + +## Step 3.3: Generate Specs + +### specs/pipelines.md + +```markdown +# Pipeline Definitions + +## Available Pipelines + +${teamConfig.pipelines.map(p => ` +### ${p.name} + +| Task ID | Role | Name | Depends On | Checkpoint | +|---------|------|------|------------|------------| +${p.tasks.map(t => + `| ${t.id} | ${t.role} | ${t.name} | ${t.dependsOn.join(', ') || '—'} | ${t.isCheckpoint ? '✓' : '—'} |` +).join('\n')} +`).join('\n')} + +## Task Metadata Registry + +Standard task description template: + +\``` +PURPOSE: [goal] +TASK: [steps] +CONTEXT: [session artifacts + specs] +EXPECTED: [deliverable format] +CONSTRAINTS: [scope limits] +\``` + +## Conditional Routing + +${teamConfig.conditionalRouting ? ` +PLAN-001 complexity assessment routes to: +- Low (1-3): Direct implementation +- Medium (4-6): Standard planning +- High (7+): Full spec → plan → implement +` : 'No conditional routing in this pipeline.'} + +## Dynamic Specialist Injection + +${teamConfig.dynamicSpecialists.length > 0 ? + teamConfig.dynamicSpecialists.map(s => `- ${s}: Injected when domain keywords detected`).join('\n') : + 'No dynamic specialists configured.' +} +``` + +### Additional Specs + +For each additional spec in `teamConfig.specs` (beyond pipelines), generate domain-appropriate content: + +- **quality-gates.md**: Thresholds (Pass≥80%, Review 60-79%, Fail<60%), scoring dimensions, per-phase gates +- **knowledge-transfer.md**: 5 transfer channels, Phase 2 loading protocol, Phase 4 publishing protocol + +## Step 3.4: Generate Templates + +For each template in `teamConfig.templates`: + +1. Check if golden sample has matching template at `.claude/skills/team-lifecycle-v4/templates/` +2. If exists: copy and adapt for new domain +3. If not: generate domain-appropriate template structure + +## Step 3.5: Generation Order + +Execute in this order (respects dependencies): + +1. **specs/** — needed by roles for reference +2. **coordinator/** — role.md + commands/ (3 files) +3. **workers/** — each role.md (+ optional commands/) +4. **templates/** — independent, generate last + +For each file: +1. Read golden sample equivalent (if exists) +2. Adapt content for current teamConfig +3. Write file +4. Verify file exists + +## Output + +- **Files**: All role.md, commands/*.md, specs/*.md, templates/*.md +- **Next**: Phase 4 - Validation diff --git a/.claude/skills/team-designer/phases/04-validation.md b/.claude/skills/team-designer/phases/04-validation.md new file mode 100644 index 00000000..650f6644 --- /dev/null +++ b/.claude/skills/team-designer/phases/04-validation.md @@ -0,0 +1,329 @@ +# Phase 4: Validation + +Validate the generated team skill package for structural completeness, reference integrity, role consistency, and team-worker compatibility. + +## Objective + +- Verify all required files exist +- Validate SKILL.md role registry matches actual role files +- Check role.md frontmatter format for team-worker compatibility +- Verify pipeline task references match existing roles +- Report validation results + +## Step 4.1: Structural Validation + +```javascript +function validateStructure(teamConfig) { + const skillDir = `.claude/skills/${teamConfig.skillName}`; + const results = { errors: [], warnings: [], info: [] }; + + // Check SKILL.md exists + if (!fileExists(`${skillDir}/SKILL.md`)) { + results.errors.push('SKILL.md not found'); + } + + // Check coordinator structure + if (!fileExists(`${skillDir}/roles/coordinator/role.md`)) { + results.errors.push('Coordinator role.md not found'); + } + for (const cmd of ['analyze', 'dispatch', 'monitor']) { + if (!fileExists(`${skillDir}/roles/coordinator/commands/${cmd}.md`)) { + results.errors.push(`Coordinator command ${cmd}.md not found`); + } + } + + // Check worker roles + for (const role of teamConfig.roles.filter(r => r.name !== 'coordinator')) { + if (!fileExists(`${skillDir}/roles/${role.name}/role.md`)) { + results.errors.push(`Worker role.md not found: ${role.name}`); + } + if (role.hasCommands) { + for (const cmd of role.commands) { + if (!fileExists(`${skillDir}/roles/${role.name}/commands/${cmd}.md`)) { + results.errors.push(`Worker command not found: ${role.name}/commands/${cmd}.md`); + } + } + } + } + + // Check specs + if (!fileExists(`${skillDir}/specs/pipelines.md`)) { + results.errors.push('specs/pipelines.md not found'); + } + + return results; +} +``` + +## Step 4.2: SKILL.md Content Validation + +```javascript +function validateSkillMd(teamConfig) { + const skillDir = `.claude/skills/${teamConfig.skillName}`; + const results = { errors: [], warnings: [], info: [] }; + const skillMd = Read(`${skillDir}/SKILL.md`); + + // Required sections + const requiredSections = [ + 'Role Registry', 'Role Router', 'Shared Constants', + 'Worker Spawn Template', 'User Commands', 'Session Directory' + ]; + for (const section of requiredSections) { + if (!skillMd.includes(section)) { + results.errors.push(`SKILL.md missing section: ${section}`); + } + } + + // Verify role registry completeness + for (const role of teamConfig.roles) { + if (!skillMd.includes(role.path || `roles/${role.name}/role.md`)) { + results.errors.push(`Role registry missing path for: ${role.name}`); + } + } + + // Verify session prefix + if (!skillMd.includes(teamConfig.sessionPrefix)) { + results.warnings.push(`Session prefix ${teamConfig.sessionPrefix} not found in SKILL.md`); + } + + // Verify NO beat model content in SKILL.md + const beatModelPatterns = [ + 'ONE_STEP_PER_INVOCATION', + 'spawn-and-stop', + 'SPAWN_MODE', + 'handleCallback', + 'handleSpawnNext' + ]; + for (const pattern of beatModelPatterns) { + if (skillMd.includes(pattern)) { + results.errors.push(`SKILL.md contains beat model content: ${pattern} (should be in coordinator only)`); + } + } + + return results; +} +``` + +## Step 4.3: Role Frontmatter Validation + +Verify role.md files have correct YAML frontmatter for team-worker agent compatibility: + +```javascript +function validateRoleFrontmatter(teamConfig) { + const skillDir = `.claude/skills/${teamConfig.skillName}`; + const results = { errors: [], warnings: [], info: [] }; + + for (const role of teamConfig.roles.filter(r => r.name !== 'coordinator')) { + const roleMd = Read(`${skillDir}/roles/${role.name}/role.md`); + + // Check frontmatter exists + if (!roleMd.startsWith('---')) { + results.errors.push(`${role.name}/role.md missing YAML frontmatter`); + continue; + } + + // Extract frontmatter + const fmMatch = roleMd.match(/^---\n([\s\S]*?)\n---/); + if (!fmMatch) { + results.errors.push(`${role.name}/role.md malformed frontmatter`); + continue; + } + + const fm = fmMatch[1]; + + // Required fields + if (!fm.includes(`role: ${role.name}`)) { + results.errors.push(`${role.name}/role.md frontmatter missing 'role: ${role.name}'`); + } + if (!fm.includes(`prefix: ${role.prefix}`)) { + results.errors.push(`${role.name}/role.md frontmatter missing 'prefix: ${role.prefix}'`); + } + if (!fm.includes(`inner_loop: ${role.inner_loop}`)) { + results.warnings.push(`${role.name}/role.md frontmatter missing 'inner_loop: ${role.inner_loop}'`); + } + if (!fm.includes('message_types:')) { + results.warnings.push(`${role.name}/role.md frontmatter missing 'message_types'`); + } + } + + return results; +} +``` + +## Step 4.4: Pipeline Consistency + +```javascript +function validatePipelines(teamConfig) { + const skillDir = `.claude/skills/${teamConfig.skillName}`; + const results = { errors: [], warnings: [], info: [] }; + + // Check every role referenced in pipelines exists + const definedRoles = new Set(teamConfig.roles.map(r => r.name)); + + for (const pipeline of teamConfig.pipelines) { + for (const task of pipeline.tasks) { + if (!definedRoles.has(task.role)) { + results.errors.push( + `Pipeline '${pipeline.name}' task ${task.id} references undefined role: ${task.role}` + ); + } + } + + // Check for circular dependencies + const visited = new Set(); + const stack = new Set(); + for (const task of pipeline.tasks) { + if (hasCycle(task, pipeline.tasks, visited, stack)) { + results.errors.push(`Pipeline '${pipeline.name}' has circular dependency involving ${task.id}`); + } + } + } + + // Verify specs/pipelines.md contains all pipelines + const pipelinesMd = Read(`${skillDir}/specs/pipelines.md`); + for (const pipeline of teamConfig.pipelines) { + if (!pipelinesMd.includes(pipeline.name)) { + results.warnings.push(`specs/pipelines.md missing pipeline: ${pipeline.name}`); + } + } + + return results; +} +``` + +## Step 4.5: Commands Distribution Validation + +```javascript +function validateCommandsDistribution(teamConfig) { + const skillDir = `.claude/skills/${teamConfig.skillName}`; + const results = { errors: [], warnings: [], info: [] }; + + for (const role of teamConfig.roles.filter(r => r.name !== 'coordinator')) { + if (role.hasCommands) { + // Verify commands/ directory exists and has files + const cmdDir = `${skillDir}/roles/${role.name}/commands`; + if (role.commands.length < 2) { + results.warnings.push( + `${role.name} has commands/ but only ${role.commands.length} command(s) — consider inline` + ); + } + // Verify role.md references commands + const roleMd = Read(`${skillDir}/roles/${role.name}/role.md`); + for (const cmd of role.commands) { + if (!roleMd.includes(`commands/${cmd}.md`)) { + results.warnings.push( + `${role.name}/role.md doesn't reference commands/${cmd}.md` + ); + } + } + } else { + // Verify no commands/ directory exists + const cmdDir = `${skillDir}/roles/${role.name}/commands`; + if (directoryExists(cmdDir)) { + results.warnings.push( + `${role.name} is inline but has commands/ directory` + ); + } + } + } + + return results; +} +``` + +## Step 4.6: Aggregate Results and Report + +```javascript +function generateValidationReport(teamConfig) { + const structural = validateStructure(teamConfig); + const skillMd = validateSkillMd(teamConfig); + const frontmatter = validateRoleFrontmatter(teamConfig); + const pipelines = validatePipelines(teamConfig); + const commands = validateCommandsDistribution(teamConfig); + + const allErrors = [ + ...structural.errors, ...skillMd.errors, + ...frontmatter.errors, ...pipelines.errors, ...commands.errors + ]; + const allWarnings = [ + ...structural.warnings, ...skillMd.warnings, + ...frontmatter.warnings, ...pipelines.warnings, ...commands.warnings + ]; + + const gate = allErrors.length === 0 ? 'PASS' : + allErrors.length <= 2 ? 'REVIEW' : 'FAIL'; + + const skillDir = `.claude/skills/${teamConfig.skillName}`; + + console.log(` +╔══════════════════════════════════════╗ +║ Team Skill Validation Report ║ +╠══════════════════════════════════════╣ +║ Skill: ${teamConfig.skillName.padEnd(28)}║ +║ Gate: ${gate.padEnd(28)}║ +╚══════════════════════════════════════╝ + +Structure: + ${skillDir}/ + ├── SKILL.md ✓ + ├── roles/ + │ ├── coordinator/ + │ │ ├── role.md ✓ + │ │ └── commands/ (analyze, dispatch, monitor) +${teamConfig.roles.filter(r => r.name !== 'coordinator').map(r => { + const structure = r.hasCommands + ? ` │ ├── ${r.name}/ (role.md + commands/)` + : ` │ ├── ${r.name}/role.md`; + return `${structure.padEnd(50)}✓`; +}).join('\n')} + ├── specs/ + │ └── pipelines.md ✓ + └── templates/ ${teamConfig.templates.length > 0 ? '✓' : '(empty)'} + +${allErrors.length > 0 ? `Errors (${allErrors.length}):\n${allErrors.map(e => ` ✗ ${e}`).join('\n')}` : 'Errors: None ✓'} + +${allWarnings.length > 0 ? `Warnings (${allWarnings.length}):\n${allWarnings.map(w => ` ⚠ ${w}`).join('\n')}` : 'Warnings: None ✓'} + +Usage: + Skill(skill="${teamConfig.skillName}", args="<task description>") + `); + + return { gate, errors: allErrors, warnings: allWarnings }; +} +``` + +## Step 4.7: Error Recovery + +```javascript +if (report.gate === 'FAIL') { + const recovery = AskUserQuestion({ + questions: [{ + question: `Validation found ${report.errors.length} errors. How to proceed?`, + header: "Recovery", + multiSelect: false, + options: [ + { label: "Auto-fix", description: "Attempt automatic fixes (missing files, frontmatter)" }, + { label: "Regenerate", description: "Re-run Phase 3 with fixes" }, + { label: "Accept as-is", description: "Manual fix later" } + ] + }] + }); +} +``` + +## Output + +- **Report**: Validation results with quality gate (PASS/REVIEW/FAIL) +- **Completion**: Team skill package ready at `.claude/skills/${teamConfig.skillName}/` + +## Completion + +Team Skill Designer has completed. The generated team skill is ready for use. + +``` +Next Steps: + 1. Review SKILL.md router for correctness + 2. Review each role.md for domain accuracy + 3. Test: Skill(skill="${teamConfig.skillName}", args="<test task>") + 4. Iterate based on execution results +``` diff --git a/.claude/skills/team-executor/SKILL.md b/.claude/skills/team-executor/SKILL.md index e498e23d..175dcd4d 100644 --- a/.claude/skills/team-executor/SKILL.md +++ b/.claude/skills/team-executor/SKILL.md @@ -157,38 +157,6 @@ AskUserQuestion({ --- -## Cadence Control - -**Beat model**: Event-driven, each beat = executor wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Executor Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker A] Phase 1-5 - | (parallel OK) --+--> [team-worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips executor for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? --> spawn team-worker B directly - +- complex case? --> SendMessage to executor -====================================================================== -``` - ---- - ## Integration with team-coordinate | Scenario | Skill | diff --git a/.claude/skills/team-frontend/SKILL.md b/.claude/skills/team-frontend/SKILL.md index 2be71a9a..a365cecf 100644 --- a/.claude/skills/team-frontend/SKILL.md +++ b/.claude/skills/team-frontend/SKILL.md @@ -1,111 +1,61 @@ --- name: team-frontend -description: Unified team skill for frontend development. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Built-in ui-ux-pro-max design intelligence. Triggers on "team frontend". -allowed-tools: Agent, TaskCreate, TaskList, TaskGet, TaskUpdate, TeamCreate, TeamDelete, SendMessage, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, mcp__ace-tool__search_context +description: Unified team skill for frontend development. Pure router — all roles read this file. Beat model is coordinator-only in monitor.md. Built-in ui-ux-pro-max design intelligence. Triggers on "team frontend". +allowed-tools: Agent(*), TaskCreate(*), TaskList(*), TaskGet(*), TaskUpdate(*), TeamCreate(*), TeamDelete(*), SendMessage(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), WebFetch(*), WebSearch(*), mcp__ace-tool__search_context(*) --- # Team Frontend Development -Unified team skill: frontend development with built-in ui-ux-pro-max design intelligence. Covers requirement analysis, design system generation, frontend implementation, and quality assurance. Built on **team-worker agent architecture** -- all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. +Unified team skill: frontend development with built-in ui-ux-pro-max design intelligence. Covers requirement analysis, design system generation, frontend implementation, and quality assurance. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from role.md specs. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-frontend") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-frontend", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -analyst archi- devel- qa - tect oper - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+ + v v v v + [analyst] [architect] [developer] [qa] + (team-worker agents, each loads roles/<role>/role.md) ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| analyst | [roles/analyst/role.md](roles/analyst/role.md) | ANALYZE-* | false | +| architect | [roles/architect/role.md](roles/architect/role.md) | ARCH-* | false | +| developer | [roles/developer/role.md](roles/developer/role.md) | DEV-* | true | +| qa | [roles/qa/role.md](roles/qa/role.md) | QA-* | false | + ## Role Router -This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -### Input Parsing +## Shared Constants -Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. +- **Session prefix**: `FE` +- **Session path**: `.workflow/.team/FE-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -### Role Registry +## Worker Spawn Template -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | ANALYZE-* | read_only_analysis | false | -| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | code_generation | false | -| developer | [role-specs/developer.md](role-specs/developer.md) | DEV-* | code_generation | true | -| qa | [role-specs/qa.md](role-specs/qa.md) | QA-* | read_only_analysis | false | - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User just provides task description. - -**Invocation**: -```bash -Skill(skill="team-frontend", args="<task-description>") -``` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: Parse requirements -> TeamCreate -> Create task chain - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances - -> GC loop (developer <-> qa) if fix_required (max 2 rounds) - -> All tasks complete -> Phase 5 report + completion action -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -116,7 +66,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-frontend/role-specs/<role>.md +role_spec: .claude/skills/team-frontend/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: frontend @@ -124,150 +74,16 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (developer): Set `inner_loop: true`. The team-worker agent handles the loop internally. +## User Commands -**Single-task roles** (analyst, architect, qa): Set `inner_loop: false`. - ---- - -## Pipeline Definitions - -### Pipeline Diagrams - -**Page Mode** (4 beats, linear): -``` -Pipeline: Page (Linear) -===================================================== -Stage 1 Stage 2 Stage 3 Stage 4 -ANALYZE-001 --> ARCH-001 --> DEV-001 --> QA-001 -[analyst] [architect] [developer] [qa] -``` - -**Feature Mode** (5 beats, with architecture review gate): -``` -Pipeline: Feature (Architecture Review Gate) -===================================================== -Stage 1 Stage 2 Stage 3 Stage 4 Stage 5 -ANALYZE-001 --> ARCH-001 --> QA-001 --> DEV-001 --> QA-002 -[analyst] [architect] [qa:arch-rev] [developer] [qa:code-rev] -``` - -**System Mode** (7 beats, dual-track parallel): -``` -Pipeline: System (Dual-Track Parallel) -===================================================== -Stage 1 Stage 2 Stage 3 Stage 4 (parallel) Stage 5 Stage 6 Stage 7 -ANALYZE-001 --> ARCH-001 --> QA-001 --> ARCH-002 ─┐ --> QA-002 --> DEV-002 --> QA-003 -[analyst] [architect] [qa:arch-rev] [architect] | [qa] [developer] [qa:final] - DEV-001 ──┘ - [developer:tokens] -``` - -### Generator-Critic Loop (developer <-> qa) - -``` -developer (Generator) -> QA artifact -> qa (Critic) - <- QA feedback <- - (max 2 rounds) - -Convergence: qa.score >= 8 && qa.critical_count === 0 -``` - ---- - -## Task Metadata Registry - -| Task ID | Role | Stage | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| ANALYZE-001 | analyst | analysis | (none) | Requirement analysis + design intelligence | -| ARCH-001 | architect | design | ANALYZE-001 | Design token system + component architecture | -| ARCH-002 | architect | design | QA-001 (system) | Component specs refinement | -| DEV-001 | developer | impl | ARCH-001 or QA-001 | Frontend implementation | -| DEV-002 | developer | impl | QA-002 (system) | Component implementation | -| QA-001 | qa | review | ARCH-001 or DEV-001 | Architecture or code review | -| QA-002 | qa | review | DEV-001 | Code review | -| QA-003 | qa | review | DEV-002 (system) | Final quality check | - ---- - -## ui-ux-pro-max Integration - -### Design Intelligence Engine - -Analyst role invokes ui-ux-pro-max via Skill to obtain industry design intelligence: - -| Action | Invocation | -|--------|------------| -| Full design system | `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` | -| Domain search | `Skill(skill="ui-ux-pro-max", args="<query> --domain <domain>")` | -| Tech stack guidance | `Skill(skill="ui-ux-pro-max", args="<query> --stack <stack>")` | - -**Supported Domains**: product, style, typography, color, landing, chart, ux, web -**Supported Stacks**: html-tailwind, react, nextjs, vue, svelte, shadcn, swiftui, react-native, flutter - -**Fallback**: If ui-ux-pro-max skill not installed, degrade to LLM general design knowledge. Suggest installation: `/plugin install ui-ux-pro-max@ui-ux-pro-max-skill` - ---- - -## Completion Action - -At Phase 5, coordinator offers interactive completion: - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - options: [ - { label: "Archive & Clean (Recommended)" }, - { label: "Keep Active" }, - { label: "Export Results" } - ] - }] -}) -``` - -| Choice | Steps | -|--------|-------| -| Archive & Clean | Verify completed -> update status -> TeamDelete() -> final summary | -| Keep Active | Status="paused" -> "Resume with: Skill(skill='team-frontend', args='resume')" | -| Export Results | Ask target dir -> copy artifacts -> Archive flow | - ---- - -## Message Bus - -Every SendMessage must be preceded by `mcp__ccw-tools__team_msg` log: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: <session-id>, - from: <role>, - type: <message-type>, - data: {ref: <artifact-path>} -}) -``` - -`to` and `summary` auto-defaulted -- do NOT specify explicitly. - -**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `task_unblocked`, `sync_checkpoint`, `fix_required`, `error`, `shutdown` | -| analyst | `analyze_ready`, `error` | -| architect | `arch_ready`, `arch_revision`, `error` | -| developer | `dev_complete`, `dev_progress`, `error` | -| qa | `qa_passed`, `qa_result`, `fix_required`, `error` | - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | ## Session Directory @@ -276,6 +92,7 @@ mcp__ccw-tools__team_msg({ ├── .msg/ │ ├── messages.jsonl # Message bus log │ └── meta.json # Session state + cross-role state +├── task-analysis.json # Coordinator analyze output ├── wisdom/ # Cross-task knowledge ├── analysis/ # Analyst output │ ├── design-intelligence.json @@ -289,13 +106,17 @@ mcp__ccw-tools__team_msg({ └── build/ # Developer output ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry + ## Error Handling | Scenario | Resolution | |----------|------------| | Unknown command | Error with available command list | +| Role not found | Error with role registry | | QA score < 6 over 2 GC rounds | Escalate to user | -| Dual-track sync failure (system mode) | Fallback to single-track sequential | | ui-ux-pro-max unavailable | Degrade to LLM general design knowledge | | Worker no response | Report waiting task, suggest user `resume` | | Pipeline deadlock | Check blockedBy chain, report blocking point | diff --git a/.claude/skills/team-frontend/roles/analyst/role.md b/.claude/skills/team-frontend/roles/analyst/role.md new file mode 100644 index 00000000..92ac6b31 --- /dev/null +++ b/.claude/skills/team-frontend/roles/analyst/role.md @@ -0,0 +1,92 @@ +--- +role: analyst +prefix: ANALYZE +inner_loop: false +message_types: + success: analyze_ready + error: error +--- + +# Requirements Analyst + +Analyze frontend requirements and retrieve industry design intelligence via ui-ux-pro-max skill. Produce design-intelligence.json and requirements.md for downstream consumption by architect and developer roles. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Industry context | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path, industry type, and tech stack from task description +2. Detect existing design system: + +| Signal | Detection Method | +|--------|-----------------| +| Token files | Glob `**/*token*.*` | +| CSS files | Glob `**/*.css` | +| Package.json | Read for framework dependencies | + +3. Detect tech stack from package.json: + +| Dependency | Stack | +|------------|-------| +| `next` | nextjs | +| `react` | react | +| `vue` | vue | +| `svelte` | svelte | +| `@shadcn/ui` | shadcn | +| (none) | html-tailwind | + +4. Load .msg/meta.json for shared state + +## Phase 3: Design Intelligence Retrieval + +Retrieve design intelligence via ui-ux-pro-max skill integration. + +**Step 1: Invoke ui-ux-pro-max** (primary path): + +| Action | Invocation | +|--------|------------| +| Full design system | `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` | +| UX guidelines | `Skill(skill="ui-ux-pro-max", args="accessibility animation responsive --domain ux")` | +| Tech stack guide | `Skill(skill="ui-ux-pro-max", args="<keywords> --stack <detected-stack>")` | + +**Step 2: Fallback** (if skill unavailable): +- Generate design recommendations from LLM general knowledge +- Log warning: `ui-ux-pro-max not installed. Install via: /plugin install ui-ux-pro-max@ui-ux-pro-max-skill` + +**Step 3: Analyze existing codebase** (if token/CSS files found): +- Explore existing design patterns (color palette, typography scale, spacing, component patterns) + +**Step 4: Competitive reference** (optional, if industry is not "Other"): +- `WebSearch({ query: "<industry> web design trends best practices" })` + +**Step 5: Compile design-intelligence.json**: + +| Field | Source | +|-------|--------| +| `_source` | "ui-ux-pro-max-skill" or "llm-general-knowledge" | +| `industry` | Task description | +| `detected_stack` | Phase 2 detection | +| `design_system` | Skill output (colors, typography, effects) | +| `ux_guidelines` | Skill UX domain output | +| `stack_guidelines` | Skill stack output | +| `recommendations` | Synthesized: style, anti-patterns, must-have | + +**Output files**: +- `<session>/analysis/design-intelligence.json` +- `<session>/analysis/requirements.md` + +## Phase 4: Self-Review + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| JSON validity | Parse design-intelligence.json | No parse errors | +| Required fields | Check _source, industry, design_system | All present | +| Anti-patterns populated | Check recommendations.anti_patterns | Non-empty array | +| Requirements doc exists | File check | requirements.md written | + +Update .msg/meta.json: merge `design_intelligence` and `industry_context` keys. diff --git a/.claude/skills/team-frontend/roles/architect/role.md b/.claude/skills/team-frontend/roles/architect/role.md new file mode 100644 index 00000000..96e167ba --- /dev/null +++ b/.claude/skills/team-frontend/roles/architect/role.md @@ -0,0 +1,86 @@ +--- +role: architect +prefix: ARCH +inner_loop: false +message_types: + success: arch_ready + error: error +--- + +# Frontend Architect + +Consume design-intelligence.json to define design token system, component architecture, and project structure. Token values prioritize ui-ux-pro-max recommendations. Produce architecture artifacts for developer consumption. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Scope | Extracted from task description (tokens/components/full) | No (default: full) | +| Design intelligence | <session>/analysis/design-intelligence.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path and scope from task description +2. Load design intelligence from analyst output +3. Load .msg/meta.json for shared state (industry_context, design_intelligence) +4. Detect existing project structure via Glob `src/**/*` + +**Fail-safe**: If design-intelligence.json not found, use default token values and log warning. + +## Phase 3: Architecture Design + +**Scope selection**: + +| Scope | Output | +|-------|--------| +| `tokens` | Design token system only | +| `components` | Component specs only | +| `full` | Both tokens and components + project structure | + +**Step 1: Design Token System** (scope: tokens or full): + +Generate `<session>/architecture/design-tokens.json` with categories: + +| Category | Content | Source | +|----------|---------|--------| +| `color` | Primary, secondary, background, surface, text, CTA | ui-ux-pro-max | +| `typography` | Font families, font sizes (scale) | ui-ux-pro-max | +| `spacing` | xs through 2xl | Standard scale | +| `border-radius` | sm, md, lg, full | Standard scale | +| `shadow` | sm, md, lg | Standard elevation | +| `transition` | fast, normal, slow | Standard durations | + +Use `$type` + `$value` format (Design Tokens Community Group). Support light/dark mode via nested values. + +**Step 2: Component Architecture** (scope: components or full): + +Generate component specs in `<session>/architecture/component-specs/`: +- Design reference (style, stack) +- Props table (name, type, default, description) +- Variants table +- Accessibility requirements (role, keyboard, ARIA, contrast) +- Anti-patterns to avoid (from design intelligence) + +**Step 3: Project Structure** (scope: full): + +Generate `<session>/architecture/project-structure.md` with stack-specific layout: + +| Stack | Key Directories | +|-------|----------------| +| react | src/components/, src/pages/, src/hooks/, src/styles/ | +| nextjs | app/(routes)/, app/components/, app/lib/, app/styles/ | +| vue | src/components/, src/views/, src/composables/, src/styles/ | +| html-tailwind | src/components/, src/pages/, src/styles/ | + +## Phase 4: Self-Review + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| JSON validity | Parse design-tokens.json | No errors | +| Required categories | Check color, typography, spacing | All present | +| Anti-pattern compliance | Token values vs anti-patterns | No violations | +| Component specs complete | Each has props + accessibility | All complete | +| File existence | Verify all planned files | All present | + +Update .msg/meta.json: merge `design_token_registry` and `component_inventory` keys. diff --git a/.claude/skills/team-frontend/roles/coordinator/commands/analyze.md b/.claude/skills/team-frontend/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..7be19b8e --- /dev/null +++ b/.claude/skills/team-frontend/roles/coordinator/commands/analyze.md @@ -0,0 +1,52 @@ +# Analyze Task + +Parse frontend task -> detect capabilities -> assess pipeline complexity -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Role | +|----------|------------|------| +| analyze, requirements, design intelligence | analyst | analyst | +| design tokens, component architecture, design system | architect | architect | +| implement, build, code, develop, page, component | developer | developer | +| review, audit, quality, test, accessibility | qa | qa | + +## Pipeline Selection + +| Scope Signal | Pipeline | +|--------------|----------| +| single page, landing, simple | page (4-beat) | +| feature, multi-component, complex | feature (5-beat with arch review gate) | +| full system, design system, multiple pages | system (7-beat dual-track) | + +Default to `feature` if ambiguous. + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| ui-ux-pro-max integration needed | +1 | +| Existing design system detected | +1 | +| Accessibility strict mode (healthcare/finance) | +2 | +| Multiple tech stacks | +2 | +| Dark mode required | +1 | + +Results: 1-2 page, 3-4 feature, 5+ system + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_type": "<page|feature|system>", + "capabilities": [{ "name": "<cap>", "role": "<role>", "keywords": ["..."] }], + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "industry": "<industry>", + "constraints": [], + "needs_ui_ux_pro_max": true +} +``` diff --git a/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md b/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md index cdb844ac..c64a127f 100644 --- a/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md @@ -1,6 +1,24 @@ # Command: Monitor -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, GC loops, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. + +## Constants + +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 2 + +## Handler Router + +| Source | Handler | +|--------|---------| +| Message contains [analyst], [architect], [developer], [qa] | handleCallback | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | ## Phase 2: Context Loading @@ -111,7 +129,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-frontend/role-specs/<role>.md +role_spec: .claude/skills/team-frontend/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: frontend diff --git a/.claude/skills/team-frontend/roles/coordinator/role.md b/.claude/skills/team-frontend/roles/coordinator/role.md index 96a889fd..8ad71d1f 100644 --- a/.claude/skills/team-frontend/roles/coordinator/role.md +++ b/.claude/skills/team-frontend/roles/coordinator/role.md @@ -1,15 +1,14 @@ -# Coordinator - Frontend Development Team +# Coordinator Role -**Role**: coordinator -**Type**: Orchestrator -**Team**: frontend +Orchestrate team-frontend: analyze -> dispatch -> spawn -> monitor -> report. -Orchestrates the frontend development pipeline: manages task chains, spawns team-worker agents, handles Generator-Critic loops (developer <-> qa), consulting pattern (developer -> analyst), and drives the pipeline to completion. +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) @@ -18,102 +17,47 @@ Orchestrates the frontend development pipeline: manages task chains, spawns team - Execute completion action in Phase 5 ### MUST NOT - - Implement domain logic (analyzing, designing, coding, reviewing) -- workers handle this - Spawn workers without creating tasks first - Skip architecture review gate when configured (feature/system modes) - Force-advance pipeline past failed QA review - Modify source code directly -- delegate to developer worker ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a command: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [analyst], [architect], [developer], [qa] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [analyst], [architect], [developer], [qa] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session in .workflow/.team/FE-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/FE-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "frontend" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/FE-*/.msg/meta.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -1. Parse user task description from $ARGUMENTS +TEXT-LEVEL ONLY. No source code reading. -2. Ask for missing parameters via AskUserQuestion: +1. Parse task description from $ARGUMENTS +2. Delegate to commands/analyze.md -> produces task-analysis.json +3. Ask for missing parameters via AskUserQuestion: **Scope Selection**: @@ -134,107 +78,50 @@ TeamCreate({ team_name: "frontend" }) **Design Constraints** (multi-select): Existing design system, WCAG AA, Responsive, Dark mode -3. Record requirements: mode, scope, industry, constraints - ---- +4. Record requirements: mode, scope, industry, constraints +5. CRITICAL: Always proceed to Phase 2, never skip team workflow ## Phase 2: Session & Team Setup -1. Create session directory: - +1. Generate session ID: `FE-<slug>-<YYYY-MM-DD>` +2. Create session folder structure: ``` -Bash("mkdir -p .workflow/.team/FE-<slug>-<YYYY-MM-DD>/{.msg,wisdom,analysis,architecture,qa,build}") +mkdir -p .workflow/.team/<session-id>/{.msg,wisdom,analysis,architecture,qa,build} ``` - -2. Write session.json: - -```json -{ - "status": "active", - "team_name": "frontend", - "requirement": "<requirement>", - "timestamp": "<ISO-8601>", - "pipeline_mode": "<page|feature|system>", - "industry": "<industry>", - "constraints": [], - "gc_rounds": {} -} -``` - -3. Initialize meta.json with pipeline metadata: +3. TeamCreate with team name: `TeamCreate({ team_name: "frontend" })` +4. Read specs/pipelines.md -> select pipeline based on scope +5. Register roles in session state +6. Initialize meta.json with pipeline metadata: ```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", data: { pipeline_mode: "<page|feature|system>", pipeline_stages: ["analyst", "architect", "developer", "qa"], roles: ["coordinator", "analyst", "architect", "developer", "qa"], - team_name: "frontend" + team_name: "frontend", + industry: "<industry>", + constraints: [] } }) ``` - -4. Create team: - -``` -TeamCreate({ team_name: "frontend" }) -``` - ---- +7. Write session.json ## Phase 3: Task Chain Creation -Execute `commands/dispatch.md` inline (Command Execution Protocol): +Delegate to commands/dispatch.md: +1. Read specs/pipelines.md for selected pipeline task registry +2. Create tasks via TaskCreate with blockedBy +3. Update session.json -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies +## Phase 4: Spawn-and-Stop ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn analyst worker", - team_name: "frontend", - name: "analyst", - run_in_background: true, - prompt: `## Role Assignment -role: analyst -role_spec: .claude/skills/team-frontend/role-specs/analyst.md -session: <session-folder> -session_id: <session-id> -team_name: frontend -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action @@ -251,28 +138,18 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger | QA Audits | <session>/qa/audit-*.md | 3. Output pipeline summary: task count, duration, QA scores +4. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -4. **Completion Action** (interactive): +## Error Handling -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -5. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-frontend', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy artifacts -> Archive & Clean flow | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Dependency cycle | Detect in analysis, halt | +| QA score < 6 over 2 GC rounds | Escalate to user | +| ui-ux-pro-max unavailable | Degrade to LLM general design knowledge | diff --git a/.claude/skills/team-frontend/roles/developer/role.md b/.claude/skills/team-frontend/roles/developer/role.md new file mode 100644 index 00000000..d57d24e8 --- /dev/null +++ b/.claude/skills/team-frontend/roles/developer/role.md @@ -0,0 +1,93 @@ +--- +role: developer +prefix: DEV +inner_loop: true +message_types: + success: dev_complete + error: error +--- + +# Frontend Developer + +Consume architecture artifacts (design tokens, component specs, project structure) to implement frontend code. Reference design-intelligence.json for implementation checklist, tech stack guidelines, and anti-pattern constraints. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Scope | Extracted from task description (tokens/components/full) | No (default: full) | +| Design intelligence | <session>/analysis/design-intelligence.json | No | +| Design tokens | <session>/architecture/design-tokens.json | Yes | +| Component specs | <session>/architecture/component-specs/*.md | No | +| Project structure | <session>/architecture/project-structure.md | No | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path and scope from task description +2. Load design tokens (required -- if missing, report to coordinator) +3. Load design intelligence for anti-patterns and guidelines +4. Load component specs and project structure +5. Detect tech stack from design intelligence `detected_stack` +6. Load .msg/meta.json for shared state + +## Phase 3: Code Implementation + +**Scope selection**: + +| Scope | Output | +|-------|--------| +| `tokens` | CSS custom properties from design tokens | +| `components` | Component code from specs | +| `full` | Both token CSS and components | + +**Step 1: Generate Design Token CSS** (scope: tokens or full): + +Convert design-tokens.json to `src/styles/tokens.css`: + +| JSON Category | CSS Variable Prefix | +|---------------|---------------------| +| color | `--color-` | +| typography.font-family | `--font-` | +| typography.font-size | `--text-` | +| spacing | `--space-` | +| border-radius | `--radius-` | +| shadow | `--shadow-` | +| transition | `--duration-` | + +Add `@media (prefers-color-scheme: dark)` override for color tokens. + +**Step 2: Implement Components** (scope: components or full): + +Implementation strategy by complexity: + +| Condition | Strategy | +|-----------|----------| +| <= 2 components | Direct inline Edit/Write | +| 3-5 components | Single batch implementation | +| > 5 components | Group by module, implement per batch | + +**Coding standards** (mandatory): +- Use design token CSS variables -- never hardcode colors/spacing +- All interactive elements: `cursor: pointer` +- Transitions: 150-300ms via `var(--duration-normal)` +- Text contrast: minimum 4.5:1 ratio +- Include `focus-visible` styles for keyboard navigation +- Support `prefers-reduced-motion` +- Responsive: mobile-first with md/lg breakpoints +- No emoji as functional icons + +## Phase 4: Self-Review + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Hardcoded colors | Scan for hex codes outside tokens.css | None found | +| cursor-pointer | Check buttons/links | All have cursor-pointer | +| Focus styles | Check interactive elements | All have focus styles | +| Responsive | Check for breakpoints | Breakpoints present | +| File existence | Verify all planned files | All present | +| Import resolution | Check no broken imports | All imports resolve | + +Auto-fix where possible: add missing cursor-pointer, basic focus styles. + +Update .msg/meta.json: merge `component_inventory` key with implemented file list. diff --git a/.claude/skills/team-frontend/roles/qa/role.md b/.claude/skills/team-frontend/roles/qa/role.md new file mode 100644 index 00000000..24ed7903 --- /dev/null +++ b/.claude/skills/team-frontend/roles/qa/role.md @@ -0,0 +1,79 @@ +--- +role: qa +prefix: QA +inner_loop: false +message_types: + success: qa_passed + error: error +--- + +# QA Engineer + +Execute 5-dimension quality audit integrating ux-guidelines Do/Don't rules, pre-delivery checklist, and industry anti-pattern library. Perform CSS-level precise review on architecture artifacts and implementation code. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Review type | Extracted from task description | No (default: code-review) | +| Design intelligence | <session>/analysis/design-intelligence.json | No | +| Design tokens | <session>/architecture/design-tokens.json | No | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path and review type from task description +2. Load design intelligence (for anti-patterns, must-have rules) +3. Load design tokens (for compliance checks) +4. Load .msg/meta.json (for industry context, strictness level) +5. Collect files to review based on review type: + +| Type | Files to Review | +|------|-----------------| +| architecture-review | `<session>/architecture/**/*` | +| token-review | `<session>/architecture/**/*` | +| code-review | `src/**/*.{tsx,jsx,vue,svelte,html,css}` | +| final | `src/**/*.{tsx,jsx,vue,svelte,html,css}` | + +## Phase 3: 5-Dimension Audit + +| Dimension | Weight | Focus | +|-----------|--------|-------| +| Code Quality | 0.20 | Structure, naming, maintainability | +| Accessibility | 0.25 | WCAG compliance, keyboard nav, screen reader | +| Design Compliance | 0.20 | Anti-pattern check, design token usage | +| UX Best Practices | 0.20 | Interaction patterns, responsive, animations | +| Pre-Delivery | 0.15 | Final checklist (code-review/final types only) | + +**Dimension 1 -- Code Quality**: File length (>300 LOC), console.log, empty catch, unused imports. + +**Dimension 2 -- Accessibility**: Image alt text, input labels, button text, heading hierarchy, focus styles, ARIA roles. Strict mode (medical/financial): prefers-reduced-motion required. + +**Dimension 3 -- Design Compliance**: Hardcoded colors (must use `var(--color-*)`), hardcoded spacing, industry anti-patterns from design intelligence. + +**Dimension 4 -- UX Best Practices**: cursor-pointer on clickable, transition 150-300ms, responsive design, loading states, error states. + +**Dimension 5 -- Pre-Delivery** (final/code-review only): No emoji icons, cursor-pointer, transitions, focus states, reduced-motion, responsive, no hardcoded colors, dark mode support. + +**Score calculation**: `score = sum(dimension_score * weight)` + +**Verdict**: + +| Condition | Verdict | Message Type | +|-----------|---------|-------------| +| score >= 8 AND critical == 0 | PASSED | `qa_passed` | +| score >= 6 AND critical == 0 | PASSED_WITH_WARNINGS | `qa_result` | +| score < 6 OR critical > 0 | FIX_REQUIRED | `fix_required` | + +## Phase 4: Self-Review + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| All dimensions scored | Check 5 dimension scores | All present | +| Audit report written | File check | audit-NNN.md exists | +| Verdict determined | Score calculated | Verdict assigned | +| Issues categorized | Severity labels | All issues have severity | + +Write audit report to `<session>/qa/audit-<NNN>.md` with: summary, dimension scores, issues by severity, passed dimensions. + +Update .msg/meta.json: append to `qa_history` array. diff --git a/.claude/skills/team-frontend/specs/pipelines.md b/.claude/skills/team-frontend/specs/pipelines.md new file mode 100644 index 00000000..1793c8c2 --- /dev/null +++ b/.claude/skills/team-frontend/specs/pipelines.md @@ -0,0 +1,76 @@ +# Frontend Pipeline Definitions + +## Pipeline Modes + +### Page Mode (4 beats, linear) + +``` +ANALYZE-001 --> ARCH-001 --> DEV-001 --> QA-001 +[analyst] [architect] [developer] [qa] +``` + +### Feature Mode (5 beats, with architecture review gate) + +``` +ANALYZE-001 --> ARCH-001 --> QA-001 --> DEV-001 --> QA-002 +[analyst] [architect] [qa:arch] [developer] [qa:code] +``` + +### System Mode (7 beats, dual-track parallel) + +``` +ANALYZE-001 --> ARCH-001 --> QA-001 --> ARCH-002 ─┐ +[analyst] [architect] [qa:arch] [architect] | + DEV-001 ──┘ --> QA-002 --> DEV-002 --> QA-003 + [developer:tokens] [qa] [developer] [qa:final] +``` + +### Generator-Critic Loop (developer <-> qa) + +``` +developer (Generator) -> QA artifact -> qa (Critic) + <- QA feedback <- + (max 2 rounds) + +Convergence: qa.score >= 8 && qa.critical_count === 0 +``` + +## Task Metadata Registry + +| Task ID | Role | Pipeline | Dependencies | Description | +|---------|------|----------|-------------|-------------| +| ANALYZE-001 | analyst | all | (none) | Requirement analysis + design intelligence | +| ARCH-001 | architect | all | ANALYZE-001 | Design token system + component architecture | +| ARCH-002 | architect | system | QA-001 | Component specs refinement | +| DEV-001 | developer | all | ARCH-001 or QA-001 | Frontend implementation | +| DEV-002 | developer | system | QA-002 | Component implementation | +| DEV-fix-N | developer | all | QA-N (GC loop trigger) | Fix issues from QA | +| QA-001 | qa | all | ARCH-001 or DEV-001 | Architecture or code review | +| QA-002 | qa | feature/system | DEV-001 | Code review | +| QA-003 | qa | system | DEV-002 | Final quality check | +| QA-recheck-N | qa | all | DEV-fix-N | Re-audit after developer fixes | + +## Pipeline Selection Logic + +| Score | Pipeline | +|-------|----------| +| 1-2 | page | +| 3-4 | feature | +| 5+ | system | + +Default: feature. + +## ui-ux-pro-max Integration + +Analyst role invokes ui-ux-pro-max via Skill to obtain industry design intelligence: + +| Action | Invocation | +|--------|------------| +| Full design system | `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` | +| Domain search | `Skill(skill="ui-ux-pro-max", args="<query> --domain <domain>")` | +| Tech stack guidance | `Skill(skill="ui-ux-pro-max", args="<query> --stack <stack>")` | + +**Supported Domains**: product, style, typography, color, landing, chart, ux, web +**Supported Stacks**: html-tailwind, react, nextjs, vue, svelte, shadcn, swiftui, react-native, flutter + +**Fallback**: If ui-ux-pro-max skill not installed, degrade to LLM general design knowledge. diff --git a/.claude/skills/team-issue/SKILL.md b/.claude/skills/team-issue/SKILL.md index 925576ee..1ab6d4d8 100644 --- a/.claude/skills/team-issue/SKILL.md +++ b/.claude/skills/team-issue/SKILL.md @@ -1,304 +1,62 @@ --- name: team-issue -description: Unified team skill for issue resolution. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team issue". +description: Unified team skill for issue resolution. Uses team-worker agent architecture with role directories for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team issue". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__ccw-tools__team_msg(*) --- # Team Issue Resolution -Unified team skill: issue processing pipeline (explore → plan → implement → review → integrate). All team members invoke with `--role=xxx` to route to role-specific execution. - -**Scope**: Issue processing flow (plan → queue → execute). Issue creation/discovery handled by `issue-discover`, CRUD management by `issue-manage`. +Orchestrate issue resolution pipeline: explore context -> plan solution -> review (optional) -> marshal queue -> implement. Supports Quick, Full, and Batch pipelines with review-fix cycle. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-issue") | -| args="<issue-ids>" | -+-------------------+-------------------------------+ +Skill(skill="team-issue", args="<issue-ids> [--mode=<mode>]") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-----+-----+-----+-----+-----+ - v v v v v - [tw] [tw] [tw] [tw] [tw] -explor plann review integ- imple- -er er er rator menter - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- clarify -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+-------+ + v v v v v + [explor] [plann] [review] [integ] [imple] ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| explorer | [roles/explorer/role.md](roles/explorer/role.md) | EXPLORE-* | false | +| planner | [roles/planner/role.md](roles/planner/role.md) | SOLVE-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | AUDIT-* | false | +| integrator | [roles/integrator/role.md](roles/integrator/role.md) | MARSHAL-* | false | +| implementer | [roles/implementer/role.md](roles/implementer/role.md) | BUILD-* | false | + ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). Extract issue IDs and `--mode` from remaining arguments. +## Shared Constants -### Role Registry +- **Session prefix**: `TISL` +- **Session path**: `.workflow/.team/TISL-<slug>-<date>/` +- **Team name**: `issue` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| explorer | [role-specs/explorer.md](role-specs/explorer.md) | EXPLORE-* | false | -| planner | [role-specs/planner.md](role-specs/planner.md) | SOLVE-* | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | AUDIT-* | false | -| integrator | [role-specs/integrator.md](role-specs/integrator.md) | MARSHAL-* | false | -| implementer | [role-specs/implementer.md](role-specs/implementer.md) | BUILD-* | false | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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 provides issue IDs and optional mode. - -**Invocation**: `Skill(skill="team-issue", args="<issue-ids> [--mode=<mode>]")` - -**Lifecycle**: -``` -User provides issue IDs - → coordinator Phase 1-3: Mode detection → TeamCreate → Create task chain - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until pipeline complete → Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Use tools declared in Toolbox | Create tasks for other roles | -| Delegate to reused agents | Modify resources outside own responsibility | - -Coordinator additional restrictions: Do not write/modify code directly, do not execute analysis/review directly. Team members use CLI tools for analysis/implementation tasks. - -### Output Tagging - -All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary. - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: - -**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - -`to` and `summary` auto-defaulted -- do NOT specify explicitly. - -**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` - - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `task_assigned`, `pipeline_update`, `escalation`, `shutdown`, `error` | -| explorer | `context_ready`, `impact_assessed`, `error` | -| planner | `solution_ready`, `multi_solution`, `error` | -| reviewer | `approved`, `rejected`, `concerns`, `error` | -| integrator | `queue_ready`, `conflict_found`, `error` | -| implementer | `impl_complete`, `impl_failed`, `error` | - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | issue | -| Session directory | `.workflow/.team-plan/issue/` | -| Issue data directory | `.workflow/issues/` | - ---- - -## Pipeline Modes - -``` -Quick Mode (1-2 simple issues): - EXPLORE-001 → SOLVE-001 → MARSHAL-001 → BUILD-001 - -Full Mode (complex issues, with review): - EXPLORE-001 → SOLVE-001 → AUDIT-001 ─┬─(approved)→ MARSHAL-001 → BUILD-001..N(parallel) - └─(rejected)→ SOLVE-fix → AUDIT-002(re-review, max 2x) - -Batch Mode (5-100 issues): - EXPLORE-001..N(batch<=5) → SOLVE-001..N(batch<=3) → AUDIT-001(batch) → MARSHAL-001 → BUILD-001..M(DAG parallel) -``` - -### Mode Auto-Detection - -When user does not specify `--mode`, auto-detect based on issue count and complexity: - -| Condition | Mode | Description | -|-----------|------|-------------| -| User explicitly specifies `--mode=<M>` | Use specified mode | User override takes priority | -| Issue count <= 2 AND no high-priority issues (priority < 4) | `quick` | Simple issues, skip review step | -| Issue count <= 2 AND has high-priority issues (priority >= 4) | `full` | Complex issues need review gate | -| Issue count > 2 | `batch` | Multiple issues, parallel exploration and implementation | - -### Review Gate (Full/Batch modes) - -| AUDIT Verdict | Action | -|---------------|--------| -| approved | Proceed to MARSHAL → BUILD | -| rejected (round < 2) | Create SOLVE-fix task → AUDIT re-review | -| rejected (round >= 2) | Force proceed with warnings, report to user | - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. Issue beat: explore → plan → implement → review → integrate. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - │ (parallel OK) ──┼──→ [Worker B] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat views**: - -``` -Quick Mode (4 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 - │ │ │ │ - EXPLORE → SOLVE → MARSHAL ──→ BUILD - ▲ ▲ - pipeline pipeline - start done - -EXPLORE=explorer SOLVE=planner MARSHAL=integrator BUILD=implementer - -Full Mode (5-7 beats, with review gate) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 - │ │ │ │ │ - EXPLORE → SOLVE → AUDIT ─┬─(ok)→ MARSHAL → BUILD - │ - (rejected?) - SOLVE-fix → AUDIT-2 → MARSHAL → BUILD - -Batch Mode (parallel windows) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 - ┌────┴────┐ ┌────┴────┐ │ │ ┌────┴────┐ - EXP-1..N → SOLVE-1..N → AUDIT → MARSHAL → BUILD-1..M - ▲ ▲ - parallel DAG parallel - window (<=5) window (<=3) -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Review gate | After AUDIT-* | If approved → MARSHAL; if rejected → SOLVE-fix (max 2 rounds) | -| Review loop limit | AUDIT round >= 2 | Force proceed with warnings | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| Review loop exceeded | AUDIT rejection > 2 rounds | Terminate loop, force proceed with current solution | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| EXPLORE-001 | explorer | explore | (none) | Context analysis and impact assessment | -| EXPLORE-002..N | explorer | explore | (none) | Parallel exploration (Batch mode only) | -| SOLVE-001 | planner | plan | EXPLORE-001 (or all EXPLORE-*) | Solution design and task decomposition | -| SOLVE-002..N | planner | plan | EXPLORE-* | Parallel solution design (Batch mode only) | -| AUDIT-001 | reviewer | review | SOLVE-001 (or all SOLVE-*) | Technical feasibility and risk review | -| MARSHAL-001 | integrator | integrate | AUDIT-001 (or last SOLVE-*) | Conflict detection and queue orchestration | -| BUILD-001 | implementer | implement | MARSHAL-001 | Code implementation and result submission | -| BUILD-002..M | implementer | implement | MARSHAL-001 | Parallel implementation (Batch DAG parallel) | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -309,7 +67,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-issue/role-specs/<role>.md +role_spec: .claude/skills/team-issue/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: issue @@ -317,42 +75,21 @@ requirement: <task-description> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**All roles** (explorer, planner, reviewer, integrator, implementer): Set `inner_loop: false`. - -### Parallel Spawn (Batch Mode) - -> When Batch mode has parallel tasks assigned to the same role, spawn N distinct team-worker agents with unique names. - -**Explorer parallel spawn** (Batch mode, N issues): - -| Condition | Action | -|-----------|--------| -| Batch mode with N issues (N > 1) | Spawn min(N, 5) team-worker agents: `explorer-1`, `explorer-2`, ... with `run_in_background: true` | -| Quick/Full mode (single explorer) | Standard spawn: single `explorer` team-worker agent | - -**Implementer parallel spawn** (Batch mode, M BUILD tasks): - -| Condition | Action | -|-----------|--------| -| Batch mode with M BUILD tasks (M > 2) | Spawn min(M, 3) team-worker agents: `implementer-1`, `implementer-2`, ... with `run_in_background: true` | -| Quick/Full mode (single implementer) | Standard spawn: single `implementer` team-worker agent | - -**Parallel spawn template**: +**Parallel spawn** (Batch mode, N explorer or M implementer instances): ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role>-<N> worker", - team_name: "issue", name: "<role>-<N>", + team_name: "issue", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-issue/role-specs/<role>.md +role_spec: .claude/skills/team-issue/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: issue @@ -361,67 +98,54 @@ agent_name: <role>-<N> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery, owner=<role>-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery, owner=<role>-<N>) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Dispatch must match agent names**: When dispatching parallel tasks, coordinator sets each task's owner to the corresponding instance name (`explorer-1`, `explorer-2`, etc. or `implementer-1`, `implementer-2`, etc.). +## User Commands ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): - -``` -AskUserQuestion({ - questions: [{ - question: "Issue resolution pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-issue", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph, no advancement | +| `resume` / `continue` | Check worker states, advance next step | ## Session Directory ``` -.workflow/.team-plan/issue/ +.workflow/.team/TISL-<slug>-<date>/ +├── session.json # Session metadata + pipeline + fix_cycles +├── task-analysis.json # Coordinator analyze output ├── .msg/ -│ ├── messages.jsonl # Message bus log -│ └── meta.json # Session state + cross-role state -├── wisdom/ # Cross-task knowledge +│ ├── messages.jsonl # Message bus log +│ └── meta.json # Session state + cross-role state +├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md │ ├── conventions.md │ └── issues.md -├── explorations/ # Explorer output -├── solutions/ # Planner output -├── audits/ # Reviewer output -├── queue/ # Integrator output -└── builds/ # Implementer output +├── explorations/ # Explorer output +│ └── context-<issueId>.json +├── solutions/ # Planner output +│ └── solution-<issueId>.json +├── audits/ # Reviewer output +│ └── audit-report.json +├── queue/ # Integrator output (also .workflow/issues/queue/) +└── builds/ # Implementer output ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry + ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>.md) | -| Task prefix conflict | Log warning, proceed | -| Review rejection exceeds 2 rounds | Force proceed with warnings | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| CLI tool fails | Worker fallback to direct implementation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | +| Review rejection exceeds 2 rounds | Force convergence to integrator | | No issues found for given IDs | Coordinator reports error to user | +| Deferred BUILD count unknown | Defer to MARSHAL callback | diff --git a/.claude/skills/team-issue/roles/coordinator/commands/analyze.md b/.claude/skills/team-issue/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..dcb06dec --- /dev/null +++ b/.claude/skills/team-issue/roles/coordinator/commands/analyze.md @@ -0,0 +1,64 @@ +# Analyze Task + +Parse user issue description -> detect required capabilities -> assess complexity -> select pipeline mode. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| explore, analyze, context, impact, understand | explorer | EXPLORE | +| plan, solve, design, solution, approach | planner | SOLVE | +| review, audit, validate, feasibility | reviewer | AUDIT | +| marshal, integrate, queue, conflict, order | integrator | MARSHAL | +| build, implement, execute, code, develop | implementer | BUILD | + +## Dependency Graph + +Natural ordering tiers: +- Tier 0: explorer (context analysis — no dependencies) +- Tier 1: planner (requires explorer output) +- Tier 2: reviewer (requires planner output, full/batch modes only) +- Tier 3: integrator (requires reviewer or planner output) +- Tier 4: implementer (requires integrator output) + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Issue count > 2 | +3 | +| Issue count > 4 | +2 more | +| Any high-priority issue (priority >= 4) | +2 | +| Multiple issue types / cross-cutting | +2 | +| Simple / single issue | -2 | + +Results: +- 0-2: Low -> quick (4 tasks: EXPLORE → SOLVE → MARSHAL → BUILD) +- 3-4: Medium -> full (5 tasks: EXPLORE → SOLVE → AUDIT → MARSHAL → BUILD) +- 5+: High -> batch (N+N+1+1+M tasks, parallel exploration and implementation) + +## Pipeline Selection + +| Complexity | Pipeline | Tasks | +|------------|----------|-------| +| Low | quick | EXPLORE → SOLVE → MARSHAL → BUILD | +| Medium | full | EXPLORE → SOLVE → AUDIT → MARSHAL → BUILD | +| High | batch | EXPLORE-001..N (parallel) → SOLVE-001..N → AUDIT → MARSHAL → BUILD-001..M (parallel) | + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_type": "<quick|full|batch>", + "issue_ids": ["<id1>", "<id2>"], + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "parallel_explorers": 1, + "parallel_builders": 1 +} +``` diff --git a/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md b/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md index 1fb39d80..e8e32a78 100644 --- a/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md @@ -1,8 +1,8 @@ -# Command: Dispatch +# Dispatch Create the issue resolution task chain with correct dependencies and structured task descriptions based on selected pipeline mode. -## Phase 2: Context Loading +## Context Loading | Input | Source | Required | |-------|--------|----------| @@ -16,9 +16,7 @@ Create the issue resolution task chain with correct dependencies and structured 1. Load requirement, pipeline mode, issue IDs, and execution method from session.json 2. Determine task chain from pipeline mode -## Phase 3: Task Chain Creation - -### Task Description Template +## Task Description Template Every task description uses structured format: @@ -44,13 +42,13 @@ code_review: <setting>" TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" }) ``` -### Pipeline Router +## Pipeline Router | Mode | Action | |------|--------| -| quick | Create 4 tasks (EXPLORE -> SOLVE -> MARSHAL -> BUILD) | -| full | Create 5 tasks (EXPLORE -> SOLVE -> AUDIT -> MARSHAL -> BUILD) | -| batch | Create N+N+1+1+M tasks (EXPLORE-001..N -> SOLVE-001..N -> AUDIT-001 -> MARSHAL-001 -> BUILD-001..M) | +| quick | Create 4 tasks (EXPLORE → SOLVE → MARSHAL → BUILD) | +| full | Create 5 tasks (EXPLORE → SOLVE → AUDIT → MARSHAL → BUILD) | +| batch | Create N+N+1+1+M tasks (EXPLORE-001..N → SOLVE-001..N → AUDIT-001 → MARSHAL-001 → BUILD-001..M) | --- @@ -83,7 +81,7 @@ TaskCreate({ description: "PURPOSE: Design solution and decompose into implementation tasks | Success: Bound solution with task decomposition TASK: - Load explorer context report - - Generate solution plan via issue-plan-agent + - Generate solution plan via CLI - Bind solution to issue CONTEXT: - Session: <session-folder> @@ -125,7 +123,7 @@ TaskCreate({ description: "PURPOSE: Implement solution plan and verify with tests | Success: Code changes committed, tests pass TASK: - Load bound solution and explorer context - - Route to execution backend (Agent/Codex/Gemini) + - Route to execution backend (Auto/Codex/Gemini) - Run tests and verify implementation - Commit changes CONTEXT: @@ -142,17 +140,17 @@ code_review: <code_review>" TaskUpdate({ taskId: "BUILD-001", addBlockedBy: ["MARSHAL-001"], owner: "implementer" }) ``` +--- + ### Full Pipeline -Creates 5 tasks. First 2 same as Quick, then AUDIT gate before MARSHAL and BUILD. - -**EXPLORE-001** and **SOLVE-001**: Same as Quick pipeline. +Creates 5 tasks. EXPLORE-001 and SOLVE-001 same as Quick, then AUDIT gate before MARSHAL and BUILD. **AUDIT-001** (reviewer): ``` TaskCreate({ subject: "AUDIT-001", - description: "PURPOSE: Review solution for technical feasibility, risk, and completeness | Success: Clear verdict (approved/rejected/concerns) with scores + description: "PURPOSE: Review solution for technical feasibility, risk, and completeness | Success: Clear verdict (approved/concerns/rejected) with scores TASK: - Load explorer context and bound solution - Score across 3 dimensions: technical feasibility (40%), risk (30%), completeness (30%) @@ -169,9 +167,11 @@ InnerLoop: false" TaskUpdate({ taskId: "AUDIT-001", addBlockedBy: ["SOLVE-001"], owner: "reviewer" }) ``` -**MARSHAL-001** (integrator): Same as Quick, but `blockedBy: ["AUDIT-001"]`. +**MARSHAL-001**: Same as Quick, but `addBlockedBy: ["AUDIT-001"]`. -**BUILD-001** (implementer): Same as Quick, `blockedBy: ["MARSHAL-001"]`. +**BUILD-001**: Same as Quick, `addBlockedBy: ["MARSHAL-001"]`. + +--- ### Batch Pipeline @@ -179,7 +179,7 @@ Creates tasks in parallel batches. Issue count = N, BUILD tasks = M (from queue **EXPLORE-001..N** (explorer, parallel): -For each issue in issue_ids, create an EXPLORE task. When N > 1, assign distinct owners for parallel spawn: +For each issue in issue_ids (up to 5), create an EXPLORE task with distinct owner: | Issue Count | Owner Assignment | |-------------|-----------------| @@ -207,8 +207,6 @@ TaskUpdate({ taskId: "EXPLORE-<NNN>", owner: "explorer-<N>" }) **SOLVE-001..N** (planner, sequential after all EXPLORE): -For each issue, create a SOLVE task blocked by all EXPLORE tasks - ``` TaskCreate({ subject: "SOLVE-<NNN>", @@ -250,11 +248,13 @@ InnerLoop: false" TaskUpdate({ taskId: "AUDIT-001", addBlockedBy: ["SOLVE-001", ..., "SOLVE-<N>"], owner: "reviewer" }) ``` -**MARSHAL-001** (integrator): `blockedBy: ["AUDIT-001"]`. +**MARSHAL-001** (integrator): `addBlockedBy: ["AUDIT-001"]`. **BUILD-001..M** (implementer, DAG parallel): -After MARSHAL produces execution queue, create M BUILD tasks based on parallel groups. When M > 2, assign distinct owners: +> Note: In Batch mode, BUILD task count M is not known at dispatch time (depends on MARSHAL queue output). Defer BUILD task creation to handleCallback when MARSHAL completes. Coordinator creates BUILD tasks dynamically after reading execution-queue.json. + +When M is known (deferred creation after MARSHAL), assign distinct owners: | Build Count | Owner Assignment | |-------------|-----------------| @@ -283,11 +283,11 @@ code_review: <code_review>" TaskUpdate({ taskId: "BUILD-<NNN>", addBlockedBy: ["MARSHAL-001"], owner: "implementer-<M>" }) ``` -> **Note**: In Batch mode, BUILD task count M may not be known at dispatch time (depends on MARSHAL queue output). Create BUILD tasks with placeholder count, or defer BUILD task creation to handleCallback when MARSHAL completes. Coordinator should check for deferred BUILD task creation in monitor.md handleCallback for integrator. +--- ### Review-Fix Cycle (Full/Batch modes) -When AUDIT rejects a solution, coordinator creates fix tasks dynamically (NOT at dispatch time): +When AUDIT rejects a solution, coordinator creates fix tasks dynamically in handleCallback — NOT at dispatch time. **SOLVE-fix-001** (planner, revision): ``` @@ -332,9 +332,7 @@ InnerLoop: false" TaskUpdate({ taskId: "AUDIT-002", addBlockedBy: ["SOLVE-fix-001"], owner: "reviewer" }) ``` -These fix tasks are created dynamically by handleCallback in monitor.md when reviewer reports rejection, NOT during initial dispatch. - -## Phase 4: Validation +## Validation 1. Verify all tasks created with `TaskList()` 2. Check dependency chain integrity: @@ -348,4 +346,4 @@ These fix tasks are created dynamically by handleCallback in monitor.md when rev |------|-----------| | quick | Exactly 4 tasks, no AUDIT | | full | Exactly 5 tasks, includes AUDIT | -| batch | N EXPLORE + N SOLVE + 1 AUDIT + 1 MARSHAL + M BUILD | +| batch | N EXPLORE + N SOLVE + 1 AUDIT + 1 MARSHAL + deferred BUILD | diff --git a/.claude/skills/team-issue/roles/coordinator/commands/monitor.md b/.claude/skills/team-issue/roles/coordinator/commands/monitor.md index 38e0182c..b1001454 100644 --- a/.claude/skills/team-issue/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-issue/roles/coordinator/commands/monitor.md @@ -1,34 +1,30 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, review-fix cycle control, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | -|-----|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| WORKER_AGENT | team-worker | -| MAX_FIX_CYCLES | 2 | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_FIX_CYCLES: 2 -## Phase 2: Context Loading +## Handler Router -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json (.msg/meta.json) | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Meta state | <session>/.msg/meta.json | Yes | +| Source | Handler | +|--------|---------| +| Message contains [explorer], [planner], [reviewer], [integrator], [implementer] | handleCallback | +| "consensus_blocked" | handleConsensus | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -1. Load session.json for current state, pipeline mode, fix_cycles -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## handleCallback -## Phase 3: Event Handlers - -### handleCallback - -Triggered when a worker sends completion message. +Worker completed. Process and advance. 1. Parse message to identify role and task ID: @@ -40,12 +36,7 @@ Triggered when a worker sends completion message. | `[integrator]` or task ID `MARSHAL-*` | integrator | | `[implementer]` or task ID `BUILD-*` | implementer | -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` - +2. Mark task as completed: `TaskUpdate({ taskId: "<task-id>", status: "completed" })` 3. Record completion in session state 4. **Review gate check** (when reviewer completes): @@ -56,7 +47,7 @@ TaskUpdate({ taskId: "<task-id>", status: "completed" }) | Verdict | fix_cycles < max | Action | |---------|-----------------|--------| | rejected | Yes | Increment fix_cycles, create SOLVE-fix + AUDIT re-review tasks (see dispatch.md Review-Fix Cycle), proceed to handleSpawnNext | - | rejected | No (>= max) | Force proceed -- log warning, unblock MARSHAL | + | rejected | No (>= max) | Force proceed — log warning, unblock MARSHAL | | concerns | - | Log concerns, proceed to MARSHAL (non-blocking) | | approved | - | Proceed to MARSHAL via handleSpawnNext | @@ -72,108 +63,96 @@ TaskUpdate({ taskId: "<task-id>", status: "completed" }) 6. Proceed to handleSpawnNext -### handleSpawnNext +## handleCheck -Find and spawn the next ready tasks. - -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" - -2. For each ready task, spawn team-worker: +Read-only status report, then STOP. ``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker for <task-id>", - team_name: "issue", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-issue/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: issue -requirement: <task-description> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) +[coordinator] Pipeline Status (<pipeline-mode>) +[coordinator] Progress: <done>/<total> (<pct>%) +[coordinator] Active: <workers with elapsed time> +[coordinator] Ready: <pending tasks with resolved deps> +[coordinator] Fix Cycles: <fix_cycles>/<max_fix_cycles> +[coordinator] Commands: 'resume' to advance | 'check' to refresh ``` -3. **Parallel spawn rules**: +## handleResume + +1. Audit task list: Tasks stuck in "in_progress" -> reset to "pending" +2. Proceed to handleSpawnNext + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect: completedSubjects, inProgressSubjects, readySubjects +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. TaskUpdate -> in_progress + b. team_msg log -> task_unblocked + c. Spawn team-worker (see SKILL.md Spawn Template): + ``` + Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <task-id>", + team_name: "issue", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment + role: <role> + role_spec: .claude/skills/team-issue/roles/<role>/role.md + session: <session-folder> + session_id: <session-id> + team_name: issue + requirement: <task-description> + inner_loop: false + + Read role_spec file to load Phase 2-4 domain instructions. + Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` + }) + ``` + d. Add to active_workers + +5. Parallel spawn rules: | Pipeline | Scenario | Spawn Behavior | |----------|----------|---------------| | Quick | All stages | One worker at a time | | Full | All stages | One worker at a time | -| Batch | EXPLORE-001..N unblocked | Spawn up to 5 explorer workers in parallel | -| Batch | BUILD-001..M unblocked | Spawn up to 3 implementer workers in parallel | +| Batch | EXPLORE-001..N unblocked | Spawn ALL N explorer workers in parallel (max 5) | +| Batch | BUILD-001..M unblocked | Spawn ALL M implementer workers in parallel (max 3) | | Batch | Other stages | One worker at a time | -4. **Parallel spawn** (Batch mode with multiple ready tasks for same role): - +**Parallel spawn** (Batch mode with multiple ready tasks for same role): ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role>-<N> worker for <task-id>", - team_name: "issue", name: "<role>-<N>", + team_name: "issue", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-issue/role-specs/<role>.md +role_spec: .claude/skills/team-issue/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: issue requirement: <task-description> +agent_name: <role>-<N> inner_loop: false -Agent name: <role>-<N> -Only process tasks where owner === "<role>-<N>". - Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +Execute built-in Phase 1 (task discovery, owner=<role>-<N>) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -5. STOP after spawning -- wait for next callback +6. Update session, output summary, STOP -### handleCheck +## handleComplete -Output current pipeline status. Do NOT advance pipeline. - -``` -Pipeline Status (<pipeline-mode>): - [DONE] EXPLORE-001 (explorer) -> explorations/context-<id>.json - [DONE] SOLVE-001 (planner) -> solutions/solution-<id>.json - [RUN] AUDIT-001 (reviewer) -> reviewing... - [WAIT] MARSHAL-001 (integrator) -> blocked by AUDIT-001 - [WAIT] BUILD-001 (implementer) -> blocked by MARSHAL-001 - -Fix Cycles: <fix_cycles>/<max_fix_cycles> -Mode: <pipeline-mode> -Session: <session-id> -Issues: <issue-id-list> -``` - -### handleResume - -Resume pipeline after user pause or interruption. - -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext - -### handleComplete - -Triggered when all pipeline tasks are completed. - -**Completion check by mode**: +Pipeline done. Generate report and completion action. +Completion check by mode: | Mode | Completion Condition | |------|---------------------| | quick | All 4 tasks completed | @@ -182,21 +161,31 @@ Triggered when all pipeline tasks are completed. 1. Verify all tasks completed via TaskList() 2. If any tasks not completed, return to handleSpawnNext -3. If all completed, transition to coordinator Phase 5 (Report + Completion Action) +3. If all completed -> transition to coordinator Phase 5 -**Stall detection** (no ready tasks and no running tasks but pipeline not complete): +## handleConsensus -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task with no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy chain, report blocking point | -| Fix cycle exceeded | AUDIT rejection > 2 rounds | Terminate loop, force proceed with current solution | +Handle consensus_blocked signals. -## Phase 4: State Persistence +| Severity | Action | +|----------|--------| +| HIGH | Pause pipeline, notify user with findings summary | +| MEDIUM | Log finding, attempt to continue | +| LOW | Log finding, continue pipeline | -After every handler execution: +## handleAdapt -1. Update session.json (.msg/meta.json) with current state (fix_cycles, last event, active tasks) -2. Update .msg/meta.json fix_cycles if changed -3. Verify task list consistency -4. STOP and wait for next event +Capability gap reported mid-pipeline. + +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 6 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 6 -> merge or pause + +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-issue/roles/coordinator/role.md b/.claude/skills/team-issue/roles/coordinator/role.md index ac10ad81..fb94fce1 100644 --- a/.claude/skills/team-issue/roles/coordinator/role.md +++ b/.claude/skills/team-issue/roles/coordinator/role.md @@ -1,241 +1,131 @@ -# Coordinator - Issue Resolution Team +--- +role: coordinator +--- -**Role**: coordinator -**Type**: Orchestrator -**Team**: issue +# Coordinator — Issue Resolution Team -Orchestrates the issue resolution pipeline: manages task chains, spawns team-worker agents, handles review-fix cycles, and drives the pipeline to completion. Supports quick, full, and batch modes. +Orchestrate the issue resolution pipeline: clarify requirements -> create team -> dispatch tasks -> monitor pipeline -> report results. Supports quick, full, and batch modes. + +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Issue clarification -> Mode detection -> Create team -> Dispatch tasks -> Monitor pipeline -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) -- Stop after spawning workers -- wait for callbacks +- Stop after spawning workers — wait for callbacks - Handle review-fix cycles with max 2 iterations - Execute completion action in Phase 5 ### MUST NOT - -- Implement domain logic (exploring, planning, reviewing, implementing) -- workers handle this +- Implement domain logic (exploring, planning, reviewing, implementing) — workers handle this - Spawn workers without creating tasks first - Skip review gate in full/batch modes - Force-advance pipeline past failed review -- Modify source code directly -- delegate to implementer worker -- Call CLI tools or spawn utility members directly for implementation (issue-plan-agent, issue-queue-agent, code-developer) - ---- +- Modify source code directly — delegate to implementer worker +- Call CLI tools directly for implementation tasks ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [explorer], [planner], [reviewer], [integrator], [implementer] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [explorer], [planner], [reviewer], [integrator], [implementer] | -> handleCallback (monitor.md) | +| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/TISL-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team-plan/issue/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/consensus/adapt/complete: load `commands/monitor.md`, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session state from `.workflow/.team-plan/issue/.msg/meta.json` -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "issue" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/TISL-*/session.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, spawn first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -1. Parse user task description from $ARGUMENTS -2. **Parse arguments** for issue IDs and mode: +TEXT-LEVEL ONLY. No source code reading. + +1. Parse issue IDs and mode from $ARGUMENTS: | Pattern | Extraction | |---------|------------| | `GH-\d+` | GitHub issue ID | | `ISS-\d{8}-\d{6}` | Local issue ID | -| `--mode=<mode>` | Explicit mode | -| `--all-pending` | Load all pending issues | +| `--mode=<mode>` | Explicit mode override | +| `--all-pending` | Load all pending issues via `Bash("ccw issue list --status registered,pending --json")` | -3. **Load pending issues** if `--all-pending`: +2. If no issue IDs found -> AskUserQuestion for clarification -``` -Bash("ccw issue list --status registered,pending --json") -``` - -4. **Ask for missing parameters** via AskUserQuestion if no issue IDs found - -5. **Mode auto-detection** (when user does not specify `--mode`): +3. **Mode auto-detection** (when `--mode` not specified): | Condition | Mode | |-----------|------| | Issue count <= 2 AND no high-priority (priority < 4) | `quick` | | Issue count <= 2 AND has high-priority (priority >= 4) | `full` | -| Issue count >= 5 | `batch` | | 3-4 issues | `full` | +| Issue count >= 5 | `batch` | -6. **Execution method selection** (for BUILD phase): +4. **Execution method selection** for BUILD phase (default: Auto): -| Option | Description | -|--------|-------------| -| `Agent` | code-developer agent (sync, for simple tasks) | -| `Codex` | Codex CLI (background, for complex tasks) | -| `Gemini` | Gemini CLI (background, for analysis tasks) | -| `Auto` | Auto-select based on solution task_count (default) | +| Option | Trigger | +|--------|---------| +| codex | task_count > 3 or explicit `--exec=codex` | +| gemini | task_count <= 3 or explicit `--exec=gemini` | +| qwen | explicit `--exec=qwen` | +| Auto | Auto-select based on task_count | -7. Record requirement with scope, mode, execution_method, code_review settings +5. Record requirements: issue_ids, mode, execution_method, code_review settings ---- +## Phase 2: Create Team + Initialize Session -## Phase 2: Session & Team Setup +1. Generate session ID: `TISL-<issue-slug>-<date>` +2. Create session folder structure: + ``` + Bash("mkdir -p .workflow/.team/TISL-<slug>-<date>/{explorations,solutions,audits,queue,builds,wisdom,.msg}") + ``` +3. TeamCreate with team name `issue` +4. Write session.json with pipeline_mode, issue_ids, execution_method, fix_cycles=0, max_fix_cycles=2 +5. Initialize meta.json via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { pipeline_mode: "<mode>", pipeline_stages: ["explorer","planner","reviewer","integrator","implementer"], team_name: "issue", issue_ids: [...], fix_cycles: 0 } + }) + ``` +6. Initialize wisdom files (learnings.md, decisions.md, conventions.md, issues.md) -1. Create session directory: +## Phase 3: Create Task Chain -``` -Bash("mkdir -p .workflow/.team-plan/issue/explorations .workflow/.team-plan/issue/solutions .workflow/.team-plan/issue/audits .workflow/.team-plan/issue/queue .workflow/.team-plan/issue/builds .workflow/.team-plan/issue/wisdom") -``` +Delegate to commands/dispatch.md: +1. Read pipeline mode and issue IDs from session.json +2. Create tasks for selected pipeline with correct blockedBy +3. Update session.json with task count -2. Initialize meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<quick|full|batch>", - pipeline_stages: ["explorer", "planner", "reviewer", "integrator", "implementer"], - roles: ["coordinator", "explorer", "planner", "reviewer", "integrator", "implementer"], - team_name: "issue" - } -}) -``` +## Phase 4: Spawn-and-Stop -3. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) - -4. Create team: - -``` -TeamCreate({ team_name: "issue" }) -``` - ---- - -## Phase 3: Task Chain Creation - -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies - ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn explorer worker", - team_name: "issue", - name: "explorer", - run_in_background: true, - prompt: `## Role Assignment -role: explorer -role_spec: .claude/skills/team-issue/role-specs/explorer.md -session: <session-folder> -session_id: <session-id> -team_name: issue -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action @@ -250,29 +140,33 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger | Execution Queue | .workflow/issues/queue/execution-queue.json | | Build Results | <session>/builds/ | -3. Output pipeline summary: task count, duration, issues resolved +3. Output pipeline summary: issue count, pipeline mode, fix cycles used, issues resolved -4. **Completion Action** (interactive): - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work" }, - { label: "New Batch", description: "Return to Phase 1 with new issue IDs" } - ] - }] -}) -``` - -5. Handle user choice: +4. Execute completion action (interactive): + ``` + AskUserQuestion({ + questions: [{ question: "Issue pipeline complete. What would you like to do?", + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team" }, + { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, + { label: "New Batch", description: "Return to Phase 1 with new issue IDs" } + ] + }] + }) + ``` | Choice | Steps | |--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-issue', args='resume')" | +| Archive & Clean | Verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | +| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-issue', args='resume')" | | New Batch | Return to Phase 1 | + +## Error Handling + +| Error | Resolution | +|-------|------------| +| No issue IDs provided | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Review rejection exceeds 2 rounds | Force convergence to MARSHAL | +| Deferred BUILD count unknown | Read execution-queue.json after MARSHAL completes | diff --git a/.claude/skills/team-issue/roles/explorer/role.md b/.claude/skills/team-issue/roles/explorer/role.md new file mode 100644 index 00000000..9634d740 --- /dev/null +++ b/.claude/skills/team-issue/roles/explorer/role.md @@ -0,0 +1,94 @@ +--- +role: explorer +prefix: EXPLORE +inner_loop: false +message_types: [context_ready, error] +--- + +# Issue Explorer + +Analyze issue context, explore codebase for relevant files, map dependencies and impact scope. Produce a shared context report for planner, reviewer, and implementer. + +## Phase 2: Issue Loading & Context Setup + +| Input | Source | Required | +|-------|--------|----------| +| Issue ID | Task description (GH-\d+ or ISS-\d{8}-\d{6}) | Yes | +| Issue details | `ccw issue status <id> --json` | Yes | +| Session path | Extracted from task description | Yes | +| wisdom meta | <session>/wisdom/.msg/meta.json | No | + +1. Extract issue ID from task description via regex: `(?:GH-\d+|ISS-\d{8}-\d{6})` +2. If no issue ID found -> report error, STOP +3. Load issue details: + +``` +Bash("ccw issue status <issueId> --json") +``` + +4. Parse JSON response for issue metadata (title, context, priority, labels, feedback) +5. Load wisdom files from `<session>/wisdom/` if available + +## Phase 3: Codebase Exploration & Impact Analysis + +**Complexity assessment determines exploration depth**: + +| Signal | Weight | Keywords | +|--------|--------|----------| +| Structural change | +2 | refactor, architect, restructure, module, system | +| Cross-cutting | +2 | multiple, across, cross | +| Integration | +1 | integrate, api, database | +| High priority | +1 | priority >= 4 | + +| Score | Complexity | Strategy | +|-------|------------|----------| +| >= 4 | High | Deep exploration via CLI tool | +| 2-3 | Medium | Hybrid: ACE search + selective CLI | +| 0-1 | Low | Direct ACE search only | + +**Exploration execution**: + +| Complexity | Execution | +|------------|-----------| +| Low | Direct ACE search: `mcp__ace-tool__search_context(project_root_path, query)` | +| Medium/High | CLI exploration: `Bash("ccw cli -p \"<exploration_prompt>\" --tool gemini --mode analysis", { run_in_background: false })` | + +**CLI exploration prompt template**: + +``` +PURPOSE: Explore codebase for issue <issueId> to identify relevant files, dependencies, and impact scope; success = comprehensive context report written to <session>/explorations/context-<issueId>.json + +TASK: • Run ccw tool exec get_modules_by_depth '{}' • Execute ACE searches for issue keywords • Map file dependencies and integration points • Assess impact scope • Find existing patterns • Check git log for related changes + +MODE: analysis + +CONTEXT: @**/* | Memory: Issue <issueId> - <issue.title> (Priority: <issue.priority>) + +EXPECTED: JSON report with: relevant_files (path + relevance), dependencies, impact_scope (low/medium/high), existing_patterns, related_changes, key_findings, complexity_assessment + +CONSTRAINTS: Focus on issue context | Write output to <session>/explorations/context-<issueId>.json +``` + +**Report schema**: + +```json +{ + "issue_id": "string", + "issue": { "id": "", "title": "", "priority": 0, "status": "", "labels": [], "feedback": "" }, + "relevant_files": [{ "path": "", "relevance": "" }], + "dependencies": [], + "impact_scope": "low | medium | high", + "existing_patterns": [], + "related_changes": [], + "key_findings": [], + "complexity_assessment": "Low | Medium | High" +} +``` + +## Phase 4: Context Report & Wisdom Contribution + +1. Write context report to `<session>/explorations/context-<issueId>.json` +2. If file not found from agent, build minimal report from ACE results +3. Update `<session>/wisdom/.msg/meta.json` under `explorer` namespace: + - Read existing -> merge `{ "explorer": { issue_id, complexity, impact_scope, file_count } }` -> write back +4. Contribute discoveries to `<session>/wisdom/learnings.md` if new patterns found diff --git a/.claude/skills/team-issue/roles/implementer/role.md b/.claude/skills/team-issue/roles/implementer/role.md new file mode 100644 index 00000000..42ede713 --- /dev/null +++ b/.claude/skills/team-issue/roles/implementer/role.md @@ -0,0 +1,87 @@ +--- +role: implementer +prefix: BUILD +inner_loop: false +message_types: [impl_complete, impl_failed, error] +--- + +# Issue Implementer + +Load solution plan, route to execution backend (Agent/Codex/Gemini), run tests, and commit. Execution method determined by coordinator during task creation. Supports parallel instances for batch mode. + +## Modes + +| Backend | Condition | Method | +|---------|-----------|--------| +| codex | task_count > 3 or explicit | `ccw cli --tool codex --mode write --id issue-<issueId>` | +| gemini | task_count <= 3 or explicit | `ccw cli --tool gemini --mode write --id issue-<issueId>` | +| qwen | explicit | `ccw cli --tool qwen --mode write --id issue-<issueId>` | + +## Phase 2: Load Solution & Resolve Executor + +| Input | Source | Required | +|-------|--------|----------| +| Issue ID | Task description (GH-\d+ or ISS-\d{8}-\d{6}) | Yes | +| Bound solution | `ccw issue solutions <id> --json` | Yes | +| Explorer context | `<session>/explorations/context-<issueId>.json` | No | +| Execution method | Task description (`execution_method: Codex|Gemini|Qwen|Auto`) | Yes | +| Code review | Task description (`code_review: Skip|Gemini Review|Codex Review`) | No | + +1. Extract issue ID from task description +2. If no issue ID -> report error, STOP +3. Load bound solution: `Bash("ccw issue solutions <issueId> --json")` +4. If no bound solution -> report error, STOP +5. Load explorer context (if available) +6. Resolve execution method (Auto: task_count <= 3 -> gemini, else codex) +7. Update issue status: `Bash("ccw issue update <issueId> --status in-progress")` + +## Phase 3: Implementation (Multi-Backend Routing) + +**Execution prompt template** (all backends): + +``` +## Issue +ID: <issueId> +Title: <solution.bound.title> + +## Solution Plan +<solution.bound JSON> + +## Codebase Context (from explorer) +Relevant files: <explorerContext.relevant_files> +Existing patterns: <explorerContext.existing_patterns> +Dependencies: <explorerContext.dependencies> + +## Implementation Requirements +1. Follow the solution plan tasks in order +2. Write clean, minimal code following existing patterns +3. Run tests after each significant change +4. Ensure all existing tests still pass +5. Do NOT over-engineer + +## Quality Checklist +- All solution tasks implemented +- No TypeScript/linting errors +- Existing tests pass +- New tests added where appropriate +``` + +Route by executor: +- **codex**: `Bash("ccw cli -p \"<prompt>\" --tool codex --mode write --id issue-<issueId>", { run_in_background: false })` +- **gemini**: `Bash("ccw cli -p \"<prompt>\" --tool gemini --mode write --id issue-<issueId>", { run_in_background: false })` +- **qwen**: `Bash("ccw cli -p \"<prompt>\" --tool qwen --mode write --id issue-<issueId>", { run_in_background: false })` + +On CLI failure, resume: `ccw cli -p "Continue" --resume issue-<issueId> --tool <tool> --mode write` + +## Phase 4: Verify & Commit + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Tests pass | Detect and run test command | No new failures | +| Code review | Optional, per task config | Review output logged | + +- Tests pass -> optional code review -> `ccw issue update <issueId> --status resolved` -> report `impl_complete` +- Tests fail -> report `impl_failed` with truncated test output + +Update `<session>/wisdom/.msg/meta.json` under `implementer` namespace: +- Read existing -> merge `{ "implementer": { issue_id, executor, test_status, review_status } }` -> write back diff --git a/.claude/skills/team-issue/roles/integrator/role.md b/.claude/skills/team-issue/roles/integrator/role.md new file mode 100644 index 00000000..7d3201d6 --- /dev/null +++ b/.claude/skills/team-issue/roles/integrator/role.md @@ -0,0 +1,84 @@ +--- +role: integrator +prefix: MARSHAL +inner_loop: false +message_types: [queue_ready, conflict_found, error] +--- + +# Issue Integrator + +Queue orchestration, conflict detection, and execution order optimization. Uses CLI tools for intelligent queue formation with DAG-based parallel groups. + +## Phase 2: Collect Bound Solutions + +| Input | Source | Required | +|-------|--------|----------| +| Issue IDs | Task description (GH-\d+ or ISS-\d{8}-\d{6}) | Yes | +| Bound solutions | `ccw issue solutions <id> --json` | Yes | +| wisdom meta | <session>/wisdom/.msg/meta.json | No | + +1. Extract issue IDs from task description via regex +2. Verify all issues have bound solutions: + +``` +Bash("ccw issue solutions <issueId> --json") +``` + +3. Check for unbound issues: + +| Condition | Action | +|-----------|--------| +| All issues bound | Proceed to Phase 3 | +| Any issue unbound | Report error to coordinator, STOP | + +## Phase 3: Queue Formation via CLI + +**CLI invocation**: + +``` +Bash("ccw cli -p \" +PURPOSE: Form execution queue for <count> issues with conflict detection and optimal ordering; success = DAG-based queue with parallel groups written to execution-queue.json + +TASK: • Load all bound solutions from .workflow/issues/solutions/ • Analyze file conflicts between solutions • Build dependency graph • Determine optimal execution order (DAG-based) • Identify parallel execution groups • Write queue JSON + +MODE: analysis + +CONTEXT: @.workflow/issues/solutions/**/*.json | Memory: Issues to queue: <issueIds> + +EXPECTED: Queue JSON with: ordered issue list, conflict analysis, parallel_groups (issues that can run concurrently), depends_on relationships +Write to: .workflow/issues/queue/execution-queue.json + +CONSTRAINTS: Resolve file conflicts | Optimize for parallelism | Maintain dependency order +\" --tool gemini --mode analysis", { run_in_background: false }) +``` + +**Parse queue result**: + +``` +Read(".workflow/issues/queue/execution-queue.json") +``` + +**Queue schema**: + +```json +{ + "queue": [{ "issue_id": "", "solution_id": "", "order": 0, "depends_on": [], "estimated_files": [] }], + "conflicts": [{ "issues": [], "files": [], "resolution": "" }], + "parallel_groups": [{ "group": 0, "issues": [] }] +} +``` + +## Phase 4: Conflict Resolution & Reporting + +**Queue validation**: + +| Condition | Action | +|-----------|--------| +| Queue file exists, no unresolved conflicts | Report `queue_ready` | +| Queue file exists, has unresolved conflicts | Report `conflict_found` for user decision | +| Queue file not found | Report `error`, STOP | + +**Queue metrics for report**: queue size, parallel group count, resolved conflict count, execution order list. + +Update `<session>/wisdom/.msg/meta.json` under `integrator` namespace: +- Read existing -> merge `{ "integrator": { queue_size, parallel_groups, conflict_count } }` -> write back diff --git a/.claude/skills/team-issue/roles/planner/role.md b/.claude/skills/team-issue/roles/planner/role.md new file mode 100644 index 00000000..c941b8f7 --- /dev/null +++ b/.claude/skills/team-issue/roles/planner/role.md @@ -0,0 +1,81 @@ +--- +role: planner +prefix: SOLVE +inner_loop: false +additional_prefixes: [SOLVE-fix] +message_types: [solution_ready, multi_solution, error] +--- + +# Issue Planner + +Design solutions and decompose into implementation tasks. Uses CLI tools for ACE exploration and solution generation. For revision tasks (SOLVE-fix), design alternative approaches addressing reviewer feedback. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Issue ID | Task description (GH-\d+ or ISS-\d{8}-\d{6}) | Yes | +| Explorer context | `<session>/explorations/context-<issueId>.json` | No | +| Review feedback | Task description (for SOLVE-fix tasks) | No | +| wisdom meta | <session>/wisdom/.msg/meta.json | No | + +1. Extract issue ID from task description via regex: `(?:GH-\d+|ISS-\d{8}-\d{6})` +2. If no issue ID found -> report error, STOP +3. Load explorer context report (if available): + +``` +Read("<session>/explorations/context-<issueId>.json") +``` + +4. Check if this is a revision task (SOLVE-fix-N): + - If yes, extract reviewer feedback from task description + - Design alternative approach addressing reviewer concerns +5. Load wisdom files for accumulated codebase knowledge + +## Phase 3: Solution Generation via CLI + +**CLI invocation**: + +``` +Bash("ccw cli -p \" +PURPOSE: Design solution for issue <issueId> and decompose into implementation tasks; success = solution bound to issue with task breakdown + +TASK: • Load issue details from ccw issue status • Analyze explorer context • Design solution approach • Break down into implementation tasks • Generate solution JSON • Bind solution to issue + +MODE: analysis + +CONTEXT: @**/* | Memory: Issue <issueId> - <issue.title> (Priority: <issue.priority>) +Explorer findings: <explorerContext.key_findings> +Relevant files: <explorerContext.relevant_files> +Complexity: <explorerContext.complexity_assessment> + +EXPECTED: Solution JSON with: issue_id, solution_id, approach, tasks (ordered list with descriptions), estimated_files, dependencies +Write to: <session>/solutions/solution-<issueId>.json +Then bind: ccw issue bind <issueId> <solution_id> + +CONSTRAINTS: Follow existing patterns | Minimal changes | Address reviewer feedback if SOLVE-fix task +\" --tool gemini --mode analysis", { run_in_background: false }) +``` + +**Expected CLI output**: Solution file path and binding confirmation + +**Parse result**: + +``` +Read("<session>/solutions/solution-<issueId>.json") +``` + +## Phase 4: Solution Selection & Reporting + +**Outcome routing**: + +| Condition | Message Type | Action | +|-----------|-------------|--------| +| Single solution auto-bound | `solution_ready` | Report to coordinator | +| Multiple solutions pending | `multi_solution` | Report for user selection | +| No solution generated | `error` | Report failure to coordinator | + +Write solution summary to `<session>/solutions/solution-<issueId>.json`. + +Update `<session>/wisdom/.msg/meta.json` under `planner` namespace: +- Read existing -> merge `{ "planner": { issue_id, solution_id, task_count, is_revision } }` -> write back diff --git a/.claude/skills/team-issue/roles/reviewer/role.md b/.claude/skills/team-issue/roles/reviewer/role.md new file mode 100644 index 00000000..27ab2b7f --- /dev/null +++ b/.claude/skills/team-issue/roles/reviewer/role.md @@ -0,0 +1,86 @@ +--- +role: reviewer +prefix: AUDIT +inner_loop: false +message_types: [approved, concerns, rejected, error] +--- + +# Issue Reviewer + +Review solution plans for technical feasibility, risk, and completeness. Quality gate role between plan and execute phases. Provides clear verdicts: approved, rejected, or concerns. + +## Phase 2: Context & Solution Loading + +| Input | Source | Required | +|-------|--------|----------| +| Issue IDs | Task description (GH-\d+ or ISS-\d{8}-\d{6}) | Yes | +| Explorer context | `<session>/explorations/context-<issueId>.json` | No | +| Bound solution | `ccw issue solutions <id> --json` | Yes | +| wisdom meta | <session>/wisdom/.msg/meta.json | No | + +1. Extract issue IDs from task description via regex +2. Load explorer context reports for each issue +3. Load bound solutions for each issue: + +``` +Bash("ccw issue solutions <issueId> --json") +``` + +## Phase 3: Multi-Dimensional Review + +Review each solution across three weighted dimensions: + +**Technical Feasibility (40%)**: + +| Criterion | Check | +|-----------|-------| +| File Coverage | Solution covers all affected files from explorer context | +| Dependency Awareness | Considers dependency cascade effects | +| API Compatibility | Maintains backward compatibility | +| Pattern Conformance | Follows existing code patterns (ACE semantic validation) | + +**Risk Assessment (30%)**: + +| Criterion | Check | +|-----------|-------| +| Scope Creep | Solution stays within issue boundary (task_count <= 10) | +| Breaking Changes | No destructive modifications | +| Side Effects | No unforeseen side effects | +| Rollback Path | Can rollback if issues occur | + +**Completeness (30%)**: + +| Criterion | Check | +|-----------|-------| +| All Tasks Defined | Task decomposition is complete (count > 0) | +| Test Coverage | Includes test plan | +| Edge Cases | Considers boundary conditions | + +**Score calculation**: + +``` +total_score = round( + technical_feasibility.score * 0.4 + + risk_assessment.score * 0.3 + + completeness.score * 0.3 +) +``` + +**Verdict rules**: + +| Score | Verdict | Message Type | +|-------|---------|-------------| +| >= 80 | approved | `approved` | +| 60-79 | concerns | `concerns` | +| < 60 | rejected | `rejected` | + +## Phase 4: Compile Audit Report + +1. Write audit report to `<session>/audits/audit-report.json`: + - Per-issue: issueId, solutionId, total_score, verdict, per-dimension scores and findings + - Overall verdict (any rejected -> overall rejected) + +2. Update `<session>/wisdom/.msg/meta.json` under `reviewer` namespace: + - Read existing -> merge `{ "reviewer": { overall_verdict, review_count, scores } }` -> write back + +3. For rejected solutions, include specific rejection reasons and actionable feedback for SOLVE-fix task creation diff --git a/.claude/skills/team-issue/specs/pipelines.md b/.claude/skills/team-issue/specs/pipelines.md new file mode 100644 index 00000000..cc6c70ae --- /dev/null +++ b/.claude/skills/team-issue/specs/pipelines.md @@ -0,0 +1,124 @@ +# Pipeline Definitions — team-issue + +## Available Pipelines + +### Quick Pipeline (4 beats, strictly serial) + +``` +EXPLORE-001 → SOLVE-001 → MARSHAL-001 → BUILD-001 +[explorer] [planner] [integrator] [implementer] +``` + +Use when: 1-2 simple issues, no high-priority (priority < 4). + +### Full Pipeline (5 beats, with review gate) + +``` +EXPLORE-001 → SOLVE-001 → AUDIT-001 ─┬─(approved/concerns)→ MARSHAL-001 → BUILD-001 +[explorer] [planner] [reviewer] │ + └─(rejected, round<2)→ SOLVE-fix-001 → AUDIT-002 → MARSHAL-001 → BUILD-001 +``` + +Use when: 1-4 issues with high-priority, or 3-4 issues regardless of priority. + +### Batch Pipeline (parallel windows) + +``` +[EXPLORE-001..N](parallel, max 5) → [SOLVE-001..N](sequential) → AUDIT-001 → MARSHAL-001 → [BUILD-001..M](parallel, max 3, deferred) +``` + +Use when: 5+ issues. + +Note: BUILD tasks are created dynamically after MARSHAL completes and execution-queue.json is available. + +## Task Metadata Registry + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| EXPLORE-001 | explorer | explore | (none) | Context analysis and impact assessment | +| EXPLORE-002..N | explorer | explore | (none) | Parallel exploration (Batch mode only, max 5) | +| SOLVE-001 | planner | plan | EXPLORE-001 (or all EXPLORE-*) | Solution design and task decomposition | +| SOLVE-002..N | planner | plan | all EXPLORE-* | Parallel solution design (Batch mode only) | +| AUDIT-001 | reviewer | review | SOLVE-001 (or all SOLVE-*) | Technical feasibility and risk review (Full/Batch) | +| SOLVE-fix-001 | planner | fix | AUDIT-001 | Revised solution addressing reviewer feedback | +| AUDIT-002 | reviewer | re-review | SOLVE-fix-001 | Re-review of revised solution | +| MARSHAL-001 | integrator | integrate | AUDIT-001 (or last SOLVE-* in quick) | Conflict detection and queue orchestration | +| BUILD-001 | implementer | implement | MARSHAL-001 | Code implementation and result submission | +| BUILD-002..M | implementer | implement | MARSHAL-001 | Parallel implementation (Batch, deferred creation) | + +## Mode Auto-Detection + +| Condition | Mode | +|-----------|------| +| User specifies `--mode=<M>` | Use specified mode | +| Issue count <= 2 AND no high-priority (priority < 4) | `quick` | +| Issue count <= 2 AND has high-priority (priority >= 4) | `full` | +| 3-4 issues | `full` | +| Issue count >= 5 | `batch` | + +## Checkpoints + +| Trigger | Location | Behavior | +|---------|----------|----------| +| Review gate | After AUDIT-* | approved/concerns → MARSHAL; rejected → SOLVE-fix (max 2 rounds) | +| Review loop limit | fix_cycles >= 2 | Force proceed to MARSHAL with warnings | +| Deferred BUILD creation | After MARSHAL-* (batch) | Read execution-queue.json, create BUILD tasks | +| Pipeline stall | No ready + no running | Check missing tasks, report to user | + +## Completion Conditions + +| Mode | Completion Condition | +|------|---------------------| +| quick | All 4 tasks completed | +| full | All 5 tasks (+ any fix cycle tasks) completed | +| batch | All N EXPLORE + N SOLVE + 1 AUDIT + 1 MARSHAL + M BUILD (+ any fix cycle tasks) completed | + +## Parallel Spawn Rules + +| Pipeline | Stage | Max Parallel | +|----------|-------|-------------| +| Batch | EXPLORE-001..N | min(N, 5) | +| Batch | BUILD-001..M | min(M, 3) | +| All | All other stages | 1 | + +## Shared State (meta.json) + +| Role | State Key | +|------|-----------| +| explorer | `explorer` (issue_id, complexity, impact_scope, file_count) | +| planner | `planner` (issue_id, solution_id, task_count, is_revision) | +| reviewer | `reviewer` (overall_verdict, review_count, scores) | +| integrator | `integrator` (queue_size, parallel_groups, conflict_count) | +| implementer | `implementer` (issue_id, executor, test_status, review_status) | + +## Message Types + +| Role | Types | +|------|-------| +| coordinator | `pipeline_selected`, `review_result`, `fix_required`, `task_unblocked`, `error`, `shutdown` | +| explorer | `context_ready`, `error` | +| planner | `solution_ready`, `multi_solution`, `error` | +| reviewer | `approved`, `concerns`, `rejected`, `error` | +| integrator | `queue_ready`, `conflict_found`, `error` | +| implementer | `impl_complete`, `impl_failed`, `error` | + +## Review-Fix Cycle + +``` +AUDIT verdict: rejected + │ + ├─ fix_cycles < 2 → create SOLVE-fix-<N> + AUDIT-<N+1> → spawn planner → wait + │ ↑ + │ (repeat if rejected again) + │ + └─ fix_cycles >= 2 → force proceed to MARSHAL with rejection warning logged +``` + +## Deferred BUILD Creation (Batch Mode) + +BUILD tasks are not created during initial dispatch. After MARSHAL-001 completes: +1. Read `.workflow/issues/queue/execution-queue.json` +2. Parse `parallel_groups` to determine M +3. Create BUILD-001..M tasks with `addBlockedBy: ["MARSHAL-001"]` +4. Assign owners: M <= 2 → "implementer"; M > 2 → "implementer-1".."implementer-M" (max 3) +5. Spawn implementer workers via handleSpawnNext diff --git a/.claude/skills/team-iterdev/SKILL.md b/.claude/skills/team-iterdev/SKILL.md index f65b353b..942f5fb8 100644 --- a/.claude/skills/team-iterdev/SKILL.md +++ b/.claude/skills/team-iterdev/SKILL.md @@ -1,415 +1,61 @@ --- name: team-iterdev -description: Unified team skill for iterative development team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team iterdev". +description: Unified team skill for iterative development team. Pure router — all roles read this file. Beat model is coordinator-only in monitor.md. Generator-Critic loops (developer<->reviewer, max 3 rounds). Triggers on "team iterdev". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) --- # Team IterDev -Iterative development team skill. Generator-Critic loops (developer<->reviewer, max 3 rounds), task ledger (task-ledger.json) for real-time progress, shared memory (cross-sprint learning), and dynamic pipeline selection for incremental delivery. All team members route via `--role=xxx`. +Iterative development team skill. Generator-Critic loops (developer<->reviewer, max 3 rounds), task ledger (task-ledger.json) for real-time progress, shared memory (cross-sprint learning), and dynamic pipeline selection for incremental delivery. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-iterdev") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-iterdev", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -archi- devel- tester review- -tect oper er - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+ + v v v v + [architect] [developer] [tester] [reviewer] + (team-worker agents, each loads roles/<role>/role.md) ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| architect | [roles/architect/role.md](roles/architect/role.md) | DESIGN-* | false | +| developer | [roles/developer/role.md](roles/developer/role.md) | DEV-* | true | +| tester | [roles/tester/role.md](roles/tester/role.md) | VERIFY-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REVIEW-* | false | + ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent -> Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `IDS` +- **Session path**: `.workflow/.team/IDS-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| architect | [role-specs/architect.md](role-specs/architect.md) | DESIGN-* | false | -| developer | [role-specs/developer.md](role-specs/developer.md) | DEV-* | true | -| tester | [role-specs/tester.md](role-specs/tester.md) | VERIFY-* | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* | false | +## Worker Spawn Template -> **COMPACT PROTECTION**: Role files are execution documents, not reference material. When context compression occurs and role instructions are reduced to summaries, you **MUST immediately `Read` the corresponding role.md to reload before continuing execution**. Never execute any Phase based on summaries alone. - -### 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-iterdev", args="task description")` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: requirement clarification -> TeamCreate -> create task chain - -> coordinator Phase 4: spawn first batch of workers (background) -> STOP - -> Worker executes -> SendMessage callback -> coordinator advances next step - -> Loop until pipeline complete -> Phase 5 report -``` - -**User Commands** (wake suspended coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status diagram, do not advance | -| `resume` / `continue` | Check worker status, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Each worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks -> idle wait -4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after recovery): -- Check if this task's output artifact already exists -- Artifact complete -> skip to Phase 5 report completion -- Artifact incomplete or missing -> normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard report flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Role Isolation Rules - -| Allowed | Prohibited | -|---------|------------| -| Process tasks with own prefix | Process other roles' prefix tasks | -| Share state via team_msg(type='state_update') | Create tasks for other roles | -| SendMessage to coordinator | Communicate directly with other workers | - -**Coordinator additional restrictions**: No direct code writing, no directly executing analysis/testing/review. - -### Message Bus - -Call `mcp__ccw-tools__team_msg` with: operation="log", session_id=<session-id>, from=<role>, type=<type>, data={ref: "<file_path>"} -`to` and `summary` auto-defaulted -- do NOT specify explicitly. - -**CLI Fallback**: `ccw team log --session-id "<session-id>" --from "<role>" --type "<type>" --json` - -| Role | Message Types | -|------|---------------| -| coordinator | `sprint_started`, `gc_loop_trigger`, `sprint_complete`, `task_unblocked`, `error`, `shutdown`, `conflict_detected`, `conflict_resolved`, `resource_locked`, `resource_unlocked`, `resource_contention`, `rollback_initiated`, `rollback_completed`, `rollback_failed`, `dependency_mismatch`, `dependency_update_needed`, `context_checkpoint_saved`, `context_restored`, `user_feedback_received`, `tech_debt_identified` | -| architect | `design_ready`, `design_revision`, `error` | -| developer | `dev_complete`, `dev_progress`, `error` | -| tester | `verify_passed`, `verify_failed`, `fix_required`, `error` | -| reviewer | `review_passed`, `review_revision`, `review_critical`, `error` | - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | iterdev | -| Session directory | `.workflow/.team/IDS-{slug}-{date}/` | -| State sharing | team_msg(type='state_update') + .msg/meta.json | -| Task ledger file | task-ledger.json | - ---- - -## Coordinator Protocol Summary - -The coordinator manages several operational protocols. Full implementations reside in [roles/coordinator.md](roles/coordinator.md). The tables below describe the behavioral contracts for each protocol. - -> **NOTE**: These are behavioral specifications only. Full procedural logic, data format details, and edge case handling are defined in the coordinator role file. - -### Resource Lock Protocol - -Concurrency control for shared resources. Prevents multiple workers from modifying the same files simultaneously. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Acquire lock | Worker requests exclusive access to a resource | Check `resource_locks` via team_msg(type='state_update'). If unlocked, record lock with task ID, timestamp, and holder role. Log `resource_locked` message. Return success. | -| Deny lock | Resource already locked by another task | Return failure with current holder's task ID. Log `resource_contention` message. Worker must wait or request alternative resource. | -| Release lock | Worker completes task or explicitly releases | Remove lock entry from `resource_locks`. Log `resource_unlocked` message to all workers. | -| Force release | Lock held beyond timeout (5 min) | Force-remove lock entry. Notify original holder and coordinator. Log warning. | -| Deadlock detection | Multiple tasks waiting on each other's locks | Abort youngest task, release its locks, notify coordinator. | - -### Conflict Detection Protocol - -Detects and resolves file-level conflicts between concurrent development tasks. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Detect conflict | DEV task completes with changed files | Compare changed files against other in_progress/completed tasks in ledger. If overlap found, update task's `conflict_info` to status "detected" with conflicting file list. Log `conflict_detected` message. | -| Resolve conflict | Conflict detected requiring resolution | Set `conflict_info.resolution_strategy` (manual/auto_merge/abort). Create `{taskId}-fix-conflict` task assigned to developer. Log `conflict_resolved` message. | -| Skip (no conflict) | No file overlap with other tasks | No action needed, task proceeds normally. | - -### Rollback Point Protocol - -Manages state snapshots for safe recovery when tasks fail or produce undesirable results. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Create rollback point | Task successfully completes a phase | Generate snapshot ID, record rollback procedure (default: `git revert HEAD`) and state reference in task's `rollback_info` in the ledger. | -| Execute rollback | Task failure or user-requested revert | Log `rollback_initiated`. Execute stored rollback procedure. On success, log `rollback_completed`. On failure, log `rollback_failed` with error details. | -| Validate snapshot | Before executing rollback | Verify snapshot ID exists and rollback procedure is valid. Abort with error if invalid. | - -### Dependency Validation Protocol - -Validates external dependencies (npm, pip, etc.) before task execution begins. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Validate dependencies | Task startup with declared dependencies | For each dependency: check installed version against expected version range. Record results in task's `external_dependencies` array in ledger (status: ok/mismatch/missing). | -| Report mismatch | Any dependency has status mismatch or missing | Log `dependency_mismatch` message listing affected packages. Block task until resolved or user overrides. | -| Update notification | External dependency has important update available | Log `dependency_update_needed` message. Add to sprint backlog for consideration. | - -### Checkpoint Management Protocol - -Saves and restores task execution state for interruption recovery. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Save checkpoint | Task reaches significant progress milestone | Store checkpoint in `task_checkpoints` via team_msg(type='state_update') with timestamp and state data pointer. Retain last 5 checkpoints per task. Log `context_checkpoint_saved`. | -| Restore checkpoint | Task resumes after interruption | Load latest checkpoint for task. Read state data from pointer path. Log `context_restored`. Return state data to worker. | -| Checkpoint not found | Resume requested but no checkpoints exist | Return failure with reason. Worker starts fresh from Phase 1. | - -### User Feedback Protocol - -Collects, categorizes, and tracks user feedback throughout the sprint. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Receive feedback | User provides feedback (via AskUserQuestion or direct) | Create feedback item with ID (FB-xxx), severity, category, timestamp. Store in `user_feedback_items` via team_msg(type='state_update') (max 50 items). Log `user_feedback_received`. | -| Link to task | Feedback relates to specific task | Update feedback item's `source_task_id` and set status to "reviewed". | -| Triage feedback | New feedback with high/critical severity | Prioritize in next sprint planning. Create task if actionable. | - -### Tech Debt Management Protocol - -Identifies, tracks, and prioritizes technical debt discovered during development. - -| Action | Trigger Condition | Coordinator Behavior | -|--------|-------------------|----------------------| -| Identify debt | Worker reports tech debt during development or review | Create debt item with ID (TD-xxx), category (code/design/test/documentation), severity, estimated effort. Store in `tech_debt_items` via team_msg(type='state_update'). Log `tech_debt_identified`. | -| Generate report | Sprint retrospective or user request | Aggregate debt items by severity and category. Report totals, open items, and in-progress items. | -| Prioritize debt | Sprint planning phase | Rank debt items by severity and priority. Recommend items for current sprint based on estimated effort and available capacity. | -| Resolve debt | Developer completes debt resolution task | Update debt item status to "resolved". Record resolution in sprint history. | - ---- - -## Three-Pipeline Architecture - -``` -Patch (simple fix): - DEV-001 -> VERIFY-001 - -Sprint (standard feature): - DESIGN-001 -> DEV-001 -> [VERIFY-001 + REVIEW-001](parallel) - -Multi-Sprint (large feature): - Sprint 1: DESIGN-001 -> DEV-001 -> DEV-002(incremental) -> VERIFY-001 -> DEV-fix -> REVIEW-001 - Sprint 2: DESIGN-002(refined) -> DEV-003 -> VERIFY-002 -> REVIEW-002 - ... -``` - -### Generator-Critic Loop - -developer <-> reviewer loop, max 3 rounds: - -``` -DEV -> REVIEW -> (if review.critical_count > 0 || review.score < 7) - -> DEV-fix -> REVIEW-2 -> (if still issues) -> DEV-fix-2 -> REVIEW-3 - -> (max 3 rounds, then accept with warning) -``` - -### Multi-Sprint Dynamic Downgrade - -If Sprint N metrics are strong (velocity >= expected, review avg >= 8), coordinator may downgrade Sprint N+1 from multi-sprint to sprint pipeline for efficiency. - -### Cadence Control - -**Beat Model**: Event-driven. Each beat = coordinator wakes -> processes -> spawns -> STOP. - -``` -Beat Cycle (single beat) -=========================================================== - Event Coordinator Workers ------------------------------------------------------------ - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [Worker A] Phase 1-5 - | (parallel OK) --+--> [Worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -=========================================================== -``` - -**Pipeline Beat Views**: - -``` -Patch (2 beats, strict serial) ----------------------------------------------------------- -Beat 1 2 - | | - DEV -> VERIFY - ^ ^ - pipeline pipeline - start done - -Sprint (3 beats, with parallel window) ----------------------------------------------------------- -Beat 1 2 3 - | | +----+----+ - DESIGN -> DEV --> VERIFY // REVIEW <- parallel window - +----+----+ - pipeline - done - -Multi-Sprint (N beats, iterative) ----------------------------------------------------------- -Sprint 1: -Beat 1 2 3 4 5 6 - | | | | +----+----+ | - DESIGN -> DEV -> DEV -> VERIFY // DEV-fix -> REVIEW - (incr) (GC loop) - -Sprint 2: (refined pipeline based on Sprint 1 metrics) -Beat 7 8 9 10 - | | | | - DESIGN -> DEV -> VERIFY -> REVIEW -``` - -**Checkpoints**: - -| Trigger Condition | Location | Behavior | -|-------------------|----------|----------| -| GC loop exceeds max rounds | After REVIEW-3 | Stop iteration, accept with warning, record in shared memory | -| Sprint transition | End of Sprint N | Pause, retrospective, user confirms `resume` for Sprint N+1 | -| Pipeline stall | No ready + no running tasks | Check missing tasks, report blockedBy chain to user | - -**Stall Detection** (coordinator `handleCheck`): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker unresponsive | in_progress task with no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | No ready + no running + has pending | Inspect blockedBy dependency chain, report blockage | -| GC loop exceeded | DEV/REVIEW iteration > max_rounds (3) | Terminate loop, output latest review report | - ---- - -## Task Metadata Registry - -| Task ID | Role | Pipeline | Dependencies | Description | -|---------|------|----------|-------------|-------------| -| DESIGN-001 | architect | sprint/multi | (none) | Technical design and task breakdown | -| DEV-001 | developer | all | DESIGN-001 (sprint/multi) or (none for patch) | Code implementation | -| DEV-002 | developer | multi | DEV-001 | Incremental implementation | -| DEV-fix | developer | sprint/multi | REVIEW-* (GC loop trigger) | Fix issues from review | -| VERIFY-001 | tester | all | DEV-001 (or last DEV) | Test execution and fix cycles | -| REVIEW-001 | reviewer | sprint/multi | DEV-001 (or last DEV) | Code review and quality scoring | - ---- - -## Wisdom Accumulation - -Cross-sprint knowledge accumulation. Coordinator initializes `wisdom/` directory at session start. Equivalent to shared-memory sprint_history but structured for long-term learning. - -**Directory**: -``` -<session-folder>/wisdom/ -+-- learnings.md # Patterns and insights -+-- decisions.md # Architecture and design decisions -+-- conventions.md # Codebase conventions -+-- issues.md # Known risks and issues -``` - -**Worker Loading** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contributing** (Phase 4/5): Write discoveries from current task into corresponding wisdom files. - -**Shared Memory** (sprint-level learning, accumulated across sprints): - -| Field | Purpose | -|-------|---------| -| `sprint_history[]` | Per-sprint: what_worked, what_failed, patterns_learned | -| `architecture_decisions[]` | Cross-sprint architecture decisions | -| `implementation_context[]` | Implementation patterns and context | -| `review_feedback_trends[]` | Review quality trends across sprints | -| `resource_locks{}` | Current resource lock state (see Resource Lock Protocol) | -| `task_checkpoints{}` | Task checkpoint data (see Checkpoint Management Protocol) | -| `user_feedback_items[]` | User feedback items (see User Feedback Protocol) | -| `tech_debt_items[]` | Tech debt tracking (see Tech Debt Management Protocol) | - ---- - -## Task Ledger - -Real-time tracking of all sprint task progress. Coordinator updates at each task state transition. - -**Structure**: - -| Field | Description | -|-------|-------------| -| `sprint_id` | Current sprint identifier | -| `sprint_goal` | Sprint objective | -| `tasks[]` | Array of task entries (see below) | -| `metrics` | Aggregated metrics: total, completed, in_progress, blocked, velocity | - -**Task Entry Fields**: - -| Field | Description | -|-------|-------------| -| `id` | Task identifier (e.g., DEV-001) | -| `title` | Task title | -| `owner` | Assigned role | -| `status` | pending / in_progress / completed / blocked | -| `started_at` / `completed_at` | Timestamps | -| `gc_rounds` | Generator-Critic iteration count | -| `review_score` | Reviewer score (null until reviewed) | -| `test_pass_rate` | Tester pass rate (null until tested) | -| `conflict_info` | Conflict state: status (none/detected/resolved), conflicting_files, resolution_strategy, resolved_by_task_id | -| `rollback_info` | Rollback state: snapshot_id, rollback_procedure, last_successful_state_id | -| `external_dependencies[]` | Dependency entries: name, version_range, actual_version, source, status (ok/mismatch/missing) | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -420,7 +66,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-iterdev/role-specs/<role>.md +role_spec: .claude/skills/team-iterdev/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: iterdev @@ -428,92 +74,54 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (developer): Set `inner_loop: true`. The team-worker agent handles the loop internally. +## User Commands -**Single-task roles** (architect, tester, reviewer): Set `inner_loop: false`. +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): +## Session Directory ``` -AskUserQuestion({ - questions: [{ - question: "IterDev pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) +.workflow/.team/IDS-<slug>-<YYYY-MM-DD>/ +├── .msg/ +│ ├── messages.jsonl # Team message bus +│ └── meta.json # Session state +├── task-analysis.json # Coordinator analyze output +├── task-ledger.json # Real-time task progress ledger +├── wisdom/ # Cross-task knowledge accumulation +│ ├── learnings.md +│ ├── decisions.md +│ ├── conventions.md +│ └── issues.md +├── design/ # Architect output +│ ├── design-001.md +│ └── task-breakdown.json +├── code/ # Developer tracking +│ └── dev-log.md +├── verify/ # Tester output +│ └── verify-001.json +└── review/ # Reviewer output + └── review-001.md ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-iterdev", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | +## Specs Reference ---- - -## Unified Session Directory - -``` -.workflow/.team/IDS-{slug}-{YYYY-MM-DD}/ -+-- .msg/meta.json -+-- .msg/messages.jsonl # Team message bus -+-- .msg/meta.json # Session metadata -+-- task-ledger.json # Real-time task progress ledger -+-- wisdom/ # Cross-task knowledge accumulation -| +-- learnings.md -| +-- decisions.md -| +-- conventions.md -| +-- issues.md -+-- design/ # Architect output -| +-- design-001.md -| +-- task-breakdown.json -+-- code/ # Developer tracking -| +-- dev-log.md -+-- verify/ # Tester output -| +-- verify-001.json -+-- review/ # Reviewer output - +-- review-001.md -``` - -## Session Resume - -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan `.workflow/.team/IDS-*/.msg/meta.json` for active/paused sessions -2. Multiple matches -> AskUserQuestion for selection -3. Audit TaskList -> reconcile session state with 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 +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry ## 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 | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | | GC loop exceeds 3 rounds | Accept with warning, record in shared memory | | Sprint velocity drops below 50% | Coordinator alerts user, suggests scope reduction | | Task ledger corrupted | Rebuild from TaskList state | | Conflict detected | Update conflict_info, notify coordinator, create DEV-fix task | -| Resource lock timeout | Force release after 5 min, notify holder and coordinator | -| Rollback requested | Validate snapshot_id, execute rollback procedure, notify all | -| Deadlock detected | Abort youngest task, release its locks, notify coordinator | -| Dependency mismatch | Log mismatch, block task until resolved or user override | -| Checkpoint restore failure | Log error, worker restarts from Phase 1 | +| Pipeline deadlock | Check blockedBy chain, report blocking point | diff --git a/.claude/skills/team-iterdev/roles/architect/role.md b/.claude/skills/team-iterdev/roles/architect/role.md new file mode 100644 index 00000000..4f96e7fd --- /dev/null +++ b/.claude/skills/team-iterdev/roles/architect/role.md @@ -0,0 +1,65 @@ +--- +role: architect +prefix: DESIGN +inner_loop: false +message_types: + success: design_ready + revision: design_revision + error: error +--- + +# Architect + +Technical design, task decomposition, and architecture decision records for iterative development. + +## Phase 2: Context Loading + Codebase Exploration + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | +| Wisdom files | <session>/wisdom/ | No | + +1. Extract session path and requirement from task description +2. Read .msg/meta.json for shared context (architecture_decisions, implementation_context) +3. Read wisdom files if available (learnings.md, decisions.md, conventions.md) +4. Explore codebase for existing patterns, module structure, dependencies: + - Use mcp__ace-tool__search_context for semantic discovery + - Identify similar implementations and integration points + +## Phase 3: Technical Design + Task Decomposition + +**Design strategy selection**: + +| Condition | Strategy | +|-----------|----------| +| Single module change | Direct inline design | +| Cross-module change | Multi-component design with integration points | +| Large refactoring | Phased approach with milestones | + +**Outputs**: + +1. **Design Document** (`<session>/design/design-<num>.md`): + - Architecture decision: approach, rationale, alternatives + - Component design: responsibility, dependencies, files, complexity + - Task breakdown: files, estimated complexity, dependencies, acceptance criteria + - Integration points and risks with mitigations + +2. **Task Breakdown JSON** (`<session>/design/task-breakdown.json`): + - Array of tasks with id, title, files, complexity, dependencies, acceptance_criteria + - Execution order for developer to follow + +## Phase 4: Design Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Components defined | Verify component list | At least 1 component | +| Task breakdown exists | Verify task list | At least 1 task | +| Dependencies mapped | All components have dependencies field | All present (can be empty) | +| Integration points | Verify integration section | Key integrations documented | + +1. Run validation checks above +2. Write architecture_decisions entry to .msg/meta.json: + - design_id, approach, rationale, components, task_count +3. Write discoveries to wisdom/decisions.md and wisdom/conventions.md diff --git a/.claude/skills/team-iterdev/roles/coordinator/commands/analyze.md b/.claude/skills/team-iterdev/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..ddaebc91 --- /dev/null +++ b/.claude/skills/team-iterdev/roles/coordinator/commands/analyze.md @@ -0,0 +1,62 @@ +# Analyze Task + +Parse iterative development task -> detect capabilities -> assess pipeline complexity -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Role | +|----------|------------|------| +| design, architect, restructure, refactor plan | architect | architect | +| implement, build, code, fix, develop | developer | developer | +| test, verify, validate, coverage | tester | tester | +| review, audit, quality, check | reviewer | reviewer | + +## Pipeline Selection + +| Signal | Score | +|--------|-------| +| Changed files > 10 | +3 | +| Changed files 3-10 | +2 | +| Structural change (refactor, architect, restructure) | +3 | +| Cross-cutting (multiple, across, cross) | +2 | +| Simple fix (fix, bug, typo, patch) | -2 | + +| Score | Pipeline | +|-------|----------| +| >= 5 | multi-sprint | +| 2-4 | sprint | +| 0-1 | patch | + +## Dependency Graph + +Natural ordering tiers: +- Tier 0: architect (design must come first) +- Tier 1: developer (implementation requires design) +- Tier 2: tester, reviewer (validation requires artifacts, can run parallel) + +## Complexity Assessment + +| Factor | Points | +|--------|--------| +| Cross-module changes | +2 | +| Serial depth > 3 | +1 | +| Multiple developers needed | +2 | +| GC loop likely needed | +1 | + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_type": "<patch|sprint|multi-sprint>", + "capabilities": [{ "name": "<cap>", "role": "<role>", "keywords": ["..."] }], + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "needs_architecture": true, + "needs_testing": true, + "needs_review": true +} +``` diff --git a/.claude/skills/team-iterdev/roles/coordinator/commands/monitor.md b/.claude/skills/team-iterdev/roles/coordinator/commands/monitor.md index de8861fa..39c776e4 100644 --- a/.claude/skills/team-iterdev/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-iterdev/roles/coordinator/commands/monitor.md @@ -1,15 +1,25 @@ # Command: Monitor -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control (developer<->reviewer), and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | -|-----|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| WORKER_AGENT | team-worker | -| MAX_GC_ROUNDS | 3 | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 3 + +## Handler Router + +| Source | Handler | +|--------|---------| +| Message contains [architect], [developer], [tester], [reviewer] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | ## Phase 2: Context Loading @@ -91,7 +101,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-iterdev/role-specs/<role>.md +role_spec: .claude/skills/team-iterdev/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: iterdev diff --git a/.claude/skills/team-iterdev/roles/coordinator/role.md b/.claude/skills/team-iterdev/roles/coordinator/role.md index 2e301f0c..4b99b964 100644 --- a/.claude/skills/team-iterdev/roles/coordinator/role.md +++ b/.claude/skills/team-iterdev/roles/coordinator/role.md @@ -1,15 +1,14 @@ -# Coordinator - Iterative Development Team +# Coordinator Role -**Role**: coordinator -**Type**: Orchestrator -**Team**: iterdev +Orchestrate team-iterdev: analyze -> dispatch -> spawn -> monitor -> report. -Orchestrates the iterative development pipeline: sprint planning, task ledger maintenance, Generator-Critic loop control (developer<->reviewer, max 3 rounds), cross-sprint learning, and pipeline advancement. +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) @@ -19,91 +18,47 @@ Orchestrates the iterative development pipeline: sprint planning, task ledger ma - Execute completion action in Phase 5 ### MUST NOT - - Implement domain logic (designing, coding, testing, reviewing) -- workers handle this - Spawn workers without creating tasks first - Write source code directly - Force-advance pipeline past failed review/validation - Modify task outputs (workers own their deliverables) ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a command: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [architect], [developer], [tester], [reviewer] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [architect], [developer], [tester], [reviewer] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session in .workflow/.team/IDS-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/IDS-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session.json from detected session folder -2. Audit task list: `TaskList()` -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: `TeamCreate({ team_name: "iterdev" })` -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/IDS-*/.msg/meta.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification +TEXT-LEVEL ONLY. No source code reading. + 1. Parse user task description from $ARGUMENTS -2. Assess complexity for pipeline selection: +2. Delegate to commands/analyze.md +3. Assess complexity for pipeline selection: | Signal | Weight | |--------|--------| @@ -119,58 +74,27 @@ Triggered when an active/paused session is detected on coordinator entry. | 2-4 | sprint | | 0-1 | patch | -3. Ask for missing parameters via AskUserQuestion (mode selection) -4. Record requirement with scope, pipeline mode - ---- +4. Ask for missing parameters via AskUserQuestion (mode selection) +5. Record requirement with scope, pipeline mode +6. CRITICAL: Always proceed to Phase 2, never skip team workflow ## Phase 2: Session & Team Setup -1. Generate session ID: `IDS-{slug}-{YYYY-MM-DD}` +1. Generate session ID: `IDS-<slug>-<YYYY-MM-DD>` 2. Create session folder structure: - ``` -Bash("mkdir -p .workflow/.team/<session-id>/design .workflow/.team/<session-id>/code .workflow/.team/<session-id>/verify .workflow/.team/<session-id>/review .workflow/.team/<session-id>/wisdom") +mkdir -p .workflow/.team/<session-id>/{design,code,verify,review,wisdom} ``` - 3. Create team: `TeamCreate({ team_name: "iterdev" })` -4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) -5. Write session.json: - -```json -{ - "status": "active", - "team_name": "iterdev", - "requirement": "<requirement>", - "pipeline": "<patch|sprint|multi-sprint>", - "timestamp": "<ISO-8601>", - "gc_round": 0, - "max_gc_rounds": 3, - "fix_cycles": {} -} -``` - -6. Initialize task-ledger.json: - -```json -{ - "sprint_id": "sprint-1", - "sprint_goal": "<task-description>", - "pipeline": "<selected-pipeline>", - "tasks": [], - "metrics": { "total": 0, "completed": 0, "in_progress": 0, "blocked": 0, "velocity": 0 } -} -``` - -7. Initialize meta.json with pipeline metadata: +4. Read specs/pipelines.md -> select pipeline based on complexity +5. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) +6. Write session.json +7. Initialize task-ledger.json +8. Initialize meta.json with pipeline metadata: ```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", data: { pipeline_mode: "<patch|sprint|multi-sprint>", pipeline_stages: ["architect", "developer", "tester", "reviewer"], @@ -180,56 +104,20 @@ mcp__ccw-tools__team_msg({ }) ``` ---- - ## Phase 3: Task Chain Creation -Execute `commands/dispatch.md` inline (Command Execution Protocol): +Delegate to commands/dispatch.md: +1. Read specs/pipelines.md for selected pipeline task registry +2. Create tasks via TaskCreate with blockedBy +3. Update task-ledger.json -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies +## Phase 4: Spawn-and-Stop ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: "iterdev", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-iterdev/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: iterdev -requirement: <task-description> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action @@ -245,27 +133,18 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger | Verification Results | <session>/verify/verify-001.json | | Review Report | <session>/review/review-001.md | -4. **Completion Action** (interactive): +4. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` +## Error Handling -5. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-iterdev', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| GC loop exceeds 3 rounds | Accept with warning, record in shared memory | +| Sprint velocity drops below 50% | Alert user, suggest scope reduction | +| Task ledger corrupted | Rebuild from TaskList state | diff --git a/.claude/skills/team-iterdev/roles/developer/role.md b/.claude/skills/team-iterdev/roles/developer/role.md new file mode 100644 index 00000000..137e47b9 --- /dev/null +++ b/.claude/skills/team-iterdev/roles/developer/role.md @@ -0,0 +1,74 @@ +--- +role: developer +prefix: DEV +inner_loop: true +message_types: + success: dev_complete + progress: dev_progress + error: error +--- + +# Developer + +Code implementer. Implements code according to design, incremental delivery. Acts as Generator in Generator-Critic loop (paired with reviewer). + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Design document | <session>/design/design-001.md | For non-fix tasks | +| Task breakdown | <session>/design/task-breakdown.json | For non-fix tasks | +| Review feedback | <session>/review/*.md | For fix tasks | +| Wisdom files | <session>/wisdom/ | No | + +1. Extract session path from task description +2. Read .msg/meta.json for shared context +3. Detect task type: + +| Task Type | Detection | Loading | +|-----------|-----------|---------| +| Fix task | Subject contains "fix" | Read latest review file for feedback | +| Normal task | No "fix" in subject | Read design document + task breakdown | + +4. Load previous implementation_context from .msg/meta.json +5. Read wisdom files for conventions and known issues + +## Phase 3: Code Implementation + +**Implementation strategy selection**: + +| Task Count | Complexity | Strategy | +|------------|------------|----------| +| <= 2 tasks | Low | Direct: inline Edit/Write | +| 3-5 tasks | Medium | Single agent: one code-developer for all | +| > 5 tasks | High | Batch agent: group by module, one agent per batch | + +**Fix Task Mode** (GC Loop): +- Focus on review feedback items only +- Fix critical issues first, then high, then medium +- Do NOT change code that was not flagged +- Maintain existing code style and patterns + +**Normal Task Mode**: +- Read target files, apply changes using Edit or Write +- Follow execution order from task breakdown +- Validate syntax after each major change + +## Phase 4: Self-Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Syntax | tsc --noEmit or equivalent | No errors | +| File existence | Verify all planned files exist | All files present | +| Import resolution | Check no broken imports | All imports resolve | + +1. Run syntax check: `tsc --noEmit` / `python -m py_compile` / equivalent +2. Auto-fix if validation fails (max 2 attempts) +3. Write dev log to `<session>/code/dev-log.md`: + - Changed files count, syntax status, fix task flag, file list +4. Update implementation_context in .msg/meta.json: + - task, changed_files, is_fix, syntax_clean +5. Write discoveries to wisdom/learnings.md diff --git a/.claude/skills/team-iterdev/roles/reviewer/role.md b/.claude/skills/team-iterdev/roles/reviewer/role.md new file mode 100644 index 00000000..b587ec02 --- /dev/null +++ b/.claude/skills/team-iterdev/roles/reviewer/role.md @@ -0,0 +1,66 @@ +--- +role: reviewer +prefix: REVIEW +inner_loop: false +message_types: + success: review_passed + revision: review_revision + critical: review_critical + error: error +--- + +# Reviewer + +Code reviewer. Multi-dimensional review, quality scoring, improvement suggestions. Acts as Critic in Generator-Critic loop (paired with developer). + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Design document | <session>/design/design-001.md | For requirements alignment | +| Changed files | Git diff | Yes | + +1. Extract session path from task description +2. Read .msg/meta.json for shared context and previous review_feedback_trends +3. Read design document for requirements alignment +4. Get changed files via git diff, read file contents (limit 20 files) + +## Phase 3: Multi-Dimensional Review + +**Review dimensions**: + +| Dimension | Weight | Focus Areas | +|-----------|--------|-------------| +| Correctness | 30% | Logic correctness, boundary handling | +| Completeness | 25% | Coverage of design requirements | +| Maintainability | 25% | Readability, code style, DRY | +| Security | 20% | Vulnerabilities, input validation | + +Per-dimension: scan modified files, record findings with severity (CRITICAL/HIGH/MEDIUM/LOW), include file:line references and suggestions. + +**Scoring**: Weighted average of dimension scores (1-10 each). + +**Output review report** (`<session>/review/review-<num>.md`): +- Files reviewed count, quality score, issue counts by severity +- Per-finding: severity, file:line, dimension, description, suggestion +- Scoring breakdown by dimension +- Signal: CRITICAL / REVISION_NEEDED / APPROVED +- Design alignment notes + +## Phase 4: Trend Analysis + Verdict + +1. Compare with previous review_feedback_trends from .msg/meta.json +2. Identify recurring issues, improvement areas, new issues + +| Verdict Condition | Message Type | +|-------------------|--------------| +| criticalCount > 0 | review_critical | +| score < 7 | review_revision | +| else | review_passed | + +3. Update review_feedback_trends in .msg/meta.json: + - review_id, score, critical count, high count, dimensions, gc_round +4. Write discoveries to wisdom/learnings.md diff --git a/.claude/skills/team-iterdev/roles/tester/role.md b/.claude/skills/team-iterdev/roles/tester/role.md new file mode 100644 index 00000000..6868e1ef --- /dev/null +++ b/.claude/skills/team-iterdev/roles/tester/role.md @@ -0,0 +1,88 @@ +--- +role: tester +prefix: VERIFY +inner_loop: false +message_types: + success: verify_passed + failure: verify_failed + fix: fix_required + error: error +--- + +# Tester + +Test validator. Test execution, fix cycles, and regression detection. + +## Phase 2: Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Changed files | Git diff | Yes | + +1. Extract session path from task description +2. Read .msg/meta.json for shared context +3. Get changed files via git diff +4. Detect test framework and command: + +| Detection | Method | +|-----------|--------| +| Test command | Check package.json scripts, pytest.ini, Makefile | +| Coverage tool | Check for nyc, coverage.py, jest --coverage config | + +Common commands: npm test, pytest, go test ./..., cargo test + +## Phase 3: Execution + Fix Cycle + +**Iterative test-fix cycle** (max 5 iterations): + +| Step | Action | +|------|--------| +| 1 | Run test command | +| 2 | Parse results, check pass rate | +| 3 | Pass rate >= 95% -> exit loop (success) | +| 4 | Extract failing test details | +| 5 | Apply fix using CLI tool | +| 6 | Increment iteration counter | +| 7 | iteration >= MAX (5) -> exit loop (report failures) | +| 8 | Go to Step 1 | + +**Fix delegation**: Use CLI tool to fix failing tests: + +```bash +ccw cli -p "PURPOSE: Fix failing tests; success = all listed tests pass +TASK: • Analyze test failure output • Identify root cause in changed files • Apply minimal fix +MODE: write +CONTEXT: @<changed-files> | Memory: Test output from current iteration +EXPECTED: Code fixes that make failing tests pass without breaking other tests +CONSTRAINTS: Only modify files in changed list | Minimal changes +Test output: <test-failure-details> +Changed files: <file-list>" --tool gemini --mode write --rule development-debug-runtime-issues +``` + +Wait for CLI completion before re-running tests. + +## Phase 4: Regression Check + Report + +1. Run full test suite for regression: `<test-command> --all` + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Regression | Run full test suite | No FAIL in output | +| Coverage | Run coverage tool | >= 80% (if configured) | + +2. Write verification results to `<session>/verify/verify-<num>.json`: + - verify_id, pass_rate, iterations, passed, timestamp, regression_passed + +3. Determine message type: + +| Condition | Message Type | +|-----------|--------------| +| passRate >= 0.95 | verify_passed | +| passRate < 0.95 && iterations >= MAX | fix_required | +| passRate < 0.95 | verify_failed | + +4. Update .msg/meta.json with test_patterns entry +5. Write discoveries to wisdom/issues.md diff --git a/.claude/skills/team-iterdev/specs/pipelines.md b/.claude/skills/team-iterdev/specs/pipelines.md new file mode 100644 index 00000000..47766b2e --- /dev/null +++ b/.claude/skills/team-iterdev/specs/pipelines.md @@ -0,0 +1,94 @@ +# IterDev Pipeline Definitions + +## Three-Pipeline Architecture + +### Patch Pipeline (2 beats, serial) + +``` +DEV-001 -> VERIFY-001 +[developer] [tester] +``` + +### Sprint Pipeline (4 beats, with parallel window) + +``` +DESIGN-001 -> DEV-001 -> [VERIFY-001 + REVIEW-001] (parallel) +[architect] [developer] [tester] [reviewer] +``` + +### Multi-Sprint Pipeline (N beats, iterative) + +``` +Sprint 1: DESIGN-001 -> DEV-001 -> DEV-002(incremental) -> VERIFY-001 -> DEV-fix -> REVIEW-001 +Sprint 2: DESIGN-002(refined) -> DEV-003 -> VERIFY-002 -> REVIEW-002 +... +``` + +## Generator-Critic Loop (developer <-> reviewer) + +``` +DEV -> REVIEW -> (if review.critical_count > 0 || review.score < 7) + -> DEV-fix -> REVIEW-2 -> (if still issues) -> DEV-fix-2 -> REVIEW-3 + -> (max 3 rounds, then accept with warning) +``` + +## Pipeline Selection Logic + +| Signal | Score | +|--------|-------| +| Changed files > 10 | +3 | +| Changed files 3-10 | +2 | +| Structural change | +3 | +| Cross-cutting concern | +2 | +| Simple fix | -2 | + +| Score | Pipeline | +|-------|----------| +| >= 5 | multi-sprint | +| 2-4 | sprint | +| 0-1 | patch | + +## Task Metadata Registry + +| Task ID | Role | Pipeline | Dependencies | Description | +|---------|------|----------|-------------|-------------| +| DESIGN-001 | architect | sprint/multi | (none) | Technical design and task breakdown | +| DEV-001 | developer | all | DESIGN-001 (sprint/multi) or (none for patch) | Code implementation | +| DEV-002 | developer | multi | DEV-001 | Incremental implementation | +| DEV-fix | developer | sprint/multi | REVIEW-* (GC loop trigger) | Fix issues from review | +| VERIFY-001 | tester | all | DEV-001 (or last DEV) | Test execution and fix cycles | +| REVIEW-001 | reviewer | sprint/multi | DEV-001 (or last DEV) | Code review and quality scoring | + +## Checkpoints + +| Trigger Condition | Location | Behavior | +|-------------------|----------|----------| +| GC loop exceeds max rounds | After REVIEW-3 | Stop iteration, accept with warning, record in wisdom | +| Sprint transition | End of Sprint N | Pause, retrospective, user confirms `resume` for Sprint N+1 | +| Pipeline stall | No ready + no running tasks | Check missing tasks, report blockedBy chain to user | + +## Multi-Sprint Dynamic Downgrade + +If Sprint N metrics are strong (velocity >= expected, review avg >= 8), coordinator may downgrade Sprint N+1 from multi-sprint to sprint pipeline for efficiency. + +## Task Ledger Schema + +| Field | Description | +|-------|-------------| +| `sprint_id` | Current sprint identifier | +| `sprint_goal` | Sprint objective | +| `tasks[]` | Array of task entries | +| `metrics` | Aggregated metrics: total, completed, in_progress, blocked, velocity | + +**Task Entry Fields**: + +| Field | Description | +|-------|-------------| +| `id` | Task identifier | +| `title` | Task title | +| `owner` | Assigned role | +| `status` | pending / in_progress / completed / blocked | +| `started_at` / `completed_at` | Timestamps | +| `gc_rounds` | Generator-Critic iteration count | +| `review_score` | Reviewer score (null until reviewed) | +| `test_pass_rate` | Tester pass rate (null until tested) | diff --git a/.claude/skills/team-lifecycle-v2/CHANGELOG.md b/.claude/skills/team-lifecycle-v2/CHANGELOG.md deleted file mode 100644 index 061bad68..00000000 --- a/.claude/skills/team-lifecycle-v2/CHANGELOG.md +++ /dev/null @@ -1,46 +0,0 @@ -# Changelog - -## v2.1 - Architecture Fix (2026-03-05) - -### Fixed -- **Critical**: Removed subagent calls from worker role-specs -- Workers now correctly use CLI tools instead of attempting Agent() spawn -- Removed subagents directory (workers cannot use it) -- Updated SKILL.md to clarify architectural constraints - -### Changed -- Multi-perspective critique: Now uses parallel CLI calls -- Codebase exploration: Now uses `ccw cli --tool gemini` -- Document generation: Now uses `ccw cli --tool gemini --mode write` - -### Impact -- No functional change for users -- Implementation now architecturally correct -- Workers will no longer fail with "Unknown skill: Agent" - -### Files Modified -- `SKILL.md`: Replaced "Subagent Registry" with "CLI Tool Usage in Workers" -- `role-specs/analyst.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls -- `role-specs/writer.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls -- `role-specs/reviewer.md`: Removed `subagents: [discuss]`, replaced discuss subagent call with parallel CLI calls -- `role-specs/planner.md`: Updated complexity routing table to reference CLI exploration -- `role-specs/architect.md`: Removed `subagents: [explore]` -- `subagents/`: Directory removed - -### Technical Details - -**Why Workers Cannot Spawn Subagents**: -When a worker attempts `Agent()`, it fails with "Unknown skill: Agent". Only the Coordinator (main conversation context) can spawn agents. - -**Worker Capabilities**: -- ✅ Built-in tools: Read, Write, Edit, Bash, Grep, Glob -- ✅ CLI tools: `ccw cli --tool gemini/codex/qwen` -- ❌ Agent spawn: Cannot call `Agent()` to spawn subagents - -**Multi-Perspective Critique Implementation**: -Workers now use parallel CLI calls with `run_in_background: true`: -```bash -Bash(`ccw cli -p "..." --tool gemini --mode analysis`, { run_in_background: true }) -Bash(`ccw cli -p "..." --tool codex --mode analysis`, { run_in_background: true }) -Bash(`ccw cli -p "..." --tool claude --mode analysis`, { run_in_background: true }) -``` diff --git a/.claude/skills/team-lifecycle-v2/SKILL.md b/.claude/skills/team-lifecycle-v2/SKILL.md deleted file mode 100644 index caa3b2ad..00000000 --- a/.claude/skills/team-lifecycle-v2/SKILL.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -name: team-lifecycle-v2 -description: Optimized team skill for full lifecycle. Reduced discuss (6→3), progressive spec refinement preserved. team-worker agent architecture. Triggers on "team lifecycle v2". -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) ---- - -# Team Lifecycle v2 - -Optimized lifecycle: specification → implementation → testing → review. Built on **team-worker agent architecture**. Key optimization: discuss rounds reduced from 6 to 3 (direction, requirements, final gate). - -## Architecture - -``` -+---------------------------------------------------+ -| Skill(skill="team-lifecycle-v2") | -| args="task description" | -+-------------------+-------------------------------+ - | - Orchestration Mode (auto -> coordinator) - | - Coordinator (inline) - Phase 0-5 orchestration - | - +----+-----+-------+-------+-------+-------+ - v v v v v v v - [team-worker agents, each loaded with a role-spec] - analyst writer planner executor tester reviewer - ^ ^ - on-demand by coordinator - +---------+ +--------+ - |architect| |fe-dev | - +---------+ +--------+ - +--------+ - | fe-qa | - +--------+ - - ⚠️ ARCHITECTURAL CONSTRAINT: Workers CANNOT spawn subagents. - Workers use CLI tools for complex analysis (see "CLI Tool Usage in Workers" section). -``` - -## Role Router - -Coordinator-only. Workers spawned as `team-worker` agents. - -### Role Registry - -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | RESEARCH-* | pipeline | false | -| writer | [role-specs/writer.md](role-specs/writer.md) | DRAFT-* | pipeline | true | -| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true | -| executor | [role-specs/executor.md](role-specs/executor.md) | IMPL-* | pipeline | true | -| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | pipeline | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* + QUALITY-* + IMPROVE-* | pipeline | false | -| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | consulting | false | -| fe-developer | [role-specs/fe-developer.md](role-specs/fe-developer.md) | DEV-FE-* | frontend | false | -| fe-qa | [role-specs/fe-qa.md](role-specs/fe-qa.md) | QA-FE-* | frontend | false | - -### CLI Tool Usage in Workers - -**⚠️ ARCHITECTURAL CONSTRAINT**: Workers CANNOT call Agent() to spawn subagents. -Workers must use CLI tools for complex analysis. - -| Capability | CLI Command | Used By | -|------------|-------------|---------| -| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel calls) | analyst, writer, reviewer | -| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner | -| Document generation | `ccw cli --tool gemini --mode write` | writer | - -### Coordinator-Only Utilities - -If Coordinator needs utility members for team-level orchestration, it can spawn them. -Workers cannot spawn utility members. - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md`. - -### Orchestration Mode - -**Invocation**: `Skill(skill="team-lifecycle-v2", args="task description")` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: clarify -> TeamCreate -> create task chain - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker executes -> SendMessage callback -> coordinator advances - -> Loop until pipeline complete -> Phase 5 report -``` - -**User Commands**: - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status, no advancement | -| `resume` / `continue` | Check worker states, advance next step | -| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream | -| `feedback <text>` | Analyze feedback, create targeted revision | -| `recheck` | Re-run QUALITY-001 quality check | -| `improve [dimension]` | Auto-improve weakest dimension | - ---- - -## Coordinator Spawn Template - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: <team-name>, - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-lifecycle-v2/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - ---- - -## Pipeline Definitions - -### Spec-only (6 tasks, 3 discuss) - -``` -RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3) -``` - -Note: DRAFT-001, DRAFT-003, DRAFT-004 use self-validation only (no discuss). - -### Impl-only (4 tasks) - -``` -PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001 -``` - -### Full-lifecycle (10 tasks) - -``` -[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001 -``` - -### Frontend Pipelines - -``` -FE-only: PLAN-001 -> DEV-FE-001 -> QA-FE-001 - (GC loop: max 2 rounds) - -Fullstack: PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001 - -Full + FE: [Spec pipeline] -> PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001 -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker B directly - | --> log fast_advance to message bus - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -### Checkpoints - -| Trigger | Position | Behavior | -|---------|----------|----------| -| Spec->Impl transition | QUALITY-001 completed | Display checkpoint, pause for user | -| GC loop max | QA-FE max 2 rounds | Stop iteration, report | -| Pipeline stall | No ready + no running | Report to user | - -**Checkpoint Output Template** (QUALITY-001): - -``` -[coordinator] ══════════════════════════════════════════ -[coordinator] SPEC PHASE COMPLETE -[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%) -[coordinator] -[coordinator] Dimension Scores: -[coordinator] Completeness: <bar> <n>% -[coordinator] Consistency: <bar> <n>% -[coordinator] Traceability: <bar> <n>% -[coordinator] Depth: <bar> <n>% -[coordinator] Coverage: <bar> <n>% -[coordinator] -[coordinator] Available Actions: -[coordinator] resume -> Proceed to implementation -[coordinator] improve -> Auto-improve weakest dimension -[coordinator] revise <TASK-ID> -> Revise specific document -[coordinator] recheck -> Re-run quality check -[coordinator] feedback <text> -> Inject feedback -[coordinator] ══════════════════════════════════════════ -``` - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Discuss | -|---------|------|-------|-------------|---------| -| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | -| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate | -| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 | -| DRAFT-003 | writer | spec | DRAFT-002 | self-validate | -| DRAFT-004 | writer | spec | DRAFT-003 | self-validate | -| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 | -| PLAN-001 | planner | impl | (none or QUALITY-001) | - | -| IMPL-001 | executor | impl | PLAN-001 | - | -| TEST-001 | tester | impl | IMPL-001 | - | -| REVIEW-001 | reviewer | impl | IMPL-001 | - | -| DEV-FE-001 | fe-developer | impl | PLAN-001 | - | -| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | - ---- - -## Session Directory - -``` -.workflow/.team/TLS-<slug>-<date>/ -+-- team-session.json -+-- spec/ -| +-- spec-config.json -| +-- discovery-context.json -| +-- product-brief.md -| +-- requirements/ -| +-- architecture/ -| +-- epics/ -| +-- readiness-report.md -+-- discussions/ -+-- plan/ -| +-- plan.json -| +-- .task/TASK-*.json -+-- explorations/ -+-- .msg/ -+-- shared-memory.json -``` - -## Session Resume - -1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions -2. Multiple matches -> AskUserQuestion -3. Audit TaskList -> reconcile session state -4. Reset in_progress -> pending (interrupted tasks) -5. Rebuild team, spawn needed workers only -6. Kick first executable task - -## Shared Resources - -| Resource | Path | Usage | -|----------|------|-------| -| Document Standards | [specs/document-standards.md](specs/document-standards.md) | YAML frontmatter, naming, structure | -| Quality Gates | [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gates | -| Team Config | [specs/team-config.json](specs/team-config.json) | Role registry, pipeline definitions | -| Product Brief Template | [templates/product-brief.md](templates/product-brief.md) | DRAFT-001 | -| Requirements Template | [templates/requirements-prd.md](templates/requirements-prd.md) | DRAFT-002 | -| Architecture Template | [templates/architecture-doc.md](templates/architecture-doc.md) | DRAFT-003 | -| Epics Template | [templates/epics-template.md](templates/epics-template.md) | DRAFT-004 | -| Discuss Subagent | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | 3-round discuss protocol | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Unknown command | Error with available command list | -| Role spec file not found | Error with expected path | -| Command file not found | Fallback to inline execution | -| Discuss subagent fails | Worker proceeds without discuss, logs warning | -| Fast-advance spawns wrong task | Coordinator reconciles on next callback | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/analyst.md b/.claude/skills/team-lifecycle-v2/role-specs/analyst.md deleted file mode 100644 index ec0c6fbc..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/analyst.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -role: analyst -prefix: RESEARCH -inner_loop: false -discuss_rounds: [DISCUSS-001] -message_types: - success: research_ready - progress: research_progress - error: error ---- - -# Analyst — Phase 2-4 - -## Phase 2: Seed Analysis - -**Objective**: Extract structured seed information from the topic. - -1. Extract session folder from task description (`Session: <path>`) -2. Parse topic from task description -3. If topic starts with `@` or ends with `.md`/`.txt` → Read referenced file -4. Run CLI seed analysis: - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Analyze topic and extract structured seed information. -TASK: * Extract problem statement * Identify target users * Determine domain context -* List constraints * Identify 3-5 exploration dimensions * Assess complexity -TOPIC: <topic-content> -MODE: analysis -EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[], complexity_assessment" --tool gemini --mode analysis`, - run_in_background: false -}) -``` - -5. Parse seed analysis JSON - -## Phase 3: Codebase Exploration (conditional) - -**Objective**: Gather codebase context if project detected. - -| Condition | Action | -|-----------|--------| -| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore | -| No project files | Skip (codebase_context = null) | - -**When project detected**: Use CLI exploration. - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase for context to inform spec generation -TASK: • Identify tech stack • Map architecture patterns • Document conventions • List integration points -MODE: analysis -CONTEXT: @**/* -EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[]" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -## Phase 4: Context Packaging + Discuss - -### 4a: Context Packaging - -**spec-config.json** → `<session>/spec/spec-config.json` -**discovery-context.json** → `<session>/spec/discovery-context.json` -**design-intelligence.json** → `<session>/analysis/design-intelligence.json` (UI mode only) - -### 4b: Inline Discuss (DISCUSS-001) - -**Multi-perspective critique via parallel CLI calls**: - -```bash -# Product perspective -Bash(`ccw cli -p "PURPOSE: Review discovery context from product perspective -CONTEXT: @<session>/spec/discovery-context.json -EXPECTED: Rating (1-5) + concerns + recommendations -CONSTRAINTS: Focus on market fit, user value, scope clarity" --tool gemini --mode analysis`, { run_in_background: true }) - -# Risk perspective -Bash(`ccw cli -p "PURPOSE: Review discovery context from risk perspective -CONTEXT: @<session>/spec/discovery-context.json -EXPECTED: Rating (1-5) + risks + mitigation strategies -CONSTRAINTS: Focus on technical risks, dependencies, unknowns" --tool codex --mode analysis`, { run_in_background: true }) - -# Coverage perspective -Bash(`ccw cli -p "PURPOSE: Review discovery context from coverage perspective -CONTEXT: @<session>/spec/discovery-context.json -EXPECTED: Rating (1-5) + gaps + missing dimensions -CONSTRAINTS: Focus on completeness, edge cases, requirements coverage" --tool claude --mode analysis`, { run_in_background: true }) -``` - -Wait for all results, aggregate ratings and feedback, determine consensus verdict: -- **HIGH**: Any rating <= 2 → User pause required -- **MEDIUM**: All ratings 3-4 → Proceed with caution -- **LOW**: All ratings >= 4 → Proceed - -Handle verdict per consensus protocol. - -**Report**: complexity, codebase presence, problem statement, dimensions, discuss verdict, output paths. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI failure | Fallback to direct Claude analysis | -| Codebase detection failed | Continue as new project | -| Topic too vague | Report with clarification questions | -| CLI critique fails | Proceed without critique, log warning | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/architect.md b/.claude/skills/team-lifecycle-v2/role-specs/architect.md deleted file mode 100644 index 0889fc96..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/architect.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -role: architect -prefix: ARCH -inner_loop: false -discuss_rounds: [] -message_types: - success: arch_ready - concern: arch_concern - error: error ---- - -# Architect — Phase 2-4 - -## Consultation Modes - -| Task Pattern | Mode | Focus | -|-------------|------|-------| -| ARCH-SPEC-* | spec-review | Review architecture docs | -| ARCH-PLAN-* | plan-review | Review plan soundness | -| ARCH-CODE-* | code-review | Assess code change impact | -| ARCH-CONSULT-* | consult | Answer architecture questions | -| ARCH-FEASIBILITY-* | feasibility | Technical feasibility | - -## Phase 2: Context Loading - -**Common**: session folder, wisdom, project-tech.json, explorations - -**Mode-specific**: - -| Mode | Additional Context | -|------|-------------------| -| spec-review | architecture/_index.md, ADR-*.md | -| plan-review | plan/plan.json | -| code-review | git diff, changed files | -| consult | Question from task description | -| feasibility | Requirements + codebase | - -## Phase 3: Assessment - -Analyze using mode-specific criteria. Output: mode, verdict (APPROVE/CONCERN/BLOCK), dimensions[], concerns[], recommendations[]. - -For complex questions → Gemini CLI with architecture review rule: - -``` -Bash({ - command: `ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture`, - run_in_background: true -}) -``` - -## Phase 4: Report - -Output to `<session-folder>/architecture/arch-<slug>.json`. Contribute decisions to wisdom/decisions.md. - -**Frontend project outputs** (when frontend tech stack detected): -- `<session-folder>/architecture/design-tokens.json` — color, spacing, typography, shadow tokens -- `<session-folder>/architecture/component-specs/*.md` — per-component design spec - -**Report**: mode, verdict, concern count, recommendations, output path(s). - -### Coordinator Integration - -| Timing | Task | -|--------|------| -| After DRAFT-003 | ARCH-SPEC-001: architecture doc review | -| After PLAN-001 | ARCH-PLAN-001: plan architecture review | -| On-demand | ARCH-CONSULT-001: architecture consultation | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Docs not found | Assess from available context | -| CLI timeout | Partial assessment | -| Insufficient context | Request explorer via coordinator | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/executor.md b/.claude/skills/team-lifecycle-v2/role-specs/executor.md deleted file mode 100644 index 03a2d274..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/executor.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -role: executor -prefix: IMPL -inner_loop: true -discuss_rounds: [] -message_types: - success: impl_complete - progress: impl_progress - error: error ---- - -# Executor — Phase 2-4 - -## Phase 2: Task & Plan Loading - -**Objective**: Load plan and determine execution strategy. - -1. Load plan.json and .task/TASK-*.json from `<session-folder>/plan/` - -**Backend selection** (priority order): - -| Priority | Source | Method | -|----------|--------|--------| -| 1 | Task metadata | task.metadata.executor field | -| 2 | Plan default | "Execution Backend:" in plan | -| 3 | Auto-select | Simple (< 200 chars, no refactor) → agent; Complex → codex | - -**Code review selection**: - -| Priority | Source | Method | -|----------|--------|--------| -| 1 | Task metadata | task.metadata.code_review field | -| 2 | Plan default | "Code Review:" in plan | -| 3 | Auto-select | Critical keywords (auth, security, payment) → enabled | - -## Phase 3: Code Implementation - -**Objective**: Execute implementation across batches. - -**Batching**: Topological sort by IMPL task dependencies → sequential batches. - -| Backend | Invocation | Use Case | -|---------|-----------|----------| -| gemini | `ccw cli --tool gemini --mode write` (foreground) | Simple, direct edits | -| codex | `ccw cli --tool codex --mode write` (foreground) | Complex, architecture | -| qwen | `ccw cli --tool qwen --mode write` (foreground) | Alternative backend | - -## Phase 4: Self-Validation - -| Step | Method | Pass Criteria | -|------|--------|--------------| -| Syntax check | `tsc --noEmit` (30s) | Exit code 0 | -| Acceptance criteria | Match criteria keywords vs implementation | All addressed | -| Test detection | Find .test.ts/.spec.ts for modified files | Tests identified | -| Code review (optional) | gemini analysis or codex review | No blocking issues | - -**Report**: task ID, status, files modified, validation results, backend used. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Syntax errors | Retry with error context (max 3) | -| Missing dependencies | Request from coordinator | -| Backend unavailable | Fallback to alternative tool | -| Circular dependencies | Abort, report graph | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/fe-developer.md b/.claude/skills/team-lifecycle-v2/role-specs/fe-developer.md deleted file mode 100644 index 162095c1..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/fe-developer.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -role: fe-developer -prefix: DEV-FE -inner_loop: false -discuss_rounds: [] -message_types: - success: dev_fe_complete - progress: dev_fe_progress - error: error ---- - -# FE Developer — Phase 2-4 - -## Phase 2: Context Loading - -**Inputs to load**: -- Plan: `<session-folder>/plan/plan.json` -- Design tokens: `<session-folder>/architecture/design-tokens.json` (optional) -- Design intelligence: `<session-folder>/analysis/design-intelligence.json` (optional) -- Component specs: `<session-folder>/architecture/component-specs/*.md` (optional) -- Shared memory, wisdom - -**Tech stack detection**: - -| Signal | Framework | Styling | -|--------|-----------|---------| -| react/react-dom in deps | react | - | -| vue in deps | vue | - | -| next in deps | nextjs | - | -| tailwindcss in deps | - | tailwind | -| @shadcn/ui in deps | - | shadcn | - -## Phase 3: Frontend Implementation - -**Step 1**: Generate design token CSS (if tokens available) -- Convert design-tokens.json → CSS custom properties (`:root { --color-*, --space-*, --text-* }`) -- Include dark mode overrides via `@media (prefers-color-scheme: dark)` -- Write to `src/styles/tokens.css` - -**Step 2**: Implement components - -| Task Size | Strategy | -|-----------|----------| -| Simple (<= 3 files, single component) | `ccw cli --tool gemini --mode write` (foreground) | -| Complex (system, multi-component) | `ccw cli --tool codex --mode write` (foreground) | - -**Coding standards** (include in agent/CLI prompt): -- Use design token CSS variables, never hardcode colors/spacing -- Interactive elements: cursor: pointer -- Transitions: 150-300ms -- Text contrast: minimum 4.5:1 -- Include focus-visible styles -- Support prefers-reduced-motion -- Responsive: mobile-first -- No emoji as functional icons - -## Phase 4: Self-Validation - -| Check | What | -|-------|------| -| hardcoded-color | No #hex outside tokens.css | -| cursor-pointer | Interactive elements have cursor: pointer | -| focus-styles | Interactive elements have focus styles | -| responsive | Has responsive breakpoints | -| reduced-motion | Animations respect prefers-reduced-motion | -| emoji-icon | No emoji as functional icons | - -Contribute to wisdom/conventions.md. Update shared-memory.json with component inventory. - -**Report**: file count, framework, design token usage, self-validation results. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Design tokens not found | Use project defaults | -| Tech stack undetected | Default HTML + CSS | -| CLI failure | Retry with alternative tool | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/fe-qa.md b/.claude/skills/team-lifecycle-v2/role-specs/fe-qa.md deleted file mode 100644 index 94103f20..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/fe-qa.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -role: fe-qa -prefix: QA-FE -inner_loop: false -discuss_rounds: [] -message_types: - success: qa_fe_passed - result: qa_fe_result - fix: fix_required - error: error ---- - -# FE QA — Phase 2-4 - -## Review Dimensions - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Code Quality | 25% | TypeScript types, component structure, error handling | -| Accessibility | 25% | Semantic HTML, ARIA, keyboard nav, contrast, focus-visible | -| Design Compliance | 20% | Token usage, no hardcoded colors, no emoji icons | -| UX Best Practices | 15% | Loading/error/empty states, cursor-pointer, responsive | -| Pre-Delivery | 15% | No console.log, dark mode, i18n readiness | - -## Phase 2: Context Loading - -**Inputs**: design tokens, design intelligence, shared memory, previous QA results (for GC round tracking), changed frontend files via git diff. - -Determine GC round from previous QA results count. Max 2 rounds. - -## Phase 3: 5-Dimension Review - -For each changed frontend file, check against all 5 dimensions. Score each dimension 0-10, deducting for issues found. - -**Scoring deductions**: - -| Severity | Deduction | -|----------|-----------| -| High | -2 to -3 | -| Medium | -1 to -1.5 | -| Low | -0.5 | - -**Overall score** = weighted sum of dimension scores. - -**Verdict routing**: - -| Condition | Verdict | -|-----------|---------| -| Score >= 8 AND no critical issues | PASS | -| GC round >= max AND score >= 6 | PASS_WITH_WARNINGS | -| GC round >= max AND score < 6 | FAIL | -| Otherwise | NEEDS_FIX | - -## Phase 4: Report - -Write audit to `<session-folder>/qa/audit-fe-<task>-r<round>.json`. Update wisdom and shared memory. - -**Report**: round, verdict, overall score, dimension scores, critical issues with Do/Don't format, action required (if NEEDS_FIX). - -### Generator-Critic Loop - -Orchestrated by coordinator: -``` -Round 1: DEV-FE-001 → QA-FE-001 - if NEEDS_FIX → coordinator creates DEV-FE-002 + QA-FE-002 -Round 2: DEV-FE-002 → QA-FE-002 - if still NEEDS_FIX → PASS_WITH_WARNINGS or FAIL (max 2) -``` - -**Convergence**: score >= 8 AND critical_count = 0 - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No changed files | Report empty, score N/A | -| Design tokens not found | Skip design compliance, adjust weights | -| Max GC rounds exceeded | Force verdict | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/planner.md b/.claude/skills/team-lifecycle-v2/role-specs/planner.md deleted file mode 100644 index 9ad9a84c..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/planner.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -role: planner -prefix: PLAN -inner_loop: true -discuss_rounds: [] -message_types: - success: plan_ready - revision: plan_revision - error: error ---- - -# Planner — Phase 2-4 - -## Phase 1.5: Load Spec Context (Full-Lifecycle) - -If `<session-folder>/spec/` exists → load requirements/_index.md, architecture/_index.md, epics/_index.md, spec-config.json. Otherwise → impl-only mode. - -**Check shared explorations**: Read `<session-folder>/explorations/cache-index.json` to see if analyst already cached useful explorations. Reuse rather than re-explore. - -## Phase 2: Multi-Angle Exploration - -**Objective**: Explore codebase to inform planning. - -**Complexity routing**: - -| Complexity | Criteria | Strategy | -|------------|----------|----------| -| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only | -| Medium | 200-500 chars or moderate scope | 2-3 angle CLI exploration | -| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle CLI exploration | - -For each angle, use CLI exploration (cache-aware — check cache-index.json before each call): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase from <angle> perspective to inform planning -TASK: • Search for <angle>-specific patterns • Identify relevant files • Document integration points -MODE: analysis -CONTEXT: @**/* | Memory: Task keywords: <keywords> -EXPECTED: JSON with: relevant_files[], patterns[], integration_points[], recommendations[] -CONSTRAINTS: Focus on <angle> perspective" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -## Phase 3: Plan Generation - -**Objective**: Generate structured implementation plan. - -| Complexity | Strategy | -|------------|----------| -| Low | Direct planning → single TASK-001 with plan.json | -| Medium/High | cli-lite-planning-agent with exploration results | - -**CLI call** (Medium/High): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate structured implementation plan from exploration results -TASK: • Create plan.json with overview • Generate TASK-*.json files (2-7 tasks) • Define dependencies • Set convergence criteria -MODE: write -CONTEXT: @<session-folder>/explorations/*.json | Memory: Complexity: <complexity> -EXPECTED: Files: plan.json + .task/TASK-*.json. Schema: ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json -CONSTRAINTS: 2-7 tasks, include id/title/files[].change/convergence.criteria/depends_on" --tool gemini --mode write --rule planning-breakdown-task-steps`, - run_in_background: false -}) -``` - -**Spec context** (full-lifecycle): Reference REQ-* IDs, follow ADR decisions, reuse Epic/Story decomposition. - -## Phase 4: Submit for Approval - -1. Read plan.json and TASK-*.json -2. Report to coordinator: complexity, task count, task list, approach, plan location -3. Wait for response: approved → complete; revision → update and resubmit - -**Session files**: -``` -<session-folder>/explorations/ (shared cache) -+-- cache-index.json -+-- explore-<angle>.json - -<session-folder>/plan/ -+-- explorations-manifest.json -+-- plan.json -+-- .task/TASK-*.json -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI exploration failure | Plan from description only | -| CLI planning failure | Fallback to direct planning | -| Plan rejected 3+ times | Notify coordinator, suggest alternative | -| Schema not found | Use basic structure | -| Cache index corrupt | Clear cache, re-explore all angles | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/reviewer.md b/.claude/skills/team-lifecycle-v2/role-specs/reviewer.md deleted file mode 100644 index b0512c2d..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/reviewer.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -role: reviewer -prefix: REVIEW -additional_prefixes: [QUALITY, IMPROVE] -inner_loop: false -discuss_rounds: [DISCUSS-003] -message_types: - success_review: review_result - success_quality: quality_result - fix: fix_required - error: error ---- - -# Reviewer — Phase 2-4 - -## Phase 2: Mode Detection - -| Task Prefix | Mode | Dimensions | Discuss | -|-------------|------|-----------|---------| -| REVIEW-* | Code Review | quality, security, architecture, requirements | None | -| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage | DISCUSS-003 | -| IMPROVE-* | Spec Quality (recheck) | Same as QUALITY | DISCUSS-003 | - -## Phase 3: Review Execution - -### Code Review (REVIEW-*) - -**Inputs**: Plan file, git diff, modified files, test results - -**4 dimensions**: - -| Dimension | Critical Issues | -|-----------|----------------| -| Quality | Empty catch, any in public APIs, @ts-ignore, console.log | -| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML | -| Architecture | Circular deps, parent imports >2 levels, files >500 lines | -| Requirements | Missing core functionality, incomplete acceptance criteria | - -### Spec Quality (QUALITY-* / IMPROVE-*) - -**Inputs**: All spec docs in session folder, quality gate config - -**5 dimensions**: - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Completeness | 25% | All sections present with substance | -| Consistency | 20% | Terminology, format, references | -| Traceability | 25% | Goals -> Reqs -> Arch -> Stories chain | -| Depth | 20% | AC testable, ADRs justified, stories estimable | -| Coverage | 10% | Original requirements mapped | - -**Quality gate**: - -| Gate | Criteria | -|------|----------| -| PASS | Score >= 80% AND coverage >= 70% | -| REVIEW | Score 60-79% OR coverage 50-69% | -| FAIL | Score < 60% OR coverage < 50% | - -**Artifacts**: readiness-report.md + spec-summary.md - -## Phase 4: Verdict + Discuss - -### Code Review Verdict - -| Verdict | Criteria | -|---------|----------| -| BLOCK | Critical issues present | -| CONDITIONAL | High/medium only | -| APPROVE | Low or none | - -### Spec Quality Discuss (DISCUSS-003) - -After generating readiness-report.md, perform multi-perspective critique via parallel CLI calls: - -```bash -# Product perspective -Bash(`ccw cli -p "PURPOSE: Review spec readiness from product perspective -CONTEXT: @<session>/spec/readiness-report.md -EXPECTED: Rating (1-5) + product concerns + recommendations -CONSTRAINTS: Focus on market alignment, user value, business viability" --tool gemini --mode analysis`, { run_in_background: true }) - -# Technical perspective -Bash(`ccw cli -p "PURPOSE: Review spec readiness from technical perspective -CONTEXT: @<session>/spec/readiness-report.md -EXPECTED: Rating (1-5) + technical risks + feasibility assessment -CONSTRAINTS: Focus on architecture soundness, tech debt, implementation complexity" --tool codex --mode analysis`, { run_in_background: true }) - -# Quality perspective -Bash(`ccw cli -p "PURPOSE: Review spec readiness from quality perspective -CONTEXT: @<session>/spec/readiness-report.md -EXPECTED: Rating (1-5) + quality gaps + improvement areas -CONSTRAINTS: Focus on completeness, testability, consistency" --tool claude --mode analysis`, { run_in_background: true }) - -# Risk perspective -Bash(`ccw cli -p "PURPOSE: Review spec readiness from risk perspective -CONTEXT: @<session>/spec/readiness-report.md -EXPECTED: Rating (1-5) + risk factors + mitigation strategies -CONSTRAINTS: Focus on dependencies, unknowns, timeline risks" --tool gemini --mode analysis`, { run_in_background: true }) - -# Coverage perspective -Bash(`ccw cli -p "PURPOSE: Review spec readiness from coverage perspective -CONTEXT: @<session>/spec/readiness-report.md -EXPECTED: Rating (1-5) + coverage gaps + missing requirements -CONSTRAINTS: Focus on edge cases, non-functional requirements, traceability" --tool codex --mode analysis`, { run_in_background: true }) -``` - -Wait for all results, aggregate ratings and feedback, determine consensus verdict per protocol. - -> **Note**: DISCUSS-003 HIGH always triggers user pause (final sign-off gate). - -**Report**: mode, verdict/gate, dimension scores, discuss verdict (QUALITY only), output paths. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Missing context | Request from coordinator | -| Invalid mode | Abort with error | -| Analysis failure | Retry, then fallback | -| CLI critique fails | Proceed without critique, log warning | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/tester.md b/.claude/skills/team-lifecycle-v2/role-specs/tester.md deleted file mode 100644 index 073e2847..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/tester.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -role: tester -prefix: TEST -inner_loop: false -discuss_rounds: [] -message_types: - success: test_result - fix: fix_required - error: error ---- - -# Tester — Phase 2-4 - -## Phase 2: Framework Detection & Test Discovery - -**Framework detection** (priority order): - -| Priority | Method | Frameworks | -|----------|--------|-----------| -| 1 | package.json devDependencies | vitest, jest, mocha, pytest | -| 2 | package.json scripts.test | vitest, jest, mocha, pytest | -| 3 | Config files | vitest.config.*, jest.config.*, pytest.ini | - -**Affected test discovery** from executor's modified files: -- Search variants: `<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts` - -## Phase 3: Test Execution & Fix Cycle - -**Config**: MAX_ITERATIONS=10, PASS_RATE_TARGET=95%, AFFECTED_TESTS_FIRST=true - -1. Run affected tests → parse results -2. Pass rate met → run full suite -3. Failures → select strategy → fix → re-run → repeat - -**Strategy selection**: - -| Condition | Strategy | Behavior | -|-----------|----------|----------| -| Iteration <= 3 or pass >= 80% | Conservative | Fix one critical failure at a time | -| Critical failures < 5 | Surgical | Fix specific pattern everywhere | -| Pass < 50% or iteration > 7 | Aggressive | Fix all failures in batch | - -**Test commands**: - -| Framework | Affected | Full Suite | -|-----------|---------|------------| -| vitest | `vitest run <files>` | `vitest run` | -| jest | `jest <files> --no-coverage` | `jest --no-coverage` | -| pytest | `pytest <files> -v` | `pytest -v` | - -## Phase 4: Result Analysis - -**Failure classification**: - -| Severity | Patterns | -|----------|----------| -| Critical | SyntaxError, cannot find module, undefined | -| High | Assertion failures, toBe/toEqual | -| Medium | Timeout, async errors | -| Low | Warnings, deprecations | - -**Report routing**: - -| Condition | Type | -|-----------|------| -| Pass rate >= target | test_result (success) | -| Pass rate < target after max iterations | fix_required | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Framework not detected | Prompt user | -| No tests found | Report to coordinator | -| Infinite fix loop | Abort after MAX_ITERATIONS | diff --git a/.claude/skills/team-lifecycle-v2/role-specs/writer.md b/.claude/skills/team-lifecycle-v2/role-specs/writer.md deleted file mode 100644 index 80cdabf9..00000000 --- a/.claude/skills/team-lifecycle-v2/role-specs/writer.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -role: writer -prefix: DRAFT -inner_loop: true -discuss_rounds: [DISCUSS-002] -message_types: - success: draft_ready - revision: draft_revision - error: error ---- - -# Writer — Phase 2-4 - -## Phase 2: Context Loading - -**Objective**: Load all required inputs for document generation. - -### Document type routing - -| Task Subject Contains | Doc Type | Template | Validation | -|----------------------|----------|----------|------------| -| Product Brief | product-brief | templates/product-brief.md | self-validate | -| Requirements / PRD | requirements | templates/requirements-prd.md | DISCUSS-002 | -| Architecture | architecture | templates/architecture-doc.md | self-validate | -| Epics | epics | templates/epics-template.md | self-validate | - -### Progressive dependency loading - -| Doc Type | Requires | -|----------|----------| -| product-brief | discovery-context.json | -| requirements | + product-brief.md | -| architecture | + requirements/_index.md | -| epics | + architecture/_index.md | - -**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to generation. - -| Input | Source | Required | -|-------|--------|----------| -| Document standards | `../../specs/document-standards.md` | Yes | -| Template | From routing table | Yes | -| Spec config | `<session>/spec/spec-config.json` | Yes | -| Discovery context | `<session>/spec/discovery-context.json` | Yes | -| Discussion feedback | `<session>/discussions/<discuss-file>` | If exists | -| Prior decisions | context_accumulator (in-memory) | If prior tasks | - -## Phase 3: Document Generation - -**Objective**: Generate document using CLI tool. - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template and standards -TASK: • Load template • Apply spec config and discovery context • Integrate prior feedback • Generate all sections -MODE: write -CONTEXT: @<session>/spec/*.json @<template-path> | Memory: Prior decisions: <accumulator summary> -EXPECTED: Document at <output-path> with: YAML frontmatter, all sections, cross-references -CONSTRAINTS: Follow document-standards.md" --tool gemini --mode write --rule development-implement-feature --cd <session>`, - run_in_background: false -}) -``` - -## Phase 4: Validation - -### 4a: Self-Validation (all doc types) - -| Check | What to Verify | -|-------|---------------| -| has_frontmatter | Starts with YAML frontmatter | -| sections_complete | All template sections present | -| cross_references | session_id included | -| progressive_consistency | References to upstream docs are valid | - -### 4b: Validation Routing - -| Doc Type | Validation Method | -|----------|------------------| -| product-brief | Self-validation only → report | -| requirements (PRD) | Self-validation + **DISCUSS-002** | -| architecture | Self-validation only → report | -| epics | Self-validation only → report | - -**DISCUSS-002** (PRD only) - Multi-perspective critique via parallel CLI calls: - -```bash -# Quality perspective -Bash(`ccw cli -p "PURPOSE: Review requirements document from quality perspective -CONTEXT: @<session>/spec/requirements/_index.md -EXPECTED: Rating (1-5) + quality issues + improvement suggestions -CONSTRAINTS: Focus on completeness, testability, consistency" --tool gemini --mode analysis`, { run_in_background: true }) - -# Product perspective -Bash(`ccw cli -p "PURPOSE: Review requirements document from product perspective -CONTEXT: @<session>/spec/requirements/_index.md -EXPECTED: Rating (1-5) + product concerns + alignment feedback -CONSTRAINTS: Focus on user value, market fit, scope clarity" --tool codex --mode analysis`, { run_in_background: true }) - -# Coverage perspective -Bash(`ccw cli -p "PURPOSE: Review requirements document from coverage perspective -CONTEXT: @<session>/spec/requirements/_index.md -EXPECTED: Rating (1-5) + coverage gaps + missing requirements -CONSTRAINTS: Focus on edge cases, non-functional requirements, traceability" --tool claude --mode analysis`, { run_in_background: true }) -``` - -Wait for all results, aggregate ratings and feedback, determine consensus verdict per protocol. - -**Report**: doc type, validation status, discuss verdict (PRD only), output path. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI failure | Retry once with alternative tool. Still fails → log, continue next | -| CLI critique fails | Skip critique, log warning | -| Cumulative 3 task failures | SendMessage to coordinator, STOP | -| Prior doc not found | Notify coordinator, request prerequisite | -| Discussion contradicts prior docs | Note conflict, flag for coordinator | diff --git a/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/dispatch.md b/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/dispatch.md deleted file mode 100644 index e6c4babb..00000000 --- a/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/dispatch.md +++ /dev/null @@ -1,134 +0,0 @@ -# Command: dispatch - -Create task chains based on execution mode. v2: 3 discuss points instead of 6. - -## Phase 2: Context Loading - -| Input | Source | Required | -|-------|--------|----------| -| Mode | Phase 1 requirements | Yes | -| Session folder | Phase 2 session init | Yes | -| Scope | User requirements | Yes | - -## Phase 3: Task Chain Creation - -### Spec Pipeline (6 tasks, 3 discuss) - -| # | Subject | Owner | BlockedBy | Description | Validation | -|---|---------|-------|-----------|-------------|------------| -| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 | -| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | self-validate | -| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-002 | -| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | self-validate | -| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | self-validate | -| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-003 | - -### Impl Pipeline (4 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Multi-angle exploration and planning | -| 2 | IMPL-001 | executor | PLAN-001 | Code implementation | -| 3 | TEST-001 | tester | IMPL-001 | Test-fix cycles | -| 4 | REVIEW-001 | reviewer | IMPL-001 | 4-dimension code review | - -### FE Pipeline (3 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Planning (frontend focus) | -| 2 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | -| 3 | QA-FE-001 | fe-qa | DEV-FE-001 | 5-dimension frontend QA | - -### Fullstack Pipeline (6 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Fullstack planning | -| 2 | IMPL-001 | executor | PLAN-001 | Backend implementation | -| 3 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | -| 4 | TEST-001 | tester | IMPL-001 | Backend test-fix | -| 5 | QA-FE-001 | fe-qa | DEV-FE-001 | Frontend QA | -| 6 | REVIEW-001 | reviewer | TEST-001, QA-FE-001 | Full code review | - -### Composite Modes - -| Mode | Construction | PLAN-001 BlockedBy | -|------|-------------|-------------------| -| full-lifecycle | Spec (6) + Impl (4) | QUALITY-001 | -| full-lifecycle-fe | Spec (6) + Fullstack (6) | QUALITY-001 | - -### Task Description Template - -``` -TaskCreate({ - subject: "<TASK-ID>", - description: "PURPOSE: <what> | Success: <criteria> -TASK: - - <step 1> - - <step 2> - - <step 3> -CONTEXT: - - Session: <session-folder> - - Scope: <scope> - - Upstream: <artifacts> -EXPECTED: <deliverable> + <quality> -CONSTRAINTS: <scope limits> ---- -Validation: <DISCUSS-NNN or self-validate> -InnerLoop: <true|false>", - addBlockedBy: [<deps>] -}) -``` - -### Revision Task Template - -``` -TaskCreate({ - subject: "<ORIGINAL-ID>-R1", - owner: "<same-role>", - description: "PURPOSE: Revision of <ORIGINAL-ID> | Success: Address feedback -TASK: - - Review original + feedback - - Apply fixes - - Validate -CONTEXT: - - Session: <session-folder> - - Original: <artifact-path> - - Feedback: <text> -EXPECTED: Updated artifact + summary ---- -Validation: <same-as-original> -InnerLoop: <true|false>", - blockedBy: [<predecessor-R1 if cascaded>] -}) -``` - -**Cascade Rules**: - -| Revised Task | Downstream | -|-------------|-----------| -| RESEARCH-001 | DRAFT-001~004-R1, QUALITY-001-R1 | -| DRAFT-001 | DRAFT-002~004-R1, QUALITY-001-R1 | -| DRAFT-002 | DRAFT-003~004-R1, QUALITY-001-R1 | -| DRAFT-003 | DRAFT-004-R1, QUALITY-001-R1 | -| DRAFT-004 | QUALITY-001-R1 | - -## Phase 4: Validation - -| Check | Criteria | -|-------|----------| -| Task count | Matches mode total | -| Dependencies | Every blockedBy references existing task | -| Owner | Each task owner matches Role Registry | -| Session ref | Every task contains `Session:` | -| Validation field | Spec tasks have Validation field | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Unknown mode | Reject with supported modes | -| Missing spec for impl-only | Error, suggest spec-only | -| TaskCreate fails | Log error, report | -| Duplicate task | Skip, log warning | diff --git a/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/monitor.md b/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/monitor.md deleted file mode 100644 index efb0fea2..00000000 --- a/.claude/skills/team-lifecycle-v2/roles/coordinator/commands/monitor.md +++ /dev/null @@ -1,134 +0,0 @@ -# Command: monitor - -Event-driven pipeline coordination. v2: 3 discuss points, simplified consensus handling. - -## Constants - -| Constant | Value | -|----------|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| FAST_ADVANCE_AWARE | true | -| WORKER_AGENT | team-worker | - -## Phase 2: Context Loading - -| Input | Source | Required | -|-------|--------|----------| -| Session file | team-session.json | Yes | -| Task list | TaskList() | Yes | -| Active workers | session.active_workers[] | Yes | - -## Phase 3: Handler Routing - -| Priority | Condition | Handler | -|----------|-----------|---------| -| 1 | `[<role-name>]` from worker | handleCallback | -| 2 | "check" or "status" | handleCheck | -| 3 | "resume" / "continue" | handleResume | -| 4 | None (initial spawn) | handleSpawnNext | -| 5 | "revise" + task ID | handleRevise | -| 6 | "feedback" + text | handleFeedback | -| 7 | "recheck" | handleRecheck | -| 8 | "improve" | handleImprove | - ---- - -### handleCallback - -``` -Receive callback from [<role>] - +- Progress update? -> Update session -> STOP - +- Task completed? -> remove from active_workers -> update session - | +- Handle checkpoints (QUALITY-001) - | +- -> handleSpawnNext - +- No matching worker -> scan all active -> handleSpawnNext or STOP -``` - -Fast-advance reconciliation: read team_msg fast_advance entries, sync active_workers. - -### handleCheck - -Read-only status report, no advancement. - -``` -[coordinator] Pipeline Status (v2) -[coordinator] Mode: <mode> | Progress: <completed>/<total> (<percent>%) -[coordinator] Discuss: <completed-discuss>/<total-discuss> rounds - -[coordinator] Execution Graph: - Spec Phase: - [<icon> RESEARCH-001(+D1)] -> [<icon> DRAFT-001] -> [<icon> DRAFT-002(+D2)] -> [<icon> DRAFT-003] -> [<icon> DRAFT-004] -> [<icon> QUALITY-001(+D3)] - Impl Phase: - [<icon> PLAN-001] -> [<icon> IMPL-001] -> [<icon> TEST-001] + [<icon> REVIEW-001] - - done=completed >>>=running o=pending -``` - -Then STOP. - -### handleResume - -``` -Load active_workers - +- No active -> handleSpawnNext - +- Has active -> check each: - +- completed -> mark done - +- in_progress -> still running - +- other -> reset to pending - After: some completed -> handleSpawnNext; all running -> STOP -``` - -### handleSpawnNext - -``` -Collect task states from TaskList() - +- readySubjects: pending + all blockedBy completed - +- NONE + work in progress -> STOP - +- NONE + nothing running -> PIPELINE_COMPLETE -> Phase 5 - +- HAS ready -> for each: - +- Inner Loop role AND already active? -> SKIP - +- Spawn team-worker (see SKILL.md Spawn Template) - +- Add to active_workers - Update session -> STOP -``` - -### handleRevise / handleFeedback / handleRecheck / handleImprove - -Same as v1 (see dispatch.md for templates). Changes: -- Revision tasks use v2 Validation field ("self-validate" or "DISCUSS-NNN") - ---- - -### Consensus-Blocked Handling (v2 simplified) - -Only 3 discuss points to handle: - -``` -handleCallback receives consensus_blocked: - +- DISCUSS-003 (QUALITY) + HIGH -> PAUSE for user (final gate) - +- Any discuss + HIGH -> Create REVISION task (max 1 per task) - +- MEDIUM -> proceed with warning, log to wisdom/issues.md - +- LOW -> proceed normally -``` - -### Fast-Advance State Sync - -On every coordinator wake: -1. Read team_msg fast_advance entries -2. Sync active_workers with spawned successors - -### Worker Failure Handling - -1. Reset task -> pending -2. Log via team_msg (type: error) -3. Report to user - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Session not found | Error, suggest re-init | -| Unknown role callback | Log, scan for completions | -| Pipeline stall | Check missing tasks, report | -| Fast-advance orphan | Reset to pending, re-spawn | diff --git a/.claude/skills/team-lifecycle-v2/roles/coordinator/role.md b/.claude/skills/team-lifecycle-v2/roles/coordinator/role.md deleted file mode 100644 index a9ee028d..00000000 --- a/.claude/skills/team-lifecycle-v2/roles/coordinator/role.md +++ /dev/null @@ -1,139 +0,0 @@ -# Coordinator Role - -Orchestrate team-lifecycle-v2: team creation, task dispatching, progress monitoring, session state. Uses **team-worker agent** for all worker spawns. - -## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report - -## Boundaries - -### MUST -- Parse user requirements and clarify via AskUserQuestion -- Create team and spawn workers using **team-worker** agent type -- Dispatch tasks with proper dependency chains -- Monitor progress via callbacks and route messages -- Maintain session state (team-session.json) - -### MUST NOT -- Execute spec/impl/research work directly -- Modify task outputs -- Skip dependency validation - ---- - -## Entry Router - -| Detection | Condition | Handler | -|-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag | -> handleCallback | -| Status check | "check" or "status" | -> handleCheck | -| Manual resume | "resume" or "continue" | -> handleResume | -| Interrupted session | Active/paused session in `.workflow/.team/TLS-*` | -> Phase 0 | -| New session | None of above | -> Phase 1 | - -For callback/check/resume: load `commands/monitor.md`, execute handler, STOP. - ---- - -## Phase 0: Session Resume Check - -1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused -2. No sessions -> Phase 1 -3. Single session -> resume (reconciliation) -4. Multiple -> AskUserQuestion - -**Session Reconciliation**: -1. Audit TaskList, reconcile with session state -2. Reset in_progress -> pending (interrupted tasks) -3. Rebuild team if disbanded -4. Create missing tasks with correct blockedBy -5. Kick first executable -> Phase 4 - ---- - -## Phase 1: Requirement Clarification - -1. Parse arguments for mode, scope, focus -2. Ask missing parameters via AskUserQuestion: - - Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe - - Scope: project description -3. Frontend auto-detection (keyword + package.json scanning) -4. Store requirements - ---- - -## Phase 2: Create Team + Initialize Session - -1. Generate session ID: `TLS-<slug>-<date>` -2. Create session folder: `.workflow/.team/<session-id>/` -3. TeamCreate -4. Initialize directories (spec/, discussions/, plan/, explorations/) -5. Write team-session.json -6. Initialize meta.json via team_msg state_update: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<mode>", - pipeline_stages: [<role-list>], - roles: [<all-roles>], - team_name: "lifecycle-v2" - } -}) -``` - ---- - -## Phase 3: Create Task Chain - -Delegate to `commands/dispatch.md`: -1. Read Task Metadata Registry for task definitions -2. Create tasks via TaskCreate with correct blockedBy -3. Include `Session: <session-folder>` in every task -4. Mark discuss rounds (DISCUSS-001, DISCUSS-002, DISCUSS-003) or "self-validate" - ---- - -## Phase 4: Spawn-and-Stop - -1. Load `commands/monitor.md` -2. Find ready tasks (pending + blockedBy resolved) -3. Spawn team-worker for each ready task -4. Output summary -5. STOP - -### Checkpoint Gate (QUALITY-001) - -When QUALITY-001 completes: -1. Read readiness-report.md -2. Parse quality gate and dimension scores -3. Output Checkpoint Template (see SKILL.md) -4. Pause for user command - ---- - -## Phase 5: Report + Next Steps - -1. Count completed tasks, duration -2. List deliverables -3. Update session status -> "completed" -4. Offer next steps: exit / view / extend / generate plan - ---- - -## Error Handling - -| Error | Resolution | -|-------|------------| -| Task timeout | Log, mark failed, ask user | -| Worker crash | Respawn worker, reassign task | -| Dependency cycle | Detect, report, halt | -| Invalid mode | Reject, ask to clarify | -| Session corruption | Attempt recovery | diff --git a/.claude/skills/team-lifecycle-v2/specs/document-standards.md b/.claude/skills/team-lifecycle-v2/specs/document-standards.md deleted file mode 100644 index 2820cd98..00000000 --- a/.claude/skills/team-lifecycle-v2/specs/document-standards.md +++ /dev/null @@ -1,192 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle-v2/specs/quality-gates.md b/.claude/skills/team-lifecycle-v2/specs/quality-gates.md deleted file mode 100644 index ae968436..00000000 --- a/.claude/skills/team-lifecycle-v2/specs/quality-gates.md +++ /dev/null @@ -1,207 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle-v2/specs/team-config.json b/.claude/skills/team-lifecycle-v2/specs/team-config.json deleted file mode 100644 index 36e87335..00000000 --- a/.claude/skills/team-lifecycle-v2/specs/team-config.json +++ /dev/null @@ -1,246 +0,0 @@ -{ - "team_name": "team-lifecycle-v2", - "team_display_name": "Team Lifecycle v2", - "description": "Optimized team-worker agent architecture: discuss reduced 6→3, progressive refinement preserved", - "version": "6.0.0", - "architecture": "team-worker agent + role-specs", - "role_structure": "role-specs/{name}.md (Phase 2-4 only)", - "worker_agent": "team-worker", - "roles": { - "coordinator": { - "task_prefix": null, - "responsibility": "Pipeline orchestration, requirement clarification, task chain creation", - "message_types": [ - "plan_approved", - "plan_revision", - "task_unblocked", - "fix_required", - "error", - "shutdown" - ] - }, - "analyst": { - "task_prefix": "RESEARCH", - "role_spec": "role-specs/analyst.md", - "responsibility": "Seed analysis, codebase exploration, context gathering + discuss", - "inline_discuss": "DISCUSS-001", - "inner_loop": false, - "message_types": [ - "research_ready", - "research_progress", - "error" - ] - }, - "writer": { - "task_prefix": "DRAFT", - "role_spec": "role-specs/writer.md", - "responsibility": "Product Brief / PRD / Architecture / Epics generation. Discuss at PRD only, self-validate others", - "inner_loop": true, - "inline_discuss": [ - "DISCUSS-002" - ], - "message_types": [ - "draft_ready", - "draft_revision", - "error" - ] - }, - "planner": { - "task_prefix": "PLAN", - "role_spec": "role-specs/planner.md", - "responsibility": "Multi-angle exploration and structured implementation planning", - "inner_loop": true, - "message_types": [ - "plan_ready", - "plan_revision", - "error" - ] - }, - "executor": { - "task_prefix": "IMPL", - "role_spec": "role-specs/executor.md", - "responsibility": "Code implementation following approved plans", - "inner_loop": true, - "message_types": [ - "impl_complete", - "impl_progress", - "error" - ] - }, - "tester": { - "task_prefix": "TEST", - "role_spec": "role-specs/tester.md", - "responsibility": "Adaptive test-fix cycles, progressive testing", - "inner_loop": false, - "message_types": [ - "test_result", - "fix_required", - "error" - ] - }, - "reviewer": { - "task_prefix": "REVIEW", - "additional_prefixes": [ - "QUALITY", - "IMPROVE" - ], - "role_spec": "role-specs/reviewer.md", - "responsibility": "Code review (REVIEW-*) + Spec quality (QUALITY-*) + Improvement (IMPROVE-*) + final discuss", - "inline_discuss": "DISCUSS-003", - "inner_loop": false, - "message_types": [ - "review_result", - "quality_result", - "quality_recheck", - "fix_required", - "error" - ] - }, - "architect": { - "task_prefix": "ARCH", - "role_spec": "role-specs/architect.md", - "responsibility": "Architecture assessment, tech feasibility. Consulting role", - "role_type": "consulting", - "inner_loop": false, - "message_types": [ - "arch_ready", - "arch_concern", - "error" - ] - }, - "fe-developer": { - "task_prefix": "DEV-FE", - "role_spec": "role-specs/fe-developer.md", - "responsibility": "Frontend implementation", - "role_type": "frontend-pipeline", - "inner_loop": false, - "message_types": [ - "dev_fe_complete", - "dev_fe_progress", - "error" - ] - }, - "fe-qa": { - "task_prefix": "QA-FE", - "role_spec": "role-specs/fe-qa.md", - "responsibility": "5-dimension frontend review, GC loop", - "role_type": "frontend-pipeline", - "inner_loop": false, - "message_types": [ - "qa_fe_passed", - "qa_fe_result", - "fix_required", - "error" - ] - } - }, - "checkpoint_commands": { - "revise": { - "handler": "handleRevise", - "pattern": "revise <TASK-ID> [feedback]", - "cascade": true - }, - "feedback": { - "handler": "handleFeedback", - "pattern": "feedback <text>", - "cascade": true - }, - "recheck": { - "handler": "handleRecheck", - "pattern": "recheck", - "cascade": false - }, - "improve": { - "handler": "handleImprove", - "pattern": "improve [dimension]", - "cascade": false - } - }, - "pipelines": { - "spec-only": { - "description": "Spec pipeline: research(+D1) -> brief -> prd(+D2) -> arch -> epics -> quality(+D3)", - "task_chain": [ - "RESEARCH-001", - "DRAFT-001", - "DRAFT-002", - "DRAFT-003", - "DRAFT-004", - "QUALITY-001" - ], - "discuss_points": [ - "RESEARCH-001", - "DRAFT-002", - "QUALITY-001" - ], - "beats": 6 - }, - "impl-only": { - "description": "Implementation pipeline: plan -> implement -> test + review", - "task_chain": [ - "PLAN-001", - "IMPL-001", - "TEST-001", - "REVIEW-001" - ], - "beats": 3 - }, - "full-lifecycle": { - "description": "Full lifecycle: spec + impl (PLAN blockedBy QUALITY)", - "task_chain": "spec-only + impl-only (PLAN-001 blockedBy QUALITY-001)", - "beats": 9 - }, - "fe-only": { - "description": "Frontend-only: plan -> dev -> qa", - "task_chain": [ - "PLAN-001", - "DEV-FE-001", - "QA-FE-001" - ], - "gc_loop": { - "max_rounds": 2, - "convergence": "score >= 8 && critical === 0" - } - }, - "fullstack": { - "description": "Fullstack: plan -> backend + frontend parallel -> test + qa -> review", - "task_chain": [ - "PLAN-001", - "IMPL-001||DEV-FE-001", - "TEST-001||QA-FE-001", - "REVIEW-001" - ] - }, - "full-lifecycle-fe": { - "description": "Full lifecycle with frontend", - "task_chain": "spec-only + fullstack (PLAN-001 blockedBy QUALITY-001)" - } - }, - "frontend_detection": { - "keywords": [ - "component", - "page", - "UI", - "frontend", - "CSS", - "HTML", - "React", - "Vue", - "Tailwind", - "Svelte", - "Next.js" - ], - "routing_rules": { - "frontend_only": "All tasks match frontend keywords", - "fullstack": "Mix of frontend and backend tasks", - "backend_only": "No frontend keywords (default impl-only)" - } - }, - "session_dirs": { - "base": ".workflow/.team/TLS-{slug}-{YYYY-MM-DD}/", - "spec": "spec/", - "discussions": "discussions/", - "plan": "plan/", - "explorations": "explorations/", - "messages": ".msg/" - } -} diff --git a/.claude/skills/team-lifecycle-v3/SKILL.md b/.claude/skills/team-lifecycle-v3/SKILL.md deleted file mode 100644 index 2ec16988..00000000 --- a/.claude/skills/team-lifecycle-v3/SKILL.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -name: team-lifecycle-v3 -description: Enhanced lifecycle with parallel execution, conditional routing, dynamic role injection, and task priority scheduling. Built on team-worker agent architecture with artifact contracts and automatic discovery. -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) ---- - -# Team Lifecycle v3 - -Enhanced lifecycle: specification → implementation → testing → review with parallel execution, conditional routing, and dynamic specialist role injection. - -## Purpose - -Team Lifecycle v3 orchestrates multi-agent software development workflows from initial requirements through implementation, testing, and review. It automatically coordinates specialized agents, manages artifact dependencies, validates quality gates, and dynamically injects expert roles based on task complexity. - -**Key Capabilities**: -- Parallel execution of independent tasks -- Dynamic specialist role injection (security, performance, data, devops, ML) -- Artifact-based validation gating -- Conditional routing based on complexity assessment -- Priority-based task scheduling (P0/P1/P2) -- Quality checkpoints with user feedback loops - -## Problem Statement - -Complex software development tasks require diverse expertise—security audits, performance optimization, data pipeline design, DevOps configuration, and ML model integration. Coordinating multiple specialized agents manually is error-prone, inefficient, and difficult to scale. Developers face several challenges: - -1. **Manual Coordination Overhead**: Tracking dependencies between agents, ensuring artifacts are validated before downstream work begins, and managing parallel execution requires constant human oversight. - -2. **Expertise Gaps**: Not all tasks require all specialists. Injecting the right expert roles at the right time based on task complexity and keywords is a manual, subjective process prone to under- or over-staffing. - -3. **Quality Assurance Bottlenecks**: Without automated quality gates and validation checkpoints, defects propagate downstream, requiring expensive rework. - -4. **Lack of Observability**: Understanding where a multi-agent workflow is stalled, which artifacts are blocking progress, and what actions are needed requires manual inspection of scattered state. - -Team Lifecycle v3 solves these problems by providing an event-driven orchestration system that automatically manages agent coordination, artifact validation, specialist injection, and quality checkpoints—turning multi-agent workflows into a repeatable, observable, and scalable process. - -## Goals - -- **Automated Agent Coordination**: Spawn workers based on task dependencies, manage parallel execution, and handle completion callbacks without manual intervention. -- **Artifact-Based Validation Gating**: Block downstream work until upstream artifacts pass validation, preventing defect propagation. -- **Dynamic Specialist Injection**: Analyze task descriptions and complexity to automatically inject expert roles (security, performance, data, devops, ML) when needed. -- **Conditional Routing**: Route tasks to appropriate implementation strategies (direct, orchestrated, architecture-first) based on quantifiable complexity assessment. -- **Priority-Based Scheduling**: Execute critical-path tasks (P0) before dependent tasks (P1/P2), optimizing workflow throughput. -- **Quality Checkpoints**: Pause at key milestones for user review, with actionable commands (resume, improve, revise, recheck) to maintain quality. -- **Session Persistence**: Support pause/resume across process restarts, preserving artifact registry and task state. -- **Observability**: Provide clear status reporting, task state visibility, and actionable error messages. - -## Non-Goals - -- **General-Purpose Workflow Engine**: Team Lifecycle v3 is specialized for software development workflows with agent coordination. It is not a generic DAG executor or distributed job scheduler. -- **Project Management Tool**: The system does not manage backlogs, sprints, or roadmaps. It executes individual tasks with clear requirements. -- **Prescriptive Agent Implementations**: The skill defines role specifications and contracts but does not mandate specific agent implementations or tools. -- **Ticket/PR Management**: State transitions, comments, and PR creation are the responsibility of individual agents using their own tools, not the orchestrator. -- **Approval/Sandbox Policies**: The skill does not enforce specific approval workflows or sandboxing. Implementations may add these based on their trust model. -- **Real-Time Collaboration**: The system is event-driven with asynchronous agent execution, not a real-time collaborative editing environment. - -## Mandatory Reading - -Before using this skill, read these documents to understand the foundational concepts: - -| Document | Purpose | Priority | -|----------|---------|----------| -| [specs/core-concepts.md](specs/core-concepts.md) | Foundational principles: team-worker architecture, artifact contracts, quality gating, dynamic role injection, priority scheduling | **P0 - Critical** | -| [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) | Artifact manifest schema and validation rules | **P0 - Critical** | -| [specs/execution-flow.md](specs/execution-flow.md) | End-to-end execution walkthrough with pipeline definitions | **P1 - High** | - -## Documentation Structure - -This skill is organized into the following directories: - -### `/roles` - Agent Role Specifications - -- **`coordinator/`**: Orchestrator agent that manages workflow, task dependencies, and role injection - - `role.md`: Coordinator specification - - `commands/`: User command handlers (dispatch, monitor) -- **`pipeline/`**: Core pipeline roles (always present) - - `analyst.md`, `writer.md`, `planner.md`, `executor.md`, `tester.md`, `reviewer.md` - - `architect.md`, `fe-developer.md`, `fe-qa.md` (consulting roles) -- **`specialists/`**: Specialist roles (dynamically injected) - - `orchestrator.role.md`, `security-expert.role.md`, `performance-optimizer.role.md` - - `data-engineer.role.md`, `devops-engineer.role.md`, `ml-engineer.role.md` - -### `/specs` - Specifications and Standards - -- **`core-concepts.md`**: Foundational principles (mandatory reading) -- **`execution-flow.md`**: End-to-end execution walkthrough -- **`artifact-contract-spec.md`**: Artifact manifest schema -- **`quality-gates.md`**: Quality validation criteria -- **`document-standards.md`**: Document formatting standards -- **`team-config.json`**: Role registry and pipeline definitions - -### `/templates` - Document Templates - -- `product-brief.md`: DRAFT-001 template -- `requirements-prd.md`: DRAFT-002 template -- `architecture-doc.md`: DRAFT-003 template -- `epics-template.md`: DRAFT-004 template - -### `/subagents` - Utility Subagents - -- `discuss-subagent.md`: 3-round discussion protocol -- `explorer-subagent.md`: Shared exploration with cache -- `doc-generator-subagent.md`: Template-based doc generation - -## Quick Start - -### Basic Usage - -``` -Skill(skill="team-lifecycle-v3", args="<task description>") -``` - -**Example**: -``` -Skill(skill="team-lifecycle-v3", args="Implement user authentication with OAuth2") -``` - -### Execution Flow - -1. **User provides task description** → Coordinator clarifies requirements -2. **Coordinator creates team** → TeamCreate with session folder -3. **Coordinator analyzes complexity** → Injects specialist roles if needed -4. **Coordinator creates task chain** → Based on pipeline selection (spec-only, impl-only, full-lifecycle) -5. **Coordinator spawns first batch** → Workers execute in background -6. **Workers report completion** → SendMessage callback to coordinator -7. **Coordinator advances pipeline** → Spawns next ready tasks -8. **Quality checkpoints** → User can review, improve, or revise -9. **Coordinator generates report** → Final summary and completion action - -### User Commands - -During execution, you can use these commands: - -| Command | Action | -|---------|--------| -| `check` / `status` | View current execution status | -| `resume` / `continue` | Advance to next step | -| `revise <TASK-ID> [feedback]` | Revise specific task with feedback | -| `feedback <text>` | Provide feedback for targeted revision | -| `recheck` | Re-run quality check | -| `improve [dimension]` | Auto-improve weakest quality dimension | - -## Pipeline Options - -The coordinator selects the appropriate pipeline based on task requirements: - -### Spec-only Pipeline (6 tasks) -``` -RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001 -``` -Use for: Documentation, requirements gathering, design work - -### Impl-only Pipeline (4 tasks) -``` -PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001 -``` -Use for: Quick implementations with clear requirements - -### Full-lifecycle Pipeline (10 tasks) -``` -[Spec pipeline] → PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001 -``` -Use for: Complete feature development from requirements to implementation - -## Advanced Features - -### Dynamic Role Injection - -Specialist roles are automatically injected based on keywords in task description: - -- **security**, **vulnerability**, **OWASP** → `security-expert` -- **performance**, **optimization**, **bottleneck** → `performance-optimizer` -- **data**, **pipeline**, **ETL**, **schema** → `data-engineer` -- **devops**, **CI/CD**, **deployment**, **docker** → `devops-engineer` -- **ML**, **model**, **training**, **inference** → `ml-engineer` - -### Conditional Routing - -PLAN-001 assesses complexity and routes to appropriate implementation strategy: - -- **Low complexity** (1-2 modules) → Direct implementation -- **Medium complexity** (3-4 modules) → Orchestrated parallel implementation -- **High complexity** (5+ modules) → Architecture design + orchestrated implementation - -### Quality Checkpoints - -At key milestones, the coordinator pauses for user review: - -- **Spec Phase Complete** (QUALITY-001): Review specification quality, choose to proceed, improve, or revise -- **Implementation Complete**: Review code quality and test coverage - -## Troubleshooting - -### Common Issues - -| Issue | Solution | -|-------|----------| -| Pipeline stalled | Use `status` to check task states, `resume` to advance | -| Quality gate failed | Use `improve` to auto-improve or `revise <TASK-ID>` to manually fix | -| Wrong specialist injected | Provide clearer keywords in task description | -| Session lost after restart | Use session resume to restore from `.workflow/.team/TLS-*` | - -### Error Handling - -| Scenario | Resolution | -|----------|------------| -| Unknown command | Error with available command list | -| Role spec file not found | Error with expected path | -| Artifact validation fails | Block downstream, trigger fix loop | -| Dynamic role injection fails | Log warning, continue with core roles | -| Parallel merge timeout | Report stall, prompt user intervention | - -## Reference Documents - -For detailed information, see: - -- [specs/core-concepts.md](specs/core-concepts.md) - Foundational principles -- [specs/execution-flow.md](specs/execution-flow.md) - Detailed execution walkthrough -- [specs/artifact-contract-spec.md](specs/artifact-contract-spec.md) - Artifact manifest specification -- [specs/quality-gates.md](specs/quality-gates.md) - Quality validation criteria -- [specs/document-standards.md](specs/document-standards.md) - Document formatting standards -- [roles/coordinator/role.md](roles/coordinator/role.md) - Coordinator specification -- [roles/README.md](roles/README.md) - Role directory guide diff --git a/.claude/skills/team-lifecycle-v3/roles/README.md b/.claude/skills/team-lifecycle-v3/roles/README.md deleted file mode 100644 index 95b180f2..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/README.md +++ /dev/null @@ -1,232 +0,0 @@ -# Role Directory Guide - -This directory contains all agent role specifications for Team Lifecycle v3. - -## Directory Structure - -``` -roles/ -├── README.md # This file -├── coordinator/ # Orchestrator agent -│ ├── role.md # Coordinator specification -│ └── commands/ # User command handlers -│ ├── dispatch.md -│ └── monitor.md -├── pipeline/ # Core pipeline roles (always present) -│ ├── analyst.md # Research and discovery -│ ├── writer.md # Document drafting -│ ├── planner.md # Implementation planning -│ ├── executor.md # Code implementation -│ ├── tester.md # Test generation -│ ├── reviewer.md # Quality review -│ ├── architect.md # Architecture design (consulting) -│ ├── fe-developer.md # Frontend development (consulting) -│ └── fe-qa.md # Frontend QA (consulting) -└── specialists/ # Specialist roles (dynamically injected) - ├── orchestrator.role.md # Multi-module coordination - ├── security-expert.role.md # Security analysis - ├── performance-optimizer.role.md # Performance optimization - ├── data-engineer.role.md # Data pipeline work - ├── devops-engineer.role.md # DevOps and deployment - └── ml-engineer.role.md # ML/AI implementation -``` - -## Role Types - -### Coordinator (Orchestrator) - -**Location**: `coordinator/` - -**Purpose**: Manages workflow orchestration, task dependencies, role injection, and artifact registry. - -**Key Responsibilities**: -- Parse user requests and clarify requirements -- Create and manage team sessions -- Analyze complexity and inject specialist roles -- Create task chains with dependencies -- Spawn workers and handle callbacks -- Validate artifacts and advance pipeline -- Display checkpoints and handle user commands - -**Always Present**: Yes - -**Spawned By**: Skill invocation - -### Pipeline Roles (Core Team) - -**Location**: `pipeline/` - -**Purpose**: Execute standard development workflow tasks. - -**Always Present**: Yes (based on pipeline selection) - -**Spawned By**: Coordinator - -#### Core Pipeline Roles - -| Role | File | Purpose | Task Prefix | -|------|------|---------|-------------| -| analyst | `analyst.md` | Research and discovery | RESEARCH-* | -| writer | `writer.md` | Document drafting | DRAFT-* | -| planner | `planner.md` | Implementation planning | PLAN-* | -| executor | `executor.md` | Code implementation | IMPL-* | -| tester | `tester.md` | Test generation and execution | TEST-* | -| reviewer | `reviewer.md` | Quality review and improvement | REVIEW-*, QUALITY-*, IMPROVE-* | - -#### Consulting Roles - -| Role | File | Purpose | Task Prefix | Injection Trigger | -|------|------|---------|-------------|-------------------| -| architect | `architect.md` | Architecture design | ARCH-* | High complexity | -| fe-developer | `fe-developer.md` | Frontend development | DEV-FE-* | Frontend tasks | -| fe-qa | `fe-qa.md` | Frontend QA | QA-FE-* | Frontend tasks | - -### Specialist Roles (Dynamic Injection) - -**Location**: `specialists/` - -**Purpose**: Provide expert capabilities for specific domains. - -**Always Present**: No (injected based on task analysis) - -**Spawned By**: Coordinator (after complexity/keyword analysis) - -| Role | File | Purpose | Task Prefix | Injection Trigger | -|------|------|---------|-------------|-------------------| -| orchestrator | `orchestrator.role.md` | Multi-module coordination | ORCH-* | Medium/High complexity | -| security-expert | `security-expert.role.md` | Security analysis and audit | SECURITY-* | Keywords: security, vulnerability, OWASP, auth | -| performance-optimizer | `performance-optimizer.role.md` | Performance optimization | PERF-* | Keywords: performance, optimization, bottleneck | -| data-engineer | `data-engineer.role.md` | Data pipeline work | DATA-* | Keywords: data, pipeline, ETL, schema | -| devops-engineer | `devops-engineer.role.md` | DevOps and deployment | DEVOPS-* | Keywords: devops, CI/CD, deployment, docker | -| ml-engineer | `ml-engineer.role.md` | ML/AI implementation | ML-* | Keywords: ML, model, training, inference | - -## Role Specification Format - -All role specifications follow this structure: - -```markdown ---- -role: <role-name> -type: <coordinator|pipeline|specialist> -task_prefix: <TASK-PREFIX> -priority: <P0|P1|P2> -injection_trigger: <always|complexity|keywords> ---- - -# Role: <Role Name> - -## Purpose - -Brief description of role purpose. - -## Responsibilities - -- Responsibility 1 -- Responsibility 2 - -## Phase Execution - -### Phase 1: Task Discovery -... - -### Phase 2: Context Gathering -... - -### Phase 3: Domain Work -... - -### Phase 4: Artifact Generation -... - -### Phase 5: Reporting -... - -## Tools & Capabilities - -- Tool 1 -- Tool 2 - -## Artifact Contract - -Expected artifacts and manifest schema. -``` - -## Worker Execution Model - -All workers (pipeline and specialist roles) follow the **5-phase execution model**: - -1. **Phase 1: Task Discovery** - Read task metadata, understand requirements -2. **Phase 2: Context Gathering** - Discover upstream artifacts, gather context -3. **Phase 3: Domain Work** - Execute role-specific work -4. **Phase 4: Artifact Generation** - Generate deliverables with manifest -5. **Phase 5: Reporting** - Report completion to coordinator - -## CLI Tool Integration - -Workers can use CLI tools for complex analysis: - -| Capability | CLI Command | Used By | -|------------|-------------|---------| -| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect | -| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer | -| Document generation | `ccw cli --tool gemini --mode write` | writer | - -**Note**: Workers CANNOT spawn utility members (explorer, discussant). Only the coordinator can spawn utility members. - -## Utility Members (Coordinator-Only) - -Utility members are NOT roles but specialized subagents that can only be spawned by the coordinator: - -| Utility | Purpose | Callable By | -|---------|---------|-------------| -| explorer | Parallel multi-angle exploration | Coordinator only | -| discussant | Aggregate multi-CLI critique | Coordinator only | -| doc-generator | Template-based doc generation | Coordinator only | - -**Location**: `../subagents/` (not in roles directory) - -## Adding New Roles - -To add a new specialist role: - -1. Create role specification file in `specialists/` directory -2. Follow the role specification format -3. Define injection trigger (keywords or complexity) -4. Update `../specs/team-config.json` role registry -5. Update coordinator's role injection logic -6. Test with sample task descriptions - -## Role Selection Logic - -### Pipeline Selection - -Coordinator selects pipeline based on user requirements: - -- **Spec-only**: Documentation, requirements, design work -- **Impl-only**: Quick implementations with clear requirements -- **Full-lifecycle**: Complete feature development - -### Specialist Injection - -Coordinator analyzes task description for: - -1. **Keywords**: Specific domain terms (security, performance, data, etc.) -2. **Complexity**: Module count, dependency depth -3. **Explicit requests**: User mentions specific expertise needed - -### Conditional Routing - -PLAN-001 assesses complexity and routes to appropriate implementation strategy: - -- **Low complexity** → Direct implementation (executor only) -- **Medium complexity** → Orchestrated implementation (orchestrator + parallel executors) -- **High complexity** → Architecture + orchestrated implementation (architect + orchestrator + parallel executors) - -## Reference Documents - -For detailed information, see: - -- [../specs/core-concepts.md](../specs/core-concepts.md) - Foundational principles -- [../specs/execution-flow.md](../specs/execution-flow.md) - Execution walkthrough -- [../specs/artifact-contract-spec.md](../specs/artifact-contract-spec.md) - Artifact manifest specification -- [coordinator/role.md](coordinator/role.md) - Coordinator specification diff --git a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/dispatch.md b/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/dispatch.md deleted file mode 100644 index f7e74dc5..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/dispatch.md +++ /dev/null @@ -1,236 +0,0 @@ -# Command: dispatch (v3 Enhanced) - -Create task chains based on execution mode with conditional routing, dynamic role injection, and priority assignment. - -## Phase 2: Context Loading - -| Input | Source | Required | -|-------|--------|----------| -| Mode | Phase 1 requirements | Yes | -| Session folder | Phase 2 session init | Yes | -| Scope | User requirements | Yes | -| Injected roles | Phase 1 keyword analysis | No | -| Complexity | Phase 1 assessment | No | - -## Phase 3: Task Chain Creation - -### Spec Pipeline (6 tasks, 3 discuss) - -| # | Subject | Owner | BlockedBy | Description | Validation | Priority | -|---|---------|-------|-----------|-------------|------------|----------| -| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 | P0 | -| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | self-validate | P0 | -| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-002 | P0 | -| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | self-validate | P0 | -| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | self-validate | P0 | -| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-003 | P0 | - -### Impl Pipeline - Dynamic Task Creation - -Initial dispatch creates **only PLAN-001**. IMPL-*, TEST-001, REVIEW-001 are dynamically created after PLAN-001 completes (see monitor.md handleCallback → PLAN-001). - -#### Initial Dispatch (all complexity levels) - -| # | Subject | Owner | BlockedBy | Description | Priority | -|---|---------|-------|-----------|-------------|----------| -| 1 | PLAN-001 | planner | (none) | Planning with complexity assessment + TASK-*.json generation | P0 | - -#### Dynamic Creation (after PLAN-001 completes) - -Coordinator reads planner's output and creates tasks dynamically: - -1. Read `<session-folder>/plan/plan.json` → extract `complexity` field -2. Read `<session-folder>/plan/.task/TASK-*.json` → enumerate sub-tasks -3. Apply complexity routing: - -| Complexity | Pre-IMPL tasks | Then | -|------------|---------------|------| -| Low | (none) | Create IMPL-* directly, blockedBy PLAN-001 | -| Medium | ORCH-001 (orchestrator, blockedBy PLAN-001) | Create IMPL-* blockedBy ORCH-001 | -| High | ARCH-001 (architect, blockedBy PLAN-001) → ORCH-001 (blockedBy ARCH-001) | Create IMPL-* blockedBy ORCH-001 | - -4. For each `TASK-N.json`, create corresponding IMPL task: - -``` -TaskCreate({ - subject: "IMPL-00N", - description: "PURPOSE: <TASK-N.title> | Success: <TASK-N.convergence.criteria> -TASK: - - <steps from TASK-N.json> -CONTEXT: - - Session: <session-folder> - - Task file: <session-folder>/plan/.task/TASK-N.json - - Files: <TASK-N.files[]> - - Priority: P0 -EXPECTED: Implementation matching task file specification -CONSTRAINTS: Only modify files listed in task file ---- -Validation: self-validate -InnerLoop: false -Priority: P0", - addBlockedBy: [<PLAN-001 or ORCH-001>] -}) -``` - -5. Create TEST-001 (tester, blockedBy all IMPL-*, P1) -6. Create REVIEW-001 (reviewer, blockedBy all IMPL-*, P1) -7. Apply dynamic role injection (see below) - -### FE Pipeline (3 tasks) - -| # | Subject | Owner | BlockedBy | Description | Priority | -|---|---------|-------|-----------|-------------|----------| -| 1 | PLAN-001 | planner | (none) | Planning (frontend focus) | P0 | -| 2 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | P0 | -| 3 | QA-FE-001 | fe-qa | DEV-FE-001 | 5-dimension frontend QA | P1 | - -### Fullstack Pipeline (6 tasks, parallel execution) - -| # | Subject | Owner | BlockedBy | Description | Priority | -|---|---------|-------|-----------|-------------|----------| -| 1 | PLAN-001 | planner | (none) | Fullstack planning | P0 | -| 2 | IMPL-001 | executor | PLAN-001 | Backend implementation | P0 | -| 3 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation (parallel) | P0 | -| 4 | TEST-001 | tester | IMPL-001 | Backend test-fix | P1 | -| 5 | QA-FE-001 | fe-qa | DEV-FE-001 | Frontend QA (parallel) | P1 | -| 6 | REVIEW-001 | reviewer | TEST-001, QA-FE-001 | Full code review | P1 | - -### Dynamic Role Injection (v3 NEW) - -When specialist roles are injected, add corresponding tasks (blockedBy references the **last IMPL-*** task dynamically): - -| Injected Role | Task ID | Owner | BlockedBy | Description | Priority | -|---------------|---------|-------|-----------|-------------|----------| -| security-expert | SECURITY-001 | security-expert | all IMPL-* | Security audit (OWASP Top 10) | P0 | -| performance-optimizer | PERF-001 | performance-optimizer | all IMPL-* | Performance profiling & optimization | P1 | -| data-engineer | DATA-001 | data-engineer | PLAN-001 | Data pipeline implementation (parallel) | P0 | -| devops-engineer | DEVOPS-001 | devops-engineer | all IMPL-* | CI/CD & infrastructure setup | P1 | -| ml-engineer | ML-001 | ml-engineer | PLAN-001 | ML pipeline implementation (parallel) | P0 | - -**Injection Rules**: -- Security tasks: P0 priority, block REVIEW-001 -- Performance tasks: P1 priority, parallel with TEST-001 -- Data/ML tasks: P0 priority, parallel with IMPL-* -- DevOps tasks: P1 priority, after all IMPL-* - -### Composite Modes - -| Mode | Construction | PLAN-001 BlockedBy | -|------|-------------|-------------------| -| full-lifecycle | Spec (6) + Impl (conditional) | QUALITY-001 | -| full-lifecycle-fe | Spec (6) + Fullstack (6) | QUALITY-001 | - -### Task Description Template - -``` -TaskCreate({ - subject: "<TASK-ID>", - description: "PURPOSE: <what> | Success: <criteria> -TASK: - - <step 1> - - <step 2> - - <step 3> -CONTEXT: - - Session: <session-folder> - - Scope: <scope> - - Upstream: <artifacts> - - Priority: <P0|P1|P2> -EXPECTED: <deliverable> + <quality> -CONSTRAINTS: <scope limits> ---- -Validation: <DISCUSS-NNN or self-validate> -InnerLoop: <true|false> -Priority: <P0|P1|P2>", - addBlockedBy: [<deps>] -}) -``` - -### Complexity Assessment Logic (v3 NEW) - -PLAN-001 task description includes complexity assessment and TASK-*.json generation instructions: - -``` -PURPOSE: Create implementation plan with complexity assessment and task decomposition | Success: plan.json + TASK-*.json files - -TASK: - - Analyze requirements and scope - - Identify modules and dependencies - - Assess complexity (Low/Medium/High) - - Generate plan.json with complexity field - - Generate .task/TASK-*.json files (1 per implementation unit, 2-7 tasks) - - Each TASK-*.json must include: id, title, files[].change, convergence.criteria, depends_on - -CONTEXT: - - Session: <session-folder> - - Spec artifacts: <paths> - - Complexity criteria: - * Low: 1-2 modules, shallow deps, single tech stack - * Medium: 3-4 modules, moderate deps, 2 tech stacks - * High: 5+ modules, deep deps, multiple tech stacks - -EXPECTED: - <session-folder>/plan/plan.json (with complexity field) - <session-folder>/plan/.task/TASK-001.json ... TASK-00N.json - -Priority: P0 -``` - -### Revision Task Template - -``` -TaskCreate({ - subject: "<ORIGINAL-ID>-R1", - owner: "<same-role>", - description: "PURPOSE: Revision of <ORIGINAL-ID> | Success: Address feedback -TASK: - - Review original + feedback - - Apply fixes - - Validate -CONTEXT: - - Session: <session-folder> - - Original: <artifact-path> - - Feedback: <text> - - Priority: <inherit-from-original> -EXPECTED: Updated artifact + summary ---- -Validation: <same-as-original> -InnerLoop: <same-as-original> -Priority: <inherit-from-original>", - addBlockedBy: [] -}) -``` - -## Phase 4: Artifact Manifest Generation - -For each task, include artifact manifest generation instructions in task description: - -``` ---- -Artifact Contract: -Generate artifact-manifest.json in Phase 4: -{ - "artifact_id": "<role>-<type>-<timestamp>", - "creator_role": "<role>", - "artifact_type": "<type>", - "version": "1.0.0", - "path": "<relative-path>", - "dependencies": [<upstream-artifact-ids>], - "validation_status": "pending|passed|failed", - "validation_summary": "<summary>", - "metadata": { - "created_at": "<ISO8601>", - "task_id": "<task-id>", - "priority": "<P0|P1|P2>" - } -} -``` - -## Error Handling - -| Error | Resolution | -|-------|------------| -| Invalid mode | Reject, ask to clarify | -| Complexity assessment missing | Default to Low complexity | -| Injected role not found | Log warning, skip injection | -| Priority conflict | P0 > P1 > P2, FIFO within same priority | -| Circular dependency | Detect, report, halt | diff --git a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/execute.md b/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/execute.md deleted file mode 100644 index 476f800d..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/execute.md +++ /dev/null @@ -1,68 +0,0 @@ -# Command: execute - -Spawn executor team-workers for IMPL tasks. All execution routes through executor role (has team interaction protocol). Coordinator only handles spawning — executor internally selects agent or CLI mode. - -## Trigger - -Called by `monitor.md handleSpawnNext` when IMPL-* tasks become ready. - -## Spawn Logic - -Each IMPL task = 1 executor team-worker. Coordinator passes task file + executor assignment, executor handles the rest. - -``` -Agent({ - subagent_type: "team-worker", - run_in_background: true, - description: "IMPL-00N: <task title>", - prompt: "## Role Assignment -role: executor -skill: team-lifecycle-v3 -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: false -priority: P0 - -Task file: <task_file> -Executor: <agent|gemini|codex|qwen> -Session: <session-folder>" -}) -``` - -## Parallel Spawn - -When multiple IMPL tasks are ready simultaneously (same blockedBy set), spawn all in a **single message with multiple Agent() calls**: - -``` -// IMPL-001 (agent), IMPL-002 (codex), IMPL-003 (gemini) all ready -Agent({ subagent_type: "team-worker", description: "IMPL-001: ...", prompt: "...Executor: agent..." }) -Agent({ subagent_type: "team-worker", description: "IMPL-002: ...", prompt: "...Executor: codex..." }) -Agent({ subagent_type: "team-worker", description: "IMPL-003: ...", prompt: "...Executor: gemini..." }) -``` - -**Rules**: -- Independent IMPL tasks (no mutual blockedBy) → parallel spawn -- Dependent IMPL tasks (TASK-B depends_on TASK-A) → sequential, spawn B after A completes -- Each worker is fully isolated — no shared context between IMPL agents - -## Coordinator State Update - -After spawning, log to message bus: - -``` -team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "impl_dispatched", - summary: "Spawned N executor workers", - data: { - tasks: [ - { id: "IMPL-001", executor: "agent", task_file: "..." }, - { id: "IMPL-002", executor: "codex", task_file: "..." } - ] - } -}) -``` diff --git a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/monitor.md b/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/monitor.md deleted file mode 100644 index 72d4c321..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/coordinator/commands/monitor.md +++ /dev/null @@ -1,275 +0,0 @@ -# Command: monitor (v3 Enhanced) - -Monitor team progress, handle callbacks, manage artifact registry, spawn next workers with priority scheduling. - -## Handlers - -| Handler | Trigger | Purpose | -|---------|---------|---------| -| handleCallback | Worker completion message | Process completion, validate artifacts, spawn next | -| handleCheck | User "check" command | Display current status | -| handleResume | User "resume" command | Advance pipeline | -| handleSpawnNext | Internal | Find ready tasks, priority sort, spawn workers | -| handleComplete | All tasks done | Trigger completion action | - ---- - -## handleCallback - -### Input -- Worker completion message via SendMessage -- Message contains: role, task_id, status, artifact_path - -### Steps - -1. **Parse Message** - - Extract role, task_id, status from message - - Load task via TaskGet - -2. **Update Task Status** - - TaskUpdate(status="completed") - - Log completion to message bus - -3. **Artifact Validation (v3 NEW)** - - Check if artifact-manifest.json exists - - If exists: - - Read manifest - - Check validation_status - - Register artifact in artifact-registry.json - - If validation_status == "failed": - - Block downstream spawn - - Create fix task - - STOP - - If validation_status == "pending": - - Prompt user for manual validation - - STOP - - If not exists (backward compatible): - - Continue without validation gating - -4. **Checkpoint Detection** - - If task_id == "QUALITY-001": - - Display checkpoint output (see SKILL.md) - - Pause for user command - - STOP - - If task_id == "PLAN-001" (v3 NEW): - - **Dynamic IMPL Task Creation from Planner DAG**: - 1. Read `<session>/plan/plan.json` → extract `complexity` field - 2. Glob `<session>/plan/.task/TASK-*.json` → enumerate task files - 3. For each TASK file, read `depends_on` field to build DAG - 4. Determine complexity routing: - - Low: no pre-IMPL tasks - - Medium: create ORCH-001 (blockedBy PLAN-001) - - High: create ARCH-001 (blockedBy PLAN-001) + ORCH-001 (blockedBy ARCH-001) - 5. For each TASK-N.json, create IMPL-00N: - - `blockedBy`: map TASK-N `depends_on` → corresponding IMPL IDs + (PLAN-001 or ORCH-001) - - `description`: include `Task file: <session>/plan/.task/TASK-N.json` - - `Priority`: P0 - 6. Collect all IMPL-* task IDs - 7. Create TEST-001 (tester, blockedBy all IMPL-*, P1) - 8. Create REVIEW-001 (reviewer, blockedBy all IMPL-*, P1) - 9. Apply dynamic role injection if specialist roles were identified - 10. Display routing decision + created task count - - Continue to handleSpawnNext - -5. **Spawn Next** - - Call handleSpawnNext - - STOP - ---- - -## handleSpawnNext (v3 Enhanced) - -### Steps - -1. **Find Ready Tasks** - - TaskList -> filter status="pending" - - For each pending task: - - Check blockedBy dependencies - - All blockedBy tasks completed? -> ready - -2. **Priority Sorting (v3 NEW)** - - Sort ready tasks by priority: - - P0 tasks first - - P1 tasks second - - P2 tasks last - - Within same priority: FIFO (creation order) - -3. **Parallel Grouping (v3 NEW)** - - Group tasks by stage (same blockedBy set) - - Tasks in same group can spawn in parallel - - Example: IMPL-001 and DEV-FE-001 both blocked by PLAN-001 -> parallel group - -4. **Artifact Discovery (v3 NEW)** - - For each ready task: - - Query artifact registry for upstream artifacts - - Generate context-artifacts.json with artifact paths - - Write to session folder for worker Phase 2 consumption - -5. **Spawn Workers** - - For each ready task (or parallel group): - - Spawn team-worker agent with role-spec - - Include priority in prompt - - Include context-artifacts.json path - - Log spawn to message bus - -6. **Output Summary** - - List spawned tasks with priorities - - Show remaining pending count - - STOP - -### Spawn Template (v3 Enhanced) - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: <team-name>, - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -skill: team-lifecycle-v3 -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: <true|false> -priority: <P0|P1|P2> -context_artifacts: <session-folder>/context-artifacts.json - -Execute built-in Phase 1 (task discovery) -> skill routes to role Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - ---- - -## handleCheck - -### Steps - -1. **Load Session State** - - Read team-session.json - - TaskList -> count by status - -2. **Display Status** - - Session ID - - Mode - - Task counts: completed / in_progress / pending - - Current running workers - - Artifact registry summary (v3 NEW) - - Priority queue status (v3 NEW) - -3. **STOP** (no advancement) - ---- - -## handleResume - -### Steps - -1. **Reconcile State** - - TaskList -> find in_progress tasks - - Check if workers still running - - If worker missing: - - Reset task to pending - - Log orphan detection - -2. **Fast-Advance Orphan Detection** - - Check message bus for fast_advance logs - - If fast_advance spawned wrong task: - - Reconcile task chain - - Respawn correct task - -3. **Spawn Next** - - Call handleSpawnNext - - STOP - ---- - -## handleComplete (v3 NEW) - -### Trigger -- All tasks have status="completed" -- No tasks with status="pending" or "in_progress" - -### Steps - -1. **Generate Summary** - - Count total tasks, duration - - List deliverables with artifact paths - - Generate artifact registry summary - - Calculate quality metrics (discuss verdicts, review scores) - -2. **Completion Action** - - Read completion_action from team-config.json - - If "interactive": - - AskUserQuestion (see coordinator role.md Phase 5) - - Execute user choice - - If "auto_archive": - - Update session status="completed" - - TeamDelete - - Archive artifacts - - If "auto_keep": - - Update session status="paused" - - Output resume instructions - -3. **Cleanup** - - Write final session state - - Log completion to message bus - - STOP - ---- - -## Artifact Registry Operations (v3 NEW) - -### Register Artifact - -```javascript -// Read existing registry -const registry = JSON.parse(Read("<session>/artifact-registry.json")) - -// Add new artifact -registry.artifacts[artifact_id] = { - manifest: <artifact-manifest>, - discovered_at: new Date().toISOString(), - consumed_by: [] -} - -// Write back -Write("<session>/artifact-registry.json", JSON.stringify(registry)) -``` - -### Generate Context Artifacts - -```javascript -// Query registry for upstream artifacts -const upstreamArtifacts = [] -for (const dep of task.blockedBy) { - const depTask = TaskGet(dep) - const artifactId = findArtifactByTaskId(registry, depTask.id) - if (artifactId) { - upstreamArtifacts.push(registry.artifacts[artifactId].manifest) - } -} - -// Write context-artifacts.json for worker consumption -Write("<session>/context-artifacts.json", JSON.stringify({ - task_id: task.id, - upstream_artifacts: upstreamArtifacts, - generated_at: new Date().toISOString() -})) -``` - ---- - -## Error Handling - -| Error | Resolution | -|-------|------------| -| Worker timeout | Mark task failed, ask user to retry | -| Artifact validation fails | Block downstream, create fix task | -| Artifact manifest missing | Continue without validation (backward compatible) | -| Priority conflict | P0 > P1 > P2, FIFO within same priority | -| Parallel spawn fails | Log error, spawn sequentially | -| Registry corruption | Rebuild from task artifacts | -| Completion action fails | Fallback to manual cleanup | diff --git a/.claude/skills/team-lifecycle-v3/roles/coordinator/role.md b/.claude/skills/team-lifecycle-v3/roles/coordinator/role.md deleted file mode 100644 index 18204187..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/coordinator/role.md +++ /dev/null @@ -1,270 +0,0 @@ -# Coordinator Role (v3 Enhanced) - -Orchestrate team-lifecycle-v3: team creation, task dispatching with priority scheduling, dynamic role injection, artifact registry management, progress monitoring. Uses **team-worker agent** for all worker spawns. - -## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse requirements -> Inject roles -> Create team -> Dispatch tasks -> Monitor progress -> Manage artifacts -> Report - -## v3 Enhancements - -| Feature | Description | -|---------|-------------| -| Dynamic Role Injection | Analyze task keywords to inject specialist roles at runtime | -| Priority Scheduling | P0/P1/P2 task prioritization with critical path optimization | -| Artifact Registry | Maintain in-memory registry for automatic artifact discovery | -| Conditional Routing | Route based on complexity assessment from PLAN-001 | -| Parallel Orchestration | Spawn multiple workers in parallel stages | - -## Boundaries - -### MUST -- Parse user requirements and clarify via AskUserQuestion -- Analyze task description for specialist role injection -- Create team and spawn workers using **team-worker** agent type -- Dispatch tasks with proper dependency chains and priority levels -- Monitor progress via callbacks and route messages -- Maintain artifact registry for validation gating -- Maintain session state (team-session.json) - -### MUST NOT -- Execute spec/impl/research work directly -- Modify task outputs -- Skip dependency validation -- Skip artifact validation gating - ---- - -## Entry Router - -| Detection | Condition | Handler | -|-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag | -> handleCallback | -| Status check | "check" or "status" | -> handleCheck | -| Manual resume | "resume" or "continue" | -> handleResume | -| Interrupted session | Active/paused session in `.workflow/.team/TLS-*` | -> Phase 0 | -| New session | None of above | -> Phase 1 | - -For callback/check/resume: load `commands/monitor.md`, execute handler, STOP. - ---- - -## Phase 0: Session Resume Check - -1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused -2. No sessions -> Phase 1 -3. Single session -> resume (reconciliation) -4. Multiple -> AskUserQuestion - -**Session Reconciliation**: -1. Audit TaskList, reconcile with session state -2. Reset in_progress -> pending (interrupted tasks) -3. Rebuild team if disbanded -4. Restore artifact registry from session -5. Create missing tasks with correct blockedBy -6. Kick first executable -> Phase 4 - ---- - -## Phase 1: Requirement Clarification - -1. Parse arguments for mode, scope, focus -2. Ask missing parameters via AskUserQuestion: - - Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe - - Scope: project description -3. Frontend auto-detection (keyword + package.json scanning) -4. **v3 NEW**: Keyword analysis for specialist role injection -5. Store requirements - -### Keyword Analysis (v3 NEW) - -Scan task description for specialist role triggers: - -| Keywords | Injected Role | Injection Point | -|----------|---------------|-----------------| -| security, vulnerability, OWASP, audit | security-expert | After PLAN-001 | -| performance, optimization, bottleneck, latency | performance-optimizer | After IMPL-* | -| data, pipeline, ETL, schema, migration | data-engineer | Parallel with IMPL-* | -| devops, CI/CD, deployment, docker, kubernetes | devops-engineer | After IMPL-* | -| ML, model, training, inference, neural | ml-engineer | Parallel with IMPL-* | -| orchestrate, complex, multi-module | orchestrator | Replace IMPL-* with ORCH-* | - ---- - -## Phase 2: Create Team + Initialize Session - -1. Generate session ID: `TLS-<slug>-<date>` -2. Create session folder: `.workflow/.team/<session-id>/` -3. **v3 NEW**: Create artifact registry: `<session-id>/artifact-registry.json` -4. TeamCreate -5. Initialize directories (spec/, discussions/, plan/, explorations/, artifacts/) -6. Write team-session.json with injected roles -7. Initialize meta.json via team_msg state_update: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<mode>", - pipeline_stages: [<role-list>], - roles: [<all-roles>], - injected_roles: [<specialist-roles>], - team_name: "lifecycle-v3", - artifact_registry_enabled: true, - priority_scheduling_enabled: true - } -}) -``` - ---- - -## Phase 3: Create Task Chain - -Delegate to `commands/dispatch.md`: -1. Read Task Metadata Registry for task definitions -2. **v3 NEW**: Assess complexity from requirements (Low/Medium/High) -3. **v3 NEW**: Apply conditional routing based on complexity -4. **v3 NEW**: Inject specialist role tasks based on keywords -5. Create tasks via TaskCreate with correct blockedBy and priority -6. Include `Session: <session-folder>` in every task -7. Mark discuss rounds (DISCUSS-001, DISCUSS-002, DISCUSS-003) or "self-validate" - -### Complexity Assessment (v3 NEW) - -| Complexity | Indicators | Route | -|------------|-----------|-------| -| Low | 1-2 modules, shallow deps, single tech stack | Direct IMPL-001 | -| Medium | 3-4 modules, moderate deps, 2 tech stacks | ORCH-001 -> parallel IMPL-* | -| High | 5+ modules, deep deps, multiple tech stacks | ARCH-001 -> ORCH-001 -> parallel IMPL-* | - -### Priority Assignment (v3 NEW) - -| Task Type | Priority | Rationale | -|-----------|----------|-----------| -| Spec pipeline | P0 | Blocking all downstream | -| PLAN-001, ARCH-001 | P0 | Critical path | -| ORCH-001, parallel IMPL-* | P0 | Critical path | -| TEST-*, QA-* | P1 | Validation phase | -| REVIEW-*, specialist analysis | P1 | Quality gate | -| IMPROVE-*, optimization | P2 | Enhancement | - ---- - -## Phase 4: Spawn-and-Stop - -1. Load `commands/monitor.md` -2. Find ready tasks (pending + blockedBy resolved) -3. **v3 NEW**: Sort by priority (P0 > P1 > P2), FIFO within same priority -4. **v3 NEW**: Identify parallel groups (same stage, no mutual blockedBy) -5. Spawn team-worker for each ready task (parallel spawn for same group) -6. Output summary with priority levels -7. STOP - -### Checkpoint Gate (QUALITY-001) - -When QUALITY-001 completes: -1. Read readiness-report.md -2. Parse quality gate and dimension scores -3. Output Checkpoint Template (see SKILL.md) -4. Pause for user command - -### Complexity Routing Gate (PLAN-001, v3 NEW) - -When PLAN-001 completes: -1. Read plan.json for complexity assessment -2. Apply conditional routing: - - Low: spawn IMPL-001 directly - - Medium: spawn ORCH-001 first - - High: spawn ARCH-001 first -3. Output routing decision -4. Continue - ---- - -## Phase 5: Report + Completion Action - -1. Count completed tasks, duration -2. List deliverables with artifact paths -3. **v3 NEW**: Generate artifact registry summary -4. Update session status -> "completed" -5. **v3 NEW**: Trigger completion action (interactive/auto-archive/auto-keep) - -### Completion Action (v3 NEW) - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed", TeamDelete, archive artifacts | -| Keep Active | Update session status="paused", output resume instructions | -| Export Results | Copy deliverables to user-specified path, then Archive & Clean | - ---- - -## Artifact Registry Management (v3 NEW) - -### Registry Structure - -```json -{ - "artifacts": { - "<artifact-id>": { - "manifest": { ... }, - "discovered_at": "timestamp", - "consumed_by": ["<role-name>"] - } - } -} -``` - -### Registry Operations - -| Operation | When | Action | -|-----------|------|--------| -| Register | Worker Phase 5 callback | Add artifact manifest to registry | -| Validate | Before spawning downstream | Check validation_status | -| Discover | Worker Phase 2 request | Generate context-artifacts.json | -| Update | Worker consumes artifact | Add to consumed_by list | - -### Validation Gating - -Before spawning downstream worker: -1. Read artifact manifest from registry -2. Check validation_status: - - `passed`: spawn next worker - - `failed`: block spawn, trigger fix loop - - `pending`: wait or prompt manual validation - ---- - -## Error Handling - -| Error | Resolution | -|-------|------------| -| Task timeout | Log, mark failed, ask user | -| Worker crash | Respawn worker, reassign task | -| Dependency cycle | Detect, report, halt | -| Invalid mode | Reject, ask to clarify | -| Session corruption | Attempt recovery | -| Artifact validation fails | Block downstream, create fix task | -| Role injection fails | Log warning, continue with core roles | -| Priority conflict | P0 > P1 > P2, FIFO within same priority | -| Parallel merge timeout | Report stall, prompt user intervention | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/analyst.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/analyst.md deleted file mode 100644 index 2a9aeb03..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/analyst.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -role: analyst -prefix: RESEARCH -inner_loop: false -discuss_rounds: [DISCUSS-001] -input_artifact_types: [] -message_types: - success: research_ready - progress: research_progress - error: error ---- - -# Analyst — Phase 2-4 - -## Phase 2: Seed Analysis - -**Objective**: Extract structured seed information from the topic. - -1. Read upstream artifacts from `context-artifacts.json` (if exists) -2. Extract session folder from task description (`Session: <path>`) -3. Parse topic from task description -4. If topic starts with `@` or ends with `.md`/`.txt` → Read referenced file -5. Run CLI seed analysis: - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Analyze topic and extract structured seed information. -TASK: * Extract problem statement * Identify target users * Determine domain context -* List constraints * Identify 3-5 exploration dimensions * Assess complexity -TOPIC: <topic-content> -MODE: analysis -EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[], complexity_assessment" --tool gemini --mode analysis`, - run_in_background: false -}) -``` - -6. Parse seed analysis JSON - -## Phase 3: Codebase Exploration (conditional) - -**Objective**: Gather codebase context if project detected. - -| Condition | Action | -|-----------|--------| -| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore | -| No project files | Skip (codebase_context = null) | - -**When project detected**: Use CLI exploration. - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase for context to inform spec generation -TASK: • Identify tech stack • Map architecture patterns • Document conventions • List integration points -MODE: analysis -CONTEXT: @**/* -EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[]" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -## Phase 4: Context Packaging + Discuss - -### 4a: Context Packaging - -**spec-config.json** → `<session>/spec/spec-config.json` -**discovery-context.json** → `<session>/spec/discovery-context.json` -**design-intelligence.json** → `<session>/analysis/design-intelligence.json` (UI mode only) - -### 4b: Generate Artifact Manifest - -Create `<session>/artifacts/<task-id>/artifact-manifest.json`: - -```json -{ - "artifact_id": "uuid-...", - "creator_role": "analyst", - "artifact_type": "spec", - "version": "1.0.0", - "path": "./spec/discovery-context.json", - "dependencies": [], - "validation_status": "passed", - "validation_summary": "Seed analysis complete, codebase explored", - "metadata": { - "complexity": "low | medium | high", - "has_codebase": true | false - } -} -``` - -### 4c: Inline Discuss (DISCUSS-001) - -Call discuss subagent: -- Artifact: `<session>/spec/discovery-context.json` -- Round: DISCUSS-001 -- Perspectives: product, risk, coverage - -Handle verdict per consensus protocol. - -**Report**: complexity, codebase presence, problem statement, dimensions, discuss verdict, output paths. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI failure | Fallback to direct Claude analysis | -| Codebase detection failed | Continue as new project | -| Topic too vague | Report with clarification questions | -| Discuss subagent fails | Proceed without discuss, log warning | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/architect.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/architect.md deleted file mode 100644 index d799a4be..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/architect.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -role: architect -prefix: ARCH -inner_loop: false -discuss_rounds: [] -input_artifact_types: [] -message_types: - success: arch_ready - concern: arch_concern - error: error ---- - -# Architect — Phase 2-4 - -## Consultation Modes - -| Task Pattern | Mode | Focus | -|-------------|------|-------| -| ARCH-SPEC-* | spec-review | Review architecture docs | -| ARCH-PLAN-* | plan-review | Review plan soundness | -| ARCH-CODE-* | code-review | Assess code change impact | -| ARCH-CONSULT-* | consult | Answer architecture questions | -| ARCH-FEASIBILITY-* | feasibility | Technical feasibility | - -## Phase 2: Context Loading - -**Common**: session folder, wisdom, project-tech.json, explorations - -**Mode-specific**: - -| Mode | Additional Context | -|------|-------------------| -| spec-review | architecture/_index.md, ADR-*.md | -| plan-review | plan/plan.json | -| code-review | git diff, changed files | -| consult | Question from task description | -| feasibility | Requirements + codebase | - -## Phase 3: Assessment - -Analyze using mode-specific criteria. Output: mode, verdict (APPROVE/CONCERN/BLOCK), dimensions[], concerns[], recommendations[]. - -For complex questions → Gemini CLI with architecture review rule: - -``` -Bash({ - command: `ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture`, - run_in_background: true -}) -``` - -## Phase 4: Report - -Output to `<session-folder>/architecture/arch-<slug>.json`. Contribute decisions to wisdom/decisions.md. - -**Frontend project outputs** (when frontend tech stack detected): -- `<session-folder>/architecture/design-tokens.json` — color, spacing, typography, shadow tokens -- `<session-folder>/architecture/component-specs/*.md` — per-component design spec - -**Report**: mode, verdict, concern count, recommendations, output path(s). - -### Coordinator Integration - -| Timing | Task | -|--------|------| -| After DRAFT-003 | ARCH-SPEC-001: architecture doc review | -| After PLAN-001 | ARCH-PLAN-001: plan architecture review | -| On-demand | ARCH-CONSULT-001: architecture consultation | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Docs not found | Assess from available context | -| CLI timeout | Partial assessment | -| Insufficient context | Request explorer via coordinator | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/executor.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/executor.md deleted file mode 100644 index db58f1f6..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/executor.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -role: executor -prefix: IMPL -inner_loop: false -discuss_rounds: [] -input_artifact_types: [plan, spec, architecture] -message_types: - success: impl_complete - progress: impl_progress - error: error ---- - -# Executor — Phase 2-4 - -**Role**: Implementation worker with team interaction protocol. Supports two execution modes: direct agent implementation or CLI delegation. Coordinator assigns mode per task via `Executor:` field. - -## Phase 2: Parse Task & Resolve Execution Mode - -**Objective**: Load task JSON, execute pre-analysis, resolve execution mode. - -### 2.1 Extract from task description - -- `Task file:` → `task_file` path -- `Session:` → `session` folder -- `Executor:` → `mode` (`agent` | `gemini` | `codex` | `qwen`) - -### 2.2 Load task JSON (read task_file) - -``` -Task JSON Fields: -├── id, title, scope, action -├── description → Implementation goal -├── files[] → Target files (path, target, change) -├── implementation[] → Step-by-step execution instructions -├── convergence.criteria[] → Done-when checklist -├── pre_analysis[] → Context gathering steps (optional) -│ └── { step, action, commands[], output_to, on_error } -├── reference → Pattern reference (pattern, files[], examples) -├── risks[] → Risk mitigations (optional) -├── rationale → Approach rationale (optional) -└── depends_on[] → (handled by coordinator, not executor) -``` - -### 2.3 Resolve execution mode (priority order) - -| Priority | Source | Resolution | -|----------|--------|------------| -| 1 | Task description `Executor:` | Coordinator assignment | -| 2 | task.meta.execution_config.method | Per-task config from planner | -| 3 | plan.json recommended_execution | Plan-level default | -| 4 | Auto-select | Low complexity → agent; Medium/High → codex | - -### 2.4 Execute pre_analysis (if exists, runs locally regardless of mode) - -``` -For each step in task.pre_analysis[]: - → Parse step.commands[] using command-to-tool mapping: - "Read(path)" → Read tool - "bash(command)" → Bash tool - "Search(pattern,path)" → Grep tool - "Glob(pattern)" → Glob tool - → Store output in [step.output_to] variable - → Handle errors per step.on_error (fail | continue | skip) -``` - -## Phase 3: Execute Implementation - -Route by resolved execution mode: - -### Mode: `agent` — Direct Implementation - -Executor implements directly using Edit/Write/Bash tools. Follows code-developer patterns. - -``` -1. Read task.files[] as target files -2. Read task.implementation[] as step-by-step instructions -3. For each implementation step: - - Substitute [variable_name] placeholders with pre_analysis results - - For each file in step: - * New file → Write tool - * Modify file → Edit tool - - Follow task.reference (pattern, files) for consistency -4. Apply task.rationale.chosen_approach -5. Mitigate task.risks[] during implementation -``` - -**Quality rules** (same as code-developer): -- Verify module/package existence before referencing (use Grep/Glob) -- Incremental progress — small working changes -- Follow existing code patterns from task.reference -- No premature abstractions -- ASCII-only, GBK-compatible - -### Mode: `gemini` / `codex` / `qwen` — CLI Delegation - -Build structured prompt from task JSON, delegate to CLI tool. - -**Build handoff prompt**: - -```javascript -function buildCliHandoffPrompt(task, preAnalysisResults) { - const context = Object.entries(preAnalysisResults) - .map(([key, value]) => `### ${key}\n${value}`) - .join('\n\n') - - return ` -PURPOSE: ${task.title} -${task.description} - -## TARGET FILES -${task.files?.map(f => `- **${f.path}** → ${f.change}`).join('\n')} - -## IMPLEMENTATION STEPS -${task.implementation?.map((s, i) => `${i+1}. ${s}`).join('\n')} - -${context ? `## PRE-ANALYSIS CONTEXT\n${context}` : ''} - -${task.reference ? `## REFERENCE\n- Pattern: ${task.reference.pattern}\n- Files: ${task.reference.files?.join(', ')}` : ''} - -${task.rationale ? `## APPROACH\n${task.rationale.chosen_approach}` : ''} - -${task.risks?.length ? `## RISKS\n${task.risks.map(r => `- ${r.description} → **${r.mitigation}**`).join('\n')}` : ''} - -## DONE WHEN -${task.convergence?.criteria?.map(c => `- [ ] ${c}`).join('\n')} - -MODE: write -CONSTRAINTS: Only modify files listed above | Follow existing patterns -`.trim() -} -``` - -**CLI call**: - -``` -Bash({ - command: `ccw cli -p "${buildCliHandoffPrompt(task, preAnalysisResults)}" - --tool <cli_tool> --mode write --rule development-implement-feature`, - run_in_background: false, - timeout: 3600000 -}) -``` - -**Resume strategy** (if task.cli_execution exists): - -| Strategy | Command | -|----------|---------| -| new | `--id <session>-<task_id>` | -| resume | `--resume <parent_id>` | -| fork | `--resume <parent_id> --id <new_id>` | -| merge_fork | `--resume <id1>,<id2> --id <new_id>` | - -## Phase 4: Self-Validation - -| Step | Method | Pass Criteria | -|------|--------|--------------| -| Convergence check | Match task.convergence.criteria vs output | All criteria addressed | -| Syntax check | `tsc --noEmit` or language-appropriate (30s) | Exit code 0 | -| Test detection | Find test files for modified files | Tests identified | - -**Report**: task ID, status, mode used, files modified, convergence results. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Agent mode: syntax errors | Retry with error context (max 3) | -| CLI mode: execution failure | Retry, or resume with --resume | -| pre_analysis failure | Follow step.on_error (fail/continue/skip) | -| CLI tool unavailable | Fallback: gemini → qwen → codex | -| Max retries exceeded | Report failure to coordinator | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-developer.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-developer.md deleted file mode 100644 index b30bf3ee..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-developer.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -role: fe-developer -prefix: DEV-FE -inner_loop: false -discuss_rounds: [] -input_artifact_types: [] -message_types: - success: dev_fe_complete - progress: dev_fe_progress - error: error ---- - -# FE Developer — Phase 2-4 - -## Phase 2: Context Loading - -**Inputs to load**: -- Plan: `<session-folder>/plan/plan.json` -- Design tokens: `<session-folder>/architecture/design-tokens.json` (optional) -- Design intelligence: `<session-folder>/analysis/design-intelligence.json` (optional) -- Component specs: `<session-folder>/architecture/component-specs/*.md` (optional) -- Shared memory, wisdom - -**Tech stack detection**: - -| Signal | Framework | Styling | -|--------|-----------|---------| -| react/react-dom in deps | react | - | -| vue in deps | vue | - | -| next in deps | nextjs | - | -| tailwindcss in deps | - | tailwind | -| @shadcn/ui in deps | - | shadcn | - -## Phase 3: Frontend Implementation - -**Step 1**: Generate design token CSS (if tokens available) -- Convert design-tokens.json → CSS custom properties (`:root { --color-*, --space-*, --text-* }`) -- Include dark mode overrides via `@media (prefers-color-scheme: dark)` -- Write to `src/styles/tokens.css` - -**Step 2**: Implement components - -| Task Size | Strategy | -|-----------|----------| -| Simple (<= 3 files, single component) | `ccw cli --tool gemini --mode write` (foreground) | -| Complex (system, multi-component) | `ccw cli --tool codex --mode write` (foreground) | - -**Coding standards** (include in agent/CLI prompt): -- Use design token CSS variables, never hardcode colors/spacing -- Interactive elements: cursor: pointer -- Transitions: 150-300ms -- Text contrast: minimum 4.5:1 -- Include focus-visible styles -- Support prefers-reduced-motion -- Responsive: mobile-first -- No emoji as functional icons - -## Phase 4: Self-Validation - -| Check | What | -|-------|------| -| hardcoded-color | No #hex outside tokens.css | -| cursor-pointer | Interactive elements have cursor: pointer | -| focus-styles | Interactive elements have focus styles | -| responsive | Has responsive breakpoints | -| reduced-motion | Animations respect prefers-reduced-motion | -| emoji-icon | No emoji as functional icons | - -Contribute to wisdom/conventions.md. Update shared-memory.json with component inventory. - -**Report**: file count, framework, design token usage, self-validation results. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Design tokens not found | Use project defaults | -| Tech stack undetected | Default HTML + CSS | -| CLI failure | Retry with alternative tool | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-qa.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-qa.md deleted file mode 100644 index 728f93c9..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/fe-qa.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -role: fe-qa -prefix: QA-FE -inner_loop: false -discuss_rounds: [] -input_artifact_types: [] -message_types: - success: qa_fe_passed - result: qa_fe_result - fix: fix_required - error: error ---- - -# FE QA — Phase 2-4 - -## Review Dimensions - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Code Quality | 25% | TypeScript types, component structure, error handling | -| Accessibility | 25% | Semantic HTML, ARIA, keyboard nav, contrast, focus-visible | -| Design Compliance | 20% | Token usage, no hardcoded colors, no emoji icons | -| UX Best Practices | 15% | Loading/error/empty states, cursor-pointer, responsive | -| Pre-Delivery | 15% | No console.log, dark mode, i18n readiness | - -## Phase 2: Context Loading - -**Inputs**: design tokens, design intelligence, shared memory, previous QA results (for GC round tracking), changed frontend files via git diff. - -Determine GC round from previous QA results count. Max 2 rounds. - -## Phase 3: 5-Dimension Review - -For each changed frontend file, check against all 5 dimensions. Score each dimension 0-10, deducting for issues found. - -**Scoring deductions**: - -| Severity | Deduction | -|----------|-----------| -| High | -2 to -3 | -| Medium | -1 to -1.5 | -| Low | -0.5 | - -**Overall score** = weighted sum of dimension scores. - -**Verdict routing**: - -| Condition | Verdict | -|-----------|---------| -| Score >= 8 AND no critical issues | PASS | -| GC round >= max AND score >= 6 | PASS_WITH_WARNINGS | -| GC round >= max AND score < 6 | FAIL | -| Otherwise | NEEDS_FIX | - -## Phase 4: Report - -Write audit to `<session-folder>/qa/audit-fe-<task>-r<round>.json`. Update wisdom and shared memory. - -**Report**: round, verdict, overall score, dimension scores, critical issues with Do/Don't format, action required (if NEEDS_FIX). - -### Generator-Critic Loop - -Orchestrated by coordinator: -``` -Round 1: DEV-FE-001 → QA-FE-001 - if NEEDS_FIX → coordinator creates DEV-FE-002 + QA-FE-002 -Round 2: DEV-FE-002 → QA-FE-002 - if still NEEDS_FIX → PASS_WITH_WARNINGS or FAIL (max 2) -``` - -**Convergence**: score >= 8 AND critical_count = 0 - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No changed files | Report empty, score N/A | -| Design tokens not found | Skip design compliance, adjust weights | -| Max GC rounds exceeded | Force verdict | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/orchestrator.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/orchestrator.md deleted file mode 100644 index d5dac8b7..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/orchestrator.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -prefix: ORCH -inner_loop: false -message_types: - success: orch_complete - error: error ---- - -# Orchestrator - -Decomposes complex multi-module tasks into coordinated sub-tasks with parallel execution and dependency management. - -## Phase 2: Context & Complexity Assessment - -| Input | Source | Required | -|-------|--------|----------| -| Task description | From coordinator | Yes | -| Plan document | Session plan/ | Yes | -| Exploration cache | Session explorations/ | No | - -### Step 1: Load Context - -Extract session path from task description. Read plan document to understand scope and requirements. - -### Step 2: Complexity Analysis - -Assess task complexity across dimensions: - -| Dimension | Indicators | Weight | -|-----------|-----------|--------| -| Module count | Number of modules affected | High | -| Dependency depth | Cross-module dependencies | High | -| Technology stack | Multiple tech stacks involved | Medium | -| Integration points | External system integrations | Medium | - -### Step 3: Decomposition Strategy - -| Complexity | Strategy | -|------------|----------| -| 2-3 modules, shallow deps | Simple parallel split | -| 4-6 modules, moderate deps | Phased parallel with integration checkpoints | -| 7+ modules, deep deps | Hierarchical decomposition with sub-orchestrators | - -### Step 4: Exploration - -If complexity is High, delegate to explorer utility member for codebase context gathering. - -## Phase 3: Task Decomposition & Coordination - -### Step 1: Generate Sub-Tasks - -Break down into parallel tracks: - -| Track Type | Characteristics | Owner Role | -|------------|----------------|------------| -| Frontend | UI components, state management | fe-developer | -| Backend | API, business logic, data access | executor | -| Data | Schema, migrations, ETL | data-engineer | -| Infrastructure | Deployment, CI/CD | devops-engineer | - -### Step 2: Dependency Mapping - -Create dependency graph: -- Identify shared interfaces (API contracts, data schemas) -- Mark blocking dependencies (schema before backend, API before frontend) -- Identify parallel-safe tracks - -### Step 3: Priority Assignment - -Assign priority levels: - -| Priority | Criteria | Impact | -|----------|----------|--------| -| P0 | Blocking dependencies, critical path | Execute first | -| P1 | Standard implementation | Execute after P0 | -| P2 | Nice-to-have, non-blocking | Execute last | - -### Step 4: Spawn Coordination - -Create sub-tasks via coordinator message: - -``` -SendMessage({ - type: "spawn_request", - recipient: "coordinator", - content: { - sub_tasks: [ - { id: "IMPL-FE-001", role: "fe-developer", priority: "P1", blockedBy: ["IMPL-BE-001"] }, - { id: "IMPL-BE-001", role: "executor", priority: "P0", blockedBy: [] }, - { id: "DATA-001", role: "data-engineer", priority: "P0", blockedBy: [] } - ], - parallel_groups: [ - ["IMPL-BE-001", "DATA-001"], - ["IMPL-FE-001"] - ] - } -}) -``` - -## Phase 4: Integration & Validation - -### Step 1: Monitor Progress - -Track sub-task completion via message bus. Wait for all sub-tasks in current parallel group to complete. - -### Step 2: Integration Check - -Validate integration points: - -| Check | Method | Pass Criteria | -|-------|--------|---------------| -| API contracts | Compare spec vs implementation | All endpoints match | -| Data schemas | Validate migrations applied | Schema version consistent | -| Type consistency | Cross-module type checking | No type mismatches | - -### Step 3: Artifact Registry - -Generate artifact manifest for orchestration result: - -```javascript -Write("artifact-manifest.json", JSON.stringify({ - artifact_id: `orchestrator-integration-${Date.now()}`, - creator_role: "orchestrator", - artifact_type: "integration", - version: "1.0.0", - path: "integration-report.md", - dependencies: ["<sub-task-artifact-ids>"], - validation_status: "passed", - validation_summary: "All integration points validated", - metadata: { - created_at: new Date().toISOString(), - task_id: "<current-task-id>", - sub_task_count: <count>, - parallel_groups: <groups> - } -})) -``` - -### Step 4: Report - -Generate integration report with: -- Sub-task completion status -- Integration validation results -- Identified issues and resolutions -- Next steps or recommendations diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/planner.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/planner.md deleted file mode 100644 index 6b06c9b2..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/planner.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -role: planner -prefix: PLAN -inner_loop: true -discuss_rounds: [] -input_artifact_types: [spec, architecture] -message_types: - success: plan_ready - revision: plan_revision - error: error ---- - -# Planner — Phase 2-4 - -## Phase 1.5: Load Spec Context (Full-Lifecycle) - -If `<session-folder>/spec/` exists → load requirements/_index.md, architecture/_index.md, epics/_index.md, spec-config.json. Otherwise → impl-only mode. - -**Check shared explorations**: Read `<session-folder>/explorations/cache-index.json` to see if analyst already cached useful explorations. Reuse rather than re-explore. - -## Phase 2: Multi-Angle Exploration - -**Objective**: Explore codebase to inform planning. - -**Complexity routing**: - -| Complexity | Criteria | Strategy | -|------------|----------|----------| -| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only | -| Medium | 200-500 chars or moderate scope | 2-3 angle explore subagent | -| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle explore subagent | - -For each angle, use CLI exploration (cache-aware — check cache-index.json before each call): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase from <angle> perspective to inform planning -TASK: • Search for <angle>-specific patterns • Identify relevant files • Document integration points -MODE: analysis -CONTEXT: @**/* | Memory: Task keywords: <keywords> -EXPECTED: JSON with: relevant_files[], patterns[], integration_points[], recommendations[] -CONSTRAINTS: Focus on <angle> perspective" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -## Phase 3: Plan Generation - -**Objective**: Generate structured implementation plan. - -| Complexity | Strategy | -|------------|----------| -| Low | Direct planning → single TASK-001 with plan.json | -| Medium/High | cli-lite-planning-agent with exploration results | - -**CLI call** (Medium/High): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate structured implementation plan from exploration results -TASK: • Create plan.json with overview • Generate TASK-*.json files (2-7 tasks) • Define dependencies • Set convergence criteria -MODE: write -CONTEXT: @<session-folder>/explorations/*.json | Memory: Complexity: <complexity> -EXPECTED: Files: plan.json + .task/TASK-*.json. Schema: ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json -CONSTRAINTS: 2-7 tasks, include id/title/files[].change/convergence.criteria/depends_on" --tool gemini --mode write --rule planning-breakdown-task-steps`, - run_in_background: false -}) -``` - -**Spec context** (full-lifecycle): Reference REQ-* IDs, follow ADR decisions, reuse Epic/Story decomposition. - -## Phase 4: Submit for Approval - -1. Read plan.json and TASK-*.json -2. Report to coordinator: complexity, task count, task list, approach, plan location -3. Wait for response: approved → complete; revision → update and resubmit - -**Session files**: -``` -<session-folder>/explorations/ (shared cache) -+-- cache-index.json -+-- explore-<angle>.json - -<session-folder>/plan/ -+-- explorations-manifest.json -+-- plan.json -+-- .task/TASK-*.json -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI exploration failure | Plan from description only | -| CLI planning failure | Fallback to direct planning | -| Plan rejected 3+ times | Notify coordinator, suggest alternative | -| Schema not found | Use basic structure | -| Cache index corrupt | Clear cache, re-explore all angles | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/reviewer.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/reviewer.md deleted file mode 100644 index 5814ae6f..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/reviewer.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -role: reviewer -prefix: REVIEW -additional_prefixes: [QUALITY, IMPROVE] -inner_loop: false -discuss_rounds: [DISCUSS-003] -input_artifact_types: [] -message_types: - success_review: review_result - success_quality: quality_result - fix: fix_required - error: error ---- - -# Reviewer — Phase 2-4 - -## Phase 2: Mode Detection - -| Task Prefix | Mode | Dimensions | Discuss | -|-------------|------|-----------|---------| -| REVIEW-* | Code Review | quality, security, architecture, requirements | None | -| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage | DISCUSS-003 | -| IMPROVE-* | Spec Quality (recheck) | Same as QUALITY | DISCUSS-003 | - -## Phase 3: Review Execution - -### Code Review (REVIEW-*) - -**Inputs**: Plan file, git diff, modified files, test results - -**4 dimensions**: - -| Dimension | Critical Issues | -|-----------|----------------| -| Quality | Empty catch, any in public APIs, @ts-ignore, console.log | -| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML | -| Architecture | Circular deps, parent imports >2 levels, files >500 lines | -| Requirements | Missing core functionality, incomplete acceptance criteria | - -### Spec Quality (QUALITY-* / IMPROVE-*) - -**Inputs**: All spec docs in session folder, quality gate config - -**5 dimensions**: - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Completeness | 25% | All sections present with substance | -| Consistency | 20% | Terminology, format, references | -| Traceability | 25% | Goals -> Reqs -> Arch -> Stories chain | -| Depth | 20% | AC testable, ADRs justified, stories estimable | -| Coverage | 10% | Original requirements mapped | - -**Quality gate**: - -| Gate | Criteria | -|------|----------| -| PASS | Score >= 80% AND coverage >= 70% | -| REVIEW | Score 60-79% OR coverage 50-69% | -| FAIL | Score < 60% OR coverage < 50% | - -**Artifacts**: readiness-report.md + spec-summary.md - -## Phase 4: Verdict + Discuss - -### Code Review Verdict - -| Verdict | Criteria | -|---------|----------| -| BLOCK | Critical issues present | -| CONDITIONAL | High/medium only | -| APPROVE | Low or none | - -### Spec Quality Discuss (DISCUSS-003) - -After generating readiness-report.md, call discuss subagent: -- Artifact: `<session>/spec/readiness-report.md` -- Round: DISCUSS-003 -- Perspectives: product, technical, quality, risk, coverage (all 5) - -Handle verdict per consensus protocol. - -> **Note**: DISCUSS-003 HIGH always triggers user pause (final sign-off gate). - -**Report**: mode, verdict/gate, dimension scores, discuss verdict (QUALITY only), output paths. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Missing context | Request from coordinator | -| Invalid mode | Abort with error | -| Analysis failure | Retry, then fallback | -| Discuss subagent fails | Proceed without discuss, log warning | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/tester.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/tester.md deleted file mode 100644 index 278ff763..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/tester.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -role: tester -prefix: TEST -inner_loop: false -discuss_rounds: [] -input_artifact_types: [] -message_types: - success: test_result - fix: fix_required - error: error ---- - -# Tester — Phase 2-4 - -## Phase 2: Framework Detection & Test Discovery - -**Framework detection** (priority order): - -| Priority | Method | Frameworks | -|----------|--------|-----------| -| 1 | package.json devDependencies | vitest, jest, mocha, pytest | -| 2 | package.json scripts.test | vitest, jest, mocha, pytest | -| 3 | Config files | vitest.config.*, jest.config.*, pytest.ini | - -**Affected test discovery** from executor's modified files: -- Search variants: `<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts` - -## Phase 3: Test Execution & Fix Cycle - -**Config**: MAX_ITERATIONS=10, PASS_RATE_TARGET=95%, AFFECTED_TESTS_FIRST=true - -1. Run affected tests → parse results -2. Pass rate met → run full suite -3. Failures → select strategy → fix → re-run → repeat - -**Strategy selection**: - -| Condition | Strategy | Behavior | -|-----------|----------|----------| -| Iteration <= 3 or pass >= 80% | Conservative | Fix one critical failure at a time | -| Critical failures < 5 | Surgical | Fix specific pattern everywhere | -| Pass < 50% or iteration > 7 | Aggressive | Fix all failures in batch | - -**Test commands**: - -| Framework | Affected | Full Suite | -|-----------|---------|------------| -| vitest | `vitest run <files>` | `vitest run` | -| jest | `jest <files> --no-coverage` | `jest --no-coverage` | -| pytest | `pytest <files> -v` | `pytest -v` | - -## Phase 4: Result Analysis - -**Failure classification**: - -| Severity | Patterns | -|----------|----------| -| Critical | SyntaxError, cannot find module, undefined | -| High | Assertion failures, toBe/toEqual | -| Medium | Timeout, async errors | -| Low | Warnings, deprecations | - -**Report routing**: - -| Condition | Type | -|-----------|------| -| Pass rate >= target | test_result (success) | -| Pass rate < target after max iterations | fix_required | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Framework not detected | Prompt user | -| No tests found | Report to coordinator | -| Infinite fix loop | Abort after MAX_ITERATIONS | diff --git a/.claude/skills/team-lifecycle-v3/roles/pipeline/writer.md b/.claude/skills/team-lifecycle-v3/roles/pipeline/writer.md deleted file mode 100644 index e90e9193..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/pipeline/writer.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -role: writer -prefix: DRAFT -inner_loop: true -discuss_rounds: [DISCUSS-002] -input_artifact_types: [spec] -message_types: - success: draft_ready - revision: draft_revision - error: error ---- - -# Writer — Phase 2-4 - -## Phase 2: Context Loading - -**Objective**: Load all required inputs for document generation. - -### 2a: Read Upstream Artifacts - -Load `context-artifacts.json` to discover upstream artifacts: - -```json -{ - "artifacts": [ - { - "artifact_id": "uuid-...", - "artifact_type": "spec", - "path": "./spec/discovery-context.json", - "creator_role": "analyst" - } - ] -} -``` - -### 2b: Document Type Routing - -| Task Subject Contains | Doc Type | Template | Validation | -|----------------------|----------|----------|------------| -| Product Brief | product-brief | templates/product-brief.md | self-validate | -| Requirements / PRD | requirements | templates/requirements-prd.md | DISCUSS-002 | -| Architecture | architecture | templates/architecture-doc.md | self-validate | -| Epics | epics | templates/epics-template.md | self-validate | - -### 2c: Progressive Dependency Loading - -| Doc Type | Requires | -|----------|----------| -| product-brief | discovery-context.json | -| requirements | + product-brief.md | -| architecture | + requirements/_index.md | -| epics | + architecture/_index.md | - -**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to generation. - -| Input | Source | Required | -|-------|--------|----------| -| Document standards | `../../specs/document-standards.md` | Yes | -| Template | From routing table | Yes | -| Spec config | `<session>/spec/spec-config.json` | Yes | -| Discovery context | `<session>/spec/discovery-context.json` | Yes | -| Discussion feedback | `<session>/discussions/<discuss-file>` | If exists | -| Prior decisions | context_accumulator (in-memory) | If prior tasks | - -## Phase 3: Document Generation - -**Objective**: Generate document using CLI tool. - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template and standards -TASK: • Load template • Apply spec config and discovery context • Integrate prior feedback • Generate all sections -MODE: write -CONTEXT: @<session>/spec/*.json @<template-path> | Memory: Prior decisions: <accumulator summary> -EXPECTED: Document at <output-path> with: YAML frontmatter, all sections, cross-references -CONSTRAINTS: Follow document-standards.md" --tool gemini --mode write --rule development-implement-feature --cd <session>`, - run_in_background: false -}) -``` - -## Phase 4: Validation + Artifact Manifest - -### 4a: Self-Validation (all doc types) - -| Check | What to Verify | -|-------|---------------| -| has_frontmatter | Starts with YAML frontmatter | -| sections_complete | All template sections present | -| cross_references | session_id included | -| progressive_consistency | References to upstream docs are valid | - -### 4b: Generate Artifact Manifest - -Create `<session>/artifacts/<task-id>/artifact-manifest.json`: - -```json -{ - "artifact_id": "uuid-...", - "creator_role": "writer", - "artifact_type": "spec", - "version": "1.0.0", - "path": "./spec/<doc-type>/_index.md", - "dependencies": ["analyst-artifact-id"], - "validation_status": "passed | failed", - "validation_summary": "All sections complete, frontmatter valid", - "metadata": { - "doc_type": "product-brief | requirements | architecture | epics", - "sections_count": 8 - } -} -``` - -### 4c: Validation Routing - -| Doc Type | Validation Method | -|----------|------------------| -| product-brief | Self-validation only → report | -| requirements (PRD) | Self-validation + **DISCUSS-002** | -| architecture | Self-validation only → report | -| epics | Self-validation only → report | - -**DISCUSS-002** (PRD only): -- Artifact: `<session>/spec/requirements/_index.md` -- Round: DISCUSS-002 -- Perspectives: quality, product, coverage - -Handle discuss verdict per consensus protocol. - -**Report**: doc type, validation status, discuss verdict (PRD only), output path. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI failure | Retry once with alternative tool. Still fails → log, continue next | -| Discuss subagent fails | Skip discuss, log warning | -| Cumulative 3 task failures | SendMessage to coordinator, STOP | -| Prior doc not found | Notify coordinator, request prerequisite | -| Discussion contradicts prior docs | Note conflict, flag for coordinator | diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/README.md b/.claude/skills/team-lifecycle-v3/roles/specialists/README.md deleted file mode 100644 index 9ffe9776..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# Role Library - Team Lifecycle v3 - -Dynamic role specification library for team-lifecycle-v3. Role definitions are loaded at runtime to extend the built-in role detection table. - -## Purpose - -- Extend role inference beyond hardcoded defaults -- Support domain-specific specialist roles -- Enable dynamic role injection based on task keywords -- Maintain backward compatibility with v2 core roles - -## Role Categories - -### Core Pipeline Roles (v2 inherited) -- analyst, writer, planner, executor, tester, reviewer -- architect, fe-developer, fe-qa - -### Specialist Roles (v3 new) -- **orchestrator**: Complex task decomposition and parallel coordination -- **security-expert**: Security analysis and vulnerability scanning -- **performance-optimizer**: Performance profiling and optimization -- **data-engineer**: Data pipeline and schema design -- **devops-engineer**: Infrastructure as code and CI/CD -- **ml-engineer**: Machine learning pipeline implementation - -## Dynamic Role Injection - -Specialist roles are injected at runtime when coordinator detects matching keywords in task descriptions: - -| Keywords | Injected Role | -|----------|---------------| -| security, vulnerability, OWASP | security-expert | -| performance, optimization, bottleneck | performance-optimizer | -| data, pipeline, ETL, schema | data-engineer | -| devops, CI/CD, deployment, docker | devops-engineer | -| machine learning, ML, model, training | ml-engineer | -| orchestrate, complex, multi-module | orchestrator | - -## Role Definition Format - -Each role definition is a `.role.md` file with YAML frontmatter + description. - -### Schema - -```yaml ---- -role: <role-name> -keywords: [<keyword1>, <keyword2>, ...] -responsibility_type: <Orchestration|Code generation|Validation|Read-only analysis> -task_prefix: <PREFIX> -default_inner_loop: <true|false> -category: <domain-category> -capabilities: [<capability1>, <capability2>, ...] ---- - -<Role description and responsibilities> -``` - -## Usage - -Role library is loaded by coordinator during Phase 1 (Requirements Collection) to extend role detection capabilities. Custom roles override built-in roles with same `role` identifier. - -## Extensibility - -Users can add custom role definitions by creating new `.role.md` files in this directory following the schema above. diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/data-engineer.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/data-engineer.role.md deleted file mode 100644 index 076a8a2e..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/data-engineer.role.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -role: data-engineer -keywords: [data, pipeline, ETL, database, schema, migration, analytics] -responsibility_type: Code generation -task_prefix: DATA -default_inner_loop: false -category: data -capabilities: - - data_pipeline_design - - schema_design - - etl_implementation ---- - -# Data Engineer - -Designs and implements data pipelines, schemas, and ETL processes. - -## Responsibilities - -- Design database schemas and data models -- Implement ETL pipelines for data processing -- Create data migration scripts -- Optimize data storage and retrieval -- Implement data validation and quality checks - -## Typical Tasks - -- Design and implement data warehouse schema -- Build ETL pipeline for analytics -- Create database migration scripts -- Implement data validation framework - -## Integration Points - -- Called by coordinator when data keywords detected -- Works with executor for backend integration -- Coordinates with planner for data architecture diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/devops-engineer.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/devops-engineer.role.md deleted file mode 100644 index 3b755d93..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/devops-engineer.role.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -role: devops-engineer -keywords: [devops, CI/CD, deployment, infrastructure, docker, kubernetes, terraform] -responsibility_type: Code generation -task_prefix: DEVOPS -default_inner_loop: false -category: devops -capabilities: - - infrastructure_as_code - - ci_cd_pipeline - - deployment_automation ---- - -# DevOps Engineer - -Implements infrastructure as code, CI/CD pipelines, and deployment automation. - -## Responsibilities - -- Design and implement CI/CD pipelines -- Create infrastructure as code (Terraform, CloudFormation) -- Implement deployment automation -- Configure monitoring and alerting -- Manage containerization and orchestration - -## Typical Tasks - -- Set up CI/CD pipeline for new project -- Implement infrastructure as code for cloud resources -- Create Docker containerization strategy -- Configure Kubernetes deployment - -## Integration Points - -- Called by coordinator when devops keywords detected -- Works with executor for deployment integration -- Coordinates with planner for infrastructure architecture diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/ml-engineer.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/ml-engineer.role.md deleted file mode 100644 index a3238f21..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/ml-engineer.role.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -role: ml-engineer -keywords: [machine learning, ML, model, training, inference, neural network, AI] -responsibility_type: Code generation -task_prefix: ML -default_inner_loop: false -category: machine-learning -capabilities: - - model_training - - feature_engineering - - model_deployment ---- - -# ML Engineer - -Implements machine learning pipelines, model training, and inference systems. - -## Responsibilities - -- Design and implement ML training pipelines -- Perform feature engineering and data preprocessing -- Train and evaluate ML models -- Implement model serving and inference -- Monitor model performance and drift - -## Typical Tasks - -- Build ML training pipeline -- Implement feature engineering pipeline -- Deploy model serving infrastructure -- Create model monitoring system - -## Integration Points - -- Called by coordinator when ML keywords detected -- Works with data-engineer for data pipeline integration -- Coordinates with planner for ML architecture diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/orchestrator.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/orchestrator.role.md deleted file mode 100644 index cbe8c35b..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/orchestrator.role.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -role: orchestrator -keywords: [orchestrate, coordinate, complex, multi-module, decompose, parallel, dependency] -responsibility_type: Orchestration -task_prefix: ORCH -default_inner_loop: false -category: orchestration -weight: 1.5 -capabilities: - - task_decomposition - - parallel_coordination - - dependency_management ---- - -# Orchestrator - -Decomposes complex multi-module tasks into coordinated sub-tasks with dependency management and parallel execution support. - -## Responsibilities - -- Analyze complex requirements and decompose into manageable sub-tasks -- Coordinate parallel execution of multiple implementation tracks -- Manage dependencies between sub-tasks -- Integrate results from parallel workers -- Validate integration points and cross-module consistency - -## Typical Tasks - -- Break down large features into frontend + backend + data components -- Coordinate multi-team parallel development -- Manage complex refactoring across multiple modules -- Orchestrate migration strategies with phased rollout - -## Integration Points - -- Works with planner to receive high-level plans -- Spawns multiple executor/fe-developer workers in parallel -- Integrates with tester for cross-module validation -- Reports to coordinator with integration status diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/performance-optimizer.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/performance-optimizer.role.md deleted file mode 100644 index fa2c03b5..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/performance-optimizer.role.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -role: performance-optimizer -keywords: [performance, optimization, bottleneck, latency, throughput, profiling, benchmark] -responsibility_type: Read-only analysis -task_prefix: PERF -default_inner_loop: false -category: performance -capabilities: - - performance_profiling - - bottleneck_identification - - optimization_recommendations ---- - -# Performance Optimizer - -Analyzes code and architecture for performance bottlenecks and provides optimization recommendations. - -## Responsibilities - -- Profile code execution and identify bottlenecks -- Analyze database query performance -- Review caching strategies and effectiveness -- Assess resource utilization (CPU, memory, I/O) -- Recommend optimization strategies - -## Typical Tasks - -- Performance audit of critical paths -- Database query optimization review -- Caching strategy assessment -- Load testing analysis and recommendations - -## Integration Points - -- Called by coordinator when performance keywords detected -- Works with reviewer for performance-focused code review -- Reports findings with impact levels and optimization priorities diff --git a/.claude/skills/team-lifecycle-v3/roles/specialists/security-expert.role.md b/.claude/skills/team-lifecycle-v3/roles/specialists/security-expert.role.md deleted file mode 100644 index 809e586f..00000000 --- a/.claude/skills/team-lifecycle-v3/roles/specialists/security-expert.role.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -role: security-expert -keywords: [security, vulnerability, OWASP, compliance, audit, penetration, threat] -responsibility_type: Read-only analysis -task_prefix: SECURITY -default_inner_loop: false -category: security -capabilities: - - vulnerability_scanning - - threat_modeling - - compliance_checking ---- - -# Security Expert - -Performs security analysis, vulnerability scanning, and compliance checking for code and architecture. - -## Responsibilities - -- Scan code for OWASP Top 10 vulnerabilities -- Perform threat modeling and attack surface analysis -- Check compliance with security standards (GDPR, HIPAA, etc.) -- Review authentication and authorization implementations -- Assess data protection and encryption strategies - -## Typical Tasks - -- Security audit of authentication module -- Vulnerability assessment of API endpoints -- Compliance review for data handling -- Threat modeling for new features - -## Integration Points - -- Called by coordinator when security keywords detected -- Works with reviewer for security-focused code review -- Reports findings with severity levels (Critical/High/Medium/Low) diff --git a/.claude/skills/team-lifecycle-v3/specs/README.md b/.claude/skills/team-lifecycle-v3/specs/README.md deleted file mode 100644 index 4a9a6879..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Specifications Directory - -This directory contains all specification documents for Team Lifecycle v3. - -## Core Specifications (Mandatory Reading) - -| Document | Purpose | When to Read | -|----------|---------|--------------| -| [core-concepts.md](core-concepts.md) | Foundational principles: team-worker architecture, artifact contracts, quality gating, dynamic role injection, priority scheduling | **Before using the skill** - P0 Critical | -| [domain-model.md](domain-model.md) | Core entity definitions (Task, Artifact, Role, Session) with JSON schemas, relationships, and state machines | **Before using the skill** - P0 Critical | -| [artifact-contract-spec.md](artifact-contract-spec.md) | Artifact manifest schema and validation rules | **Before using the skill** - P0 Critical | -| [execution-flow.md](execution-flow.md) | End-to-end execution walkthrough with pipeline definitions, beat cycle, conditional routing, and examples | **When understanding workflow** - P1 High | - -## Supporting Specifications - -| Document | Purpose | When to Read | -|----------|---------|--------------| -| [quality-gates.md](quality-gates.md) | Quality validation criteria for each phase | When reviewing quality checkpoints | -| [document-standards.md](document-standards.md) | Document formatting standards (YAML frontmatter, naming conventions) | When creating new documents | -| [team-config.json](team-config.json) | Role registry and pipeline definitions (machine-readable) | When modifying role configuration | - -## Document Hierarchy - -``` -specs/ -├── README.md # This file -├── core-concepts.md # P0 - Foundational principles -├── artifact-contract-spec.md # P0 - Artifact manifest schema -├── execution-flow.md # P1 - Execution walkthrough -├── quality-gates.md # Supporting - Quality criteria -├── document-standards.md # Supporting - Formatting standards -└── team-config.json # Supporting - Role registry -``` - -## Reading Path - -### For New Users - -1. **Start here**: [core-concepts.md](core-concepts.md) - Understand the system architecture and principles -2. **Then read**: [artifact-contract-spec.md](artifact-contract-spec.md) - Learn how artifacts flow between agents -3. **Finally read**: [execution-flow.md](execution-flow.md) - See how tasks execute end-to-end - -### For Developers Extending the Skill - -1. Read all core specifications above -2. Review [quality-gates.md](quality-gates.md) for validation logic -3. Review [document-standards.md](document-standards.md) for formatting rules -4. Modify [team-config.json](team-config.json) for role changes - -### For Troubleshooting - -1. Check [execution-flow.md](execution-flow.md) for pipeline definitions -2. Check [artifact-contract-spec.md](artifact-contract-spec.md) for validation rules -3. Check [quality-gates.md](quality-gates.md) for quality criteria - -## Cross-References - -- **Role specifications**: See [../roles/README.md](../roles/README.md) -- **Templates**: See [../templates/README.md](../templates/README.md) -- **Subagents**: See [../subagents/](../subagents/) -- **Main entry**: See [../SKILL.md](../SKILL.md) diff --git a/.claude/skills/team-lifecycle-v3/specs/artifact-contract-spec.md b/.claude/skills/team-lifecycle-v3/specs/artifact-contract-spec.md deleted file mode 100644 index a6ca6040..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/artifact-contract-spec.md +++ /dev/null @@ -1,101 +0,0 @@ -# Artifact Contract Specification - -## Overview - -Every worker role must generate an artifact manifest in Phase 4 to enable quality gating and automatic artifact discovery. - -## Manifest Schema - -**Location**: `<session>/artifacts/<task-id>/artifact-manifest.json` - -```json -{ - "artifact_id": "uuid-...", - "creator_role": "role-name", - "artifact_type": "spec | architecture | plan | code | test | review", - "version": "1.0.0", - "path": "./artifacts/output.md", - "dependencies": ["upstream-artifact-id"], - "validation_status": "pending | passed | failed", - "validation_summary": "Details...", - "metadata": { - "complexity": "low | medium | high", - "priority": "P0 | P1 | P2" - } -} -``` - -## Field Definitions - -| Field | Type | Description | -|-------|------|-------------| -| artifact_id | string | UUID for this artifact | -| creator_role | string | Role that created this artifact | -| artifact_type | enum | Type of artifact (spec/architecture/plan/code/test/review) | -| version | string | Semantic version | -| path | string | Relative path to artifact file | -| dependencies | array | List of upstream artifact IDs this depends on | -| validation_status | enum | pending/passed/failed | -| validation_summary | string | Human-readable validation result | -| metadata | object | Additional context (complexity, priority, etc.) | - -## Validation Status - -- **pending**: Artifact created, validation not yet run -- **passed**: All quality checks passed, ready for downstream consumption -- **failed**: Quality issues detected, blocks downstream spawn - -## Coordinator Integration - -The coordinator checks manifests in `handleCallback`: - -1. Read `<session>/artifacts/<task-id>/artifact-manifest.json` -2. If `validation_status == "passed"`: - - Register to artifact_registry - - Spawn next dependent task -3. If `validation_status == "failed"`: - - Create fix task - - Notify user - - Block downstream tasks - -## Context Artifacts Discovery - -Workers read `context-artifacts.json` to discover upstream artifacts: - -```json -{ - "artifacts": [ - { - "artifact_id": "uuid-...", - "artifact_type": "spec", - "path": "./spec/discovery-context.json", - "creator_role": "analyst" - } - ] -} -``` - -## Auto-Discovery (v5) - -In v5, workers declare `input_artifact_types: []` in frontmatter. The coordinator automatically discovers and provides matching artifacts without manual path configuration. - -## Quality Gates - -Validation checks vary by artifact type: - -| Artifact Type | Required Checks | -|---------------|----------------| -| spec | Completeness, schema compliance | -| architecture | ADR presence, component diagram | -| plan | Task count (2-7), dependency graph validity | -| code | Syntax check, test coverage | -| test | Test count > 0, all passing | -| review | Issue count, severity distribution | - -## Example Workflow - -1. **Analyst** creates spec → manifest with `validation_status: "passed"` -2. **Coordinator** reads manifest → registers to artifact_registry -3. **Writer** spawned → reads `context-artifacts.json` → finds analyst's spec -4. **Writer** creates document → manifest with `validation_status: "passed"` -5. **Coordinator** spawns next role based on dependency graph diff --git a/.claude/skills/team-lifecycle-v3/specs/core-concepts.md b/.claude/skills/team-lifecycle-v3/specs/core-concepts.md deleted file mode 100644 index 5ef0f2d3..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/core-concepts.md +++ /dev/null @@ -1,264 +0,0 @@ -# Core Concepts - -## Overview - -Team Lifecycle v3 is an enhanced multi-agent orchestration system that manages the complete software development lifecycle from specification to implementation, testing, and review. It uses a **team-worker agent architecture** with **artifact contracts** and **automatic discovery** to coordinate parallel execution across specialized roles. - -## Architecture - -``` -+---------------------------------------------------+ -| Skill(skill="team-lifecycle-v3") | -| args="task description" | -+-------------------+-------------------------------+ - | - Orchestration Mode (auto -> coordinator) - | - Coordinator (inline) - Phase 0-5 orchestration - + Dynamic role injection - + Priority scheduling - + Artifact registry - | - +----+-----+-------+-------+-------+-------+-------+ - v v v v v v v v - [team-worker agents, each loaded with a role-spec] - - Core Pipeline (9 roles from v2): - analyst writer planner executor tester reviewer - architect fe-developer fe-qa - - Specialist Roles (6 new roles, injected on-demand): - orchestrator security-expert performance-optimizer - data-engineer devops-engineer ml-engineer - - Utility Members (3): - [explorer] [discussant] [doc-generator] -``` - -## Foundational Principles - -### 1. Team-Worker Agent Architecture - -The system uses a **coordinator-worker pattern**: - -- **Coordinator**: Orchestrates the workflow, manages task dependencies, injects specialist roles dynamically, and maintains the artifact registry -- **Workers**: Specialized agents (analyst, writer, planner, executor, etc.) that execute specific tasks and produce artifacts -- **Communication**: Workers report completion via `SendMessage` callbacks to the coordinator - -**Key Benefits**: -- Clear separation of concerns (orchestration vs execution) -- Parallel execution of independent tasks -- Dynamic scaling with specialist role injection - -### 2. Artifact Contracts - -All workers generate **artifact manifests** alongside their deliverables for validation gating and automatic discovery. - -**Manifest Schema**: -```json -{ - "artifact_id": "string", - "creator_role": "string", - "artifact_type": "string", - "version": "string", - "path": "string", - "dependencies": ["string"], - "validation_status": "pending|passed|failed", - "validation_summary": "string", - "metadata": { - "created_at": "ISO8601 timestamp", - "task_id": "string", - "priority": "P0|P1|P2" - } -} -``` - -**Validation Gating**: -- Coordinator checks `validation_status` before spawning downstream workers -- `passed` → spawn next worker -- `failed` → block spawn, trigger fix loop -- `pending` → wait or prompt manual validation - -**Automatic Discovery**: -- Coordinator maintains in-memory artifact registry -- Workers read `context-artifacts.json` in Phase 2 to discover upstream artifacts automatically -- No manual artifact passing required - -### 3. Quality Gating - -Quality gates ensure artifact quality before proceeding to next phase: - -- **Spec Phase Gate** (QUALITY-001): Multi-dimensional quality check - - Completeness, Consistency, Traceability, Depth, Coverage - - Checkpoint with user actions: resume, improve, revise, recheck, feedback -- **Implementation Gate**: Test coverage and review approval -- **Per-Artifact Validation**: Manifest-based validation status - -### 4. Dynamic Role Injection - -Coordinator analyzes task description and plan complexity to inject specialist roles at runtime: - -| Trigger | Injected Role | Injection Point | -|---------|---------------|-----------------| -| Keywords: security, vulnerability, OWASP | security-expert | After PLAN-001 | -| Keywords: performance, optimization, bottleneck | performance-optimizer | After IMPL-* | -| Keywords: data, pipeline, ETL, schema | data-engineer | Parallel with IMPL-* | -| Keywords: devops, CI/CD, deployment, docker | devops-engineer | After IMPL-* | -| Keywords: ML, model, training, inference | ml-engineer | Parallel with IMPL-* | -| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* | - -**Benefits**: -- Automatic expertise injection based on task requirements -- No manual role configuration needed -- Scales from simple to complex tasks - -### 5. Priority Scheduling - -Tasks are assigned priorities for execution ordering: - -- **P0**: Critical path tasks (RESEARCH, DRAFT, PLAN, core IMPL) -- **P1**: Dependent tasks (TEST, REVIEW, QA) -- **P2**: Optional enhancements - -**Scheduling Rules**: -- P0 > P1 > P2 -- FIFO within same priority -- Parallel execution for independent tasks at same priority - -### 6. Conditional Routing - -PLAN-001 assesses complexity and routes accordingly: - -| Complexity | Route | Roles | -|------------|-------|-------| -| Low (1-2 modules, shallow deps) | Direct IMPL | executor | -| Medium (3-4 modules, moderate deps) | Orchestrated IMPL | orchestrator → executor (parallel) | -| High (5+ modules, deep deps) | Architecture + Orchestrated IMPL | architect → orchestrator → executor (parallel) | - -### 7. Beat-Based Cadence - -Event-driven execution model where each beat = coordinator wake → process → spawn → STOP: - -``` -Beat Cycle (v3 Enhanced) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check artifacts | <- v3: artifact validation - | update registry | <- v3: artifact registry - +- handleSpawnNext -+ - | find ready tasks | - | priority sort | <- v3: P0/P1/P2 scheduling - | inject roles | <- v3: dynamic injection - | spawn workers ---+--> [team-worker] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ -``` - -**Fast-Advance Optimization**: -- Workers can spawn simple linear successors directly -- Skips coordinator for simple cases -- Logs fast_advance to message bus - -## Role Types - -### Core Pipeline Roles (Always Present) - -| Role | Purpose | Task Prefix | -|------|---------|-------------| -| analyst | Research and discovery | RESEARCH-* | -| writer | Document drafting | DRAFT-* | -| planner | Implementation planning | PLAN-* | -| executor | Code implementation | IMPL-* | -| tester | Test generation and execution | TEST-* | -| reviewer | Quality review and improvement | REVIEW-*, QUALITY-*, IMPROVE-* | - -### Consulting Roles (High Complexity) - -| Role | Purpose | Task Prefix | -|------|---------|-------------| -| architect | Architecture design | ARCH-* | -| fe-developer | Frontend development | DEV-FE-* | -| fe-qa | Frontend QA | QA-FE-* | - -### Specialist Roles (Dynamic Injection) - -| Role | Purpose | Task Prefix | Injection Trigger | -|------|---------|-------------|-------------------| -| orchestrator | Multi-module coordination | ORCH-* | Multi-module complexity | -| security-expert | Security analysis | SECURITY-* | Security keywords | -| performance-optimizer | Performance optimization | PERF-* | Performance keywords | -| data-engineer | Data pipeline work | DATA-* | Data keywords | -| devops-engineer | DevOps and deployment | DEVOPS-* | DevOps keywords | -| ml-engineer | ML/AI implementation | ML-* | ML keywords | - -### Utility Members (Coordinator-Only) - -| Utility | Purpose | Callable By | -|---------|---------|-------------| -| explorer | Parallel multi-angle exploration | Coordinator only | -| discussant | Aggregate multi-CLI critique | Coordinator only | - -**Note**: Workers cannot spawn utility members. Workers needing similar capabilities must use CLI tools (`ccw cli --tool gemini --mode analysis`). - -## CLI Tool Integration - -Workers use CLI tools for complex analysis: - -| Capability | CLI Command | Used By | -|------------|-------------|---------| -| Codebase exploration | `ccw cli --tool gemini --mode analysis` | analyst, planner, architect | -| Multi-perspective critique | `ccw cli --tool gemini --mode analysis` (parallel) | analyst, writer, reviewer | -| Document generation | `ccw cli --tool gemini --mode write` | writer | - -## Session Management - -### Session Directory Structure - -``` -.workflow/.team/TLS-<slug>-<date>/ -+-- team-session.json -+-- artifact-registry.json <- v3 NEW -+-- spec/ -| +-- spec-config.json -| +-- discovery-context.json -| +-- product-brief.md -| +-- requirements/ -| +-- architecture/ -| +-- epics/ -| +-- readiness-report.md -+-- discussions/ -+-- plan/ -| +-- plan.json -| +-- .task/TASK-*.json -+-- explorations/ -+-- artifacts/ <- v3 NEW: artifact manifests -| +-- artifact-manifest-*.json -+-- .msg/ -+-- shared-memory.json -``` - -### Session Resume - -1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions -2. Multiple matches → AskUserQuestion -3. Audit TaskList → reconcile session state -4. Reset in_progress → pending (interrupted tasks) -5. Rebuild team, spawn needed workers only -6. Restore artifact registry from session -7. Kick first executable task - -## User Commands - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status, no advancement | -| `resume` / `continue` | Check worker states, advance next step | -| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream | -| `feedback <text>` | Analyze feedback, create targeted revision | -| `recheck` | Re-run QUALITY-001 quality check | -| `improve [dimension]` | Auto-improve weakest dimension | diff --git a/.claude/skills/team-lifecycle-v3/specs/document-standards.md b/.claude/skills/team-lifecycle-v3/specs/document-standards.md deleted file mode 100644 index 2820cd98..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/document-standards.md +++ /dev/null @@ -1,192 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle-v3/specs/domain-model.md b/.claude/skills/team-lifecycle-v3/specs/domain-model.md deleted file mode 100644 index c650f68d..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/domain-model.md +++ /dev/null @@ -1,619 +0,0 @@ -# Domain Model - -This document defines the core entities, schemas, relationships, and state machines for Team Lifecycle v3. - -## 1. Core Entities - -### 1.1 Task - -A **Task** represents a unit of work assigned to a specific role. Tasks have dependencies, priorities, and lifecycle states. - -**Definition**: An atomic work item with a unique identifier, assigned role, execution phase, dependency constraints, and status tracking. - -**Fields**: -- `id` (string): Unique task identifier following pattern `{PREFIX}-{NNN}` (e.g., `IMPL-001`, `TEST-001`) -- `role` (string): Role name responsible for execution (e.g., `executor`, `tester`, `reviewer`) -- `phase` (string): Execution phase (`spec`, `impl`, `test`, `review`) -- `dependencies` (array): List of task IDs that must complete before this task can start (blockedBy) -- `status` (enum): Current task state (`pending`, `ready`, `in_progress`, `completed`, `failed`) -- `priority` (enum): Execution priority (`P0`, `P1`, `P2`) -- `metadata` (object): Additional context (created_at, updated_at, attempt_count, error_message) - -### 1.2 Artifact - -An **Artifact** represents a deliverable produced by a worker, with validation status and dependency tracking. - -**Definition**: A versioned output (document, code, test suite) with a manifest describing its type, creator, validation status, and dependencies. - -**Fields**: -- `artifact_id` (string): Unique artifact identifier (e.g., `product-brief-v1`, `impl-auth-service`) -- `artifact_type` (string): Type classification (`document`, `code`, `test`, `config`, `report`) -- `path` (string): File system path relative to session directory -- `creator_role` (string): Role that produced this artifact -- `version` (string): Semantic version (e.g., `1.0`, `1.1`) -- `validation_status` (enum): Validation state (`pending`, `passed`, `failed`) -- `validation_summary` (string): Human-readable validation result -- `dependencies` (array): List of artifact IDs this artifact depends on -- `metadata` (object): Additional context (created_at, task_id, priority, file_size, checksum) - -### 1.3 Role - -A **Role** defines a specialized agent's capabilities, task prefix, and injection trigger. - -**Definition**: A specification for an agent type, including its responsibilities, task naming convention, and conditions for activation. - -**Fields**: -- `name` (string): Role identifier (e.g., `executor`, `security-expert`, `orchestrator`) -- `type` (enum): Role classification (`coordinator`, `pipeline`, `specialist`, `utility`) -- `task_prefix` (string): Task ID prefix pattern (e.g., `IMPL-*`, `SECURITY-*`, `ORCH-*`) -- `injection_trigger` (enum): Activation condition (`always`, `complexity`, `keywords`, `manual`) -- `injection_criteria` (object): Specific trigger conditions (keywords, complexity_threshold) -- `capabilities` (array): List of capabilities (e.g., `code_generation`, `security_audit`, `performance_analysis`) -- `inner_loop` (boolean): Whether role supports iterative refinement -- `phase_execution` (array): List of execution phases (1-5) - -### 1.4 Session - -A **Session** represents a complete workflow execution instance with persistent state. - -**Definition**: A stateful execution context that tracks all tasks, artifacts, and coordination state for a single workflow run. - -**Fields**: -- `session_id` (string): Unique session identifier (e.g., `TLS-auth-impl-20260305`) -- `slug` (string): Human-readable short name derived from task description -- `created_at` (string): ISO8601 timestamp of session creation -- `updated_at` (string): ISO8601 timestamp of last state change -- `status` (enum): Session lifecycle state (`created`, `active`, `paused`, `completed`, `archived`, `failed`) -- `pipeline_type` (enum): Selected pipeline (`spec-only`, `impl-only`, `full-lifecycle`, `enhanced-parallel`) -- `artifact_registry` (object): Map of artifact_id → Artifact manifest -- `task_list` (array): Ordered list of Task objects -- `injected_roles` (array): List of dynamically injected specialist roles -- `checkpoint_history` (array): Record of user checkpoint interactions -- `session_directory` (string): File system path to session workspace - ---- - -## 2. Entity Schemas - -### 2.1 Task Schema (JSON Schema) - -```json -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "title": "Task", - "required": ["id", "role", "phase", "status", "priority"], - "properties": { - "id": { - "type": "string", - "pattern": "^[A-Z]+-[0-9]{3}$", - "description": "Unique task identifier (e.g., IMPL-001)" - }, - "role": { - "type": "string", - "description": "Role name responsible for execution" - }, - "phase": { - "type": "string", - "enum": ["spec", "impl", "test", "review"], - "description": "Execution phase" - }, - "dependencies": { - "type": "array", - "items": {"type": "string", "pattern": "^[A-Z]+-[0-9]{3}$"}, - "default": [], - "description": "List of task IDs that must complete first" - }, - "status": { - "type": "string", - "enum": ["pending", "ready", "in_progress", "completed", "failed"], - "description": "Current task state" - }, - "priority": { - "type": "string", - "enum": ["P0", "P1", "P2"], - "description": "Execution priority (P0 = highest)" - }, - "metadata": { - "type": "object", - "properties": { - "created_at": {"type": "string", "format": "date-time"}, - "updated_at": {"type": "string", "format": "date-time"}, - "attempt_count": {"type": "integer", "minimum": 0}, - "error_message": {"type": "string"} - } - } - } -} -``` - -### 2.2 Artifact Schema (JSON Schema) - -```json -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "title": "Artifact", - "required": ["artifact_id", "artifact_type", "path", "creator_role", "validation_status"], - "properties": { - "artifact_id": { - "type": "string", - "description": "Unique artifact identifier" - }, - "artifact_type": { - "type": "string", - "enum": ["document", "code", "test", "config", "report"], - "description": "Type classification" - }, - "path": { - "type": "string", - "description": "File system path relative to session directory" - }, - "creator_role": { - "type": "string", - "description": "Role that produced this artifact" - }, - "version": { - "type": "string", - "pattern": "^[0-9]+\\.[0-9]+$", - "description": "Semantic version (e.g., 1.0)" - }, - "validation_status": { - "type": "string", - "enum": ["pending", "passed", "failed"], - "description": "Validation state" - }, - "validation_summary": { - "type": "string", - "description": "Human-readable validation result" - }, - "dependencies": { - "type": "array", - "items": {"type": "string"}, - "default": [], - "description": "List of artifact IDs this depends on" - }, - "metadata": { - "type": "object", - "properties": { - "created_at": {"type": "string", "format": "date-time"}, - "task_id": {"type": "string", "pattern": "^[A-Z]+-[0-9]{3}$"}, - "priority": {"type": "string", "enum": ["P0", "P1", "P2"]}, - "file_size": {"type": "integer", "minimum": 0}, - "checksum": {"type": "string"} - } - } - } -} -``` - -### 2.3 Role Schema (JSON Schema) - -```json -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "title": "Role", - "required": ["name", "type", "task_prefix", "injection_trigger"], - "properties": { - "name": { - "type": "string", - "description": "Role identifier" - }, - "type": { - "type": "string", - "enum": ["coordinator", "pipeline", "specialist", "utility"], - "description": "Role classification" - }, - "task_prefix": { - "type": "string", - "pattern": "^[A-Z]+-\\*$", - "description": "Task ID prefix pattern (e.g., IMPL-*)" - }, - "injection_trigger": { - "type": "string", - "enum": ["always", "complexity", "keywords", "manual"], - "description": "Activation condition" - }, - "injection_criteria": { - "type": "object", - "properties": { - "keywords": {"type": "array", "items": {"type": "string"}}, - "complexity_threshold": {"type": "string", "enum": ["low", "medium", "high"]} - } - }, - "capabilities": { - "type": "array", - "items": {"type": "string"}, - "description": "List of capabilities" - }, - "inner_loop": { - "type": "boolean", - "description": "Supports iterative refinement" - }, - "phase_execution": { - "type": "array", - "items": {"type": "integer", "minimum": 1, "maximum": 5}, - "description": "Execution phases (1-5)" - } - } -} -``` - -### 2.4 Session Schema (JSON Schema) - -```json -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "title": "Session", - "required": ["session_id", "slug", "status", "pipeline_type"], - "properties": { - "session_id": { - "type": "string", - "pattern": "^TLS-[a-z0-9-]+-[0-9]{8}$", - "description": "Unique session identifier" - }, - "slug": { - "type": "string", - "description": "Human-readable short name" - }, - "created_at": { - "type": "string", - "format": "date-time", - "description": "Session creation timestamp" - }, - "updated_at": { - "type": "string", - "format": "date-time", - "description": "Last state change timestamp" - }, - "status": { - "type": "string", - "enum": ["created", "active", "paused", "completed", "archived", "failed"], - "description": "Session lifecycle state" - }, - "pipeline_type": { - "type": "string", - "enum": ["spec-only", "impl-only", "full-lifecycle", "enhanced-parallel"], - "description": "Selected pipeline" - }, - "artifact_registry": { - "type": "object", - "additionalProperties": {"$ref": "#/definitions/Artifact"}, - "description": "Map of artifact_id to Artifact manifest" - }, - "task_list": { - "type": "array", - "items": {"$ref": "#/definitions/Task"}, - "description": "Ordered list of tasks" - }, - "injected_roles": { - "type": "array", - "items": {"type": "string"}, - "description": "Dynamically injected specialist roles" - }, - "checkpoint_history": { - "type": "array", - "items": { - "type": "object", - "properties": { - "checkpoint_id": {"type": "string"}, - "timestamp": {"type": "string", "format": "date-time"}, - "user_action": {"type": "string", "enum": ["resume", "improve", "revise", "recheck", "feedback"]}, - "context": {"type": "string"} - } - } - }, - "session_directory": { - "type": "string", - "description": "File system path to session workspace" - } - } -} -``` - ---- - -## 3. Entity Relationships - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ Session │ -│ - session_id │ -│ - status: created|active|paused|completed|archived|failed │ -│ - pipeline_type: spec-only|impl-only|full-lifecycle|enhanced │ -├─────────────────────────────────────────────────────────────────┤ -│ artifact_registry: Map<artifact_id, Artifact> │ -│ task_list: Task[] │ -│ injected_roles: string[] │ -│ checkpoint_history: Checkpoint[] │ -└──────────────┬──────────────────────────────┬───────────────────┘ - │ │ - │ 1:N │ 1:N - ▼ ▼ - ┌───────────────┐ ┌──────────────┐ - │ Artifact │ │ Task │ - ├───────────────┤ ├──────────────┤ - │ artifact_id │ │ id │ - │ artifact_type │ │ role ────────┼──┐ - │ path │ │ phase │ │ - │ creator_role ─┼──┐ │ dependencies │ │ N:1 - │ validation_ │ │ │ status │ │ - │ status │ │ │ priority │ │ - │ dependencies ─┼──┼───┐ └──────┬───────┘ │ - └───────────────┘ │ │ │ │ - │ │ │ produces │ - │ │ │ 1:1 │ - │ │ ▼ │ - │ │ ┌──────────────┐ │ - │ └──────▶│ Artifact │ │ - │ └──────────────┘ │ - │ │ - │ N:1 │ - ▼ ▼ - ┌──────────────┐ ┌──────────────┐ - │ Role │ │ Role │ - ├──────────────┤ ├──────────────┤ - │ name │ │ name │ - │ type │ │ type │ - │ task_prefix │ │ task_prefix │ - │ injection_ │ │ injection_ │ - │ trigger │ │ trigger │ - │ capabilities │ │ capabilities │ - └──────────────┘ └──────────────┘ -``` - -**Relationship Descriptions**: - -1. **Session → Task** (1:N): A session contains multiple tasks in its task_list -2. **Session → Artifact** (1:N): A session tracks multiple artifacts in its artifact_registry -3. **Task → Role** (N:1): Each task is assigned to one role for execution -4. **Task → Artifact** (1:1): Each task produces one primary artifact upon completion -5. **Task → Task** (N:N): Tasks can depend on other tasks (dependencies field) -6. **Artifact → Role** (N:1): Each artifact is created by one role (creator_role) -7. **Artifact → Artifact** (N:N): Artifacts can depend on other artifacts (dependencies field) - ---- - -## 4. State Machines - -### 4.1 Task Status State Machine - -``` - ┌─────────────┐ - │ pending │ (initial state) - └──────┬──────┘ - │ - │ dependencies met - ▼ - ┌─────────────┐ - │ ready │ - └──────┬──────┘ - │ - │ worker spawned - ▼ - ┌─────────────┐ - │ in_progress │ - └──────┬──────┘ - │ - ┌──────────┴──────────┐ - │ │ - │ success │ failure - ▼ ▼ - ┌─────────────┐ ┌─────────────┐ - │ completed │ │ failed │ - └─────────────┘ └──────┬──────┘ - │ - │ retry (attempt_count++) - ▼ - ┌─────────────┐ - │ pending │ - └─────────────┘ -``` - -**State Transitions**: -- `pending → ready`: All dependencies completed -- `ready → in_progress`: Worker spawned by coordinator -- `in_progress → completed`: Worker reports success via SendMessage -- `in_progress → failed`: Worker reports failure or timeout -- `failed → pending`: Coordinator triggers retry (with exponential backoff) - -**Terminal States**: `completed` - -**Retry Logic**: Failed tasks return to `pending` with incremented `attempt_count`. Max retries configurable (default: 3). - -### 4.2 Session Lifecycle State Machine - -``` - ┌─────────────┐ - │ created │ (initial state) - └──────┬──────┘ - │ - │ first task spawned - ▼ - ┌─────────────┐ - │ active │◀──────────┐ - └──────┬──────┘ │ - │ │ - ┌──────────┴──────────┐ │ - │ │ │ - │ user pause │ resume│ - ▼ │ │ - ┌─────────────┐ │ │ - │ paused │──────────────┘ │ - └─────────────┘ │ - │ - ┌─────────────┐ │ - │ active │───────────┘ - └──────┬──────┘ - │ - ┌──────────┴──────────┐ - │ │ - │ all tasks done │ unrecoverable error - ▼ ▼ - ┌─────────────┐ ┌─────────────┐ - │ completed │ │ failed │ - └──────┬──────┘ └──────┬──────┘ - │ │ - │ archive │ archive - ▼ ▼ - ┌─────────────┐ ┌─────────────┐ - │ archived │ │ archived │ - └─────────────┘ └─────────────┘ -``` - -**State Transitions**: -- `created → active`: Coordinator spawns first batch of tasks -- `active → paused`: User issues pause command or checkpoint requires review -- `paused → active`: User issues resume command -- `active → completed`: All tasks in task_list reach `completed` status -- `active → failed`: Unrecoverable error (e.g., circular dependency, resource exhaustion) -- `completed → archived`: Session archived after retention period -- `failed → archived`: Failed session archived after investigation - -**Terminal States**: `archived` - -**Checkpoint Behavior**: Session transitions to `paused` at quality checkpoints (e.g., after QUALITY-001). User actions (`resume`, `improve`, `revise`) transition back to `active`. - -### 4.3 Artifact Validation State Machine - -``` - ┌─────────────┐ - │ pending │ (initial state) - └──────┬──────┘ - │ - │ validation triggered - ▼ - ┌─────────────┐ - │ validating │ - └──────┬──────┘ - │ - ┌──────────┴──────────┐ - │ │ - │ validation success │ validation failure - ▼ ▼ - ┌─────────────┐ ┌─────────────┐ - │ passed │ │ failed │ - └─────────────┘ └──────┬──────┘ - │ - │ fix applied - ▼ - ┌─────────────┐ - │ pending │ - └─────────────┘ -``` - -**State Transitions**: -- `pending → validating`: Coordinator triggers validation (e.g., quality gate check) -- `validating → passed`: Artifact meets quality criteria -- `validating → failed`: Artifact fails quality criteria -- `failed → pending`: Worker applies fix and re-submits artifact - -**Terminal States**: `passed` - -**Validation Gating**: Downstream tasks blocked until upstream artifacts reach `passed` state. - ---- - -## 5. Invariants and Constraints - -### 5.1 Task Invariants - -1. **Unique Task IDs**: No two tasks in a session can have the same `id` -2. **Acyclic Dependencies**: Task dependency graph must be a DAG (no cycles) -3. **Valid Dependencies**: All task IDs in `dependencies` array must exist in session's task_list -4. **Priority Ordering**: P0 tasks execute before P1, P1 before P2 (within same dependency level) -5. **Single Active Worker**: A task can only be `in_progress` for one worker at a time - -### 5.2 Artifact Invariants - -1. **Unique Artifact IDs**: No two artifacts in a session can have the same `artifact_id` -2. **Valid Creator Role**: `creator_role` must match a defined role in the system -3. **Path Uniqueness**: No two artifacts can have the same `path` within a session -4. **Dependency Validity**: All artifact IDs in `dependencies` array must exist in artifact_registry - -### 5.3 Session Invariants - -1. **Unique Session IDs**: No two sessions can have the same `session_id` -2. **Monotonic Timestamps**: `updated_at` >= `created_at` -3. **Task Completeness**: All tasks in `task_list` must reach terminal state before session can be `completed` -4. **Artifact Registry Consistency**: All artifacts referenced in task metadata must exist in `artifact_registry` - ---- - -## 6. Usage Examples - -### 6.1 Creating a Task - -```json -{ - "id": "IMPL-001", - "role": "executor", - "phase": "impl", - "dependencies": ["PLAN-001"], - "status": "pending", - "priority": "P0", - "metadata": { - "created_at": "2026-03-05T10:00:00Z", - "updated_at": "2026-03-05T10:00:00Z", - "attempt_count": 0 - } -} -``` - -### 6.2 Creating an Artifact Manifest - -```json -{ - "artifact_id": "auth-service-impl-v1", - "artifact_type": "code", - "path": "artifacts/auth-service.ts", - "creator_role": "executor", - "version": "1.0", - "validation_status": "passed", - "validation_summary": "Code review passed: 95% test coverage, no security issues", - "dependencies": ["auth-service-plan-v1"], - "metadata": { - "created_at": "2026-03-05T11:30:00Z", - "task_id": "IMPL-001", - "priority": "P0", - "file_size": 15420, - "checksum": "sha256:abc123..." - } -} -``` - -### 6.3 Session State Example - -```json -{ - "session_id": "TLS-auth-impl-20260305", - "slug": "auth-impl", - "created_at": "2026-03-05T09:00:00Z", - "updated_at": "2026-03-05T12:00:00Z", - "status": "active", - "pipeline_type": "impl-only", - "artifact_registry": { - "auth-service-plan-v1": { ... }, - "auth-service-impl-v1": { ... } - }, - "task_list": [ - {"id": "PLAN-001", "status": "completed", ...}, - {"id": "IMPL-001", "status": "in_progress", ...}, - {"id": "TEST-001", "status": "pending", ...} - ], - "injected_roles": ["security-expert"], - "checkpoint_history": [], - "session_directory": ".workflow/.team/TLS-auth-impl-20260305/" -} -``` - ---- - -## 7. Cross-References - -- **Artifact Contract Specification**: [artifact-contract-spec.md](artifact-contract-spec.md) -- **Execution Flow**: [execution-flow.md](execution-flow.md) -- **Core Concepts**: [core-concepts.md](core-concepts.md) -- **Role Specifications**: [../roles/README.md](../roles/README.md) diff --git a/.claude/skills/team-lifecycle-v3/specs/execution-flow.md b/.claude/skills/team-lifecycle-v3/specs/execution-flow.md deleted file mode 100644 index d9664b03..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/execution-flow.md +++ /dev/null @@ -1,643 +0,0 @@ -# Execution Flow - -This document provides a detailed walkthrough of how tasks flow through the Team Lifecycle v3 system, from initial user request to final completion. - -## Table of Contents - -1. [Overview](#overview) -2. [Pipeline Definitions](#pipeline-definitions) -3. [Execution Lifecycle](#execution-lifecycle) -4. [Beat-Based Cadence](#beat-based-cadence) -5. [Conditional Routing](#conditional-routing) -6. [Dynamic Role Injection](#dynamic-role-injection) -7. [Quality Checkpoints](#quality-checkpoints) -8. [Task Metadata Registry](#task-metadata-registry) - -## Overview - -Team Lifecycle v3 uses an **event-driven, beat-based execution model**: - -1. User provides task description -2. Coordinator clarifies requirements and creates team -3. Coordinator analyzes complexity and injects specialist roles -4. Coordinator creates task chain based on pipeline selection -5. Coordinator spawns first batch of workers (background execution) -6. Workers execute and report completion via SendMessage callbacks -7. Coordinator advances pipeline, spawning next ready tasks -8. Process repeats until pipeline complete -9. Coordinator generates final report - -## Pipeline Definitions - -### Spec-only Pipeline (6 tasks, 3 discussions) - -For documentation, requirements gathering, and design work. - -``` -RESEARCH-001(+D1) → DRAFT-001 → DRAFT-002(+D2) → DRAFT-003 → DRAFT-004 → QUALITY-001(+D3) -``` - -**Tasks**: -- **RESEARCH-001** (analyst): Research and discovery with DISCUSS-001 -- **DRAFT-001** (writer): Product brief with self-validation -- **DRAFT-002** (writer): Requirements PRD with DISCUSS-002 -- **DRAFT-003** (writer): Architecture document with self-validation -- **DRAFT-004** (writer): Epics breakdown with self-validation -- **QUALITY-001** (reviewer): Multi-dimensional quality check with DISCUSS-003 - -**Checkpoint**: After QUALITY-001, user can review, improve, or revise before proceeding. - -### Impl-only Pipeline (4 tasks) - -For quick implementations with clear requirements. - -``` -PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001 -``` - -**Tasks**: -- **PLAN-001** (planner): Implementation planning and complexity assessment -- **IMPL-001** (executor): Code implementation -- **TEST-001** (tester): Test generation and execution (parallel with REVIEW-001) -- **REVIEW-001** (reviewer): Code quality review (parallel with TEST-001) - -### Full-lifecycle Pipeline (10 tasks, v2 compatible) - -Complete feature development from requirements to implementation. - -``` -[Spec pipeline] → PLAN-001(blockedBy: QUALITY-001) → IMPL-001 → TEST-001 + REVIEW-001 -``` - -**Checkpoint**: After QUALITY-001, user reviews spec quality before proceeding to implementation. - -### Enhanced Parallel Pipeline (v3 NEW) - -Advanced pipeline with conditional routing and parallel execution. - -``` -RESEARCH-001(+D1) → DRAFT-001 → DRAFT-002(+D2) → DRAFT-003 → DRAFT-004 → QUALITY-001(+D3) - | - v - PLAN-001 (complexity assessment) - | - +---------------+---------------+ - | | | - Low: IMPL-001 Med: ORCH-001 High: ARCH-001 - | → IMPL-* → ORCH-001 - | → IMPL-* - v - IMPL-001 || DEV-FE-001 (parallel, P0) - | - v - TEST-001 || QA-FE-001 (parallel, P1) - | - v - REVIEW-001 (P1) -``` - -**Key Features**: -- Conditional routing based on complexity assessment -- Parallel execution of independent tasks (IMPL-001 || DEV-FE-001) -- Priority-based scheduling (P0 > P1 > P2) -- Dynamic specialist role injection - -## Execution Lifecycle - -### Phase 0: User Request - -User invokes the skill with a task description: - -``` -Skill(skill="team-lifecycle-v3", args="Implement user authentication with OAuth2") -``` - -### Phase 1: Clarification & Team Creation - -**Coordinator Actions**: -1. Parse task description -2. Ask clarifying questions if needed (via AskUserQuestion) -3. Determine pipeline type (spec-only, impl-only, full-lifecycle) -4. Create team session folder: `.workflow/.team/TLS-<slug>-<date>/` -5. Initialize team via TeamCreate - -**Output**: Team session created, requirements clarified - -### Phase 2: Complexity Analysis & Role Injection - -**Coordinator Actions**: -1. Analyze task description for keywords -2. Assess complexity indicators (module count, dependencies) -3. Inject specialist roles based on triggers: - - Security keywords → `security-expert` - - Performance keywords → `performance-optimizer` - - Data keywords → `data-engineer` - - DevOps keywords → `devops-engineer` - - ML keywords → `ml-engineer` - - High complexity → `orchestrator`, `architect` - -**Output**: Role injection plan, updated task chain - -### Phase 3: Task Chain Creation - -**Coordinator Actions**: -1. Select pipeline based on requirements -2. Create task metadata for each step -3. Assign priorities (P0/P1/P2) -4. Establish dependencies (blockedBy relationships) -5. Register tasks via TaskCreate - -**Output**: Complete task chain with dependencies - -### Phase 4: Worker Spawning & Execution - -**Coordinator Actions**: -1. Find ready tasks (no unmet dependencies) -2. Sort by priority (P0 > P1 > P2) -3. Spawn workers via Agent tool (background execution) -4. Update task status to `in_progress` -5. Enter idle state (STOP) - -**Worker Actions**: -1. Load role specification -2. Execute Phase 1-5 (task discovery, domain work, reporting) -3. Generate artifacts with manifest -4. Send completion callback to coordinator via SendMessage - -**Output**: Workers executing in background - -### Phase 5: Callback Handling & Advancement - -**Coordinator Actions** (on callback): -1. Mark completed task -2. Validate artifact (check manifest validation_status) -3. Update artifact registry -4. Find next ready tasks -5. Check for checkpoints (e.g., QUALITY-001 complete) -6. If checkpoint: display status, wait for user command -7. If no checkpoint: spawn next batch, return to idle - -**Output**: Pipeline advances, next workers spawned - -### Phase 6: Completion & Reporting - -**Coordinator Actions** (when all tasks complete): -1. Generate final report -2. Summarize artifacts produced -3. Display completion status -4. Offer completion actions (archive session, continue work) - -**Output**: Final report, session complete - -## Beat-Based Cadence - -The system uses an **event-driven beat model** where each beat = coordinator wake → process → spawn → STOP. - -### Beat Cycle (v3 Enhanced) - -``` -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check artifacts | <- v3: artifact validation - | update registry | <- v3: artifact registry - +- handleSpawnNext -+ - | find ready tasks | - | priority sort | <- v3: P0/P1/P2 scheduling - | inject roles | <- v3: dynamic injection - | spawn workers ---+--> [team-worker] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ -====================================================================== -``` - -### Fast-Advance Optimization - -For simple linear successors, workers can spawn the next worker directly: - -``` -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker B directly - | --> log fast_advance to message bus - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -**Benefits**: -- Reduces coordinator overhead for simple chains -- Faster execution for linear pipelines -- Coordinator still maintains authority via message bus logs - -## Conditional Routing - -PLAN-001 assesses complexity and routes to appropriate implementation strategy. - -### Complexity Assessment Algorithm - -**Module Definition**: A **module** is a cohesive unit of code with clear boundaries and a single primary responsibility. Typically corresponds to: -- A file or class with related functionality -- A directory containing related files (e.g., `auth/`, `payment/`) -- A service or component with well-defined interfaces - -**Quantifiable Complexity Criteria**: - -| Metric | Low | Medium | High | -|--------|-----|--------|------| -| **Module Count** | 1-2 modules | 3-5 modules | 6+ modules | -| **Lines of Code (LOC)** | <500 LOC | 500-2000 LOC | 2000+ LOC | -| **Dependency Depth** | 1-2 levels | 3-4 levels | 5+ levels | -| **Responsibilities** | Single responsibility | 2-3 responsibilities | 4+ responsibilities | -| **Cross-Cutting Concerns** | None | 1-2 (e.g., logging, validation) | 3+ (e.g., auth, caching, monitoring) | -| **External Integrations** | 0-1 (e.g., database) | 2-3 (e.g., DB, API, cache) | 4+ (e.g., DB, APIs, queues, storage) | - -**Complexity Score Calculation** (Pseudocode): - -``` -function assessComplexity(plan): - score = 0 - - // Module count (weight: 3) - if plan.module_count >= 6: - score += 3 * 3 - else if plan.module_count >= 3: - score += 2 * 3 - else: - score += 1 * 3 - - // Lines of code (weight: 2) - if plan.estimated_loc >= 2000: - score += 3 * 2 - else if plan.estimated_loc >= 500: - score += 2 * 2 - else: - score += 1 * 2 - - // Dependency depth (weight: 2) - if plan.dependency_depth >= 5: - score += 3 * 2 - else if plan.dependency_depth >= 3: - score += 2 * 2 - else: - score += 1 * 2 - - // Responsibilities (weight: 1) - if plan.responsibilities >= 4: - score += 3 * 1 - else if plan.responsibilities >= 2: - score += 2 * 1 - else: - score += 1 * 1 - - // Cross-cutting concerns (weight: 1) - if plan.cross_cutting_concerns >= 3: - score += 3 * 1 - else if plan.cross_cutting_concerns >= 1: - score += 2 * 1 - else: - score += 1 * 1 - - // External integrations (weight: 1) - if plan.external_integrations >= 4: - score += 3 * 1 - else if plan.external_integrations >= 2: - score += 2 * 1 - else: - score += 1 * 1 - - // Total score range: 10-30 - // Low: 10-15, Medium: 16-22, High: 23-30 - - if score >= 23: - return "High" - else if score >= 16: - return "Medium" - else: - return "Low" -``` - -**Routing Decision Tree**: - -``` - ┌─────────────────────┐ - │ PLAN-001 Complete │ - │ Assess Complexity │ - └──────────┬──────────┘ - │ - ┌──────────────┼──────────────┐ - │ │ │ - ▼ ▼ ▼ - ┌────────────┐ ┌────────────┐ ┌────────────┐ - │ Low │ │ Medium │ │ High │ - │ Score:10-15│ │ Score:16-22│ │ Score:23-30│ - └──────┬─────┘ └──────┬─────┘ └──────┬─────┘ - │ │ │ - ▼ ▼ ▼ - ┌────────────┐ ┌────────────┐ ┌────────────┐ - │ IMPL-001 │ │ ORCH-001 │ │ ARCH-001 │ - │ (direct) │ │ (parallel) │ │ (design) │ - └──────┬─────┘ └──────┬─────┘ └──────┬─────┘ - │ │ │ - │ ▼ ▼ - │ ┌────────────┐ ┌────────────┐ - │ │ IMPL-001 │ │ ORCH-001 │ - │ │ IMPL-002 │ │ (parallel) │ - │ │ IMPL-003 │ └──────┬─────┘ - │ │ (parallel) │ │ - │ └──────┬─────┘ ▼ - │ │ ┌────────────┐ - │ │ │ IMPL-001 │ - │ │ │ IMPL-002 │ - │ │ │ ... │ - │ │ │ (parallel) │ - │ │ └──────┬─────┘ - │ │ │ - └──────────────┴──────────────┘ - │ - ▼ - ┌────────────┐ - │ TEST-001 │ - │ REVIEW-001 │ - │ (parallel) │ - └────────────┘ -``` - -### Complexity Assessment Criteria - -| Complexity | Module Count | Dependency Depth | Routing Decision | -|------------|--------------|------------------|------------------| -| Low | 1-2 modules | Shallow (1-2 levels) | Direct IMPL | -| Medium | 3-5 modules | Moderate (3-4 levels) | Orchestrated IMPL | -| High | 6+ modules | Deep (5+ levels) | Architecture + Orchestrated IMPL | - -### Routing Paths - -#### Low Complexity Route - -``` -PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001 -``` - -**Roles**: planner → executor → tester + reviewer - -**Use Case**: Simple feature, single module, clear implementation path - -#### Medium Complexity Route - -``` -PLAN-001 → ORCH-001 → IMPL-001 || IMPL-002 || IMPL-003 → TEST-001 + REVIEW-001 -``` - -**Roles**: planner → orchestrator → executor (parallel) → tester + reviewer - -**Use Case**: Multi-module feature, moderate dependencies, parallel implementation possible - -#### High Complexity Route - -``` -PLAN-001 → ARCH-001 → ORCH-001 → IMPL-001 || IMPL-002 || ... → TEST-001 + REVIEW-001 -``` - -**Roles**: planner → architect → orchestrator → executor (parallel) → tester + reviewer - -**Use Case**: Complex feature, many modules, deep dependencies, architecture design needed - -## Dynamic Role Injection - -Specialist roles are automatically injected based on task analysis. - -### Injection Triggers - -| Trigger | Injected Role | Injection Point | Priority | -|---------|---------------|-----------------|----------| -| Keywords: security, vulnerability, OWASP, auth | security-expert | After PLAN-001 | P0 | -| Keywords: performance, optimization, bottleneck, latency | performance-optimizer | After IMPL-* | P1 | -| Keywords: data, pipeline, ETL, schema, database | data-engineer | Parallel with IMPL-* | P0 | -| Keywords: devops, CI/CD, deployment, docker, kubernetes | devops-engineer | After IMPL-* | P1 | -| Keywords: ML, model, training, inference, AI | ml-engineer | Parallel with IMPL-* | P0 | -| Complexity: High + multi-module | orchestrator | Replace IMPL-* with ORCH-* | P0 | -| Complexity: High + deep dependencies | architect | Before ORCH-* | P0 | - -### Injection Example - -**Task Description**: "Implement user authentication with OAuth2, add security audit, optimize login performance" - -**Analysis**: -- Keywords detected: "authentication", "OAuth2", "security", "audit", "optimize", "performance" -- Complexity: Medium (3-4 modules) - -**Injected Roles**: -- `security-expert` (keywords: security, audit, authentication) -- `performance-optimizer` (keywords: optimize, performance) - -**Resulting Pipeline**: -``` -PLAN-001 → IMPL-001 || SECURITY-001 || PERF-001 → TEST-001 → REVIEW-001 -``` - -## Quality Checkpoints - -Checkpoints pause execution for user review and feedback. - -### Checkpoint 1: Spec Phase Complete (QUALITY-001) - -**Trigger**: QUALITY-001 task completes - -**Coordinator Output**: -``` -[coordinator] ══════════════════════════════════════════ -[coordinator] SPEC PHASE COMPLETE -[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%) -[coordinator] -[coordinator] Dimension Scores: -[coordinator] Completeness: ████████░░ 80% -[coordinator] Consistency: █████████░ 90% -[coordinator] Traceability: ███████░░░ 70% -[coordinator] Depth: ████████░░ 80% -[coordinator] Coverage: ██████████ 100% -[coordinator] -[coordinator] Available Actions: -[coordinator] resume -> Proceed to implementation -[coordinator] improve -> Auto-improve weakest dimension -[coordinator] revise <TASK-ID> -> Revise specific document -[coordinator] recheck -> Re-run quality check -[coordinator] feedback <text> -> Inject feedback -[coordinator] ══════════════════════════════════════════ -``` - -**User Actions**: -- `resume` → Proceed to PLAN-001 -- `improve` → Auto-improve weakest dimension (Traceability in example) -- `revise DRAFT-003` → Revise architecture document -- `recheck` → Re-run QUALITY-001 -- `feedback "Add more API examples"` → Targeted revision - -### Checkpoint 2: Complexity Routing Decision (PLAN-001) - -**Trigger**: PLAN-001 completes with complexity assessment - -**Coordinator Output**: -``` -[coordinator] ══════════════════════════════════════════ -[coordinator] COMPLEXITY ASSESSMENT COMPLETE -[coordinator] Complexity: Medium (3 modules, moderate dependencies) -[coordinator] Routing: Orchestrated Implementation -[coordinator] -[coordinator] Next Steps: -[coordinator] ORCH-001: Coordinate parallel implementation -[coordinator] IMPL-001: Core authentication module -[coordinator] IMPL-002: OAuth2 integration -[coordinator] IMPL-003: Session management -[coordinator] -[coordinator] Continuing automatically... -[coordinator] ══════════════════════════════════════════ -``` - -**Note**: This checkpoint is informational only; execution continues automatically. - -### Checkpoint 3: Parallel Merge (All Parallel Tasks Complete) - -**Trigger**: All parallel tasks at same level complete - -**Coordinator Actions**: -1. Validate integration (check for conflicts) -2. Merge artifacts if needed -3. Continue to next phase - -**Note**: If integration issues detected, coordinator may pause for user intervention. - -### Checkpoint 4: Pipeline Stall (No Ready + No Running) - -**Trigger**: No tasks ready to execute and no tasks currently running - -**Coordinator Output**: -``` -[coordinator] ══════════════════════════════════════════ -[coordinator] PIPELINE STALLED -[coordinator] Reason: Circular dependency or missing task -[coordinator] -[coordinator] Current State: -[coordinator] Completed: 5 tasks -[coordinator] Blocked: 2 tasks (waiting on IMPL-001) -[coordinator] Running: 0 tasks -[coordinator] -[coordinator] Action Required: Check task dependencies -[coordinator] ══════════════════════════════════════════ -``` - -**User Actions**: Investigate and resolve dependency issues - -## Task Metadata Registry - -Complete task metadata for all pipeline tasks. - -| Task ID | Role | Phase | Dependencies | Discuss | Priority | Notes | -|---------|------|-------|-------------|---------|----------|-------| -| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | P0 | Initial research | -| DRAFT-001 | writer | spec | RESEARCH-001 | self-validate | P0 | Product brief | -| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-002 | P0 | Requirements PRD | -| DRAFT-003 | writer | spec | DRAFT-002 | self-validate | P0 | Architecture doc | -| DRAFT-004 | writer | spec | DRAFT-003 | self-validate | P0 | Epics breakdown | -| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-003 | P0 | Quality gate | -| PLAN-001 | planner | impl | (none or QUALITY-001) | - | P0 | Implementation plan | -| ARCH-001 | architect | impl | PLAN-001 | - | P0 | Architecture design (if High complexity) | -| ORCH-001 | orchestrator | impl | PLAN-001 or ARCH-001 | - | P0 | Orchestration (if Med/High complexity) | -| IMPL-001 | executor | impl | PLAN-001 or ORCH-001 | - | P0 | Core implementation | -| DEV-FE-001 | fe-developer | impl | PLAN-001 or ORCH-001 | - | P0 | Frontend (parallel with IMPL-001) | -| TEST-001 | tester | impl | IMPL-001 | - | P1 | Test generation | -| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | P1 | Frontend QA (parallel with TEST-001) | -| REVIEW-001 | reviewer | impl | IMPL-001 | - | P1 | Code review | -| SECURITY-001 | security-expert | impl | IMPL-001 | - | P0 | Security audit (if injected) | -| PERF-001 | performance-optimizer | impl | IMPL-001 | - | P1 | Performance optimization (if injected) | -| DATA-001 | data-engineer | impl | PLAN-001 | - | P0 | Data pipeline (if injected, parallel) | -| DEVOPS-001 | devops-engineer | impl | IMPL-001 | - | P1 | DevOps setup (if injected) | -| ML-001 | ml-engineer | impl | PLAN-001 | - | P0 | ML implementation (if injected, parallel) | - -### Task State Transitions - -``` -pending → ready → in_progress → completed - → failed → pending (retry) -``` - -**States**: -- `pending`: Task created, waiting for dependencies -- `ready`: Dependencies met, ready to execute -- `in_progress`: Worker spawned, executing -- `completed`: Worker finished successfully -- `failed`: Worker encountered error (triggers retry) - -### Dependency Resolution - -**Rules**: -1. Task becomes `ready` when all `blockedBy` tasks are `completed` -2. Coordinator checks dependencies on each beat -3. Failed tasks block downstream until retry succeeds -4. Parallel tasks (no dependencies) execute simultaneously - -## Execution Examples - -### Example 1: Simple Implementation (Low Complexity) - -**Task**: "Add logging to user service" - -**Pipeline**: Impl-only -``` -PLAN-001 → IMPL-001 → TEST-001 + REVIEW-001 -``` - -**Execution**: -1. Beat 1: Spawn PLAN-001 (planner) -2. Beat 2: PLAN-001 completes → Spawn IMPL-001 (executor) -3. Beat 3: IMPL-001 completes → Spawn TEST-001 + REVIEW-001 (parallel) -4. Beat 4: Both complete → Generate report - -**Duration**: ~4 beats - -### Example 2: Full Lifecycle with Specialist Injection (High Complexity) - -**Task**: "Implement user authentication with OAuth2, add security audit, optimize login performance" - -**Pipeline**: Full-lifecycle with injections -``` -RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001 - → PLAN-001 → ARCH-001 → ORCH-001 → IMPL-001 || SECURITY-001 || PERF-001 - → TEST-001 → REVIEW-001 -``` - -**Execution**: -1. Beat 1-6: Spec phase (RESEARCH → DRAFT-* → QUALITY) -2. Checkpoint: User reviews spec quality, chooses `resume` -3. Beat 7: Spawn PLAN-001 (planner) -4. Beat 8: PLAN-001 completes (High complexity) → Spawn ARCH-001 (architect) -5. Beat 9: ARCH-001 completes → Spawn ORCH-001 (orchestrator) -6. Beat 10: ORCH-001 completes → Spawn IMPL-001 || SECURITY-001 || PERF-001 (parallel, P0) -7. Beat 11: All parallel tasks complete → Spawn TEST-001 (P1) -8. Beat 12: TEST-001 completes → Spawn REVIEW-001 (P1) -9. Beat 13: REVIEW-001 completes → Generate report - -**Duration**: ~13 beats + 1 checkpoint - -### Example 3: Spec-only with Revision Loop - -**Task**: "Design API for payment processing" - -**Pipeline**: Spec-only -``` -RESEARCH-001 → DRAFT-001 → DRAFT-002 → DRAFT-003 → DRAFT-004 → QUALITY-001 -``` - -**Execution**: -1. Beat 1-6: Spec phase completes -2. Checkpoint: User reviews, quality score 65% (FAIL) -3. User: `improve` → Auto-improve weakest dimension (Traceability) -4. Beat 7: Spawn IMPROVE-001 (reviewer) -5. Beat 8: IMPROVE-001 completes → Spawn QUALITY-001 (recheck) -6. Beat 9: QUALITY-001 completes, quality score 85% (PASS) -7. Checkpoint: User reviews, chooses `resume` → Generate report - -**Duration**: ~9 beats + 2 checkpoints diff --git a/.claude/skills/team-lifecycle-v3/specs/quality-gates.md b/.claude/skills/team-lifecycle-v3/specs/quality-gates.md deleted file mode 100644 index ae968436..00000000 --- a/.claude/skills/team-lifecycle-v3/specs/quality-gates.md +++ /dev/null @@ -1,207 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle-v3/templates/README.md b/.claude/skills/team-lifecycle-v3/templates/README.md deleted file mode 100644 index ab87b2a1..00000000 --- a/.claude/skills/team-lifecycle-v3/templates/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# Templates Directory - -This directory contains document templates used by workers during execution. - -## Available Templates - -| Template | Used By | Task | Purpose | -|----------|---------|------|---------| -| [product-brief.md](product-brief.md) | writer | DRAFT-001 | Product vision and high-level requirements | -| [requirements-prd.md](requirements-prd.md) | writer | DRAFT-002 | Detailed product requirements document | -| [architecture-doc.md](architecture-doc.md) | writer | DRAFT-003 | System architecture and design decisions | -| [epics-template.md](epics-template.md) | writer | DRAFT-004 | Epic breakdown and user stories | - -## Template Structure - -All templates follow this structure: - -```markdown ---- -title: <Document Title> -type: <product-brief|requirements|architecture|epics> -version: 1.0 -created: <ISO8601 timestamp> -author: <role-name> ---- - -# <Document Title> - -## Section 1 -... - -## Section 2 -... -``` - -## Usage - -### By Workers - -Workers load templates during Phase 3 (Domain Work): - -1. Read template file -2. Fill in sections based on research/context -3. Generate artifact with proper frontmatter -4. Create artifact manifest - -### By Coordinator - -Coordinator references templates when creating tasks: - -- DRAFT-001 → `product-brief.md` -- DRAFT-002 → `requirements-prd.md` -- DRAFT-003 → `architecture-doc.md` -- DRAFT-004 → `epics-template.md` - -## Template Customization - -To customize templates: - -1. Modify template files in this directory -2. Ensure YAML frontmatter structure is preserved -3. Update section headings as needed -4. Test with a sample task - -## Document Standards - -All generated documents must follow: - -- **Formatting**: See [../specs/document-standards.md](../specs/document-standards.md) -- **Quality criteria**: See [../specs/quality-gates.md](../specs/quality-gates.md) -- **Artifact contract**: See [../specs/artifact-contract-spec.md](../specs/artifact-contract-spec.md) - -## Cross-References - -- **Specifications**: See [../specs/README.md](../specs/README.md) -- **Role specifications**: See [../roles/README.md](../roles/README.md) -- **Writer role**: See [../roles/pipeline/writer.md](../roles/pipeline/writer.md) -- **Main entry**: See [../SKILL.md](../SKILL.md) diff --git a/.claude/skills/team-lifecycle-v3/templates/architecture-doc.md b/.claude/skills/team-lifecycle-v3/templates/architecture-doc.md deleted file mode 100644 index 5106de03..00000000 --- a/.claude/skills/team-lifecycle-v3/templates/architecture-doc.md +++ /dev/null @@ -1,254 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle-v3/templates/epics-template.md b/.claude/skills/team-lifecycle-v3/templates/epics-template.md deleted file mode 100644 index 939d933c..00000000 --- a/.claude/skills/team-lifecycle-v3/templates/epics-template.md +++ /dev/null @@ -1,196 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle-v3/templates/product-brief.md b/.claude/skills/team-lifecycle-v3/templates/product-brief.md deleted file mode 100644 index ffbdf437..00000000 --- a/.claude/skills/team-lifecycle-v3/templates/product-brief.md +++ /dev/null @@ -1,133 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle-v3/templates/requirements-prd.md b/.claude/skills/team-lifecycle-v3/templates/requirements-prd.md deleted file mode 100644 index 0b1dbf28..00000000 --- a/.claude/skills/team-lifecycle-v3/templates/requirements-prd.md +++ /dev/null @@ -1,224 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle-v4/SKILL.md b/.claude/skills/team-lifecycle-v4/SKILL.md new file mode 100644 index 00000000..4a1a550e --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/SKILL.md @@ -0,0 +1,140 @@ +--- +name: team-lifecycle-v4 +description: Full lifecycle team skill with clean architecture. SKILL.md is a universal router — all roles read it. Beat model is coordinator-only. Structure is roles/ + specs/ + templates/. Triggers on "team lifecycle v4". +allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +--- + +# Team Lifecycle v4 + +Orchestrate multi-agent software development: specification → planning → implementation → testing → review. + +## Architecture + +``` +Skill(skill="team-lifecycle-v4", args="task description") + | + SKILL.md (this file) = Router + | + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+ + v v v v + [team-worker agents, each loads roles/<role>/role.md] +``` + +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| analyst | [roles/analyst/role.md](roles/analyst/role.md) | RESEARCH-* | false | +| writer | [roles/writer/role.md](roles/writer/role.md) | DRAFT-* | true | +| planner | [roles/planner/role.md](roles/planner/role.md) | PLAN-* | true | +| executor | [roles/executor/role.md](roles/executor/role.md) | IMPL-* | true | +| tester | [roles/tester/role.md](roles/tester/role.md) | TEST-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REVIEW-*, QUALITY-*, IMPROVE-* | false | + +## Role Router + +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router + +## Shared Constants + +- **Session prefix**: `TLV4` +- **Session path**: `.workflow/.team/TLV4-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` + +## Worker Spawn Template + +Coordinator spawns workers using this template: + +``` +Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker", + team_name: <team-name>, + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-lifecycle-v4/roles/<role>/role.md +session: <session-folder> +session_id: <session-id> +team_name: <team-name> +requirement: <task-description> +inner_loop: <true|false> + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` +}) +``` + +## User Commands + +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | +| `revise <TASK-ID> [feedback]` | Revise specific task | +| `feedback <text>` | Inject feedback for revision | +| `recheck` | Re-run quality check | +| `improve [dimension]` | Auto-improve weakest dimension | + +## Completion Action + +When pipeline completes, coordinator presents: + +``` +AskUserQuestion({ + questions: [{ + question: "Pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory" } + ] + }] +}) +``` + +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry +- [specs/quality-gates.md](specs/quality-gates.md) — Quality gate criteria and scoring +- [specs/knowledge-transfer.md](specs/knowledge-transfer.md) — Artifact and state transfer protocols + +## Session Directory + +``` +.workflow/.team/TLV4-<slug>-<date>/ +├── team-session.json # Session state + role registry +├── spec/ # Spec phase outputs +├── plan/ # Implementation plan + TASK-*.json +├── artifacts/ # All deliverables +├── wisdom/ # Cross-task knowledge +├── explorations/ # Shared explore cache +├── discussions/ # Discuss round records +└── .msg/ # Team message bus +``` + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| CLI tool fails | Worker fallback to direct implementation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-lifecycle-v4/roles/analyst/role.md b/.claude/skills/team-lifecycle-v4/roles/analyst/role.md new file mode 100644 index 00000000..62f0a9e8 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/analyst/role.md @@ -0,0 +1,78 @@ +--- +role: analyst +prefix: RESEARCH +inner_loop: false +discuss_rounds: [DISCUSS-001] +message_types: + success: research_ready + error: error +--- + +# Analyst + +Research and codebase exploration for context gathering. + +## Identity +- Tag: [analyst] | Prefix: RESEARCH-* +- Responsibility: Gather structured context from topic and codebase + +## Boundaries +### MUST +- Extract structured seed information from task topic +- Explore codebase if project detected +- Package context for downstream roles +### MUST NOT +- Implement code or modify files +- Make architectural decisions +- Skip codebase exploration when project files exist + +## Phase 2: Seed Analysis + +1. Read upstream artifacts via team_msg(operation="get_state") +2. Extract session folder from task description +3. Parse topic from task description +4. If topic references file (@path or .md/.txt) → read it +5. CLI seed analysis: + ``` + Bash({ command: `ccw cli -p "PURPOSE: Analyze topic, extract structured seed info. + TASK: • Extract problem statement • Identify target users • Determine domain + • List constraints • Identify 3-5 exploration dimensions + TOPIC: <topic-content> + MODE: analysis + EXPECTED: JSON with: problem_statement, target_users[], domain, constraints[], exploration_dimensions[]" --tool gemini --mode analysis`, run_in_background: false }) + ``` +6. Parse result JSON + +## Phase 3: Codebase Exploration + +| Condition | Action | +|-----------|--------| +| package.json / Cargo.toml / pyproject.toml / go.mod exists | Explore | +| No project files | Skip (codebase_context = null) | + +When project detected: +``` +Bash({ command: `ccw cli -p "PURPOSE: Explore codebase for context +TASK: • Identify tech stack • Map architecture patterns • Document conventions • List integration points +MODE: analysis +CONTEXT: @**/* +EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[]" --tool gemini --mode analysis`, run_in_background: false }) +``` + +## Phase 4: Context Packaging + +1. Write spec-config.json → <session>/spec/ +2. Write discovery-context.json → <session>/spec/ +3. Inline Discuss (DISCUSS-001): + - Artifact: <session>/spec/discovery-context.json + - Perspectives: product, risk, coverage +4. Handle verdict per consensus protocol +5. Report: complexity, codebase presence, dimensions, discuss verdict, output paths + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| CLI failure | Fallback to direct analysis | +| No project detected | Continue as new project | +| Topic too vague | Report with clarification questions | diff --git a/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/analyze.md b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..409cc8c5 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/analyze.md @@ -0,0 +1,56 @@ +# Analyze Task + +Parse user task -> detect capabilities -> build dependency graph -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| investigate, explore, research | analyst | RESEARCH | +| write, draft, document | writer | DRAFT | +| implement, build, code, fix | executor | IMPL | +| design, architect, plan | planner | PLAN | +| test, verify, validate | tester | TEST | +| analyze, review, audit | reviewer | REVIEW | + +## Dependency Graph + +Natural ordering tiers: +- Tier 0: analyst, planner (knowledge gathering) +- Tier 1: writer (creation requires context) +- Tier 2: executor (implementation requires plan/design) +- Tier 3: tester, reviewer (validation requires artifacts) + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per capability | +1 | +| Cross-domain | +2 | +| Parallel tracks | +1 per track | +| Serial depth > 3 | +1 | + +Results: 1-3 Low, 4-6 Medium, 7+ High + +## Role Minimization + +- Cap at 5 roles +- Merge overlapping capabilities +- Absorb trivial single-step roles + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_type": "<spec-only|impl-only|full-lifecycle|...>", + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "needs_research": true +} +``` diff --git a/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/dispatch.md b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..19a02fec --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/dispatch.md @@ -0,0 +1,46 @@ +# Dispatch Tasks + +Create task chains from dependency graph with proper blockedBy relationships. + +## Workflow + +1. Read task-analysis.json -> extract dependency_graph +2. Read specs/pipelines.md -> get task registry for selected pipeline +3. Topological sort tasks (respect blockedBy) +4. Validate all owners exist in role registry (SKILL.md) +5. For each task (in order): + - TaskCreate with structured description (see template below) + - TaskUpdate with blockedBy + owner assignment +6. Update team-session.json with pipeline.tasks_total +7. Validate chain (no orphans, no cycles, all refs valid) + +## Task Description Template + +``` +PURPOSE: <goal> | Success: <criteria> +TASK: + - <step 1> + - <step 2> +CONTEXT: + - Session: <session-folder> + - Upstream artifacts: <list> + - Key files: <list> +EXPECTED: <artifact path> + <quality criteria> +CONSTRAINTS: <scope limits> +--- +InnerLoop: <true|false> +RoleSpec: .claude/skills/team-lifecycle-v4/roles/<role>/role.md +``` + +## InnerLoop Flag Rules + +- true: Role has 2+ serial same-prefix tasks (writer: DRAFT-001->004) +- false: Role has 1 task, or tasks are parallel + +## Dependency Validation + +- No orphan tasks (all tasks have valid owner) +- No circular dependencies +- All blockedBy references exist +- Session reference in every task description +- RoleSpec reference in every task description diff --git a/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/monitor.md b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..d3868a54 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/coordinator/commands/monitor.md @@ -0,0 +1,98 @@ +# Monitor Pipeline + +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. + +## Constants + +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker + +## Handler Router + +| Source | Handler | +|--------|---------| +| Message contains [role-name] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | + +## handleCallback + +Worker completed. Process and advance. + +1. Find matching worker by role in message +2. Check if progress update (inner loop) or final completion +3. Progress -> update session state, STOP +4. Completion -> mark task done, remove from active_workers +5. Check for checkpoints: + - QUALITY-001 -> display quality gate, pause for user commands + - PLAN-001 -> read plan.json complexity, create dynamic IMPL tasks per specs/pipelines.md routing +6. -> handleSpawnNext + +## handleCheck + +Read-only status report, then STOP. + +Output: +``` +[coordinator] Pipeline Status +[coordinator] Progress: <done>/<total> (<pct>%) +[coordinator] Active: <workers with elapsed time> +[coordinator] Ready: <pending tasks with resolved deps> +[coordinator] Commands: 'resume' to advance | 'check' to refresh +``` + +## handleResume + +1. No active workers -> handleSpawnNext +2. Has active -> check each status + - completed -> mark done + - in_progress -> still running +3. Some completed -> handleSpawnNext +4. All running -> report status, STOP + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect: completedSubjects, inProgressSubjects, readySubjects +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Check if inner loop role with active worker -> skip (worker picks up) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker (see SKILL.md Spawn Template) + e. Add to active_workers +5. Update session, output summary, STOP + +## handleComplete + +Pipeline done. Generate report and completion action. + +1. Generate summary (deliverables, stats, discussions) +2. Read session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) + +## handleAdapt + +Capability gap reported mid-pipeline. + +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause + +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-lifecycle-v4/roles/coordinator/role.md b/.claude/skills/team-lifecycle-v4/roles/coordinator/role.md new file mode 100644 index 00000000..fd7fcdf5 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/coordinator/role.md @@ -0,0 +1,116 @@ +# Coordinator Role + +Orchestrate team-lifecycle-v4: analyze -> dispatch -> spawn -> monitor -> report. + +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results + +## Boundaries + +### MUST +- Parse task description (text-level only, no codebase reading) +- Create team and spawn team-worker agents in background +- Dispatch tasks with proper dependency chains +- Monitor progress via callbacks and route messages +- Maintain session state (team-session.json) +- Handle capability_gap reports +- Execute completion action when pipeline finishes + +### MUST NOT +- Read source code or explore codebase (delegate to workers) +- Execute task work directly +- Modify task output artifacts +- Spawn workers with general-purpose agent (MUST use team-worker) +- Generate more than 5 worker roles + +## Command Execution Protocol +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding + +## Entry Router + +| Detection | Condition | Handler | +|-----------|-----------|---------| +| Worker callback | Message contains [role-name] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/TLV4-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | + +For callback/check/resume/adapt/complete: load commands/monitor.md, execute handler, STOP. + +## Phase 0: Session Resume Check + +1. Scan .workflow/.team/TLV4-*/team-session.json for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection + +## Phase 1: Requirement Clarification + +TEXT-LEVEL ONLY. No source code reading. + +1. Parse task description +2. Clarify if ambiguous (AskUserQuestion: scope, deliverables, constraints) +3. Delegate to commands/analyze.md +4. Output: task-analysis.json +5. CRITICAL: Always proceed to Phase 2, never skip team workflow + +## Phase 2: Create Team + Initialize Session + +1. Generate session ID: TLV4-<slug>-<date> +2. Create session folder structure +3. TeamCreate with team name +4. Read specs/pipelines.md -> select pipeline +5. Register roles in team-session.json +6. Initialize shared infrastructure (wisdom/*.md, explorations/cache-index.json) +7. Initialize pipeline via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { pipeline_mode: "<mode>", pipeline_stages: [...], team_name: "<name>" } + }) + ``` +8. Write team-session.json + +## Phase 3: Create Task Chain + +Delegate to commands/dispatch.md: +1. Read dependency graph from task-analysis.json +2. Read specs/pipelines.md for selected pipeline's task registry +3. Topological sort tasks +4. Create tasks via TaskCreate with blockedBy +5. Update team-session.json + +## Phase 4: Spawn-and-Stop + +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP + +## Phase 5: Report + Completion Action + +1. Generate summary (deliverables, pipeline stats, discussions) +2. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean + - auto_keep -> Keep Active + +## Error Handling + +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Dependency cycle | Detect in analysis, halt | +| Role limit exceeded | Merge overlapping roles | diff --git a/.claude/skills/team-lifecycle-v4/roles/executor/commands/fix.md b/.claude/skills/team-lifecycle-v4/roles/executor/commands/fix.md new file mode 100644 index 00000000..7974a1cc --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/executor/commands/fix.md @@ -0,0 +1,35 @@ +# Fix + +Revision workflow for bug fixes and feedback-driven changes. + +## Workflow + +1. Read original task + feedback/revision notes from task description +2. Load original implementation context (files modified, approach taken) +3. Analyze feedback to identify specific changes needed +4. Apply fixes: + - Agent mode: Edit tool for targeted changes + - CLI mode: Resume previous session with fix prompt +5. Re-validate convergence criteria +6. Report: original task, changes applied, validation result + +## Fix Prompt Template (CLI mode) + +``` +PURPOSE: Fix issues in <task.title> based on feedback +TASK: + - Review original implementation + - Apply feedback: <feedback text> + - Verify fixes address all feedback points +MODE: write +CONTEXT: @<modified files> +EXPECTED: All feedback points addressed, convergence criteria met +CONSTRAINTS: Minimal changes | No scope creep +``` + +## Quality Rules + +- Fix ONLY what feedback requests +- No refactoring beyond fix scope +- Verify original convergence criteria still pass +- Report partial_completion if some feedback unclear diff --git a/.claude/skills/team-lifecycle-v4/roles/executor/commands/implement.md b/.claude/skills/team-lifecycle-v4/roles/executor/commands/implement.md new file mode 100644 index 00000000..00f071da --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/executor/commands/implement.md @@ -0,0 +1,62 @@ +# Implement + +Execute implementation from task JSON via agent or CLI delegation. + +## Agent Mode + +Direct implementation using Edit/Write/Bash tools: + +1. Read task.files[] as target files +2. Read task.implementation[] as step-by-step instructions +3. For each step: + - Substitute [variable] placeholders with pre_analysis results + - New file → Write tool; Modify file → Edit tool + - Follow task.reference patterns +4. Apply task.rationale.chosen_approach +5. Mitigate task.risks[] during implementation + +Quality rules: +- Verify module existence before referencing +- Incremental progress — small working changes +- Follow existing patterns from task.reference +- ASCII-only, no premature abstractions + +## CLI Delegation Mode + +Build prompt from task JSON, delegate to CLI: + +Prompt structure: +``` +PURPOSE: <task.title> +<task.description> + +TARGET FILES: +<task.files[] with paths and changes> + +IMPLEMENTATION STEPS: +<task.implementation[] numbered> + +PRE-ANALYSIS CONTEXT: +<pre_analysis results> + +REFERENCE: +<task.reference pattern and files> + +DONE WHEN: +<task.convergence.criteria[]> + +MODE: write +CONSTRAINTS: Only modify listed files | Follow existing patterns +``` + +CLI call: +``` +Bash({ command: `ccw cli -p "<prompt>" --tool <tool> --mode write --rule development-implement-feature`, + run_in_background: false, timeout: 3600000 }) +``` + +Resume strategy: +| Strategy | Command | +|----------|---------| +| new | --id <session>-<task_id> | +| resume | --resume <parent_id> | diff --git a/.claude/skills/team-lifecycle-v4/roles/executor/role.md b/.claude/skills/team-lifecycle-v4/roles/executor/role.md new file mode 100644 index 00000000..b335e9e7 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/executor/role.md @@ -0,0 +1,67 @@ +--- +role: executor +prefix: IMPL +inner_loop: true +message_types: + success: impl_complete + progress: impl_progress + error: error +--- + +# Executor + +Code implementation worker with dual execution modes. + +## Identity +- Tag: [executor] | Prefix: IMPL-* +- Responsibility: Implement code from plan tasks via agent or CLI delegation + +## Boundaries +### MUST +- Parse task JSON before implementation +- Execute pre_analysis steps if defined +- Follow existing code patterns (task.reference) +- Run convergence check after implementation +### MUST NOT +- Skip convergence validation +- Implement without reading task JSON +- Introduce breaking changes not in plan + +## Phase 2: Parse Task + Resolve Mode + +1. Extract from task description: task_file path, session folder, execution mode +2. Read task JSON (id, title, files[], implementation[], convergence.criteria[]) +3. Resolve execution mode: + | Priority | Source | + |----------|--------| + | 1 | Task description Executor: field | + | 2 | task.meta.execution_config.method | + | 3 | plan.json recommended_execution | + | 4 | Auto: Low → agent, Medium/High → codex | +4. Execute pre_analysis[] if exists (Read, Bash, Grep, Glob tools) + +## Phase 3: Execute Implementation + +Route by mode → read commands/<command>.md: +- agent / gemini / codex / qwen → commands/implement.md +- Revision task → commands/fix.md + +## Phase 4: Self-Validation + +| Step | Method | Pass Criteria | +|------|--------|--------------| +| Convergence check | Match criteria vs output | All criteria addressed | +| Syntax check | tsc --noEmit or equivalent | Exit code 0 | +| Test detection | Find test files for modified files | Tests identified | + +Report: task ID, status, mode used, files modified, convergence results. + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Agent mode syntax errors | Retry with error context (max 3) | +| CLI mode failure | Retry or resume with --resume | +| pre_analysis failure | Follow on_error (fail/continue/skip) | +| CLI tool unavailable | Fallback: gemini → qwen → codex | +| Max retries exceeded | Report failure to coordinator | diff --git a/.claude/skills/team-lifecycle-v4/roles/planner/role.md b/.claude/skills/team-lifecycle-v4/roles/planner/role.md new file mode 100644 index 00000000..e860e2d9 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/planner/role.md @@ -0,0 +1,76 @@ +--- +role: planner +prefix: PLAN +inner_loop: true +message_types: + success: plan_ready + revision: plan_revision + error: error +--- + +# Planner + +Codebase-informed implementation planning with complexity assessment. + +## Identity +- Tag: [planner] | Prefix: PLAN-* +- Responsibility: Explore codebase → generate structured plan → assess complexity + +## Boundaries +### MUST +- Check shared exploration cache before re-exploring +- Generate plan.json + TASK-*.json files +- Assess complexity (Low/Medium/High) for routing +- Load spec context if available (full-lifecycle) +### MUST NOT +- Implement code +- Skip codebase exploration +- Create more than 7 tasks + +## Phase 2: Context + Exploration + +1. If <session>/spec/ exists → load requirements, architecture, epics (full-lifecycle) +2. Check <session>/explorations/cache-index.json for cached explorations +3. Explore codebase (cache-aware): + ``` + Bash({ command: `ccw cli -p "PURPOSE: Explore codebase to inform planning + TASK: • Search for relevant patterns • Identify files to modify • Document integration points + MODE: analysis + CONTEXT: @**/* + EXPECTED: JSON with: relevant_files[], patterns[], integration_points[], recommendations[]" --tool gemini --mode analysis`, run_in_background: false }) + ``` +4. Store results in <session>/explorations/ + +## Phase 3: Plan Generation + +Generate plan.json + .task/TASK-*.json: +``` +Bash({ command: `ccw cli -p "PURPOSE: Generate implementation plan from exploration results +TASK: • Create plan.json overview • Generate TASK-*.json files (2-7 tasks) • Define dependencies • Set convergence criteria +MODE: write +CONTEXT: @<session>/explorations/*.json +EXPECTED: Files: plan.json + .task/TASK-*.json +CONSTRAINTS: 2-7 tasks, include id/title/files[]/convergence.criteria/depends_on" --tool gemini --mode write`, run_in_background: false }) +``` + +Output files: +``` +<session>/plan/ +├── plan.json # Overview + complexity assessment +└── .task/TASK-*.json # Individual task definitions +``` + +## Phase 4: Submit for Approval + +1. Read plan.json and TASK-*.json +2. Report to coordinator: complexity, task count, approach, plan location +3. Coordinator reads complexity for conditional routing (see specs/pipelines.md) + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| CLI exploration failure | Plan from description only | +| CLI planning failure | Fallback to direct planning | +| Plan rejected 3+ times | Notify coordinator | +| Cache index corrupt | Clear cache, re-explore | diff --git a/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-code.md b/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-code.md new file mode 100644 index 00000000..2a6fe868 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-code.md @@ -0,0 +1,34 @@ +# Code Review + +4-dimension code review for implementation quality. + +## Inputs + +- Plan file (plan.json) +- Git diff or modified files list +- Test results (if available) + +## Dimensions + +| Dimension | Critical Issues | +|-----------|----------------| +| Quality | Empty catch, any casts, @ts-ignore, console.log | +| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML | +| Architecture | Circular deps, imports >2 levels deep, files >500 lines | +| Requirements | Missing core functionality, incomplete acceptance criteria | + +## Review Process + +1. Gather modified files from executor's state (team_msg get_state) +2. Read each modified file +3. Score per dimension (0-100%) +4. Classify issues by severity (Critical/High/Medium/Low) +5. Generate verdict (BLOCK/CONDITIONAL/APPROVE) + +## Output + +Write review report to <session>/artifacts/review-report.md: +- Per-dimension scores +- Issue list with file:line references +- Verdict with justification +- Recommendations (if CONDITIONAL) diff --git a/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-spec.md b/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-spec.md new file mode 100644 index 00000000..91e57f66 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/reviewer/commands/review-spec.md @@ -0,0 +1,44 @@ +# Spec Quality Review + +5-dimension spec quality gate with discuss protocol. + +## Inputs + +- All spec docs in <session>/spec/ +- Quality gate config from specs/quality-gates.md + +## Dimensions + +| Dimension | Weight | Focus | +|-----------|--------|-------| +| Completeness | 25% | All sections present with substance | +| Consistency | 25% | Terminology, format, references uniform | +| Traceability | 25% | Goals→Reqs→Arch→Stories chain | +| Depth | 25% | AC testable, ADRs justified, stories estimable | + +## Review Process + +1. Read all spec documents from <session>/spec/ +2. Load quality gate thresholds from specs/quality-gates.md +3. Score each dimension +4. Run cross-document validation +5. Generate readiness-report.md + spec-summary.md +6. Run DISCUSS-003: + - Artifact: <session>/spec/readiness-report.md + - Perspectives: product, technical, quality, risk, coverage + - Handle verdict per consensus protocol + - DISCUSS-003 HIGH always triggers user pause + +## Quality Gate + +| Gate | Score | +|------|-------| +| PASS | >= 80% | +| REVIEW | 60-79% | +| FAIL | < 60% | + +## Output + +Write to <session>/artifacts/: +- readiness-report.md: Dimension scores, issue list, traceability matrix +- spec-summary.md: Executive summary of all spec docs diff --git a/.claude/skills/team-lifecycle-v4/roles/reviewer/role.md b/.claude/skills/team-lifecycle-v4/roles/reviewer/role.md new file mode 100644 index 00000000..b6eb8611 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/reviewer/role.md @@ -0,0 +1,69 @@ +--- +role: reviewer +prefix: REVIEW +additional_prefixes: [QUALITY, IMPROVE] +inner_loop: false +discuss_rounds: [DISCUSS-003] +message_types: + success_review: review_result + success_quality: quality_result + fix: fix_required + error: error +--- + +# Reviewer + +Quality review for both code (REVIEW-*) and specifications (QUALITY-*, IMPROVE-*). + +## Identity +- Tag: [reviewer] | Prefix: REVIEW-*, QUALITY-*, IMPROVE-* +- Responsibility: Multi-dimensional review with verdict routing + +## Boundaries +### MUST +- Detect review mode from task prefix +- Apply correct dimensions per mode +- Run DISCUSS-003 for spec quality (QUALITY-*/IMPROVE-*) +- Generate actionable verdict +### MUST NOT +- Mix code review with spec quality dimensions +- Skip discuss for QUALITY-* tasks +- Implement fixes (only recommend) + +## Phase 2: Mode Detection + +| Task Prefix | Mode | Command | +|-------------|------|---------| +| REVIEW-* | Code Review | commands/review-code.md | +| QUALITY-* | Spec Quality | commands/review-spec.md | +| IMPROVE-* | Spec Quality (recheck) | commands/review-spec.md | + +## Phase 3: Review Execution + +Route to command based on detected mode. + +## Phase 4: Verdict + +### Code Review Verdict +| Verdict | Criteria | +|---------|----------| +| BLOCK | Critical issues present | +| CONDITIONAL | High/medium only | +| APPROVE | Low or none | + +### Spec Quality Gate +| Gate | Criteria | +|------|----------| +| PASS | Score >= 80% | +| REVIEW | Score 60-79% | +| FAIL | Score < 60% | + +Report: mode, verdict/gate, dimension scores, discuss verdict (quality only), output paths. + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Missing context | Request from coordinator | +| Invalid mode | Abort with error | +| Discuss fails | Proceed without discuss, log warning | diff --git a/.claude/skills/team-lifecycle-v4/roles/tester/role.md b/.claude/skills/team-lifecycle-v4/roles/tester/role.md new file mode 100644 index 00000000..83afaab6 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/tester/role.md @@ -0,0 +1,87 @@ +--- +role: tester +prefix: TEST +inner_loop: false +message_types: + success: test_result + fix: fix_required + error: error +--- + +# Tester + +Test execution with iterative fix cycle. + +## Identity +- Tag: [tester] | Prefix: TEST-* +- Responsibility: Detect framework → run tests → fix failures → report results + +## Boundaries +### MUST +- Auto-detect test framework before running +- Run affected tests first, then full suite +- Classify failures by severity +- Iterate fix cycle up to MAX_ITERATIONS +### MUST NOT +- Skip framework detection +- Run full suite before affected tests +- Exceed MAX_ITERATIONS without reporting + +## 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: <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 + +Loop: +1. Run affected tests → parse results +2. Pass rate met → run full suite +3. Failures → select strategy → fix → re-run + +Strategy selection: +| Condition | Strategy | +|-----------|----------| +| Iteration <= 3 or pass >= 80% | Conservative: fix one critical failure | +| Critical failures < 5 | Surgical: fix specific pattern everywhere | +| Pass < 50% or iteration > 7 | Aggressive: fix all 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 coordinator | +| No tests found | Report to coordinator | +| Infinite fix loop | Abort after MAX_ITERATIONS | diff --git a/.claude/skills/team-lifecycle-v4/roles/writer/role.md b/.claude/skills/team-lifecycle-v4/roles/writer/role.md new file mode 100644 index 00000000..0dd24f83 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/roles/writer/role.md @@ -0,0 +1,95 @@ +--- +role: writer +prefix: DRAFT +inner_loop: true +discuss_rounds: [DISCUSS-002] +message_types: + success: draft_ready + revision: draft_revision + error: error +--- + +# Writer + +Template-driven document generation with progressive dependency loading. + +## Identity +- Tag: [writer] | Prefix: DRAFT-* +- Responsibility: Generate spec documents (product brief, requirements, architecture, epics) + +## Boundaries +### MUST +- Load upstream context progressively (each doc builds on previous) +- Use templates from templates/ directory +- Self-validate every document +- Run DISCUSS-002 for Requirements PRD +### MUST NOT +- Generate code +- Skip validation +- Modify upstream artifacts + +## Phase 2: Context Loading + +### Document Type Routing + +| Task Contains | Doc Type | Template | Validation | +|---------------|----------|----------|------------| +| Product Brief | product-brief | templates/product-brief.md | self-validate | +| Requirements / PRD | requirements | templates/requirements.md | DISCUSS-002 | +| Architecture | architecture | templates/architecture.md | self-validate | +| Epics | epics | templates/epics.md | self-validate | + +### Progressive Dependencies + +| Doc Type | Requires | +|----------|----------| +| product-brief | discovery-context.json | +| requirements | + product-brief.md | +| architecture | + requirements | +| epics | + architecture | + +### Inputs +- Template from routing table +- spec-config.json from <session>/spec/ +- discovery-context.json from <session>/spec/ +- Prior decisions from context_accumulator (inner loop) +- Discussion feedback from <session>/discussions/ (if exists) + +## Phase 3: Document Generation + +CLI generation: +``` +Bash({ command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template +TASK: • Load template • Apply spec config and discovery context • Integrate prior feedback • Generate all sections +MODE: write +CONTEXT: @<session>/spec/*.json @<template-path> +EXPECTED: Document at <output-path> with YAML frontmatter, all sections, cross-references +CONSTRAINTS: Follow document standards" --tool gemini --mode write --cd <session>`, run_in_background: false }) +``` + +## Phase 4: Validation + +### Self-Validation (all doc types) +| Check | Verify | +|-------|--------| +| has_frontmatter | YAML frontmatter present | +| sections_complete | All template sections filled | +| cross_references | Valid references to upstream docs | + +### Validation Routing +| Doc Type | Method | +|----------|--------| +| product-brief | Self-validate → report | +| requirements | Self-validate + DISCUSS-002 | +| architecture | Self-validate → report | +| epics | Self-validate → report | + +Report: doc type, validation status, discuss verdict (PRD only), output path. + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| CLI failure | Retry once with alternative tool | +| Prior doc missing | Notify coordinator | +| Discussion contradicts prior | Note conflict, flag for coordinator | diff --git a/.claude/skills/team-lifecycle-v4/specs/knowledge-transfer.md b/.claude/skills/team-lifecycle-v4/specs/knowledge-transfer.md new file mode 100644 index 00000000..3d67348b --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/specs/knowledge-transfer.md @@ -0,0 +1,96 @@ +# Knowledge Transfer Protocols + +## 1. Transfer Channels + +| Channel | Method | Producer | Consumer | +|---------|--------|----------|----------| +| Artifacts | Files in `<session>/artifacts/` | Task executor | Next task in pipeline | +| State Updates | `team_msg(type="state_update")` | Task executor | Coordinator + downstream | +| Wisdom | Append to `<session>/wisdom/*.md` | Any role | All roles | +| Context Accumulator | In-memory aggregation | Inner loop only | Current task | +| Exploration Cache | `<session>/explorations/` | Analyst / researcher | All roles | + +## 2. Context Loading Protocol (Before Task Execution) + +Every role MUST load context in this order before starting work. + +| Step | Action | Required | +|------|--------|----------| +| 1 | `team_msg(operation="get_state", role=<upstream>)` | Yes | +| 2 | Read artifact files from upstream state's `ref` paths | Yes | +| 3 | Read `<session>/wisdom/*.md` if exists | Yes | +| 4 | Check `<session>/explorations/cache-index.json` before new exploration | If exploring | + +**Loading rules**: +- Never skip step 1 -- state contains key decisions and findings +- If `ref` path in state does not exist, log warning and continue +- Wisdom files are append-only -- read all entries, newest last + +## 3. Context Publishing Protocol (After Task Completion) + +| Step | Action | Required | +|------|--------|----------| +| 1 | Write deliverable to `<session>/artifacts/<task-id>-<name>.md` | Yes | +| 2 | Send `team_msg(type="state_update")` with payload (see schema below) | Yes | +| 3 | Append wisdom entries for learnings, decisions, issues found | If applicable | + +## 4. State Update Schema + +Sent via `team_msg(type="state_update")` on task completion. + +```json +{ + "status": "task_complete", + "task_id": "<TASK-NNN>", + "ref": "<session>/artifacts/<filename>", + "key_findings": [ + "Finding 1", + "Finding 2" + ], + "decisions": [ + "Decision with rationale" + ], + "files_modified": [ + "path/to/file.ts" + ], + "verification": "self-validated | peer-reviewed | tested" +} +``` + +**Field rules**: +- `ref`: Always an artifact path, never inline content +- `key_findings`: Max 5 items, each under 100 chars +- `decisions`: Include rationale, not just the choice +- `files_modified`: Only for implementation tasks +- `verification`: One of `self-validated`, `peer-reviewed`, `tested` + +## 5. Exploration Cache Protocol + +Prevents redundant research across tasks and discussion rounds. + +| Step | Action | +|------|--------| +| 1 | Read `<session>/explorations/cache-index.json` | +| 2 | If angle already explored, read cached result from `explore-<angle>.json` | +| 3 | If not cached, perform exploration | +| 4 | Write result to `<session>/explorations/explore-<angle>.json` | +| 5 | Update `cache-index.json` with new entry | + +**cache-index.json format**: +```json +{ + "entries": [ + { + "angle": "competitor-analysis", + "file": "explore-competitor-analysis.json", + "created_by": "RESEARCH-001", + "timestamp": "2026-01-15T10:30:00Z" + } + ] +} +``` + +**Rules**: +- Cache key is the exploration `angle` (normalized to kebab-case) +- Cache entries never expire within a session +- Any role can read cached explorations; only the creator updates them diff --git a/.claude/skills/team-lifecycle-v4/specs/pipelines.md b/.claude/skills/team-lifecycle-v4/specs/pipelines.md new file mode 100644 index 00000000..d991c73d --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/specs/pipelines.md @@ -0,0 +1,113 @@ +# Pipeline Definitions + +## 1. Pipeline Selection Criteria + +| Keywords | Pipeline | +|----------|----------| +| spec, design, document, requirements | `spec-only` | +| implement, build, fix, code | `impl-only` | +| full, lifecycle, end-to-end | `full-lifecycle` | +| frontend, UI, react, vue | `fe-only` or `fullstack` | +| Ambiguous / unclear | AskUserQuestion | + +## 2. Spec-Only Pipeline + +**6 tasks, 3 discussion rounds** + +``` +RESEARCH-001(+D1) -> DRAFT-001 -> DRAFT-002(+D2) -> DRAFT-003 -> DRAFT-004 -> QUALITY-001(+D3) +``` + +| Task | Role | Description | Discuss | +|------|------|-------------|---------| +| RESEARCH-001 | analyst | Research domain, competitors, constraints | D1: scope alignment | +| DRAFT-001 | writer | Product brief, self-validate | - | +| DRAFT-002 | writer | Requirements PRD | D2: requirements review | +| DRAFT-003 | writer | Architecture design, self-validate | - | +| DRAFT-004 | writer | Epics & stories, self-validate | - | +| QUALITY-001 | reviewer | Quality gate scoring | D3: readiness decision | + +**Checkpoint**: After QUALITY-001 -- pause for user approval before any implementation. + +## 3. Impl-Only Pipeline + +**4 tasks, 0 discussion rounds** + +``` +PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001 +``` + +| Task | Role | Description | +|------|------|-------------| +| PLAN-001 | planner | Break down into implementation steps, assess complexity | +| IMPL-001 | implementer | Execute implementation plan | +| TEST-001 | tester | Validate against acceptance criteria | +| REVIEW-001 | reviewer | Code review | + +TEST-001 and REVIEW-001 run in parallel after IMPL-001 completes. + +## 4. Full-Lifecycle Pipeline + +**10 tasks = spec-only (6) + impl (4)** + +``` +[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001 +``` + +PLAN-001 is blocked until QUALITY-001 passes and user approves the checkpoint. + +## 5. Frontend Pipelines + +| Pipeline | Description | +|----------|-------------| +| `fe-only` | Frontend implementation only: PLAN-001 -> IMPL-001 (fe-implementer) -> TEST-001 + REVIEW-001 | +| `fullstack` | Backend + frontend: PLAN-001 -> IMPL-001 (backend) + IMPL-002 (frontend) -> TEST-001 + REVIEW-001 | +| `full-lifecycle-fe` | Full spec pipeline -> fullstack impl pipeline | + +## 6. Conditional Routing + +PLAN-001 outputs a complexity assessment that determines the impl topology. + +| Complexity | Modules | Route | +|------------|---------|-------| +| Low | 1-2 | PLAN-001 -> IMPL-001 -> TEST + REVIEW | +| Medium | 3-4 | PLAN-001 -> ORCH-001 -> IMPL-{1..N} (parallel) -> TEST + REVIEW | +| High | 5+ | PLAN-001 -> ARCH-001 -> ORCH-001 -> IMPL-{1..N} -> TEST + REVIEW | + +- **ORCH-001** (orchestrator): Coordinates parallel IMPL tasks, manages dependencies +- **ARCH-001** (architect): Detailed architecture decisions before orchestration + +## 7. Task Metadata Registry + +| Task ID | Role | Phase | Depends On | Discuss | Priority | +|---------|------|-------|------------|---------|----------| +| RESEARCH-001 | analyst | research | - | D1 | P0 | +| DRAFT-001 | writer | product-brief | RESEARCH-001 | - | P0 | +| DRAFT-002 | writer | requirements | DRAFT-001 | D2 | P0 | +| DRAFT-003 | writer | architecture | DRAFT-002 | - | P0 | +| DRAFT-004 | writer | epics | DRAFT-003 | - | P0 | +| QUALITY-001 | reviewer | readiness | DRAFT-004 | D3 | P0 | +| PLAN-001 | planner | planning | QUALITY-001 (or user input) | - | P0 | +| ARCH-001 | architect | arch-detail | PLAN-001 | - | P1 | +| ORCH-001 | orchestrator | orchestration | PLAN-001 or ARCH-001 | - | P1 | +| IMPL-001 | implementer | implementation | PLAN-001 or ORCH-001 | - | P0 | +| IMPL-{N} | implementer | implementation | ORCH-001 | - | P0 | +| TEST-001 | tester | validation | IMPL-* | - | P0 | +| REVIEW-001 | reviewer | review | IMPL-* | - | P0 | + +## 8. Dynamic Specialist Injection + +When task content or user request matches trigger keywords, inject a specialist task. + +| Trigger Keywords | Specialist Role | Task Prefix | Priority | Insert After | +|------------------|----------------|-------------|----------|--------------| +| security, vulnerability, OWASP | security-expert | SECURITY-* | P0 | PLAN | +| performance, optimization, latency | performance-optimizer | PERF-* | P1 | IMPL | +| data, pipeline, ETL, migration | data-engineer | DATA-* | P0 | parallel with IMPL | +| devops, CI/CD, deployment, infra | devops-engineer | DEVOPS-* | P1 | IMPL | +| ML, model, training, inference | ml-engineer | ML-* | P0 | parallel with IMPL | + +**Injection rules**: +- Specialist tasks inherit the session context and wisdom +- They publish state_update on completion like any other task +- P0 specialists block downstream tasks; P1 run in parallel diff --git a/.claude/skills/team-lifecycle-v4/specs/quality-gates.md b/.claude/skills/team-lifecycle-v4/specs/quality-gates.md new file mode 100644 index 00000000..3ca378b8 --- /dev/null +++ b/.claude/skills/team-lifecycle-v4/specs/quality-gates.md @@ -0,0 +1,130 @@ +# Quality Gates + +## 1. Quality Thresholds + +| Result | Score | Action | +|--------|-------|--------| +| Pass | >= 80% | Proceed to next phase | +| Review | 60-79% | Revise flagged items, re-evaluate | +| Fail | < 60% | Return to producer for rework | + +## 2. Scoring Dimensions + +| Dimension | Weight | Criteria | +|-----------|--------|----------| +| Completeness | 25% | All required sections present with substantive content | +| Consistency | 25% | Terminology, formatting, cross-references are uniform | +| Traceability | 25% | Clear chain: Goals -> Requirements -> Architecture -> Stories | +| Depth | 25% | ACs are testable, ADRs justified, stories estimable | + +**Score** = weighted average of all dimensions (0-100 per dimension). + +## 3. Per-Phase Quality Gates + +### Phase 2: Product Brief + +| Check | Pass Criteria | +|-------|---------------| +| Vision statement | Clear, one-paragraph, measurable outcome | +| Problem definition | Specific pain points with evidence | +| Target users | Defined personas or segments | +| Success goals | Quantifiable metrics (KPIs) | +| Success metrics | Measurement method specified | + +### Phase 3: Requirements PRD + +| Check | Pass Criteria | +|-------|---------------| +| Functional requirements | Each has unique ID (FR-NNN) | +| Acceptance criteria | Testable given/when/then format | +| Prioritization | MoSCoW applied to all requirements | +| User stories | Format: As a [role], I want [goal], so that [benefit] | +| Non-functional reqs | Performance, security, scalability addressed | + +### Phase 4: Architecture + +| Check | Pass Criteria | +|-------|---------------| +| Component diagram | All major components identified with boundaries | +| Tech stack | Each choice justified against alternatives | +| ADRs | At least 1 ADR per major decision, with status | +| Data model | Entities, relationships, key fields defined | +| Integration points | APIs, protocols, data formats specified | + +### Phase 5: Epics & Stories + +| Check | Pass Criteria | +|-------|---------------| +| Epic count | 2-8 epics (too few = too broad, too many = too granular) | +| MVP subset | Clearly marked MVP epics/stories | +| Stories per epic | 3-12 stories each | +| Story format | Title, description, ACs, estimate present | + +### Phase 6: Readiness Gate + +| Check | Pass Criteria | +|-------|---------------| +| All docs exist | Brief, PRD, Architecture, Epics all present | +| Cross-refs valid | All document references resolve correctly | +| Overall score | >= 60% across all dimensions | +| No P0 issues | Zero Error-class issues outstanding | + +## 4. Cross-Document Validation + +| Source | Target | Validation | +|--------|--------|------------| +| Brief goals | PRD requirements | Every goal has >= 1 requirement | +| PRD requirements | Architecture components | Every requirement maps to a component | +| PRD requirements | Epic stories | Every requirement covered by >= 1 story | +| Architecture components | Epic stories | Every component has implementation stories | +| Brief success metrics | Epic ACs | Metrics traceable to acceptance criteria | + +## 5. Code Review Dimensions + +For REVIEW-* tasks during implementation phases. + +### Quality + +| Check | Severity | +|-------|----------| +| Empty catch blocks | Error | +| `as any` type casts | Warning | +| `@ts-ignore` / `@ts-expect-error` | Warning | +| `console.log` in production code | Warning | +| Unused imports/variables | Info | + +### Security + +| Check | Severity | +|-------|----------| +| Hardcoded secrets/credentials | Error | +| SQL injection vectors | Error | +| `eval()` or `Function()` usage | Error | +| `innerHTML` assignment | Warning | +| Missing input validation | Warning | + +### Architecture + +| Check | Severity | +|-------|----------| +| Circular dependencies | Error | +| Deep cross-boundary imports (3+ levels) | Warning | +| Files > 500 lines | Warning | +| Functions > 50 lines | Info | + +### Requirements Coverage + +| Check | Severity | +|-------|----------| +| Core functionality implemented | Error if missing | +| Acceptance criteria covered | Error if missing | +| Edge cases handled | Warning | +| Error states handled | Warning | + +## 6. Issue Classification + +| Class | Label | Action | +|-------|-------|--------| +| Error | Must fix | Blocks progression, must resolve before proceeding | +| Warning | Should fix | Should resolve, can proceed with justification | +| Info | Nice to have | Optional improvement, log for future | diff --git a/.claude/skills/team-lifecycle-v2/templates/architecture-doc.md b/.claude/skills/team-lifecycle-v4/templates/architecture.md similarity index 100% rename from .claude/skills/team-lifecycle-v2/templates/architecture-doc.md rename to .claude/skills/team-lifecycle-v4/templates/architecture.md diff --git a/.claude/skills/team-lifecycle-v2/templates/epics-template.md b/.claude/skills/team-lifecycle-v4/templates/epics.md similarity index 100% rename from .claude/skills/team-lifecycle-v2/templates/epics-template.md rename to .claude/skills/team-lifecycle-v4/templates/epics.md diff --git a/.claude/skills/team-lifecycle-v2/templates/product-brief.md b/.claude/skills/team-lifecycle-v4/templates/product-brief.md similarity index 100% rename from .claude/skills/team-lifecycle-v2/templates/product-brief.md rename to .claude/skills/team-lifecycle-v4/templates/product-brief.md diff --git a/.claude/skills/team-lifecycle-v2/templates/requirements-prd.md b/.claude/skills/team-lifecycle-v4/templates/requirements.md similarity index 100% rename from .claude/skills/team-lifecycle-v2/templates/requirements-prd.md rename to .claude/skills/team-lifecycle-v4/templates/requirements.md diff --git a/.claude/skills/team-lifecycle/SKILL.md b/.claude/skills/team-lifecycle/SKILL.md deleted file mode 100644 index 6013a663..00000000 --- a/.claude/skills/team-lifecycle/SKILL.md +++ /dev/null @@ -1,319 +0,0 @@ ---- -name: team-lifecycle -description: Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on "team lifecycle". -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) ---- - -# Team Lifecycle - -Unified team skill: specification -> implementation -> testing -> review. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. - -## Architecture - -``` -+---------------------------------------------------+ -| Skill(skill="team-lifecycle") | -| args="task description" | -+-------------------+-------------------------------+ - | - Orchestration Mode (auto -> coordinator) - | - Coordinator (inline) - Phase 0-5 orchestration - | - +----+-----+-------+-------+-------+-------+ - v v v v v v v - [team-worker agents, each loaded with a role-spec] - analyst writer planner executor tester reviewer - ^ ^ - on-demand by coordinator - +---------+ +--------+ - |architect| |fe-dev | - +---------+ +--------+ - +--------+ - | fe-qa | - +--------+ - - Utility Functions (callable by workers): - [multi-perspective discussion] - CLI tools for critique - [codebase exploration] - Explore agent with cache - [document generation] - CLI execution -``` - -## Role Router - -This skill is **coordinator-only**. Workers do NOT invoke this skill — they are spawned as `team-worker` agents directly. - -### Input Parsing - -Parse `$ARGUMENTS`. No `--role` needed — always routes to coordinator. - -### Role Registry - -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | RESEARCH-* | pipeline | false | -| writer | [role-specs/writer.md](role-specs/writer.md) | DRAFT-* | pipeline | true | -| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true | -| executor | [role-specs/executor.md](role-specs/executor.md) | IMPL-* | pipeline | true | -| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | pipeline | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* + QUALITY-* + IMPROVE-* | pipeline | false | -| architect | [role-specs/architect.md](role-specs/architect.md) | ARCH-* | consulting | false | -| fe-developer | [role-specs/fe-developer.md](role-specs/fe-developer.md) | DEV-FE-* | frontend | false | -| fe-qa | [role-specs/fe-qa.md](role-specs/fe-qa.md) | QA-FE-* | frontend | false | - -### Utility Functions - -| Function | Implementation | Callable By | Purpose | -|----------|----------------|-------------|---------| -| Multi-perspective discussion | CLI tools (ccw cli --mode analysis) | analyst, writer, reviewer | Multi-perspective critique | -| Codebase exploration | Explore agent | analyst, planner, any role | Codebase exploration with cache | -| Document generation | CLI tools (ccw cli --mode write) | writer | Document generation | - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User just provides task description. - -**Invocation**: `Skill(skill="team-lifecycle", args="task description")` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: requirement clarification -> TeamCreate -> create task chain - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker executes -> SendMessage callback -> coordinator advances next step - -> Loop until pipeline complete -> Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | -| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream | -| `feedback <text>` | Analyze feedback impact, create targeted revision chain | -| `recheck` | Re-run QUALITY-001 quality check | -| `improve [dimension]` | Auto-improve weakest dimension from readiness-report | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: - -``` -Agent({ - agent_type: "team-worker", - description: "Spawn <role> worker", - team_name: <team-name>, - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-lifecycle/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - -**Inner Loop roles** (writer, planner, executor): Set `inner_loop: true`. The team-worker agent handles the loop internally. - -**Single-task roles** (analyst, tester, reviewer, architect, fe-developer, fe-qa): Set `inner_loop: false`. - ---- - -## Pipeline Definitions - -### Spec-only (6 tasks) - -``` -RESEARCH-001(+D1) -> DRAFT-001(+D2) -> DRAFT-002(+D3) -> DRAFT-003(+D4) -> DRAFT-004(+D5) -> QUALITY-001(+D6) -``` - -### Impl-only (4 tasks) - -``` -PLAN-001 -> IMPL-001 -> TEST-001 + REVIEW-001 -``` - -### Full-lifecycle (10 tasks) - -``` -[Spec pipeline] -> PLAN-001(blockedBy: QUALITY-001) -> IMPL-001 -> TEST-001 + REVIEW-001 -``` - -### Frontend Pipelines - -``` -FE-only: PLAN-001 -> DEV-FE-001 -> QA-FE-001 - (GC loop: QA-FE verdict=NEEDS_FIX -> DEV-FE-002 -> QA-FE-002, max 2 rounds) - -Fullstack: PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001 - -Full + FE: [Spec pipeline] -> PLAN-001 -> IMPL-001 || DEV-FE-001 -> TEST-001 || QA-FE-001 -> REVIEW-001 -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker A] Phase 1-5 - | (parallel OK) --+--> [team-worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker B directly - | --> log fast_advance to message bus (coordinator syncs on next wake) - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -### Checkpoints - -| Trigger | Position | Behavior | -|---------|----------|----------| -| Spec->Impl transition | QUALITY-001 completed | Read readiness-report.md, display checkpoint, pause for user action | -| GC loop max | QA-FE max 2 rounds | Stop iteration, report current state | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Checkpoint Output Template** (QUALITY-001 completion): - -``` -[coordinator] ══════════════════════════════════════════ -[coordinator] SPEC PHASE COMPLETE -[coordinator] Quality Gate: <PASS|REVIEW|FAIL> (<score>%) -[coordinator] -[coordinator] Dimension Scores: -[coordinator] Completeness: <bar> <n>% -[coordinator] Consistency: <bar> <n>% -[coordinator] Traceability: <bar> <n>% -[coordinator] Depth: <bar> <n>% -[coordinator] Coverage: <bar> <n>% -[coordinator] -[coordinator] Available Actions: -[coordinator] resume -> Proceed to implementation -[coordinator] improve -> Auto-improve weakest dimension -[coordinator] improve <dimension> -> Improve specific dimension -[coordinator] revise <TASK-ID> -> Revise specific document -[coordinator] recheck -> Re-run quality check -[coordinator] feedback <text> -> Inject feedback, create revision -[coordinator] ══════════════════════════════════════════ -``` - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Inline Discuss | -|---------|------|-------|-------------|---------------| -| RESEARCH-001 | analyst | spec | (none) | DISCUSS-001 | -| DRAFT-001 | writer | spec | RESEARCH-001 | DISCUSS-002 | -| DRAFT-002 | writer | spec | DRAFT-001 | DISCUSS-003 | -| DRAFT-003 | writer | spec | DRAFT-002 | DISCUSS-004 | -| DRAFT-004 | writer | spec | DRAFT-003 | DISCUSS-005 | -| QUALITY-001 | reviewer | spec | DRAFT-004 | DISCUSS-006 | -| PLAN-001 | planner | impl | (none or QUALITY-001) | - | -| IMPL-001 | executor | impl | PLAN-001 | - | -| TEST-001 | tester | impl | IMPL-001 | - | -| REVIEW-001 | reviewer | impl | IMPL-001 | - | -| DEV-FE-001 | fe-developer | impl | PLAN-001 | - | -| QA-FE-001 | fe-qa | impl | DEV-FE-001 | - | - ---- - -## Session Directory - -``` -.workflow/.team/TLS-<slug>-<date>/ -+-- team-session.json -+-- spec/ -| +-- spec-config.json -| +-- discovery-context.json -| +-- product-brief.md -| +-- requirements/ -| +-- architecture/ -| +-- epics/ -| +-- readiness-report.md -| +-- spec-summary.md -+-- discussions/ -+-- plan/ -| +-- plan.json -| +-- .task/TASK-*.json -+-- explorations/ -| +-- cache-index.json -| +-- explore-<angle>.json -+-- architecture/ -+-- analysis/ -+-- qa/ -+-- wisdom/ -| +-- learnings.md -| +-- decisions.md -| +-- conventions.md -| +-- issues.md -+-- .msg/ -+-- shared-memory.json -``` - -## Session Resume - -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions -2. Multiple matches -> AskUserQuestion for selection -3. Audit TaskList -> reconcile session state <-> task status -4. Reset in_progress -> pending (interrupted tasks) -5. Rebuild team and spawn needed workers only -6. Create missing tasks with correct blockedBy -7. Kick first executable task -> Phase 4 coordination loop - -## Shared Resources - -| Resource | Path | Usage | -|----------|------|-------| -| Document Standards | [specs/document-standards.md](specs/document-standards.md) | YAML frontmatter, naming, structure | -| Quality Gates | [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gates | -| Team Config | [specs/team-config.json](specs/team-config.json) | Role registry, pipeline definitions | -| Product Brief Template | [templates/product-brief.md](templates/product-brief.md) | DRAFT-001 | -| Requirements Template | [templates/requirements-prd.md](templates/requirements-prd.md) | DRAFT-002 | -| Architecture Template | [templates/architecture-doc.md](templates/architecture-doc.md) | DRAFT-003 | -| Epics Template | [templates/epics-template.md](templates/epics-template.md) | DRAFT-004 | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Unknown command | Error with available command list | -| Role spec file not found | Error with expected path | -| Command file not found | Fallback to inline execution | -| Multi-perspective discussion fails | Worker proceeds without discuss, logs warning | -| Explore cache corrupt | Clear cache, re-explore | -| Fast-advance spawns wrong task | Coordinator reconciles on next callback | diff --git a/.claude/skills/team-lifecycle/role-specs/analyst.md b/.claude/skills/team-lifecycle/role-specs/analyst.md deleted file mode 100644 index 3ca73d08..00000000 --- a/.claude/skills/team-lifecycle/role-specs/analyst.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -role: analyst -prefix: RESEARCH -inner_loop: false -discuss_rounds: [DISCUSS-001] -cli_tools: [discuss] -message_types: - success: research_ready - progress: research_progress - error: error ---- - -# Analyst — Phase 2-4 - -## Phase 2: Seed Analysis - -**Objective**: Extract structured seed information from the topic/idea. - -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 - -## 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**: Use CLI exploration with Gemini. - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase for general context to inform spec generation -TASK: • Identify tech stack and frameworks • Map architecture patterns • Document conventions • List integration points -MODE: analysis -CONTEXT: @**/* | Memory: Seed analysis keywords: <keywords> -EXPECTED: JSON with: tech_stack[], architecture_patterns[], conventions[], integration_points[] -CONSTRAINTS: Focus on general context" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -Parse CLI output to build codebase context: tech_stack, architecture_patterns, conventions, integration_points. - -## Phase 4: Context Packaging + Inline Discuss - -### 4a: Context Packaging - -**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 - -**design-intelligence.json** → `<session-folder>/analysis/design-intelligence.json` (UI mode only): -- Produced when frontend keywords detected in seed_analysis -- Fields: industry, style_direction, ux_patterns, color_strategy, typography, component_patterns - -### 4b: Inline Discuss (DISCUSS-001) - -Invoke multi-perspective discussion using CLI tools: -- Artifact: `<session-folder>/spec/discovery-context.json` -- Round: DISCUSS-001 -- Perspectives: product, risk, coverage - -Handle discuss verdict per team-worker consensus handling protocol. - -**Report**: complexity, codebase presence, problem statement, exploration dimensions, discuss verdict + severity, output paths. - -## 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 | -| CLI exploration fails | Continue without codebase context | -| Multi-perspective discussion fails | Proceed without discuss, log warning | diff --git a/.claude/skills/team-lifecycle/role-specs/architect.md b/.claude/skills/team-lifecycle/role-specs/architect.md deleted file mode 100644 index 83949645..00000000 --- a/.claude/skills/team-lifecycle/role-specs/architect.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -role: architect -prefix: ARCH -inner_loop: false -discuss_rounds: [] -cli_tools: [explore] -message_types: - success: arch_ready - concern: arch_concern - error: error ---- - -# Architect — Phase 2-4 - -## Consultation Modes - -| Task Pattern | Mode | Focus | -|-------------|------|-------| -| ARCH-SPEC-* | spec-review | Review architecture docs | -| ARCH-PLAN-* | plan-review | Review plan soundness | -| ARCH-CODE-* | code-review | Assess code change impact | -| ARCH-CONSULT-* | consult | Answer architecture questions | -| ARCH-FEASIBILITY-* | feasibility | Technical feasibility | - -## Phase 2: Context Loading - -**Common**: session folder, wisdom, project-tech.json, explorations - -**Mode-specific**: - -| Mode | Additional Context | -|------|-------------------| -| spec-review | architecture/_index.md, ADR-*.md | -| plan-review | plan/plan.json | -| code-review | git diff, changed files | -| consult | Question from task description | -| feasibility | Requirements + codebase | - -## Phase 3: Assessment - -Analyze using mode-specific criteria. Output: mode, verdict (APPROVE/CONCERN/BLOCK), dimensions[], concerns[], recommendations[]. - -For complex questions → Gemini CLI with architecture review rule: - -``` -Bash({ - command: `ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architecture`, - run_in_background: true -}) -``` - -## Phase 4: Report - -Output to `<session-folder>/architecture/arch-<slug>.json`. Contribute decisions to wisdom/decisions.md. - -**Frontend project outputs** (when frontend tech stack detected): -- `<session-folder>/architecture/design-tokens.json` — color, spacing, typography, shadow tokens -- `<session-folder>/architecture/component-specs/*.md` — per-component design spec - -**Report**: mode, verdict, concern count, recommendations, output path(s). - -### Coordinator Integration - -| Timing | Task | -|--------|------| -| After DRAFT-003 | ARCH-SPEC-001: architecture doc review | -| After PLAN-001 | ARCH-PLAN-001: plan architecture review | -| On-demand | ARCH-CONSULT-001: architecture consultation | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Docs not found | Assess from available context | -| CLI timeout | Partial assessment | -| Insufficient context | Request explorer via coordinator | diff --git a/.claude/skills/team-lifecycle/role-specs/executor.md b/.claude/skills/team-lifecycle/role-specs/executor.md deleted file mode 100644 index 57e5c2ca..00000000 --- a/.claude/skills/team-lifecycle/role-specs/executor.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -role: executor -prefix: IMPL -inner_loop: true -discuss_rounds: [] -cli_tools: [] -message_types: - success: impl_complete - progress: impl_progress - error: error ---- - -# Executor — Phase 2-4 - -## Phase 2: Task & Plan Loading - -**Objective**: Load plan and determine execution strategy. - -1. Load plan.json and .task/TASK-*.json from `<session-folder>/plan/` - -**Backend selection** (priority order): - -| Priority | Source | Method | -|----------|--------|--------| -| 1 | Task metadata | task.metadata.executor field | -| 2 | Plan default | "Execution Backend:" in plan | -| 3 | Auto-select | Simple (< 200 chars, no refactor) → agent; Complex → codex | - -**Code review selection**: - -| Priority | Source | Method | -|----------|--------|--------| -| 1 | Task metadata | task.metadata.code_review field | -| 2 | Plan default | "Code Review:" in plan | -| 3 | Auto-select | Critical keywords (auth, security, payment) → enabled | - -## Phase 3: Code Implementation - -**Objective**: Execute implementation across batches. - -**Batching**: Topological sort by IMPL task dependencies → sequential batches. - -| Backend | Invocation | Use Case | -|---------|-----------|----------| -| gemini | `ccw cli --tool gemini --mode write` (foreground) | Simple, direct edits | -| codex | `ccw cli --tool codex --mode write` (foreground) | Complex, architecture | -| qwen | `ccw cli --tool qwen --mode write` (foreground) | Alternative backend | - -## Phase 4: Self-Validation - -| Step | Method | Pass Criteria | -|------|--------|--------------| -| Syntax check | `tsc --noEmit` (30s) | Exit code 0 | -| Acceptance criteria | Match criteria keywords vs implementation | All addressed | -| Test detection | Find .test.ts/.spec.ts for modified files | Tests identified | -| Code review (optional) | gemini analysis or codex review | No blocking issues | - -**Report**: task ID, status, files modified, validation results, backend used. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Syntax errors | Retry with error context (max 3) | -| Missing dependencies | Request from coordinator | -| Backend unavailable | Fallback to alternative tool | -| Circular dependencies | Abort, report graph | diff --git a/.claude/skills/team-lifecycle/role-specs/fe-developer.md b/.claude/skills/team-lifecycle/role-specs/fe-developer.md deleted file mode 100644 index e90ed42c..00000000 --- a/.claude/skills/team-lifecycle/role-specs/fe-developer.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -role: fe-developer -prefix: DEV-FE -inner_loop: false -discuss_rounds: [] -cli_tools: [] -message_types: - success: dev_fe_complete - progress: dev_fe_progress - error: error ---- - -# FE Developer — Phase 2-4 - -## Phase 2: Context Loading - -**Inputs to load**: -- Plan: `<session-folder>/plan/plan.json` -- Design tokens: `<session-folder>/architecture/design-tokens.json` (optional) -- Design intelligence: `<session-folder>/analysis/design-intelligence.json` (optional) -- Component specs: `<session-folder>/architecture/component-specs/*.md` (optional) -- Shared memory, wisdom - -**Tech stack detection**: - -| Signal | Framework | Styling | -|--------|-----------|---------| -| react/react-dom in deps | react | - | -| vue in deps | vue | - | -| next in deps | nextjs | - | -| tailwindcss in deps | - | tailwind | -| @shadcn/ui in deps | - | shadcn | - -## Phase 3: Frontend Implementation - -**Step 1**: Generate design token CSS (if tokens available) -- Convert design-tokens.json → CSS custom properties (`:root { --color-*, --space-*, --text-* }`) -- Include dark mode overrides via `@media (prefers-color-scheme: dark)` -- Write to `src/styles/tokens.css` - -**Step 2**: Implement components - -| Task Size | Strategy | -|-----------|----------| -| Simple (<= 3 files, single component) | `ccw cli --tool gemini --mode write` (foreground) | -| Complex (system, multi-component) | `ccw cli --tool codex --mode write` (foreground) | - -**Coding standards** (include in agent/CLI prompt): -- Use design token CSS variables, never hardcode colors/spacing -- Interactive elements: cursor: pointer -- Transitions: 150-300ms -- Text contrast: minimum 4.5:1 -- Include focus-visible styles -- Support prefers-reduced-motion -- Responsive: mobile-first -- No emoji as functional icons - -## Phase 4: Self-Validation - -| Check | What | -|-------|------| -| hardcoded-color | No #hex outside tokens.css | -| cursor-pointer | Interactive elements have cursor: pointer | -| focus-styles | Interactive elements have focus styles | -| responsive | Has responsive breakpoints | -| reduced-motion | Animations respect prefers-reduced-motion | -| emoji-icon | No emoji as functional icons | - -Contribute to wisdom/conventions.md. Update shared-memory.json with component inventory. - -**Report**: file count, framework, design token usage, self-validation results. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Design tokens not found | Use project defaults | -| Tech stack undetected | Default HTML + CSS | -| CLI failure | Retry with alternative tool | diff --git a/.claude/skills/team-lifecycle/role-specs/fe-qa.md b/.claude/skills/team-lifecycle/role-specs/fe-qa.md deleted file mode 100644 index f4deda1f..00000000 --- a/.claude/skills/team-lifecycle/role-specs/fe-qa.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -role: fe-qa -prefix: QA-FE -inner_loop: false -discuss_rounds: [] -cli_tools: [] -message_types: - success: qa_fe_passed - result: qa_fe_result - fix: fix_required - error: error ---- - -# FE QA — Phase 2-4 - -## Review Dimensions - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Code Quality | 25% | TypeScript types, component structure, error handling | -| Accessibility | 25% | Semantic HTML, ARIA, keyboard nav, contrast, focus-visible | -| Design Compliance | 20% | Token usage, no hardcoded colors, no emoji icons | -| UX Best Practices | 15% | Loading/error/empty states, cursor-pointer, responsive | -| Pre-Delivery | 15% | No console.log, dark mode, i18n readiness | - -## Phase 2: Context Loading - -**Inputs**: design tokens, design intelligence, shared memory, previous QA results (for GC round tracking), changed frontend files via git diff. - -Determine GC round from previous QA results count. Max 2 rounds. - -## Phase 3: 5-Dimension Review - -For each changed frontend file, check against all 5 dimensions. Score each dimension 0-10, deducting for issues found. - -**Scoring deductions**: - -| Severity | Deduction | -|----------|-----------| -| High | -2 to -3 | -| Medium | -1 to -1.5 | -| Low | -0.5 | - -**Overall score** = weighted sum of dimension scores. - -**Verdict routing**: - -| Condition | Verdict | -|-----------|---------| -| Score >= 8 AND no critical issues | PASS | -| GC round >= max AND score >= 6 | PASS_WITH_WARNINGS | -| GC round >= max AND score < 6 | FAIL | -| Otherwise | NEEDS_FIX | - -## Phase 4: Report - -Write audit to `<session-folder>/qa/audit-fe-<task>-r<round>.json`. Update wisdom and shared memory. - -**Report**: round, verdict, overall score, dimension scores, critical issues with Do/Don't format, action required (if NEEDS_FIX). - -### Generator-Critic Loop - -Orchestrated by coordinator: -``` -Round 1: DEV-FE-001 → QA-FE-001 - if NEEDS_FIX → coordinator creates DEV-FE-002 + QA-FE-002 -Round 2: DEV-FE-002 → QA-FE-002 - if still NEEDS_FIX → PASS_WITH_WARNINGS or FAIL (max 2) -``` - -**Convergence**: score >= 8 AND critical_count = 0 - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No changed files | Report empty, score N/A | -| Design tokens not found | Skip design compliance, adjust weights | -| Max GC rounds exceeded | Force verdict | diff --git a/.claude/skills/team-lifecycle/role-specs/planner.md b/.claude/skills/team-lifecycle/role-specs/planner.md deleted file mode 100644 index 3012c863..00000000 --- a/.claude/skills/team-lifecycle/role-specs/planner.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -role: planner -prefix: PLAN -inner_loop: true -discuss_rounds: [] -cli_tools: [explore] -message_types: - success: plan_ready - revision: plan_revision - error: error ---- - -# Planner — Phase 2-4 - -## Phase 1.5: Load Spec Context (Full-Lifecycle) - -If `<session-folder>/spec/` exists → load requirements/_index.md, architecture/_index.md, epics/_index.md, spec-config.json. Otherwise → impl-only mode. - -**Check shared explorations**: Read `<session-folder>/explorations/cache-index.json` to see if analyst already cached useful explorations. Reuse rather than re-explore. - -## Phase 2: Multi-Angle Exploration - -**Objective**: Explore codebase to inform planning. - -**Complexity routing**: - -| Complexity | Criteria | Strategy | -|------------|----------|----------| -| Low | < 200 chars, no refactor/architecture keywords | ACE semantic search only | -| Medium | 200-500 chars or moderate scope | 2-3 angle CLI explore | -| High | > 500 chars, refactor/architecture, multi-module | 3-5 angle CLI explore | - -For each angle, use CLI exploration (cache-aware — check cache-index.json before each call): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Explore codebase from <angle> perspective to inform planning -TASK: • Search for <angle>-specific patterns • Identify relevant files • Document integration points -MODE: analysis -CONTEXT: @**/* | Memory: Task keywords: <keywords> -EXPECTED: JSON with: relevant_files[], patterns[], integration_points[], recommendations[] -CONSTRAINTS: Focus on <angle> perspective" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, - run_in_background: false -}) -``` - -## Phase 3: Plan Generation - -**Objective**: Generate structured implementation plan. - -| Complexity | Strategy | -|------------|----------| -| Low | Direct planning → single TASK-001 with plan.json | -| Medium/High | cli-lite-planning-agent with exploration results | - -**CLI call** (Medium/High): - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate structured implementation plan from exploration results -TASK: • Create plan.json with overview • Generate TASK-*.json files (2-7 tasks) • Define dependencies • Set convergence criteria -MODE: write -CONTEXT: @<session-folder>/explorations/*.json | Memory: Complexity: <complexity> -EXPECTED: Files: plan.json + .task/TASK-*.json. Schema: ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json -CONSTRAINTS: 2-7 tasks, include id/title/files[].change/convergence.criteria/depends_on" --tool gemini --mode write --rule planning-breakdown-task-steps`, - run_in_background: false -}) -``` - -**Spec context** (full-lifecycle): Reference REQ-* IDs, follow ADR decisions, reuse Epic/Story decomposition. - -## Phase 4: Submit for Approval - -1. Read plan.json and TASK-*.json -2. Report to coordinator: complexity, task count, task list, approach, plan location -3. Wait for response: approved → complete; revision → update and resubmit - -**Session files**: -``` -<session-folder>/explorations/ (shared cache) -+-- cache-index.json -+-- explore-<angle>.json - -<session-folder>/plan/ -+-- explorations-manifest.json -+-- plan.json -+-- .task/TASK-*.json -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI exploration failure | Plan from description only | -| CLI planning failure | Fallback to direct planning | -| Plan rejected 3+ times | Notify coordinator, suggest alternative | -| Schema not found | Use basic structure | -| Cache index corrupt | Clear cache, re-explore all angles | diff --git a/.claude/skills/team-lifecycle/role-specs/reviewer.md b/.claude/skills/team-lifecycle/role-specs/reviewer.md deleted file mode 100644 index 498e4a60..00000000 --- a/.claude/skills/team-lifecycle/role-specs/reviewer.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -role: reviewer -prefix: REVIEW -additional_prefixes: [QUALITY, IMPROVE] -inner_loop: false -discuss_rounds: [DISCUSS-006] -cli_tools: [discuss] -message_types: - success_review: review_result - success_quality: quality_result - fix: fix_required - error: error ---- - -# Reviewer — Phase 2-4 - -## Phase 2: Mode Detection - -| Task Prefix | Mode | Dimensions | Inline Discuss | -|-------------|------|-----------|---------------| -| REVIEW-* | Code Review | quality, security, architecture, requirements | None | -| QUALITY-* | Spec Quality | completeness, consistency, traceability, depth, coverage | DISCUSS-006 | -| IMPROVE-* | Spec Quality (recheck) | Same as QUALITY | DISCUSS-006 | - -## Phase 3: Review Execution - -### Code Review (REVIEW-*) - -**Inputs**: Plan file, git diff, modified files, test results (if available) - -**4 dimensions**: - -| Dimension | Critical Issues | -|-----------|----------------| -| Quality | Empty catch, any in public APIs, @ts-ignore, console.log | -| Security | Hardcoded secrets, SQL injection, eval/exec, innerHTML | -| Architecture | Circular deps, parent imports >2 levels, files >500 lines | -| Requirements | Missing core functionality, incomplete acceptance criteria | - -### Spec Quality (QUALITY-* / IMPROVE-*) - -**Inputs**: All spec docs in session folder, quality gate config - -**5 dimensions**: - -| Dimension | Weight | Focus | -|-----------|--------|-------| -| Completeness | 25% | All sections present with substance | -| Consistency | 20% | Terminology, format, references | -| Traceability | 25% | Goals -> Reqs -> Arch -> Stories chain | -| Depth | 20% | AC testable, ADRs justified, stories estimable | -| Coverage | 10% | Original requirements mapped | - -**Quality gate**: - -| Gate | Criteria | -|------|----------| -| PASS | Score >= 80% AND coverage >= 70% | -| REVIEW | Score 60-79% OR coverage 50-69% | -| FAIL | Score < 60% OR coverage < 50% | - -**Artifacts**: readiness-report.md + spec-summary.md - -## Phase 4: Verdict + Inline Discuss - -### Code Review Verdict - -| Verdict | Criteria | -|---------|----------| -| BLOCK | Critical issues present | -| CONDITIONAL | High/medium only | -| APPROVE | Low or none | - -### Spec Quality Inline Discuss (DISCUSS-006) - -After generating readiness-report.md, call CLI discuss tool: -- Artifact: `<session-folder>/spec/readiness-report.md` -- Round: DISCUSS-006 -- Perspectives: product, technical, quality, risk, coverage (all 5) - -```bash -ccw cli -p "PURPOSE: Multi-perspective critique of spec readiness -TASK: Review from product, technical, quality, risk, coverage perspectives -ARTIFACT: @<session-folder>/spec/readiness-report.md -MODE: analysis -EXPECTED: JSON with perspectives[], consensus, severity, recommendations[]" --tool gemini --mode analysis -``` - -Handle discuss verdict per team-worker consensus handling protocol. - -> **Note**: DISCUSS-006 HIGH always triggers user pause (final sign-off gate), regardless of revision count. - -**Report**: mode, verdict/gate, dimension scores, discuss verdict (QUALITY only), output paths. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Missing context | Request from coordinator | -| Invalid mode | Abort with error | -| Analysis failure | Retry, then fallback template | -| CLI discuss fails | Proceed without final discuss, log warning | diff --git a/.claude/skills/team-lifecycle/role-specs/tester.md b/.claude/skills/team-lifecycle/role-specs/tester.md deleted file mode 100644 index 34fae37a..00000000 --- a/.claude/skills/team-lifecycle/role-specs/tester.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -role: tester -prefix: TEST -inner_loop: false -discuss_rounds: [] -cli_tools: [] -message_types: - success: test_result - fix: fix_required - error: error ---- - -# Tester — Phase 2-4 - -## Phase 2: Framework Detection & Test Discovery - -**Framework detection** (priority order): - -| Priority | Method | Frameworks | -|----------|--------|-----------| -| 1 | package.json devDependencies | vitest, jest, mocha, pytest | -| 2 | package.json scripts.test | vitest, jest, mocha, pytest | -| 3 | Config files | vitest.config.*, jest.config.*, pytest.ini | - -**Affected test discovery** from executor's modified files: -- Search variants: `<name>.test.ts`, `<name>.spec.ts`, `tests/<name>.test.ts`, `__tests__/<name>.test.ts` - -## Phase 3: Test Execution & Fix Cycle - -**Config**: MAX_ITERATIONS=10, PASS_RATE_TARGET=95%, AFFECTED_TESTS_FIRST=true - -1. Run affected tests → parse results -2. Pass rate met → run full suite -3. Failures → select strategy → fix → re-run → repeat - -**Strategy selection**: - -| Condition | Strategy | Behavior | -|-----------|----------|----------| -| Iteration <= 3 or pass >= 80% | Conservative | Fix one critical failure at a time | -| Critical failures < 5 | Surgical | Fix specific pattern everywhere | -| Pass < 50% or iteration > 7 | Aggressive | Fix all failures in batch | - -**Test commands**: - -| Framework | Affected | Full Suite | -|-----------|---------|------------| -| vitest | `vitest run <files>` | `vitest run` | -| jest | `jest <files> --no-coverage` | `jest --no-coverage` | -| pytest | `pytest <files> -v` | `pytest -v` | - -## Phase 4: Result Analysis - -**Failure classification**: - -| Severity | Patterns | -|----------|----------| -| Critical | SyntaxError, cannot find module, undefined | -| High | Assertion failures, toBe/toEqual | -| Medium | Timeout, async errors | -| Low | Warnings, deprecations | - -**Report routing**: - -| Condition | Type | -|-----------|------| -| Pass rate >= target | test_result (success) | -| Pass rate < target after max iterations | fix_required | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Framework not detected | Prompt user | -| No tests found | Report to coordinator | -| Infinite fix loop | Abort after MAX_ITERATIONS | diff --git a/.claude/skills/team-lifecycle/role-specs/writer.md b/.claude/skills/team-lifecycle/role-specs/writer.md deleted file mode 100644 index 9867080f..00000000 --- a/.claude/skills/team-lifecycle/role-specs/writer.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -role: writer -prefix: DRAFT -inner_loop: true -discuss_rounds: [DISCUSS-002, DISCUSS-003, DISCUSS-004, DISCUSS-005] -cli_tools: [discuss] -message_types: - success: draft_ready - revision: draft_revision - error: error ---- - -# Writer — Phase 2-4 - -## Phase 2: Context Loading - -**Objective**: Load all required inputs for document generation. - -### Document type routing - -| Task Subject Contains | Doc Type | Template | Prior Discussion Input | -|----------------------|----------|----------|----------------------| -| Product Brief | product-brief | templates/product-brief.md | discussions/DISCUSS-001-discussion.md | -| Requirements / PRD | requirements | templates/requirements-prd.md | discussions/DISCUSS-002-discussion.md | -| Architecture | architecture | templates/architecture-doc.md | discussions/DISCUSS-003-discussion.md | -| Epics | epics | templates/epics-template.md | discussions/DISCUSS-004-discussion.md | - -### Inline discuss mapping - -| Doc Type | Inline Discuss Round | Perspectives | -|----------|---------------------|-------------| -| product-brief | DISCUSS-002 | product, technical, quality, coverage | -| requirements | DISCUSS-003 | quality, product, coverage | -| architecture | DISCUSS-004 | technical, risk | -| epics | DISCUSS-005 | product, technical, quality, coverage | - -### Progressive dependency loading - -| Doc Type | Requires | -|----------|----------| -| product-brief | discovery-context.json | -| requirements | + product-brief.md | -| architecture | + requirements/_index.md | -| epics | + architecture/_index.md | - -**Prior decisions from accumulator**: Pass context_accumulator summaries as "Prior Decisions" to CLI tool. - -| Input | Source | Required | -|-------|--------|----------| -| Document standards | `../../specs/document-standards.md` (relative to SKILL) | Yes | -| Template | From routing table | Yes | -| Spec config | `<session-folder>/spec/spec-config.json` | Yes | -| Discovery context | `<session-folder>/spec/discovery-context.json` | Yes | -| Discussion feedback | `<session-folder>/discussions/<discuss-file>` | If exists | -| Prior decisions | context_accumulator (in-memory) | If prior tasks exist | - -## Phase 3: CLI Document Generation - -**Objective**: Generate document using CLI tool. - -Use Gemini CLI for document generation: - -``` -Bash({ - command: `ccw cli -p "PURPOSE: Generate <doc-type> document following template and standards -TASK: • Load template from <template-path> • Apply spec config and discovery context • Integrate prior discussion feedback • Generate all required sections -MODE: write -CONTEXT: @<session-folder>/spec/*.json @<template-path> | Memory: Prior decisions: <context_accumulator summary> -EXPECTED: Document at <output-path> with: YAML frontmatter, all template sections, cross-references, session_id -CONSTRAINTS: Follow document-standards.md" --tool gemini --mode write --rule development-implement-feature --cd <session-folder>`, - run_in_background: false -}) -``` - -Parse CLI output for artifact path and summary. Document is written to disk by CLI. - -## Phase 4: Self-Validation + Inline Discuss - -### 4a: Self-Validation - -| Check | What to Verify | -|-------|---------------| -| has_frontmatter | Starts with YAML frontmatter | -| sections_complete | All template sections present | -| cross_references | session_id included | -| discussion_integrated | Reflects prior round feedback (if exists) | - -### 4b: Inline Discuss - -Call CLI discuss tool for this task's discuss round: -- Artifact: `<output-path>` (the generated document) -- Round: `<DISCUSS-NNN>` from mapping table -- Perspectives: from mapping table - -```bash -ccw cli -p "PURPOSE: Multi-perspective critique of <doc-type> -TASK: Review from <perspectives> -ARTIFACT: @<output-path> -MODE: analysis -EXPECTED: JSON with perspectives[], consensus, severity, recommendations[]" --tool gemini --mode analysis -``` - -Handle discuss verdict per team-worker consensus handling protocol. - -**Report**: doc type, validation status, discuss verdict + severity, average rating, summary, output path. - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| CLI failure | Retry once with alternative tool. Still fails → log error, continue next task | -| CLI discuss fails | Skip discuss, log warning | -| Cumulative 3 task failures | SendMessage to coordinator, STOP | -| Prior doc not found | Notify coordinator, request prerequisite | -| Discussion contradicts prior docs | Note conflict, flag for coordinator | diff --git a/.claude/skills/team-lifecycle/roles/coordinator/commands/dispatch.md b/.claude/skills/team-lifecycle/roles/coordinator/commands/dispatch.md deleted file mode 100644 index dfbab431..00000000 --- a/.claude/skills/team-lifecycle/roles/coordinator/commands/dispatch.md +++ /dev/null @@ -1,218 +0,0 @@ -# Command: dispatch - -## Purpose - -Create task chains based on execution mode. v5: uses team-worker agent for all spawns. Task descriptions include role_spec paths. - -## Phase 2: Context Loading - -| Input | Source | Required | -|-------|--------|----------| -| Mode | Phase 1 requirements | Yes | -| Session folder | Phase 2 session init | Yes | -| Scope | User requirements description | Yes | -| Spec file | User-provided path (impl-only mode only) | Conditional | - -## Phase 3: Task Chain Creation - -### Mode-to-Pipeline Routing - -| Mode | Tasks | Pipeline | First Task | -|------|-------|----------|------------| -| spec-only | 6 | Spec pipeline | RESEARCH-001 | -| impl-only | 4 | Impl pipeline | PLAN-001 | -| fe-only | 3 | FE pipeline | PLAN-001 | -| fullstack | 6 | Fullstack pipeline | PLAN-001 | -| full-lifecycle | 10 | Spec + Impl | RESEARCH-001 | -| full-lifecycle-fe | 12 | Spec + Fullstack | RESEARCH-001 | - ---- - -### Spec Pipeline (6 tasks) - -| # | Subject | Owner | BlockedBy | Description | Inline Discuss | -|---|---------|-------|-----------|-------------|---------------| -| 1 | RESEARCH-001 | analyst | (none) | Seed analysis and context gathering | DISCUSS-001 | -| 2 | DRAFT-001 | writer | RESEARCH-001 | Generate Product Brief | DISCUSS-002 | -| 3 | DRAFT-002 | writer | DRAFT-001 | Generate Requirements/PRD | DISCUSS-003 | -| 4 | DRAFT-003 | writer | DRAFT-002 | Generate Architecture Document | DISCUSS-004 | -| 5 | DRAFT-004 | writer | DRAFT-003 | Generate Epics & Stories | DISCUSS-005 | -| 6 | QUALITY-001 | reviewer | DRAFT-004 | 5-dimension spec quality + sign-off | DISCUSS-006 | - -### Impl Pipeline (4 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Multi-angle exploration and planning | -| 2 | IMPL-001 | executor | PLAN-001 | Code implementation | -| 3 | TEST-001 | tester | IMPL-001 | Test-fix cycles | -| 4 | REVIEW-001 | reviewer | IMPL-001 | 4-dimension code review | - -### FE Pipeline (3 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Planning (frontend focus) | -| 2 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | -| 3 | QA-FE-001 | fe-qa | DEV-FE-001 | 5-dimension frontend QA | - -GC loop (max 2 rounds): QA-FE verdict=NEEDS_FIX -> create DEV-FE-002 + QA-FE-002 dynamically. - -### Fullstack Pipeline (6 tasks) - -| # | Subject | Owner | BlockedBy | Description | -|---|---------|-------|-----------|-------------| -| 1 | PLAN-001 | planner | (none) | Fullstack planning | -| 2 | IMPL-001 | executor | PLAN-001 | Backend implementation | -| 3 | DEV-FE-001 | fe-developer | PLAN-001 | Frontend implementation | -| 4 | TEST-001 | tester | IMPL-001 | Backend test-fix cycles | -| 5 | QA-FE-001 | fe-qa | DEV-FE-001 | Frontend QA | -| 6 | REVIEW-001 | reviewer | TEST-001, QA-FE-001 | Full code review | - -### Composite Modes - -| Mode | Construction | PLAN-001 BlockedBy | -|------|-------------|-------------------| -| full-lifecycle | Spec (6) + Impl (4) | QUALITY-001 | -| full-lifecycle-fe | Spec (6) + Fullstack (6) | QUALITY-001 | - ---- - -### Task Description Template - -Every task description uses structured format for clarity: - -``` -TaskCreate({ - subject: "<TASK-ID>", - - description: "PURPOSE: <what this task achieves> | Success: <measurable completion criteria> -TASK: - - <step 1: specific action> - - <step 2: specific action> - - <step 3: specific action> -CONTEXT: - - Session: <session-folder> - - Scope: <scope> - - Upstream artifacts: <artifact-1.md>, <artifact-2.md> - - Key files: <file1>, <file2> (if applicable) - - Shared memory: <session>/shared-memory.json -EXPECTED: <deliverable path> + <quality criteria> -CONSTRAINTS: <scope limits, focus areas> ---- -InlineDiscuss: <DISCUSS-NNN or none> -InnerLoop: <true|false>", - addBlockedBy: [<dependency-list>] - -}) -``` - -**Field Guidelines**: -- **PURPOSE**: Clear goal statement + success criteria -- **TASK**: 2-5 actionable steps with specific verbs -- **CONTEXT**: Session path, scope, upstream artifacts, relevant files -- **EXPECTED**: Output artifact path + quality requirements -- **CONSTRAINTS**: Scope boundaries, focus areas, exclusions - -**InnerLoop Flag Rules**: - -| Role | InnerLoop | -|------|-----------| -| writer (DRAFT-*) | true | -| planner (PLAN-*) | true | -| executor (IMPL-*) | true | -| analyst, tester, reviewer, architect, fe-developer, fe-qa | false | - -### Revision Task Template - -``` -TaskCreate({ - subject: "<ORIGINAL-ID>-R1", - owner: "<same-role-as-original>", - description: "PURPOSE: <revision-type> revision of <ORIGINAL-ID> | Success: Address feedback and pass quality checks -TASK: - - Review original artifact and feedback - - Apply targeted fixes to weak areas - - Validate against quality criteria -CONTEXT: - - Session: <session-folder> - - Original artifact: <artifact-path> - - User feedback: <feedback-text or 'system-initiated'> - - Revision scope: <targeted|full> - - Shared memory: <session>/shared-memory.json -EXPECTED: Updated artifact at <artifact-path> + revision summary -CONSTRAINTS: <revision scope limits> ---- -InlineDiscuss: <same-discuss-round-as-original> -InnerLoop: <true|false based on role>", - status: "pending", - blockedBy: [<predecessor-R1 if cascaded>] -}) -``` - -**Revision naming**: `<ORIGINAL-ID>-R1` (max 1 revision per task; second -> `-R2`; third -> escalate to user) - -**Cascade Rules**: - -| Revised Task | Downstream (auto-cascade) | -|-------------|--------------------------| -| RESEARCH-001 | DRAFT-001~004-R1, QUALITY-001-R1 | -| DRAFT-001 | DRAFT-002~004-R1, QUALITY-001-R1 | -| DRAFT-002 | DRAFT-003~004-R1, QUALITY-001-R1 | -| DRAFT-003 | DRAFT-004-R1, QUALITY-001-R1 | -| DRAFT-004 | QUALITY-001-R1 | -| QUALITY-001 | (no cascade, just recheck) | - -### Improvement Task Template - -``` -TaskCreate({ - subject: "IMPROVE-<dimension>-001", - owner: "writer", - description: "PURPOSE: Improve <dimension> quality from <X>% to 80% | Success: Pass quality threshold -TASK: - - Review readiness report weak areas - - Apply dimension-specific improvement strategy - - Validate improvements against criteria -CONTEXT: - - Session: <session-folder> - - Current score: <X>% - - Target: 80% - - Readiness report: <session>/spec/readiness-report.md - - Weak areas: <extracted-from-report> - - Strategy: <from-dimension-strategy-table> - - Shared memory: <session>/shared-memory.json -EXPECTED: Improved artifacts + quality improvement summary -CONSTRAINTS: Focus on <dimension> only ---- -InnerLoop: true", - -}) -``` - -Improvement tasks always followed by QUALITY-001-R1 recheck (blockedBy: IMPROVE task). - -### Impl-Only Pre-check - -Before creating impl-only tasks, verify specification exists: -- Spec exists? YES -> read spec path -> proceed -- NO -> error: "impl-only requires existing spec" - -## Phase 4: Validation - -| Check | Criteria | -|-------|----------| -| Task count | Matches mode total | -| Dependencies | Every blockedBy references existing task subject | -| Owner assignment | Each task owner matches Role Registry prefix | -| Session reference | Every task contains `Session: <session-folder>` | -| Inline discuss | Spec tasks have InlineDiscuss field | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Unknown mode | Reject with supported mode list | -| Missing spec for impl-only | Error, suggest spec-only or full-lifecycle | -| TaskCreate fails | Log error, report to user | -| Duplicate task subject | Skip creation, log warning | diff --git a/.claude/skills/team-lifecycle/roles/coordinator/commands/monitor.md b/.claude/skills/team-lifecycle/roles/coordinator/commands/monitor.md deleted file mode 100644 index 8b9cacfe..00000000 --- a/.claude/skills/team-lifecycle/roles/coordinator/commands/monitor.md +++ /dev/null @@ -1,249 +0,0 @@ -# Command: monitor - -## Purpose - -Event-driven pipeline coordination with Spawn-and-Stop pattern. v5: spawns team-worker agents instead of general-purpose. Three wake-up sources: worker callbacks, user `check`, user `resume`. - -## Constants - -| Constant | Value | Description | -|----------|-------|-------------| -| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` | -| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS | -| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors | -| WORKER_AGENT | team-worker | All workers are team-worker agents | - -## Phase 2: Context Loading - -| Input | Source | Required | -|-------|--------|----------| -| Session file | `<session-folder>/team-session.json` | Yes | -| Task list | `TaskList()` | Yes | -| Active workers | session.active_workers[] | Yes | -| Pipeline mode | session.mode | Yes | - -## Phase 3: Handler Routing - -### Wake-up Source Detection - -| Priority | Condition | Handler | -|----------|-----------|---------| -| 1 | Message contains `[<role-name>]` from known worker role | handleCallback | -| 2 | Contains "check" or "status" | handleCheck | -| 3 | Contains "resume", "continue", or "next" | handleResume | -| 4 | None of the above (initial spawn) | handleSpawnNext | -| 5 | Contains "revise" + task ID | handleRevise | -| 6 | Contains "feedback" + text | handleFeedback | -| 7 | Contains "recheck" | handleRecheck | -| 8 | Contains "improve" | handleImprove | - -Known worker roles: analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa. - ---- - -### Handler: handleCallback - -``` -Receive callback from [<role>] - +- Find matching active worker by role - +- Progress update (not final)? - | +- YES -> Update session, do NOT remove from active_workers -> STOP - +- Task status = completed? - | +- YES -> remove from active_workers -> update session - | | +- Handle checkpoints - | | +- -> handleSpawnNext - | +- NO -> progress message -> STOP - +- No matching worker found - +- Scan all active workers for completed tasks - +- Found completed -> process -> handleSpawnNext - +- None completed -> STOP -``` - -**Fast-advance reconciliation**: When processing any callback or resume: -1. Read recent `fast_advance` messages from team_msg (type="fast_advance") -2. For each: add spawned successor to `active_workers` if not already present -3. Check if expected next task is already `in_progress` (fast-advanced) -4. If yes -> skip spawning (already running) -5. If no -> normal handleSpawnNext - ---- - -### Handler: handleCheck - -Read-only status report. No advancement. - -``` -[coordinator] Pipeline Status (v5) -[coordinator] Mode: <mode> | Progress: <completed>/<total> (<percent>%) - -[coordinator] Execution Graph: - Spec Phase: - [<icon> RESEARCH-001(+D1)] -> [<icon> DRAFT-001(+D2)] -> ... - Impl Phase: - [<icon> PLAN-001] - +- BE: [<icon> IMPL-001] -> [<icon> TEST-001] -> [<icon> REVIEW-001] - +- FE: [<icon> DEV-FE-001] -> [<icon> QA-FE-001] - - done=completed >>>=running o=pending .=not created - -[coordinator] Active Workers: - > <subject> (<role>) - running <elapsed> - -[coordinator] Ready to spawn: <subjects> -[coordinator] Commands: 'resume' to advance | 'check' to refresh -``` - -Then STOP. - ---- - -### Handler: handleResume - -``` -Load active_workers - +- No active workers -> handleSpawnNext - +- Has active workers -> check each: - +- completed -> mark done, log - +- in_progress -> still running - +- other -> worker failure -> reset to pending - After: - +- Some completed -> handleSpawnNext - +- All running -> report status -> STOP - +- All failed -> handleSpawnNext (retry) -``` - ---- - -### Handler: handleSpawnNext - -``` -Collect task states from TaskList() - +- readySubjects: pending + all blockedBy completed - +- NONE + work in progress -> report waiting -> STOP - +- NONE + nothing running -> PIPELINE_COMPLETE -> Phase 5 - +- HAS ready tasks -> for each: - +- Inner Loop role AND already has active_worker? - | +- YES -> SKIP spawn (existing worker picks up via inner loop) - | +- NO -> spawn below - +- TaskUpdate -> in_progress - +- team_msg log -> task_unblocked - +- Spawn team-worker: - Agent({ - agent_type: "team-worker", - description: "Spawn <role> worker for <subject>", - team_name: <team-name>, - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-lifecycle/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: <true|false>` - }) - +- Add to session.active_workers - Update session -> output summary -> STOP -``` - ---- - -### Handler: handleRevise - -``` -Parse: revise <TASK-ID> [feedback-text] - +- Validate TASK-ID exists and is completed - +- Create revision task (see dispatch.md Revision Task Template) - +- Cascade downstream completed tasks - +- Spawn worker for first revision task -> STOP -``` - -### Handler: handleFeedback - -``` -Parse: feedback <text> - +- Determine pipeline state -> find affected task - +- Write feedback to wisdom/decisions.md - +- Create revision chain - +- Spawn worker -> STOP -``` - -### Handler: handleRecheck - -``` -Parse: recheck - +- Create QUALITY-001-R1 task - +- Spawn reviewer -> STOP -``` - -### Handler: handleImprove - -``` -Parse: improve [dimension] - +- Read readiness-report.md -> extract dimension scores - +- Select target dimension (specified or lowest) - +- Create IMPROVE-<dimension>-001 task - +- Create QUALITY-001-R1 (blockedBy: IMPROVE task) - +- Spawn writer -> STOP -``` - ---- - -### Checkpoints - -| Completed Task | Mode Condition | Action | -|---------------|----------------|--------| -| QUALITY-001 | full-lifecycle or full-lifecycle-fe | Read readiness-report.md -> checkpoint template -> pause | - -### Worker Failure Handling - -1. Reset task -> pending via TaskUpdate -2. Log via team_msg (type: error) -3. Report to user - -### Fast-Advance Failure Recovery - -``` -Detect orphaned in_progress task (no active_worker): - +- Check creation time: if > 5 min with no progress - +- Reset to pending -> handleSpawnNext -``` - -### Fast-Advance State Sync - -On every coordinator wake (handleCallback, handleResume, handleCheck): -1. Read team_msg entries with `type="fast_advance"` since last coordinator wake -2. For each entry: sync `active_workers` with the spawned successor -3. This ensures coordinator's state reflects fast-advance decisions even before the successor's callback arrives - -### Consensus-Blocked Handling - -``` -handleCallback receives consensus_blocked: - +- severity = HIGH - | +- DISCUSS-006? -> PAUSE for user - | +- Other -> Create REVISION task (max 1 per task) - +- severity = MEDIUM -> proceed with warning, log to wisdom/issues.md - +- severity = LOW -> proceed normally -``` - -## Phase 4: Validation - -| Check | Criteria | -|-------|----------| -| Session state consistent | active_workers matches in_progress tasks | -| No orphaned tasks | Every in_progress has active_worker | -| Pipeline completeness | All expected tasks exist | -| Fast-advance tracking | Detect already-running tasks, sync active_workers | - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Session file not found | Error, suggest re-initialization | -| Unknown role callback | Log, scan for other completions | -| All workers running on resume | Report status, suggest check later | -| Pipeline stall | Check missing tasks, report | -| Fast-advance orphan | Reset to pending, re-spawn | -| consensus_blocked HIGH | Revision or pause | diff --git a/.claude/skills/team-lifecycle/roles/coordinator/role.md b/.claude/skills/team-lifecycle/roles/coordinator/role.md deleted file mode 100644 index 7bebabaa..00000000 --- a/.claude/skills/team-lifecycle/roles/coordinator/role.md +++ /dev/null @@ -1,213 +0,0 @@ -# Coordinator Role - -Orchestrate the team-lifecycle workflow: team creation, task dispatching, progress monitoring, session state. Uses **team-worker agent** for all worker spawns — no Skill indirection. - -## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results - -## Boundaries - -### MUST -- Parse user requirements and clarify ambiguous inputs via AskUserQuestion -- Create team and spawn worker agents in background using **team-worker** agent type -- Dispatch tasks with proper dependency chains (see SKILL.md Task Metadata Registry) -- Monitor progress via worker callbacks and route messages -- Maintain session state persistence (team-session.json) - -### MUST NOT -- Execute spec/impl/research work directly (delegate to workers) -- Modify task outputs (workers own their deliverables) -- Skip dependency validation when creating task chains - ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** - NOT separate agents or subprocesses -4. **Execute synchronously** - complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- - -## Entry Router - -When coordinator is invoked, detect invocation type: - -| Detection | Condition | Handler | -|-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Interrupted session | Active/paused session exists in `.workflow/.team/TLS-*` | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | - -For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/TLS-*/team-session.json` for active/paused sessions - - If found, extract known worker roles from session or SKILL.md Role Registry - -2. **Parse $ARGUMENTS** for detection keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler section, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- - -## Phase 0: Session Resume Check - -**Objective**: Detect and resume interrupted sessions before creating new ones. - -1. Scan `.workflow/.team/TLS-*/team-session.json` for sessions with status "active" or "paused" -2. No sessions found -> proceed to Phase 1 -3. Single session found -> resume it (-> Session Reconciliation) -4. Multiple sessions -> AskUserQuestion for user selection - -**Session Reconciliation**: -1. Audit TaskList -> get real status of all tasks -2. Reconcile: session.completed_tasks <-> TaskList status -3. Reset any in_progress tasks -> pending (they were interrupted) -4. Determine remaining pipeline from reconciled state -5. Rebuild team if disbanded (TeamCreate + spawn needed workers only) -6. Create missing tasks with correct blockedBy dependencies -7. Verify dependency chain integrity -8. Update session file with reconciled state -9. Kick first executable task's worker -> Phase 4 - ---- - -## Phase 1: Requirement Clarification - -**Objective**: Parse user input and gather execution parameters. - -1. **Parse arguments** for explicit settings: mode, scope, focus areas, depth - -2. **Ask for missing parameters** via AskUserQuestion: - - Mode: spec-only / impl-only / full-lifecycle / fe-only / fullstack / full-lifecycle-fe - - Scope: project description - - Execution method: sequential / parallel - -3. **Frontend auto-detection** (for impl-only and full-lifecycle modes): - - | Signal | Detection | Pipeline Upgrade | - |--------|----------|-----------------| - | FE keywords | Keyword match in description | impl-only -> fe-only or fullstack | - | BE keywords also present | Both FE + BE keywords | impl-only -> fullstack | - | FE framework in package.json | grep react/vue/svelte/next | full-lifecycle -> full-lifecycle-fe | - -4. **Store requirements**: mode, scope, focus, depth, executionMethod - ---- - -## Phase 2: Create Team + Initialize Session - -1. Generate session ID: `TLS-<slug>-<date>` -2. Create session folder: `.workflow/.team/<session-id>/` -3. Call TeamCreate with team name -4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) -5. Initialize explorations directory with empty cache-index.json -6. Write team-session.json -7. **Initialize meta.json with pipeline metadata** (CRITICAL for UI): - -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<mode>", // e.g., "full", "spec-only", "impl-only" - pipeline_stages: ["analyst", "writer", "planner", "executor", "tester", "reviewer"], // Roles as stages - roles: ["coordinator", "analyst", "writer", "planner", "executor", "tester", "reviewer"], - team_name: "lifecycle" // Skill name for badge display - } -}) -``` - -**pipeline_stages format**: Array of role names that represent pipeline stages. The UI will display these as the pipeline workflow. - -**Task counts by mode**: - -| Mode | Tasks | pipeline_stages | -|------|-------|-----------------| -| spec-only | 6 | `["analyst", "writer", "reviewer"]` | -| impl-only | 4 | `["planner", "executor", "tester", "reviewer"]` | -| fe-only | 3 | `["planner", "fe-developer", "fe-qa"]` | -| fullstack | 6 | `["planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]` | -| full-lifecycle | 10 | `["analyst", "writer", "planner", "executor", "tester", "reviewer"]` | -| full-lifecycle-fe | 12 | `["analyst", "writer", "planner", "executor", "fe-developer", "tester", "fe-qa", "reviewer"]` | - ---- - -## Phase 3: Create Task Chain - -Delegate to `commands/dispatch.md` which creates the full task chain: -1. Reads SKILL.md Task Metadata Registry for task definitions -2. Creates tasks via TaskCreate with correct blockedBy -3. Assigns owner based on role mapping -4. Includes `Session: <session-folder>` in every task description -5. Marks inline discuss round in task description - ---- - -## Phase 4: Spawn-and-Stop - -Spawn first batch of ready workers in background, then STOP. - -1. Load `commands/monitor.md` -2. Find tasks with: status=pending, blockedBy all resolved, owner assigned -3. For each ready task -> spawn team-worker (see SKILL.md Spawn Template) -4. Output status summary -5. STOP - -### Checkpoint Gate Handling - -When QUALITY-001 completes (spec->impl transition): - -1. Read `<session-folder>/spec/readiness-report.md` -2. Parse quality gate and dimension scores -3. Output Checkpoint Output Template (see SKILL.md) -4. Write gate result to team-session.json -5. Pause and wait for user command - ---- - -## Phase 5: Report + Next Steps - -1. Load session state -> count completed tasks, duration -2. List deliverables with output paths -3. Update session status -> "completed" -4. Offer next steps: exit / view artifacts / extend tasks / generate lite-plan / create Issue - ---- - -## Error Handling - -| Error | Resolution | -|-------|------------| -| Task timeout | Log, mark failed, ask user to retry or skip | -| Worker crash | Respawn worker, reassign task | -| Dependency cycle | Detect, report to user, halt | -| Invalid mode | Reject with error, ask to clarify | -| Session corruption | Attempt recovery, fallback to manual reconciliation | diff --git a/.claude/skills/team-lifecycle/specs/document-standards.md b/.claude/skills/team-lifecycle/specs/document-standards.md deleted file mode 100644 index 2820cd98..00000000 --- a/.claude/skills/team-lifecycle/specs/document-standards.md +++ /dev/null @@ -1,192 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle/specs/quality-gates.md b/.claude/skills/team-lifecycle/specs/quality-gates.md deleted file mode 100644 index ae968436..00000000 --- a/.claude/skills/team-lifecycle/specs/quality-gates.md +++ /dev/null @@ -1,207 +0,0 @@ -# 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 diff --git a/.claude/skills/team-lifecycle/specs/team-config.json b/.claude/skills/team-lifecycle/specs/team-config.json deleted file mode 100644 index 6a2485b5..00000000 --- a/.claude/skills/team-lifecycle/specs/team-config.json +++ /dev/null @@ -1,216 +0,0 @@ -{ - "team_name": "team-lifecycle", - "team_display_name": "Team Lifecycle", - "description": "Unified team-worker agent architecture: shared Phase 1/5/Inner Loop in agent, role-specific Phase 2-4 from spec files", - "version": "5.0.0", - "architecture": "team-worker agent + role-specs", - "role_structure": "role-specs/{name}.md (Phase 2-4 only)", - "worker_agent": "team-worker", - - "roles": { - "coordinator": { - "task_prefix": null, - "responsibility": "Pipeline orchestration, requirement clarification, task chain creation, message dispatch", - "message_types": ["plan_approved", "plan_revision", "task_unblocked", "fix_required", "error", "shutdown"] - }, - "analyst": { - "task_prefix": "RESEARCH", - "role_spec": "role-specs/analyst.md", - "responsibility": "Seed analysis, codebase exploration, multi-dimensional context gathering + inline discuss", - "inline_discuss": "DISCUSS-001", - "inner_loop": false, - "message_types": ["research_ready", "research_progress", "error"] - }, - "writer": { - "task_prefix": "DRAFT", - "role_spec": "role-specs/writer.md", - "responsibility": "Product Brief / PRD / Architecture / Epics document generation + inline discuss", - "inner_loop": true, - "inline_discuss": ["DISCUSS-002", "DISCUSS-003", "DISCUSS-004", "DISCUSS-005"], - "message_types": ["draft_ready", "draft_revision", "error"] - }, - "planner": { - "task_prefix": "PLAN", - "role_spec": "role-specs/planner.md", - "responsibility": "Multi-angle code exploration (via shared explore), structured implementation planning", - "inner_loop": true, - "message_types": ["plan_ready", "plan_revision", "error"] - }, - "executor": { - "task_prefix": "IMPL", - "role_spec": "role-specs/executor.md", - "responsibility": "Code implementation following approved plans", - "inner_loop": true, - "message_types": ["impl_complete", "impl_progress", "error"] - }, - "tester": { - "task_prefix": "TEST", - "role_spec": "role-specs/tester.md", - "responsibility": "Adaptive test-fix cycles, progressive testing, quality gates", - "inner_loop": false, - "message_types": ["test_result", "fix_required", "error"] - }, - "reviewer": { - "task_prefix": "REVIEW", - "additional_prefixes": ["QUALITY", "IMPROVE"], - "role_spec": "role-specs/reviewer.md", - "responsibility": "Code review (REVIEW-*) + Spec quality validation (QUALITY-*) + Quality improvement recheck (IMPROVE-*) + inline discuss for sign-off", - "inline_discuss": "DISCUSS-006", - "inner_loop": false, - "message_types": ["review_result", "quality_result", "quality_recheck", "fix_required", "error"] - }, - "architect": { - "task_prefix": "ARCH", - "role_spec": "role-specs/architect.md", - "responsibility": "Architecture assessment, tech feasibility, design pattern review. Consulting role -- on-demand by coordinator", - "role_type": "consulting", - "inner_loop": false, - "consultation_modes": ["spec-review", "plan-review", "code-review", "consult", "feasibility"], - "message_types": ["arch_ready", "arch_concern", "arch_progress", "error"] - }, - "fe-developer": { - "task_prefix": "DEV-FE", - "role_spec": "role-specs/fe-developer.md", - "responsibility": "Frontend component/page implementation, design token consumption, responsive UI", - "role_type": "frontend-pipeline", - "inner_loop": false, - "message_types": ["dev_fe_complete", "dev_fe_progress", "error"] - }, - "fe-qa": { - "task_prefix": "QA-FE", - "role_spec": "role-specs/fe-qa.md", - "responsibility": "5-dimension frontend review (quality, a11y, design compliance, UX, pre-delivery), GC loop", - "role_type": "frontend-pipeline", - "inner_loop": false, - "message_types": ["qa_fe_passed", "qa_fe_result", "fix_required", "error"] - } - }, - - "utility_functions": { - "discuss": { - "type": "cli-tool", - "callable_by": ["analyst", "writer", "reviewer"], - "purpose": "Multi-perspective critique with CLI tools, consensus synthesis", - "implementation": "Bash with ccw cli --mode analysis" - }, - "explore": { - "type": "explore-agent", - "callable_by": ["analyst", "planner", "any"], - "purpose": "Codebase exploration with centralized cache", - "implementation": "Agent with agent_type: Explore" - }, - "doc-generation": { - "type": "cli-tool", - "callable_by": ["writer"], - "purpose": "Document generation engine (CLI execution)", - "implementation": "Bash with ccw cli --mode write" - } - }, - - "checkpoint_commands": { - "revise": { - "handler": "handleRevise", - "pattern": "revise <TASK-ID> [feedback]", - "cascade": true, - "creates": "revision_task" - }, - "feedback": { - "handler": "handleFeedback", - "pattern": "feedback <text>", - "cascade": true, - "creates": "revision_chain" - }, - "recheck": { - "handler": "handleRecheck", - "pattern": "recheck", - "cascade": false, - "creates": "quality_recheck" - }, - "improve": { - "handler": "handleImprove", - "pattern": "improve [dimension]", - "cascade": false, - "creates": "improvement_task + quality_recheck" - } - }, - - "pipelines": { - "spec-only": { - "description": "Specification pipeline: research+discuss -> draft+discuss x4 -> quality+discuss", - "task_chain": [ - "RESEARCH-001", - "DRAFT-001", "DRAFT-002", "DRAFT-003", "DRAFT-004", - "QUALITY-001" - ], - "beats": 6 - }, - "impl-only": { - "description": "Implementation pipeline: plan -> implement -> test + review", - "task_chain": ["PLAN-001", "IMPL-001", "TEST-001", "REVIEW-001"], - "beats": 3 - }, - "full-lifecycle": { - "description": "Full lifecycle: spec pipeline -> implementation pipeline", - "task_chain": "spec-only + impl-only (PLAN-001 blockedBy QUALITY-001)", - "beats": 9 - }, - "fe-only": { - "description": "Frontend-only pipeline: plan -> frontend dev -> frontend QA", - "task_chain": ["PLAN-001", "DEV-FE-001", "QA-FE-001"], - "gc_loop": { "max_rounds": 2, "convergence": "score >= 8 && critical === 0" } - }, - "fullstack": { - "description": "Fullstack pipeline: plan -> backend + frontend parallel -> test + QA", - "task_chain": ["PLAN-001", "IMPL-001||DEV-FE-001", "TEST-001||QA-FE-001", "REVIEW-001"], - "sync_points": ["REVIEW-001"] - }, - "full-lifecycle-fe": { - "description": "Full lifecycle with frontend: spec -> plan -> backend + frontend -> test + QA", - "task_chain": "spec-only + fullstack (PLAN-001 blockedBy QUALITY-001)" - } - }, - - "frontend_detection": { - "keywords": ["component", "page", "UI", "frontend", "CSS", "HTML", "React", "Vue", "Tailwind", "Svelte", "Next.js", "Nuxt", "shadcn", "design system"], - "file_patterns": ["*.tsx", "*.jsx", "*.vue", "*.svelte", "*.css", "*.scss", "*.html"], - "routing_rules": { - "frontend_only": "All tasks match frontend keywords, no backend/API mentions", - "fullstack": "Mix of frontend and backend tasks", - "backend_only": "No frontend keywords detected (default impl-only)" - } - }, - - "ui_ux_pro_max": { - "skill_name": "ui-ux-pro-max", - "invocation": "Skill(skill=\"ui-ux-pro-max\", args=\"...\")", - "domains": ["product", "style", "typography", "color", "landing", "chart", "ux", "web"], - "stacks": ["html-tailwind", "react", "nextjs", "vue", "svelte", "shadcn", "swiftui", "react-native", "flutter"], - "design_intelligence_chain": ["analyst -> design-intelligence.json", "architect -> design-tokens.json", "fe-developer -> tokens.css", "fe-qa -> anti-pattern audit"] - }, - - "shared_memory": { - "file": "shared-memory.json", - "schema": { - "design_intelligence": "From analyst via ui-ux-pro-max", - "design_token_registry": "From architect, consumed by fe-developer/fe-qa", - "component_inventory": "From fe-developer, list of implemented components", - "style_decisions": "Accumulated design decisions", - "qa_history": "From fe-qa, audit trail", - "industry_context": "Industry + strictness config", - "exploration_cache": "From exploration utility (Explore agent), shared by all roles" - } - }, - - "session_dirs": { - "base": ".workflow/.team/TLS-{slug}-{YYYY-MM-DD}/", - "spec": "spec/", - "discussions": "discussions/", - "plan": "plan/", - "explorations": "explorations/", - "architecture": "architecture/", - "analysis": "analysis/", - "qa": "qa/", - "wisdom": "wisdom/", - "messages": ".msg/" - } -} diff --git a/.claude/skills/team-lifecycle/templates/architecture-doc.md b/.claude/skills/team-lifecycle/templates/architecture-doc.md deleted file mode 100644 index 5106de03..00000000 --- a/.claude/skills/team-lifecycle/templates/architecture-doc.md +++ /dev/null @@ -1,254 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle/templates/epics-template.md b/.claude/skills/team-lifecycle/templates/epics-template.md deleted file mode 100644 index 939d933c..00000000 --- a/.claude/skills/team-lifecycle/templates/epics-template.md +++ /dev/null @@ -1,196 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle/templates/product-brief.md b/.claude/skills/team-lifecycle/templates/product-brief.md deleted file mode 100644 index ffbdf437..00000000 --- a/.claude/skills/team-lifecycle/templates/product-brief.md +++ /dev/null @@ -1,133 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-lifecycle/templates/requirements-prd.md b/.claude/skills/team-lifecycle/templates/requirements-prd.md deleted file mode 100644 index 0b1dbf28..00000000 --- a/.claude/skills/team-lifecycle/templates/requirements-prd.md +++ /dev/null @@ -1,224 +0,0 @@ -# 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 | diff --git a/.claude/skills/team-perf-opt/SKILL.md b/.claude/skills/team-perf-opt/SKILL.md index 6c991fd9..e2ef8261 100644 --- a/.claude/skills/team-perf-opt/SKILL.md +++ b/.claude/skills/team-perf-opt/SKILL.md @@ -1,92 +1,99 @@ --- name: team-perf-opt -description: Unified team skill for performance optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team perf-opt". +description: Unified team skill for performance optimization. Coordinator orchestrates pipeline, workers are team-worker agents. Supports single/fan-out/independent parallel modes. Triggers on "team perf-opt". allowed-tools: Agent, TaskCreate, TaskList, TaskGet, TaskUpdate, TeamCreate, TeamDelete, SendMessage, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context --- # Team Performance Optimization -Unified team skill: Profile application performance, identify bottlenecks, design optimization strategies, implement changes, benchmark improvements, and review code quality. Built on **team-worker agent architecture** -- all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. +Profile application performance, identify bottlenecks, design optimization strategies, implement changes, benchmark improvements, and review code quality. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-perf-opt") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-perf-opt", args="<task-description>") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v v - [tw] [tw] [tw] [tw] [tw] -profiler strate- optim- bench- review- - gist izer marker er + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+-------+-------+ + v v v v v + [profiler] [strategist] [optimizer] [benchmarker] [reviewer] + (team-worker agents) -(tw) = team-worker agent +Pipeline (Single mode): + PROFILE-001 -> STRATEGY-001 -> IMPL-001 -> BENCH-001 + REVIEW-001 (fix cycle) + +Pipeline (Fan-out mode): + PROFILE-001 -> STRATEGY-001 -> [IMPL-B01..N](parallel) -> BENCH+REVIEW per branch + +Pipeline (Independent mode): + [Pipeline A: PROFILE-A->STRATEGY-A->IMPL-A->BENCH-A+REVIEW-A] + [Pipeline B: PROFILE-B->STRATEGY-B->IMPL-B->BENCH-B+REVIEW-B] (parallel) ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| profiler | [roles/profiler/role.md](roles/profiler/role.md) | PROFILE-* | false | +| strategist | [roles/strategist/role.md](roles/strategist/role.md) | STRATEGY-* | false | +| optimizer | [roles/optimizer/role.md](roles/optimizer/role.md) | IMPL-*, FIX-* | true | +| benchmarker | [roles/benchmarker/role.md](roles/benchmarker/role.md) | BENCH-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REVIEW-*, QUALITY-* | false | + ## Role Router -This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -### Input Parsing +## Shared Constants -Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. +- **Session prefix**: `PERF-OPT` +- **Session path**: `.workflow/.team/PERF-OPT-<slug>-<date>/` +- **Team name**: `perf-opt` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -### Role Registry +## Worker Spawn Template -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| profiler | [role-specs/profiler.md](role-specs/profiler.md) | PROFILE-* | orchestration | false | -| strategist | [role-specs/strategist.md](role-specs/strategist.md) | STRATEGY-* | orchestration | false | -| optimizer | [role-specs/optimizer.md](role-specs/optimizer.md) | IMPL-* / FIX-* | code_generation | true | -| benchmarker | [role-specs/benchmarker.md](role-specs/benchmarker.md) | BENCH-* | validation | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* / QUALITY-* | read_only_analysis | false | +Coordinator spawns workers using this template: -### Dispatch +``` +Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker", + team_name: "perf-opt", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-perf-opt/roles/<role>/role.md +session: <session-folder> +session_id: <session-id> +team_name: perf-opt +requirement: <task-description> +inner_loop: <true|false> -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User just provides task description. - -**Invocation**: -```bash -Skill(skill="team-perf-opt", args="<task-description>") # auto mode -Skill(skill="team-perf-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out -Skill(skill="team-perf-opt", args='--parallel-mode=independent "target1" "target2"') # independent -Skill(skill="team-perf-opt", args="--max-branches=3 <task-description>") # limit branches +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` +}) ``` -**Parallel Modes**: +**Inner Loop roles** (optimizer): Set `inner_loop: true`. +**Single-task roles** (profiler, strategist, benchmarker, reviewer): Set `inner_loop: false`. -| Mode | Description | When to Use | -|------|-------------|------------| -| `auto` (default) | count <= 2 -> single, count >= 3 -> fan-out | General optimization requests | -| `single` | Linear pipeline, no branching | Simple or tightly coupled optimizations | -| `fan-out` | Shared PROFILE+STRATEGY, then N parallel IMPL->BENCH+REVIEW branches | Multiple independent bottlenecks | -| `independent` | M fully independent pipelines from profiling to review | Separate optimization targets | - -**Lifecycle**: -``` -User provides task description + optional --parallel-mode / --max-branches - -> coordinator Phase 1-3: Parse flags -> TeamCreate -> Create task chain (mode-aware) - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances - -> [auto/fan-out] CP-2.5: Strategy complete -> create N branch tasks -> spawn all IMPL-B* in parallel - -> [independent] All pipelines run in parallel from the start - -> Per-branch/pipeline fix cycles run independently - -> All branches/pipelines complete -> AGGREGATE -> Phase 5 report + completion action -``` - -**User Commands** (wake paused coordinator): +## User Commands | Command | Action | |---------|--------| @@ -97,242 +104,29 @@ User provides task description + optional --parallel-mode / --max-branches | `recheck` | Re-run quality check | | `improve [dimension]` | Auto-improve weakest dimension | ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +## Session Directory ``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: <team-name>, - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-perf-opt/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: <team-name> -requirement: <task-description> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) +.workflow/.team/PERF-OPT-<slug>-<date>/ ++-- session.json # Session metadata + status + parallel_mode ++-- artifacts/ +| +-- baseline-metrics.json # Profiler: before-optimization metrics +| +-- bottleneck-report.md # Profiler: ranked bottleneck findings +| +-- optimization-plan.md # Strategist: prioritized optimization plan +| +-- benchmark-results.json # Benchmarker: after-optimization metrics +| +-- review-report.md # Reviewer: code review findings +| +-- branches/B01/... # Fan-out branch artifacts +| +-- pipelines/A/... # Independent pipeline artifacts ++-- explorations/ # Shared explore cache ++-- wisdom/patterns.md # Discovered patterns and conventions ++-- discussions/ # Discussion records ++-- .msg/messages.jsonl # Team message bus ++-- .msg/meta.json # Session metadata ``` -**Inner Loop roles** (optimizer): Set `inner_loop: true`. The team-worker agent handles the loop internally. - -**Single-task roles** (profiler, strategist, benchmarker, reviewer): Set `inner_loop: false`. - ---- - -## Pipeline Definitions - -### Pipeline Diagrams - -**Single Mode** (linear, backward compatible): -``` -Pipeline: Single (Linear with Review-Fix Cycle) -===================================================================== -Stage 1 Stage 2 Stage 3 Stage 4 -PROFILE-001 --> STRATEGY-001 --> IMPL-001 --> BENCH-001 -[profiler] [strategist] [optimizer] [benchmarker] - ^ | - +<--FIX-001---->+ - | REVIEW-001 - +<--------> [reviewer] - (max 3 iterations) | - COMPLETE -===================================================================== -``` - -**Fan-out Mode** (shared stages 1-2, parallel branches 3-4): -``` -Pipeline: Fan-out (N parallel optimization branches) -===================================================================== -Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch) - (branch creation) -PROFILE-001 --> STRATEGY-001 --+-> IMPL-B01 --> BENCH-B01 + REVIEW-B01 (fix cycle) -[profiler] [strategist] | [optimizer] [bench] [reviewer] - +-> IMPL-B02 --> BENCH-B02 + REVIEW-B02 (fix cycle) - | [optimizer] [bench] [reviewer] - +-> IMPL-B0N --> BENCH-B0N + REVIEW-B0N (fix cycle) - | - AGGREGATE -> Phase 5 -===================================================================== -``` - -**Independent Mode** (M fully independent pipelines): -``` -Pipeline: Independent (M complete pipelines) -===================================================================== -Pipeline A: PROFILE-A01 --> STRATEGY-A01 --> IMPL-A01 --> BENCH-A01 + REVIEW-A01 -Pipeline B: PROFILE-B01 --> STRATEGY-B01 --> IMPL-B01 --> BENCH-B01 + REVIEW-B01 -Pipeline C: PROFILE-C01 --> STRATEGY-C01 --> IMPL-C01 --> BENCH-C01 + REVIEW-C01 - | - AGGREGATE -> Phase 5 -===================================================================== -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker A] Phase 1-5 - | (parallel OK) --+--> [team-worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker A] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker B directly - | --> log fast_advance to message bus (coordinator syncs on next wake) - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -``` -Beat View: Performance Optimization Pipeline -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - new task --> +- Phase 1-3: clarify -+ - | TeamCreate | - | create PROFILE-001 | - +- Phase 4: spawn ------+--> [profiler] Phase 1-5 - +- STOP (idle) ---------+ | - | - callback <----------------------------------------------+ - (profiler done) --> +- handleCallback ------+ profile_complete - | mark PROFILE done | - | spawn strategist ----+--> [strategist] Phase 1-5 - +- STOP ----------------+ | - | - callback <----------------------------------------------+ - (strategist done)--> +- handleCallback ------+ strategy_complete - | mark STRATEGY done | - | spawn optimizer -----+--> [optimizer] Phase 1-5 - +- STOP ----------------+ | - | - callback <----------------------------------------------+ - (optimizer done) --> +- handleCallback ------+ impl_complete - | mark IMPL done | - | spawn bench+reviewer-+--> [benchmarker] Phase 1-5 - | (parallel) -------+--> [reviewer] Phase 1-5 - +- STOP ----------------+ | | - | | - callback x2 <--------------------------------------+-----------+ - --> +- handleCallback ------+ - | both done? | - | YES + pass -> Phase 5| - | NO / fail -> FIX task| - | spawn optimizer -----+--> [optimizer] FIX-001 - +- STOP or Phase 5 -----+ -====================================================================== -``` - -**Checkpoints**: - -| Checkpoint | Trigger | Location | Behavior | -|------------|---------|----------|----------| -| CP-1 | PROFILE-001 complete | After Stage 1 | User reviews bottleneck report, can refine scope | -| CP-2 | STRATEGY-001 complete | After Stage 2 | User reviews optimization plan, can adjust priorities | -| CP-2.5 | STRATEGY-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks from optimization plan, spawn all IMPL-B* in parallel | -| CP-3 | REVIEW/BENCH fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) | -| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action | - -### Task Metadata Registry - -**Single mode** (backward compatible): - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| PROFILE-001 | profiler | Stage 1 | (none) | Profile application, identify bottlenecks | -| STRATEGY-001 | strategist | Stage 2 | PROFILE-001 | Design optimization plan from bottleneck report | -| IMPL-001 | optimizer | Stage 3 | STRATEGY-001 | Implement highest-priority optimizations | -| BENCH-001 | benchmarker | Stage 4 | IMPL-001 | Run benchmarks, compare vs baseline | -| REVIEW-001 | reviewer | Stage 4 | IMPL-001 | Review optimization code for correctness | -| FIX-001 | optimizer | Stage 3 (cycle) | REVIEW-001 or BENCH-001 | Fix issues found in review/benchmark | - -**Fan-out mode** (branch tasks created at CP-2.5): - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| PROFILE-001 | profiler | Stage 1 (shared) | (none) | Profile application | -| STRATEGY-001 | strategist | Stage 2 (shared) | PROFILE-001 | Design plan with discrete OPT-IDs | -| IMPL-B{NN} | optimizer | Stage 3 (branch) | STRATEGY-001 | Implement OPT-{NNN} only | -| BENCH-B{NN} | benchmarker | Stage 4 (branch) | IMPL-B{NN} | Benchmark branch B{NN} | -| REVIEW-B{NN} | reviewer | Stage 4 (branch) | IMPL-B{NN} | Review branch B{NN} | -| FIX-B{NN}-{cycle} | optimizer | Fix (branch) | (none) | Fix issues in branch B{NN} | -| BENCH-B{NN}-R{cycle} | benchmarker | Retry (branch) | FIX-B{NN}-{cycle} | Re-benchmark after fix | -| REVIEW-B{NN}-R{cycle} | reviewer | Retry (branch) | FIX-B{NN}-{cycle} | Re-review after fix | - -**Independent mode**: - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| PROFILE-{P}01 | profiler | Stage 1 | (none) | Profile for pipeline {P} target | -| STRATEGY-{P}01 | strategist | Stage 2 | PROFILE-{P}01 | Strategy for pipeline {P} | -| IMPL-{P}01 | optimizer | Stage 3 | STRATEGY-{P}01 | Implement pipeline {P} optimizations | -| BENCH-{P}01 | benchmarker | Stage 4 | IMPL-{P}01 | Benchmark pipeline {P} | -| REVIEW-{P}01 | reviewer | Stage 4 | IMPL-{P}01 | Review pipeline {P} | -| FIX-{P}01-{cycle} | optimizer | Fix | (none) | Fix issues in pipeline {P} | - -### Task Naming Rules - -| Mode | Stage 3 | Stage 4 | Fix | Retry | -|------|---------|---------|-----|-------| -| Single | IMPL-001 | BENCH-001, REVIEW-001 | FIX-001 | BENCH-001-R1, REVIEW-001-R1 | -| Fan-out | IMPL-B01 | BENCH-B01, REVIEW-B01 | FIX-B01-1 | BENCH-B01-R1, REVIEW-B01-R1 | -| Independent | IMPL-A01 | BENCH-A01, REVIEW-A01 | FIX-A01-1 | BENCH-A01-R1, REVIEW-A01-R1 | - ---- - ## Completion Action -When the pipeline completes (all tasks done, coordinator Phase 5): +When the pipeline completes: ``` AskUserQuestion({ @@ -349,117 +143,20 @@ AskUserQuestion({ }) ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-perf-opt", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | +## Specs Reference ---- - -## Session Directory - -**Single mode**: -``` -.workflow/<session-id>/ -+-- session.json # Session metadata + status + parallel_mode -+-- artifacts/ -| +-- baseline-metrics.json # Profiler: before-optimization metrics -| +-- bottleneck-report.md # Profiler: ranked bottleneck findings -| +-- optimization-plan.md # Strategist: prioritized optimization plan -| +-- benchmark-results.json # Benchmarker: after-optimization metrics -| +-- review-report.md # Reviewer: code review findings -+-- explorations/ -| +-- cache-index.json # Shared explore cache -| +-- <hash>.md # Cached exploration results -+-- wisdom/ -| +-- patterns.md # Discovered patterns and conventions -| +-- .msg/messages.jsonl # Team message bus -| +-- .msg/meta.json # Session metadata -+-- discussions/ -| +-- DISCUSS-OPT.md # Strategy discussion record -| +-- DISCUSS-REVIEW.md # Review discussion record -``` - -**Fan-out mode** (adds branches/ directory): -``` -.workflow/<session-id>/ -+-- session.json # + parallel_mode, branches, fix_cycles -+-- artifacts/ -| +-- baseline-metrics.json # Shared baseline (all branches use this) -| +-- bottleneck-report.md # Shared bottleneck report -| +-- optimization-plan.md # Shared plan with discrete OPT-IDs -| +-- aggregate-results.json # Aggregated results from all branches -| +-- branches/ -| +-- B01/ -| | +-- optimization-detail.md # Extracted OPT-001 detail -| | +-- benchmark-results.json # Branch B01 benchmark -| | +-- review-report.md # Branch B01 review -| +-- B02/ -| | +-- optimization-detail.md -| | +-- benchmark-results.json -| | +-- review-report.md -| +-- B0N/ -+-- explorations/ wisdom/ discussions/ # Same as single -``` - -**Independent mode** (adds pipelines/ directory): -``` -.workflow/<session-id>/ -+-- session.json # + parallel_mode, independent_targets, fix_cycles -+-- artifacts/ -| +-- aggregate-results.json # Aggregated results from all pipelines -| +-- pipelines/ -| +-- A/ -| | +-- baseline-metrics.json -| | +-- bottleneck-report.md -| | +-- optimization-plan.md -| | +-- benchmark-results.json -| | +-- review-report.md -| +-- B/ -| +-- baseline-metrics.json -| +-- ... -+-- explorations/ wisdom/ discussions/ # Same as single -``` - -## Session Resume - -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan session directory for sessions with status "active" or "paused" -2. Multiple matches -> AskUserQuestion for selection -3. Audit TaskList -> reconcile session state <-> task status -4. Reset in_progress -> pending (interrupted tasks) -5. Rebuild team and spawn needed workers only -6. Create missing tasks with correct blockedBy -7. Kick first executable task -> Phase 4 coordination loop - -## Shared Resources - -| Resource | Path | Usage | -|----------|------|-------| -| Performance Baseline | [<session>/artifacts/baseline-metrics.json](<session>/artifacts/baseline-metrics.json) | Before-optimization metrics for comparison | -| Bottleneck Report | [<session>/artifacts/bottleneck-report.md](<session>/artifacts/bottleneck-report.md) | Profiler output consumed by strategist | -| Optimization Plan | [<session>/artifacts/optimization-plan.md](<session>/artifacts/optimization-plan.md) | Strategist output consumed by optimizer | -| Benchmark Results | [<session>/artifacts/benchmark-results.json](<session>/artifacts/benchmark-results.json) | Benchmarker output consumed by reviewer | +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry +- [specs/team-config.json](specs/team-config.json) — Team configuration ## Error Handling | Scenario | Resolution | |----------|------------| -| Role spec file not found | Error with expected path (role-specs/<name>.md) | -| Command file not found | Fallback to inline execution in coordinator role.md | -| Role file not found | Error with expected path (role-specs/<name>.md) | -| Fast-advance orphan detected | Coordinator resets task to pending on next check | -| consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline | -| team-worker agent unavailable | Error: requires .claude/agents/team-worker.md | -| Completion action timeout | Default to Keep Active | +| Unknown --role value | Error with role registry list | +| Role file not found | Error with expected path (roles/{name}/role.md) | | Profiling tool not available | Fallback to static analysis methods | -| Benchmark regression detected | Auto-create FIX task with regression details (scoped to branch/pipeline) | -| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues (per-branch/pipeline scope) | -| One branch IMPL fails | Mark that branch failed, other branches continue to completion | -| Branch scope overlap detected | Strategist constrains non-overlapping target files; IMPL logs warning on detection | -| Shared-memory concurrent writes | Each worker writes only its own namespace key (e.g., `optimizer.B01`) | -| Branch fix cycle >= 3 | Escalate only that branch to user, other branches continue independently | -| max_branches exceeded | Coordinator truncates to top N optimizations by priority at CP-2.5 | -| Independent pipeline partial failure | Failed pipeline marked, others continue; aggregate reports partial results | +| Benchmark regression detected | Auto-create FIX task with regression details | +| Review-fix cycle exceeds 3 iterations | Escalate to user | +| One branch IMPL fails | Mark that branch failed, other branches continue | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-perf-opt/roles/benchmarker/role.md b/.claude/skills/team-perf-opt/roles/benchmarker/role.md new file mode 100644 index 00000000..82545102 --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/benchmarker/role.md @@ -0,0 +1,89 @@ +--- +role: benchmarker +prefix: BENCH +inner_loop: false +message_types: + success: bench_complete + error: error + fix: fix_required +--- + +# Performance Benchmarker + +Run benchmarks comparing before/after optimization metrics. Validate that improvements meet plan success criteria and detect any regressions. + +## Phase 2: Environment & Baseline Loading + +| Input | Source | Required | +|-------|--------|----------| +| Baseline metrics | <session>/artifacts/baseline-metrics.json (shared) | Yes | +| Optimization plan / detail | Varies by mode (see below) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | + +1. Extract session path from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- benchmark only this branch's metrics | +| `PipelineId: {P}` | Present | Independent pipeline -- use pipeline-scoped baseline | +| Neither present | - | Single mode -- full benchmark | + +3. **Load baseline metrics**: + - Single / Fan-out: Read `<session>/artifacts/baseline-metrics.json` (shared baseline) + - Independent: Read `<session>/artifacts/pipelines/{P}/baseline-metrics.json` + +4. **Load optimization context**: + - Single: Read `<session>/artifacts/optimization-plan.md` + - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/optimization-detail.md` + - Independent: Read `<session>/artifacts/pipelines/{P}/optimization-plan.md` + +5. Load .msg/meta.json for project type and optimization scope +6. Detect available benchmark tools from project: + +| Signal | Benchmark Tool | Method | +|--------|---------------|--------| +| package.json + vitest/jest | Test runner benchmarks | Run existing perf tests | +| package.json + webpack/vite | Bundle analysis | Compare build output sizes | +| Cargo.toml + criterion | Rust benchmarks | cargo bench | +| go.mod | Go benchmarks | go test -bench | +| Makefile with bench target | Custom benchmarks | make bench | +| No tooling detected | Manual measurement | Timed execution via Bash | + +7. Get changed files scope from shared-memory (optimizer namespace, scoped by branch/pipeline) + +## Phase 3: Benchmark Execution + +Run benchmarks matching detected project type: + +**Frontend benchmarks**: Compare bundle size, render performance, dependency weight changes. + +**Backend benchmarks**: Measure endpoint response times, memory usage under load, database query improvements. + +**CLI / Library benchmarks**: Execution time, memory peak, throughput under sustained load. + +**All project types**: +- Run existing test suite to verify no regressions +- Collect post-optimization metrics matching baseline format +- Calculate improvement percentages per metric + +**Branch-scoped benchmarking** (fan-out mode): +- Only benchmark metrics relevant to this branch's optimization +- Still check for regressions across all metrics + +## Phase 4: Result Analysis + +Compare against baseline and plan criteria: + +| Metric | Threshold | Verdict | +|--------|-----------|---------| +| Target improvement vs baseline | Meets plan success criteria | PASS | +| No regression in unrelated metrics | < 5% degradation allowed | PASS | +| All plan success criteria met | Every criterion satisfied | PASS | +| Improvement below target | > 50% of target achieved | WARN | +| Regression detected | Any unrelated metric degrades > 5% | FAIL -> fix_required | +| Plan criteria not met | Any criterion not satisfied | FAIL -> fix_required | + +1. Write benchmark results to output path (scoped by branch/pipeline/single) +2. Update `<session>/.msg/meta.json` under scoped namespace +3. If verdict is FAIL, include detailed feedback in message for FIX task creation diff --git a/.claude/skills/team-perf-opt/roles/coordinator/commands/analyze.md b/.claude/skills/team-perf-opt/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..72c55fdb --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/coordinator/commands/analyze.md @@ -0,0 +1,61 @@ +# Analyze Task - Performance Optimization + +Parse optimization request -> detect parallel mode -> determine scope -> design pipeline structure. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +### Parallel Mode Detection + +| Flag | Value | Pipeline Shape | +|------|-------|----------------| +| `--parallel-mode=single` | explicit | Single linear pipeline | +| `--parallel-mode=fan-out` | explicit | Shared profile+strategy, N parallel IMPL branches | +| `--parallel-mode=independent` | explicit | M fully independent pipelines | +| `--parallel-mode=auto` or absent | default | Auto-detect from bottleneck count at CP-2.5 | +| `auto` with count <= 2 | auto-resolved | single mode | +| `auto` with count >= 3 | auto-resolved | fan-out mode | + +### Scope Detection + +| Signal | Target | +|--------|--------| +| Specific file/module mentioned | Scoped optimization | +| "slow", "performance", generic | Full application profiling | +| Specific metric mentioned (FCP, memory, startup) | Targeted metric optimization | +| Multiple quoted targets (independent mode) | Per-target scoped optimization | + +### Optimization Keywords + +| Keywords | Capability | +|----------|------------| +| profile, bottleneck, slow, benchmark | profiler | +| optimize, improve, reduce, speed | optimizer | +| strategy, plan, prioritize | strategist | +| verify, test, validate | benchmarker | +| review, audit, quality | reviewer | + +## Output + +Coordinator state from this command (used by dispatch.md): + +```json +{ + "parallel_mode": "<auto|single|fan-out|independent>", + "max_branches": 5, + "optimization_targets": ["<target1>", "<target2>"], + "independent_targets": [], + "scope": "<specific|full-app|targeted>", + "target_metrics": ["<metric1>", "<metric2>"] +} +``` + +## Pipeline Structure by Mode + +| Mode | Stages | +|------|--------| +| single | PROFILE-001 -> STRATEGY-001 -> IMPL-001 -> BENCH-001 + REVIEW-001 | +| fan-out | PROFILE-001 -> STRATEGY-001 -> [IMPL-B01..N in parallel] -> BENCH+REVIEW per branch | +| independent | N complete pipelines (PROFILE+STRATEGY+IMPL+BENCH+REVIEW) in parallel | +| auto | Decided at CP-2.5 after STRATEGY-001 completes based on bottleneck count | diff --git a/.claude/skills/team-perf-opt/roles/coordinator/role.md b/.claude/skills/team-perf-opt/roles/coordinator/role.md index 3b072f3b..c083e6aa 100644 --- a/.claude/skills/team-perf-opt/roles/coordinator/role.md +++ b/.claude/skills/team-perf-opt/roles/coordinator/role.md @@ -14,7 +14,7 @@ Orchestrates the performance optimization pipeline: manages task chains, spawns - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) - Stop after spawning workers -- wait for callbacks -- Handle review-fix cycles with max 3 iterations +- Handle review-fix cycles with max 3 iterations per branch - Execute completion action in Phase 5 ### MUST NOT @@ -36,16 +36,6 @@ When coordinator needs to execute a command (dispatch, monitor): 3. **Commands are inline execution guides** -- NOT separate agents or subprocesses 4. **Execute synchronously** -- complete the command workflow before proceeding -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - --- ## Entry Router @@ -54,15 +44,15 @@ When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [profiler], [strategist], [optimizer], [benchmarker], [reviewer] | -> handleCallback | -| Branch callback | Message contains branch tag [optimizer-B01], [benchmarker-B02], etc. | -> handleCallback (branch-aware) | -| Pipeline callback | Message contains pipeline tag [profiler-A], [optimizer-B], etc. | -> handleCallback (pipeline-aware) | -| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains role tag [profiler], [strategist], [optimizer], [benchmarker], [reviewer] | -> handleCallback (monitor.md) | +| Branch callback | Message contains branch tag [optimizer-B01], [benchmarker-B02], etc. | -> handleCallback branch-aware (monitor.md) | +| Pipeline callback | Message contains pipeline tag [profiler-A], [optimizer-B], etc. | -> handleCallback pipeline-aware (monitor.md) | +| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) | +| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) | +| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session exists | -> Phase 0 | +| New session | None of above | -> Phase 1 | For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. @@ -72,10 +62,7 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match - Scan `.workflow/.team/PERF-OPT-*/.msg/meta.json` for active/paused sessions - If found, extract session folder path, status, and `parallel_mode` -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content (including branch variants like `[optimizer-B01]`) - - Check for "check", "status", "resume", "continue" keywords - - Check for "consensus_blocked" signal +2. **Parse $ARGUMENTS** for detection keywords 3. **Route to handler**: - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP @@ -89,136 +76,34 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match Triggered when an active/paused session is detected on coordinator entry. 1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "perf-opt" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop +2. Audit task list: `TaskList()` +3. Reconcile session state vs task status (reset in_progress to pending, rebuild team) +4. Spawn workers for ready tasks -> Phase 4 coordination loop --- ## Phase 1: Requirement Clarification 1. Parse user task description from $ARGUMENTS -2. **Parse parallel mode flags**: - -| Flag | Value | Default | -|------|-------|---------| -| `--parallel-mode` | `single`, `fan-out`, `independent`, `auto` | `auto` | -| `--max-branches` | integer 1-10 | 5 (from config) | - - - For `independent` mode: remaining positional arguments after flags are `independent_targets` array - - Example: `--parallel-mode=independent "optimize rendering" "optimize API"` -> targets = ["optimize rendering", "optimize API"] - -3. Identify optimization target: - -| Signal | Target | -|--------|--------| -| Specific file/module mentioned | Scoped optimization | -| "slow", "performance", generic | Full application profiling | -| Specific metric mentioned (FCP, memory, startup) | Targeted metric optimization | -| Multiple quoted targets (independent mode) | Per-target scoped optimization | - -4. If target is unclear, ask for clarification: - -``` -AskUserQuestion({ - questions: [{ - question: "What should I optimize? Provide a target scope or describe the performance issue.", - header: "Scope" - }] -}) -``` - -5. Record optimization requirement with scope, target metrics, parallel_mode, and max_branches +2. **Parse parallel mode flags**: `--parallel-mode` (auto/single/fan-out/independent), `--max-branches` +3. Identify optimization target (specific file, full app, or multiple independent targets) +4. If target is unclear, AskUserQuestion for scope clarification +5. Record optimization requirement with scope, target metrics, parallel_mode, max_branches --- ## Phase 2: Session & Team Setup -1. Create session directory: - -``` -Bash("mkdir -p .workflow/<session-id>/artifacts .workflow/<session-id>/explorations .workflow/<session-id>/wisdom .workflow/<session-id>/discussions") -``` - - For independent mode, also create pipeline subdirectories: -``` -// For each target in independent_targets -Bash("mkdir -p .workflow/<session-id>/artifacts/pipelines/A .workflow/<session-id>/artifacts/pipelines/B ...") -``` - -2. Write session.json with extended fields: - -```json -{ - "status": "active", - "team_name": "perf-opt", - "requirement": "<requirement>", - "timestamp": "<ISO-8601>", - "parallel_mode": "<auto|single|fan-out|independent>", - "max_branches": 5, - "branches": [], - "independent_targets": [], - "fix_cycles": {} -} -``` - - - `parallel_mode`: from Phase 1 parsing (default: "auto") - - `max_branches`: from Phase 1 parsing (default: 5) - - `branches`: populated at CP-2.5 for fan-out mode (e.g., ["B01", "B02", "B03"]) - - `independent_targets`: populated for independent mode (e.g., ["optimize rendering", "optimize API"]) - - `fix_cycles`: populated per-branch/pipeline as fix cycles occur - -3. Initialize meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<auto|single|fan-out|independent>", - pipeline_stages: ["profiler", "strategist", "optimizer", "benchmarker", "reviewer"], - roles: ["coordinator", "profiler", "strategist", "optimizer", "benchmarker", "reviewer"], - team_name: "perf-opt" - } -}) -``` - -4. Create team: - -``` -TeamCreate({ team_name: "perf-opt" }) -``` +1. Create session directory with artifacts/, explorations/, wisdom/, discussions/ subdirs +2. Write session.json with extended fields (parallel_mode, max_branches, branches, fix_cycles) +3. Initialize meta.json with pipeline metadata via team_msg +4. Call `TeamCreate({ team_name: "perf-opt" })` --- -## Phase 3: Task Chain Creation +## Phase 3: Create Task Chain -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies +Execute `commands/dispatch.md` inline (Command Execution Protocol). --- @@ -226,78 +111,34 @@ Execute `commands/dispatch.md` inline (Command Execution Protocol): ### Initial Spawn -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn profiler worker", - team_name: "perf-opt", - name: "profiler", - run_in_background: true, - prompt: `## Role Assignment -role: profiler -role_spec: .claude/skills/team-perf-opt/role-specs/profiler.md -session: <session-folder> -session_id: <session-id> -team_name: perf-opt -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` +Find first unblocked task and spawn its worker using SKILL.md Worker Spawn Template with: +- `role_spec: .claude/skills/team-perf-opt/roles/<role>/role.md` +- `team_name: perf-opt` **STOP** after spawning. Wait for worker callback. ### Coordination (via monitor.md handlers) -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 +All subsequent coordination handled by `commands/monitor.md`. --- ## Phase 5: Report + Completion Action 1. Load session state -> count completed tasks, calculate duration -2. List deliverables: +2. List deliverables (baseline-metrics.json, bottleneck-report.md, optimization-plan.md, benchmark-results.json, review-report.md) +3. Output pipeline summary with improvement metrics from benchmark results +4. Execute completion action per SKILL.md Completion Action section -| Deliverable | Path | -|-------------|------| -| Baseline Metrics | <session>/artifacts/baseline-metrics.json | -| Bottleneck Report | <session>/artifacts/bottleneck-report.md | -| Optimization Plan | <session>/artifacts/optimization-plan.md | -| Benchmark Results | <session>/artifacts/benchmark-results.json | -| Review Report | <session>/artifacts/review-report.md | +--- -3. Include discussion summaries if discuss rounds were used -4. Output pipeline summary: task count, duration, improvement metrics from benchmark results +## Error Handling -5. **Completion Action** (interactive): - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -6. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-perf-opt', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | +| Scenario | Resolution | +|----------|------------| +| Teammate unresponsive | Send follow-up, 2x -> respawn | +| Profiling tool not available | Fallback to static analysis methods | +| Benchmark regression detected | Auto-create FIX task with regression details | +| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues | +| One branch IMPL fails | Mark that branch failed, other branches continue | +| max_branches exceeded | Truncate to top N optimizations by priority at CP-2.5 | diff --git a/.claude/skills/team-perf-opt/roles/optimizer/role.md b/.claude/skills/team-perf-opt/roles/optimizer/role.md new file mode 100644 index 00000000..439f28d2 --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/optimizer/role.md @@ -0,0 +1,97 @@ +--- +role: optimizer +prefix: IMPL +inner_loop: true +additional_prefixes: [FIX] +message_types: + success: impl_complete + error: error + fix: fix_required +--- + +# Code Optimizer + +Implement optimization changes following the strategy plan. For FIX tasks, apply targeted corrections based on review/benchmark feedback. + +## Modes + +| Mode | Task Prefix | Trigger | Focus | +|------|-------------|---------|-------| +| Implement | IMPL | Strategy plan ready | Apply optimizations per plan priority | +| Fix | FIX | Review/bench feedback | Targeted fixes for identified issues | + +## Phase 2: Plan & Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Optimization plan | <session>/artifacts/optimization-plan.md | Yes (IMPL, no branch) | +| Branch optimization detail | <session>/artifacts/branches/B{NN}/optimization-detail.md | Yes (IMPL with branch) | +| Pipeline optimization plan | <session>/artifacts/pipelines/{P}/optimization-plan.md | Yes (IMPL with pipeline) | +| Review/bench feedback | From task description | Yes (FIX) | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Wisdom files | <session>/wisdom/patterns.md | No | +| Context accumulator | From prior IMPL/FIX tasks | Yes (inner loop) | + +1. Extract session path and task mode (IMPL or FIX) from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- load single optimization detail | +| `PipelineId: {P}` | Present | Independent pipeline -- load pipeline-scoped plan | +| Neither present | - | Single mode -- load full optimization plan | + +3. **Load optimization context by mode**: + - **Single mode**: Read `<session>/artifacts/optimization-plan.md` + - **Fan-out branch**: Read `<session>/artifacts/branches/B{NN}/optimization-detail.md` + - **Independent pipeline**: Read `<session>/artifacts/pipelines/{P}/optimization-plan.md` + +4. For FIX: parse review/benchmark feedback for specific issues to address +5. Use ACE search or CLI tools to load implementation context for target files +6. For inner loop (single mode only): load context_accumulator from prior IMPL/FIX tasks + +## Phase 3: Code Implementation + +Implementation backend selection: + +| Backend | Condition | Method | +|---------|-----------|--------| +| CLI | Multi-file optimization with clear plan | ccw cli --tool gemini --mode write | +| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools | + +For IMPL tasks: +- **Single mode**: Apply optimizations in plan priority order (P0 first, then P1, etc.) +- **Fan-out branch**: Apply ONLY this branch's single optimization +- **Independent pipeline**: Apply this pipeline's optimizations in priority order +- Follow implementation guidance from plan (target files, patterns) +- Preserve existing behavior -- optimization must not break functionality + +For FIX tasks: +- Read specific issues from review/benchmark feedback +- Apply targeted corrections to flagged code locations +- Verify the fix addresses the exact concern raised + +General rules: +- Make minimal, focused changes per optimization +- Add comments only where optimization logic is non-obvious +- Preserve existing code style and conventions + +## Phase 4: Self-Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Syntax | IDE diagnostics or build check | No new errors | +| File integrity | Verify all planned files exist and are modified | All present | +| Acceptance | Match optimization plan success criteria | All target metrics addressed | +| No regression | Run existing tests if available | No new failures | + +If validation fails, attempt auto-fix (max 2 attempts) before reporting error. + +Append to context_accumulator for next IMPL/FIX task (single/inner-loop mode only): +- Files modified, optimizations applied, validation results +- Any discovered patterns or caveats for subsequent iterations + +**Branch output paths**: +- Single: write artifacts to `<session>/artifacts/` +- Fan-out: write artifacts to `<session>/artifacts/branches/B{NN}/` +- Independent: write artifacts to `<session>/artifacts/pipelines/{P}/` diff --git a/.claude/skills/team-perf-opt/roles/profiler/role.md b/.claude/skills/team-perf-opt/roles/profiler/role.md new file mode 100644 index 00000000..94e46c76 --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/profiler/role.md @@ -0,0 +1,73 @@ +--- +role: profiler +prefix: PROFILE +inner_loop: false +message_types: + success: profile_complete + error: error +--- + +# Performance Profiler + +Profile application performance to identify CPU, memory, I/O, network, and rendering bottlenecks. Produce quantified baseline metrics and a ranked bottleneck report. + +## Phase 2: Context & Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path and target scope from task description +2. Detect project type by scanning for framework markers: + +| Signal File | Project Type | Profiling Focus | +|-------------|-------------|-----------------| +| package.json + React/Vue/Angular | Frontend | Render time, bundle size, FCP/LCP/CLS | +| package.json + Express/Fastify/NestJS | Backend Node | CPU hotspots, memory, DB queries | +| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | CPU, memory, GC tuning | +| Mixed framework markers | Full-stack | Split into FE + BE profiling passes | +| CLI entry / bin/ directory | CLI Tool | Startup time, throughput, memory peak | +| No detection | Generic | All profiling dimensions | + +3. Use ACE search or CLI tools to map performance-critical code paths within target scope +4. Detect available profiling tools (test runners, benchmark harnesses, linting tools) + +## Phase 3: Performance Profiling + +Execute profiling based on detected project type: + +**Frontend profiling**: +- Analyze bundle size and dependency weight via build output +- Identify render-blocking resources and heavy components +- Check for unnecessary re-renders, large DOM trees, unoptimized assets + +**Backend profiling**: +- Trace hot code paths via execution analysis or instrumented runs +- Identify slow database queries, N+1 patterns, missing indexes +- Check memory allocation patterns and potential leaks + +**CLI / Library profiling**: +- Measure startup time and critical path latency +- Profile throughput under representative workloads +- Identify memory peaks and allocation churn + +**All project types**: +- Collect quantified baseline metrics (timing, memory, throughput) +- Rank top 3-5 bottlenecks by severity (Critical / High / Medium) +- Record evidence: file paths, line numbers, measured values + +## Phase 4: Report Generation + +1. Write baseline metrics to `<session>/artifacts/baseline-metrics.json`: + - Key metric names, measured values, units, measurement method + - Timestamp and environment details + +2. Write bottleneck report to `<session>/artifacts/bottleneck-report.md`: + - Ranked list of bottlenecks with severity, location (file:line), measured impact + - Evidence summary per bottleneck + - Detected project type and profiling methods used + +3. Update `<session>/.msg/meta.json` under `profiler` namespace: + - Read existing -> merge `{ "profiler": { project_type, bottleneck_count, top_bottleneck, scope } }` -> write back diff --git a/.claude/skills/team-perf-opt/roles/reviewer/role.md b/.claude/skills/team-perf-opt/roles/reviewer/role.md new file mode 100644 index 00000000..c14cb888 --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/reviewer/role.md @@ -0,0 +1,75 @@ +--- +role: reviewer +prefix: REVIEW +inner_loop: false +additional_prefixes: [QUALITY] +discuss_rounds: [DISCUSS-REVIEW] +message_types: + success: review_complete + error: error + fix: fix_required +--- + +# Optimization Reviewer + +Review optimization code changes for correctness, side effects, regression risks, and adherence to best practices. Provide structured verdicts with actionable feedback. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Optimization code changes | From IMPL task artifacts / git diff | Yes | +| Optimization plan / detail | Varies by mode (see below) | Yes | +| Benchmark results | Varies by mode (see below) | No | +| .msg/meta.json | <session>/.msg/meta.json | Yes | + +1. Extract session path from task description +2. **Detect branch/pipeline context** from task description: + +| Task Description Field | Value | Context | +|----------------------|-------|---------| +| `BranchId: B{NN}` | Present | Fan-out branch -- review only this branch's changes | +| `PipelineId: {P}` | Present | Independent pipeline -- review pipeline-scoped changes | +| Neither present | - | Single mode -- review all optimization changes | + +3. **Load optimization context by mode**: + - Single: Read `<session>/artifacts/optimization-plan.md` + - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/optimization-detail.md` + - Independent: Read `<session>/artifacts/pipelines/{P}/optimization-plan.md` + +4. Load .msg/meta.json for scoped optimizer namespace +5. Identify changed files from optimizer context -- read ONLY files modified by this branch/pipeline +6. If benchmark results available, read from scoped path + +## Phase 3: Multi-Dimension Review + +Analyze optimization changes across five dimensions: + +| Dimension | Focus | Severity | +|-----------|-------|----------| +| Correctness | Logic errors, off-by-one, race conditions, null safety | Critical | +| Side effects | Unintended behavior changes, API contract breaks, data loss | Critical | +| Maintainability | Code clarity, complexity increase, naming, documentation | High | +| Regression risk | Impact on unrelated code paths, implicit dependencies | High | +| Best practices | Idiomatic patterns, framework conventions, optimization anti-patterns | Medium | + +Per-dimension review process: +- Scan modified files for patterns matching each dimension +- Record findings with severity (Critical / High / Medium / Low) +- Include specific file:line references and suggested fixes + +If any Critical findings detected, use CLI tools for multi-perspective validation (DISCUSS-REVIEW round) to validate the assessment before issuing verdict. + +## Phase 4: Verdict & Feedback + +Classify overall verdict based on findings: + +| Verdict | Condition | Action | +|---------|-----------|--------| +| APPROVE | No Critical or High findings | Send review_complete | +| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback | +| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for strategist escalation | + +1. Write review report to scoped output path (single/fan-out/independent) +2. Update `<session>/.msg/meta.json` under scoped namespace +3. If DISCUSS-REVIEW was triggered, record discussion summary in discussions directory diff --git a/.claude/skills/team-perf-opt/roles/strategist/role.md b/.claude/skills/team-perf-opt/roles/strategist/role.md new file mode 100644 index 00000000..9522fd4d --- /dev/null +++ b/.claude/skills/team-perf-opt/roles/strategist/role.md @@ -0,0 +1,94 @@ +--- +role: strategist +prefix: STRATEGY +inner_loop: false +discuss_rounds: [DISCUSS-OPT] +message_types: + success: strategy_complete + error: error +--- + +# Optimization Strategist + +Analyze bottleneck reports and baseline metrics to design a prioritized optimization plan with concrete strategies, expected improvements, and risk assessments. + +## Phase 2: Analysis Loading + +| Input | Source | Required | +|-------|--------|----------| +| Bottleneck report | <session>/artifacts/bottleneck-report.md | Yes | +| Baseline metrics | <session>/artifacts/baseline-metrics.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Wisdom files | <session>/wisdom/patterns.md | No | + +1. Extract session path from task description +2. Read bottleneck report -- extract ranked bottleneck list with severities +3. Read baseline metrics -- extract current performance numbers +4. Load .msg/meta.json for profiler findings (project_type, scope) +5. Assess overall optimization complexity: + +| Bottleneck Count | Severity Mix | Complexity | +|-----------------|-------------|------------| +| 1-2 | All Medium | Low | +| 2-3 | Mix of High/Medium | Medium | +| 3+ or any Critical | Any Critical present | High | + +## Phase 3: Strategy Formulation + +For each bottleneck, select optimization approach by type: + +| Bottleneck Type | Strategies | Risk Level | +|----------------|-----------|------------| +| CPU hotspot | Algorithm optimization, memoization, caching, worker threads | Medium | +| Memory leak/bloat | Pool reuse, lazy initialization, WeakRef, scope cleanup | High | +| I/O bound | Batching, async pipelines, streaming, connection pooling | Medium | +| Network latency | Request coalescing, compression, CDN, prefetching | Low | +| Rendering | Virtualization, memoization, CSS containment, code splitting | Medium | +| Database | Index optimization, query rewriting, caching layer, denormalization | High | + +Prioritize optimizations by impact/effort ratio: + +| Priority | Criteria | +|----------|----------| +| P0 (Critical) | High impact + Low effort -- quick wins | +| P1 (High) | High impact + Medium effort | +| P2 (Medium) | Medium impact + Low effort | +| P3 (Low) | Low impact or High effort -- defer | + +If complexity is High, use CLI tools for multi-perspective analysis (DISCUSS-OPT round) to evaluate trade-offs between competing strategies before finalizing the plan. + +Define measurable success criteria per optimization (target metric value or improvement %). + +## Phase 4: Plan Output + +1. Write optimization plan to `<session>/artifacts/optimization-plan.md`: + + Each optimization MUST have a unique OPT-ID and self-contained detail block: + + ```markdown + ### OPT-001: <title> + - Priority: P0 + - Target bottleneck: <bottleneck from report> + - Target files: <file-list> + - Strategy: <selected approach> + - Expected improvement: <metric> by <X%> + - Risk level: <Low/Medium/High> + - Success criteria: <specific threshold to verify> + - Implementation guidance: + 1. <step 1> + 2. <step 2> + 3. <step 3> + + ### OPT-002: <title> + ... + ``` + + Requirements: + - Each OPT-ID is sequentially numbered (OPT-001, OPT-002, ...) + - Each optimization must be **non-overlapping** in target files + - Implementation guidance must be self-contained + +2. Update `<session>/.msg/meta.json` under `strategist` namespace: + - Read existing -> merge -> write back with optimization metadata + +3. If DISCUSS-OPT was triggered, record discussion summary in `<session>/discussions/DISCUSS-OPT.md` diff --git a/.claude/skills/team-perf-opt/specs/pipelines.md b/.claude/skills/team-perf-opt/specs/pipelines.md new file mode 100644 index 00000000..9579642c --- /dev/null +++ b/.claude/skills/team-perf-opt/specs/pipelines.md @@ -0,0 +1,65 @@ +# Pipeline Definitions — Team Performance Optimization + +## Pipeline Modes + +### Single Mode (Linear with Review-Fix Cycle) + +``` +Stage 1 Stage 2 Stage 3 Stage 4 +PROFILE-001 --> STRATEGY-001 --> IMPL-001 --> BENCH-001 +[profiler] [strategist] [optimizer] [benchmarker] + ^ | + +<--FIX-001---->+ + | REVIEW-001 + +<--------> [reviewer] + (max 3 iterations) +``` + +### Fan-out Mode (Shared stages 1-2, parallel branches 3-4) + +``` +Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch) +PROFILE-001 --> STRATEGY-001 --+-> IMPL-B01 --> BENCH-B01 + REVIEW-B01 (fix cycle) + +-> IMPL-B02 --> BENCH-B02 + REVIEW-B02 (fix cycle) + +-> IMPL-B0N --> BENCH-B0N + REVIEW-B0N (fix cycle) + | + AGGREGATE -> Phase 5 +``` + +### Independent Mode (M fully independent pipelines) + +``` +Pipeline A: PROFILE-A01 --> STRATEGY-A01 --> IMPL-A01 --> BENCH-A01 + REVIEW-A01 +Pipeline B: PROFILE-B01 --> STRATEGY-B01 --> IMPL-B01 --> BENCH-B01 + REVIEW-B01 + | + AGGREGATE -> Phase 5 +``` + +## Task Metadata Registry (Single Mode) + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| PROFILE-001 | profiler | Stage 1 | (none) | Profile application, identify bottlenecks | +| STRATEGY-001 | strategist | Stage 2 | PROFILE-001 | Design optimization plan from bottleneck report | +| IMPL-001 | optimizer | Stage 3 | STRATEGY-001 | Implement highest-priority optimizations | +| BENCH-001 | benchmarker | Stage 4 | IMPL-001 | Run benchmarks, compare vs baseline | +| REVIEW-001 | reviewer | Stage 4 | IMPL-001 | Review optimization code for correctness | +| FIX-001 | optimizer | Stage 3 (cycle) | REVIEW-001 or BENCH-001 | Fix issues found in review/benchmark | + +## Checkpoints + +| Checkpoint | Trigger | Behavior | +|------------|---------|----------| +| CP-1 | PROFILE-001 complete | User reviews bottleneck report, can refine scope | +| CP-2 | STRATEGY-001 complete | User reviews optimization plan, can adjust priorities | +| CP-2.5 | STRATEGY-001 complete (auto/fan-out) | Auto-create N branch tasks, spawn all IMPL-B* in parallel | +| CP-3 | REVIEW/BENCH fail | Auto-create FIX task for that branch only (max 3x per branch) | +| CP-4 | All tasks/branches complete | Aggregate results, interactive completion action | + +## Task Naming Rules + +| Mode | Stage 3 | Stage 4 | Fix | Retry | +|------|---------|---------|-----|-------| +| Single | IMPL-001 | BENCH-001, REVIEW-001 | FIX-001 | BENCH-001-R1, REVIEW-001-R1 | +| Fan-out | IMPL-B01 | BENCH-B01, REVIEW-B01 | FIX-B01-1 | BENCH-B01-R1, REVIEW-B01-R1 | +| Independent | IMPL-A01 | BENCH-A01, REVIEW-A01 | FIX-A01-1 | BENCH-A01-R1, REVIEW-A01-R1 | diff --git a/.claude/skills/team-planex/SKILL.md b/.claude/skills/team-planex/SKILL.md index 1979879e..68d988e5 100644 --- a/.claude/skills/team-planex/SKILL.md +++ b/.claude/skills/team-planex/SKILL.md @@ -1,304 +1,123 @@ --- name: team-planex -description: Unified team skill for plan-and-execute pipeline. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team planex". -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +description: Unified team skill for plan-and-execute pipeline. Pure router — coordinator always. Beat model is coordinator-only in monitor.md. Triggers on "team planex". +allowed-tools: Agent(*), TaskCreate(*), TaskList(*), TaskGet(*), TaskUpdate(*), TeamCreate(*), TeamDelete(*), SendMessage(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), mcp__ccw-tools__team_msg(*) --- # Team PlanEx -Unified team skill: plan-and-execute pipeline for issue-based development. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. - -> **Note**: This skill has its own coordinator implementation (`roles/coordinator/role.md`), independent of `team-lifecycle`. It follows the same v5 architectural patterns (team-worker agents, role-specs, Spawn-and-Stop) but with a simplified 2-role pipeline (planner + executor) tailored for plan-and-execute workflows. +Unified team skill: plan-and-execute pipeline for issue-based development. Built on **team-worker agent architecture** — coordinator orchestrates, workers are team-worker agents loading role-specific instructions from `roles/<role>/role.md`. ## Architecture ``` -┌─────────────────────────────────────────────┐ -│ Skill(skill="team-planex", args="需求描述") │ -└──────────────────┬──────────────────────────┘ - │ Always → coordinator - ↓ - ┌──────────────┐ - │ coordinator │ Phase 1-5 + dispatch/monitor commands - └───┬──────┬───┘ - │ │ - ↓ ↓ - ┌──────────┐ ┌──────────┐ - │ planner │ │ executor │ team-worker agents - │ PLAN-* │ │ EXEC-* │ with role-spec injection - └──────────┘ └──────────┘ +Skill(skill="team-planex", args="task description") + | + SKILL.md (this file) = Router + | + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +---------------+---------------+ + v v + [planner] [executor] + (team-worker agent, (team-worker agent, + loads roles/planner/role.md) loads roles/executor/role.md) ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| planner | [roles/planner/role.md](roles/planner/role.md) | PLAN-* | true | +| executor | [roles/executor/role.md](roles/executor/role.md) | EXEC-* | true | + ## Role Router -This skill is **coordinator-only**. Workers do NOT invoke this skill — they are spawned as `team-worker` agents directly. +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -### Input Parsing +## Shared Constants -Parse `$ARGUMENTS`. No `--role` needed — always routes to coordinator. +- **Session prefix**: `PEX` +- **Session path**: `.workflow/.team/PEX-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -Optional flags: `--exec` (execution method), `-y`/`--yes` (auto mode). +## Worker Spawn Template -### Role Registry - -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | pipeline | true | -| executor | [role-specs/executor.md](role-specs/executor.md) | EXEC-* | pipeline | true | - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User provides task description. - -**Invocation**: `Skill(skill="team-planex", args="<task-description>")` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: Parse input -> TeamCreate -> Create task chain (dispatch) - -> coordinator Phase 4: spawn planner worker (background) -> STOP - -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances - -> Loop until pipeline complete -> Phase 5 report + completion action -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | -| `add <issue-ids or --text '...' or --plan path>` | Append new tasks to planner queue | - ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** - NOT separate agents or subprocesses -4. **Execute synchronously** - complete the command workflow before proceeding - ---- - -## Input Types - -支持 3 种输入方式: - -| 输入类型 | 格式 | 示例 | -|----------|------|------| -| Issue IDs | 直接传入 ID | `ISS-20260215-001 ISS-20260215-002` | -| 需求文本 | `--text '...'` | `--text '实现用户认证模块'` | -| Plan 文件 | `--plan path` | `--plan plan/2026-02-15-auth.md` | - -## Execution Method Selection - -支持 2 种执行后端: - -| Executor | 后端 | 适用场景 | -|----------|------|----------| -| `codex` | `ccw cli --tool codex --mode write` | 复杂任务、后台执行 | -| `gemini` | `ccw cli --tool gemini --mode write` | 分析类任务、后台执行 | - -### Selection Decision Table - -| Condition | Execution Method | -|-----------|-----------------| -| `--exec=codex` specified | Codex | -| `--exec=gemini` specified | Gemini | -| `-y` or `--yes` flag present | Auto (default Gemini) | -| No flags (interactive) | AskUserQuestion -> user choice | -| Auto + task_count <= 3 | Gemini | -| Auto + task_count > 3 | Codex | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ - agent_type: "team-worker", + subagent_type: "team-worker", description: "Spawn <role> worker", - team_name: <team-name>, + team_name: "planex", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-planex/role-specs/<role>.md +role_spec: .claude/skills/team-planex/roles/<role>/role.md session: <session-folder> session_id: <session-id> -team_name: <team-name> +team_name: planex requirement: <task-description> inner_loop: <true|false> -execution_method: <agent|codex|gemini> +execution_method: <codex|gemini> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (planner, executor): Set `inner_loop: true`. The team-worker agent handles the loop internally. +## User Commands ---- - -## Pipeline Definitions - -### Pipeline Diagram - -``` -Issue-based beat pipeline (逐 Issue 节拍) -═══════════════════════════════════════════════════ - PLAN-001 ──> [planner] issue-1 solution → EXEC-001 - issue-2 solution → EXEC-002 - ... - issue-N solution → EXEC-00N - all_planned signal - - EXEC-001 ──> [executor] implement issue-1 - EXEC-002 ──> [executor] implement issue-2 - ... - EXEC-00N ──> [executor] implement issue-N -═══════════════════════════════════════════════════ -``` - -### Cadence Control - -**Beat model**: Event-driven Spawn-and-Stop. Each beat = coordinator wake -> process callback -> spawn next -> STOP. - -``` -Beat Cycle (Coordinator Spawn-and-Stop) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - 用户调用 ----------> ┌─ Phase 1-3 ──────────┐ - │ 解析输入 │ - │ TeamCreate │ - │ 创建 PLAN-001 │ - ├─ Phase 4 ─────────────┤ - │ spawn planner ────────┼──> [planner] Phase 1-5 - └─ STOP (idle) ──────────┘ │ - │ - callback <─ planner issue_ready ────────────────────────┘ - ┌─ monitor.handleCallback ─┐ - │ 检查新 EXEC-* 任务 │ - │ spawn executor ─────────┼──> [executor] Phase 1-5 - └─ STOP (idle) ───────────┘ │ - │ - callback <─ executor impl_complete ────────┘ - ┌─ monitor.handleCallback ─┐ - │ 标记完成 │ - │ 检查下一个 ready task │ - └─ spawn/STOP ────────────┘ -====================================================================== -``` - -**Checkpoints**: - -| 触发条件 | 位置 | 行为 | -|----------|------|------| -| Planner 全部完成 | all_planned 信号 | Executor 完成剩余 EXEC-* 后结束 | -| Pipeline 停滞 | 无 ready + 无 running | Coordinator escalate to user | -| Executor 阻塞 | blocked > 2 tasks | Coordinator escalate to user | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| PLAN-001 | planner | planning | (none) | 初始规划:需求拆解、issue 创建、方案设计 | -| EXEC-001 | executor | execution | (created by planner at runtime) | 第一个 issue 的代码实现 | -| EXEC-N | executor | execution | (created by planner at runtime) | 第 N 个 issue 的代码实现 | - -> 注: EXEC-* 任务由 planner 在运行时逐个创建(逐 Issue 节拍),不预先定义完整任务链。 - ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): - -```javascript -if (autoYes) { - // Auto mode: Archive & Clean without prompting - completionAction = "Archive & Clean"; -} else { - AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] - }) -} -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | +| `add <issue-ids or --text '...' or --plan path>` | Append new tasks to planner queue | ## Session Directory ``` -.workflow/.team/PEX-{slug}-{date}/ -├── .msg/meta.json # Session state +.workflow/.team/PEX-<slug>-<YYYY-MM-DD>/ +├── .msg/ +│ ├── messages.jsonl # Message bus log +│ └── meta.json # Session state +├── task-analysis.json # Coordinator analyze output ├── artifacts/ │ └── solutions/ # Planner solution output per issue -│ ├── {issueId-1}.json -│ └── {issueId-N}.json -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── .msg/messages.jsonl # Team message bus -└── .msg/meta.json # Session metadata +│ ├── <issueId-1>.json +│ └── <issueId-N>.json +└── wisdom/ # Cross-task knowledge + ├── learnings.md + ├── decisions.md + ├── conventions.md + └── issues.md ``` ---- +## Specs Reference -## Message Bus - -每次 SendMessage 前,先调用 `mcp__ccw-tools__team_msg` 记录: - -- 参数: operation="log", session_id=`<session-id>`, from=`<role>`, type=`<type>`, data={ref: "`<artifact-path>`"} -- `to` and `summary` auto-defaulted -- do NOT specify explicitly -- **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` - -**Message types by role**: - -| Role | Types | -|------|-------| -| planner | `issue_ready`, `all_planned`, `error` | -| executor | `impl_complete`, `impl_failed`, `error` | - ---- +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions, task metadata registry, execution method selection ## Error Handling | Scenario | Resolution | |----------|------------| -| Role spec file not found | Error with expected path (role-specs/<name>.md) | -| Command file not found | Fallback to inline execution in coordinator role.md | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| Role spec file not found | Error with expected path (roles/<name>/role.md) | | team-worker agent unavailable | Error: requires .claude/agents/team-worker.md | | Planner issue planning failure | Retry once, then skip to next issue | | Executor impl failure | Report to coordinator, continue with next EXEC-* task | | Pipeline stall | Coordinator monitors, escalate to user | -| Completion action timeout | Default to Keep Active | +| Worker no response | Report waiting task, suggest user `resume` | diff --git a/.claude/skills/team-planex/roles/coordinator/commands/analyze.md b/.claude/skills/team-planex/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..d7c80da5 --- /dev/null +++ b/.claude/skills/team-planex/roles/coordinator/commands/analyze.md @@ -0,0 +1,52 @@ +# Analyze Task + +Parse plan-and-execute input -> detect input type -> determine execution method -> assess scope. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Input Pattern | Type | Action | +|--------------|------|--------| +| `ISS-\d{8}-\d{6}` pattern | Issue IDs | Use directly | +| `--text '...'` flag | Text requirement | Create issues via CLI | +| `--plan <path>` flag | Plan file | Read file, parse phases | + +## Execution Method Selection + +| Condition | Execution Method | +|-----------|-----------------| +| `--exec=codex` specified | Codex | +| `--exec=gemini` specified | Gemini | +| `-y` or `--yes` flag present | Auto (default Gemini) | +| No flags (interactive) | AskUserQuestion -> user choice | +| Auto + task_count <= 3 | Gemini | +| Auto + task_count > 3 | Codex | + +## Scope Assessment + +| Factor | Complexity | +|--------|------------| +| Issue count 1-3 | Low | +| Issue count 4-10 | Medium | +| Issue count > 10 | High | +| Cross-cutting concern | +1 level | + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "input_type": "<issues|text|plan>", + "raw_input": "<original input>", + "execution_method": "<codex|gemini>", + "issue_count_estimate": 0, + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "pipeline_type": "plan-execute", + "roles": [ + { "name": "planner", "prefix": "PLAN", "inner_loop": true }, + { "name": "executor", "prefix": "EXEC", "inner_loop": true } + ] +} +``` diff --git a/.claude/skills/team-planex/roles/coordinator/commands/monitor.md b/.claude/skills/team-planex/roles/coordinator/commands/monitor.md index 4e6ad4f5..e26cec58 100644 --- a/.claude/skills/team-planex/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-planex/roles/coordinator/commands/monitor.md @@ -118,14 +118,14 @@ Collect task states from TaskList() | +- EXEC-* -> executor +- Spawn team-worker: Agent({ - agent_type: "team-worker", + subagent_type: "team-worker", description: "Spawn <role> worker for <subject>", team_name: <team-name>, name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-planex/role-specs/<role>.md +role_spec: .claude/skills/team-planex/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: <team-name> diff --git a/.claude/skills/team-planex/roles/coordinator/role.md b/.claude/skills/team-planex/roles/coordinator/role.md index 0c2aab14..4f2c8f4d 100644 --- a/.claude/skills/team-planex/roles/coordinator/role.md +++ b/.claude/skills/team-planex/roles/coordinator/role.md @@ -1,11 +1,10 @@ # Coordinator Role -Orchestrate the team-planex pipeline: parse input, create team, dispatch tasks, monitor progress via Spawn-and-Stop beats. Uses **team-worker agent** for all worker spawns. +Orchestrate team-planex: analyze -> dispatch -> spawn -> monitor -> report. ## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse input -> Create team -> Dispatch PLAN-001 -> Spawn planner -> Monitor callbacks -> Spawn executors -> Report +- Name: coordinator | Tag: [coordinator] +- Responsibility: Parse input -> Create team -> Dispatch PLAN-001 -> Spawn planner -> Monitor callbacks -> Spawn executors -> Report ## Boundaries @@ -22,29 +21,22 @@ Orchestrate the team-planex pipeline: parse input, create team, dispatch tasks, - Call implementation CLI tools (code-developer, etc.) directly - Skip dependency validation when creating task chains ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file -3. **Commands are inline execution guides** - NOT separate agents -4. **Execute synchronously** - complete the command workflow before proceeding - ---- +When coordinator needs to execute a command: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[planner]` or `[executor]` tag | -> handleCallback (monitor.md) | -| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) | -| Add tasks | Arguments contain "add" | -> handleAdd | +| Worker callback | Message contains [planner] or [executor] tag | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Add tasks | Args contain "add" | -> handleAdd | | Interrupted session | Active/paused session exists in `.workflow/.team/PEX-*` | -> Phase 0 | | New session | None of above | -> Phase 1 | @@ -58,13 +50,11 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat 4. If planner already sent `all_planned` (check team_msg) -> `SendMessage` to planner to re-enter loop 5. STOP ---- - ## Phase 0: Session Resume Check 1. Scan `.workflow/.team/PEX-*/.msg/meta.json` for sessions with status "active" or "paused" -2. No sessions found -> proceed to Phase 1 -3. Single session found -> resume (Session Reconciliation) +2. No sessions -> Phase 1 +3. Single session -> resume (Session Reconciliation) 4. Multiple sessions -> AskUserQuestion for selection **Session Reconciliation**: @@ -73,20 +63,18 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat 3. Rebuild team if needed (TeamCreate + spawn needed workers) 4. Kick first executable task -> Phase 4 ---- - ## Phase 1: Input Parsing + Execution Method -1. **Parse arguments**: Extract input type (Issue IDs / --text / --plan) and optional flags (--exec, -y) +TEXT-LEVEL ONLY. No source code reading. -2. **Determine execution method** (see SKILL.md Selection Decision Table): +1. Delegate to commands/analyze.md -> produces task-analysis.json +2. Parse arguments: Extract input type (Issue IDs / --text / --plan) and optional flags (--exec, -y) +3. Determine execution method (see specs/pipelines.md Selection Decision Table): - Explicit `--exec` flag -> use specified method - `-y` / `--yes` flag -> Auto mode - No flags -> AskUserQuestion for method choice - -3. **Store requirements**: input_type, raw_input, execution_method - ---- +4. Store requirements: input_type, raw_input, execution_method +5. CRITICAL: Always proceed to Phase 2, never skip team workflow ## Phase 2: Create Team + Initialize Session @@ -97,57 +85,46 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat 5. Initialize wisdom files (learnings.md, decisions.md, conventions.md, issues.md) 6. Initialize meta.json with pipeline metadata: ```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", data: { pipeline_mode: "plan-execute", pipeline_stages: ["planner", "executor"], roles: ["coordinator", "planner", "executor"], team_name: "planex", input_type: "<issues|text|plan>", - execution_method: "<agent|codex|gemini>" + execution_method: "<codex|gemini>" } }) ``` ---- - ## Phase 3: Create Task Chain Delegate to `commands/dispatch.md`: - 1. Read `roles/coordinator/commands/dispatch.md` 2. Execute its workflow to create PLAN-001 task 3. PLAN-001 contains input info + execution method in description ---- - ## Phase 4: Spawn-and-Stop 1. Load `commands/monitor.md` 2. Execute `handleSpawnNext` to find ready tasks and spawn planner worker 3. Output status summary -4. **STOP** (idle, wait for worker callback) +4. STOP (idle, wait for worker callback) **ONE_STEP_PER_INVOCATION**: true — coordinator does one operation per wake-up, then STOPS. ---- - ## Phase 5: Report + Completion Action -When all tasks are complete (monitor.md detects PIPELINE_COMPLETE): - 1. Load session state -> count completed tasks, duration 2. List deliverables with output paths 3. Update session status -> "completed" -4. Execute Completion Action (see SKILL.md) - ---- +4. Execute Completion Action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) + - auto_yes -> Archive & Clean without prompting ## Error Handling diff --git a/.claude/skills/team-planex/roles/executor/role.md b/.claude/skills/team-planex/roles/executor/role.md new file mode 100644 index 00000000..1e30741d --- /dev/null +++ b/.claude/skills/team-planex/roles/executor/role.md @@ -0,0 +1,91 @@ +--- +role: executor +prefix: EXEC +inner_loop: true +message_types: + success: impl_complete + error: impl_failed +--- + +# Executor + +Single-issue implementation agent. Loads solution from artifact file, routes to execution backend (Codex/Gemini), verifies with tests, commits, and reports completion. + +## Phase 2: Task & Solution Loading + +| Input | Source | Required | +|-------|--------|----------| +| Issue ID | Task description `Issue ID:` field | Yes | +| Solution file | Task description `Solution file:` field | Yes | +| Session folder | Task description `Session:` field | Yes | +| Execution method | Task description `Execution method:` field | Yes | +| Wisdom | `<session>/wisdom/` | No | + +1. Extract issue ID, solution file path, session folder, execution method +2. Load solution JSON from file (file-first) +3. If file not found -> fallback: `ccw issue solution <issueId> --json` +4. Load wisdom files for conventions and patterns +5. Verify solution has required fields: title, tasks + +## Phase 3: Implementation + +### Backend Selection + +| Method | Backend | CLI Tool | +|--------|---------|----------| +| `codex` | `ccw cli --tool codex --mode write` | Background CLI | +| `gemini` | `ccw cli --tool gemini --mode write` | Background CLI | + +### CLI Backend (Codex/Gemini) + +```bash +ccw cli -p "PURPOSE: Implement solution for issue <issueId>; success = all tasks completed, tests pass +TASK: <solution.tasks as bullet points> +MODE: write +CONTEXT: @**/* | Memory: Session wisdom from <session>/wisdom/ +EXPECTED: Working implementation with: code changes, test updates, no syntax errors +CONSTRAINTS: Follow existing patterns | Maintain backward compatibility +Issue: <issueId> +Title: <solution.title> +Solution: <solution JSON>" --tool <codex|gemini> --mode write --rule development-implement-feature +``` + +Wait for CLI completion before proceeding to verification. + +## Phase 4: Verification + Commit + +### Test Verification + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Tests | Detect and run project test command | All pass | +| Syntax | IDE diagnostics or `tsc --noEmit` | No errors | + +If tests fail: retry implementation once, then report `impl_failed`. + +### Commit + +```bash +git add -A +git commit -m "feat(<issueId>): <solution.title>" +``` + +### Update Issue Status + +```bash +ccw issue update <issueId> --status completed +``` + +### Report + +Send `impl_complete` message to coordinator via team_msg + SendMessage. + +## Boundaries + +| Allowed | Prohibited | +|---------|-----------| +| Load solution from file | Create or modify issues | +| Implement via CLI tools (Codex/Gemini) | Modify solution artifacts | +| Run tests | Spawn additional agents (use CLI tools instead) | +| git commit | Direct user interaction | +| Update issue status | Create tasks for other roles | diff --git a/.claude/skills/team-planex/roles/planner/role.md b/.claude/skills/team-planex/roles/planner/role.md new file mode 100644 index 00000000..2c814a92 --- /dev/null +++ b/.claude/skills/team-planex/roles/planner/role.md @@ -0,0 +1,111 @@ +--- +role: planner +prefix: PLAN +inner_loop: true +message_types: + success: issue_ready + error: error +--- + +# Planner + +Requirement decomposition -> issue creation -> solution design -> EXEC-* task creation. Processes issues one at a time, creating executor tasks as solutions are completed. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Input type + raw input | Task description | Yes | +| Session folder | Task description `Session:` field | Yes | +| Execution method | Task description `Execution method:` field | Yes | +| Wisdom | `<session>/wisdom/` | No | + +1. Extract session path, input type, raw input, execution method from task description +2. Load wisdom files if available +3. Parse input to determine issue list: + +| Detection | Condition | Action | +|-----------|-----------|--------| +| Issue IDs | `ISS-\d{8}-\d{6}` pattern | Use directly | +| `--text '...'` | Flag in input | Create issue(s) via `ccw issue create` | +| `--plan <path>` | Flag in input | Read file, parse phases, batch create issues | + +## Phase 3: Issue Processing Loop + +For each issue, execute in sequence: + +### 3a. Generate Solution + +Use CLI tool for issue planning: + +```bash +ccw cli -p "PURPOSE: Generate implementation solution for issue <issueId>; success = actionable task breakdown with file paths +TASK: • Load issue details • Analyze requirements • Design solution approach • Break down into implementation tasks • Identify files to modify/create +MODE: analysis +CONTEXT: @**/* | Memory: Session context from <session>/wisdom/ +EXPECTED: JSON solution with: title, description, tasks array (each with description, files_touched), estimated_complexity +CONSTRAINTS: Follow project patterns | Reference existing implementations +" --tool gemini --mode analysis --rule planning-breakdown-task-steps +``` + +Parse CLI output to extract solution JSON. If CLI fails, fallback to `ccw issue solution <issueId> --json`. + +### 3b. Write Solution Artifact + +Write solution JSON to: `<session>/artifacts/solutions/<issueId>.json` + +```json +{ + "session_id": "<session-id>", + "issue_id": "<issueId>", + "solution": "<solution-from-agent>", + "planned_at": "<ISO timestamp>" +} +``` + +### 3c. Check Conflicts + +Extract `files_touched` from solution. Compare against prior solutions in session. +Overlapping files -> log warning to `wisdom/issues.md`, continue. + +### 3d. Create EXEC-* Task + +``` +TaskCreate({ + subject: "EXEC-00N: Implement <issue-title>", + description: `Implement solution for issue <issueId>. + +Issue ID: <issueId> +Solution file: <session>/artifacts/solutions/<issueId>.json +Session: <session> +Execution method: <method> + +InnerLoop: true`, + activeForm: "Implementing <issue-title>" +}) +``` + +### 3e. Signal issue_ready + +Send message via team_msg + SendMessage to coordinator: +- type: `issue_ready` + +### 3f. Continue Loop + +Process next issue. Do NOT wait for executor. + +## Phase 4: Completion Signal + +After all issues processed: +1. Send `all_planned` message to coordinator via team_msg + SendMessage +2. Summary: total issues planned, EXEC-* tasks created + +## Boundaries + +| Allowed | Prohibited | +|---------|-----------| +| Parse input, create issues | Write/modify business code | +| Generate solutions (CLI) | Run tests | +| Write solution artifacts | git commit | +| Create EXEC-* tasks | Call code-developer | +| Conflict checking | Direct user interaction | diff --git a/.claude/skills/team-planex/specs/pipelines.md b/.claude/skills/team-planex/specs/pipelines.md new file mode 100644 index 00000000..3de0fc07 --- /dev/null +++ b/.claude/skills/team-planex/specs/pipelines.md @@ -0,0 +1,93 @@ +# PlanEx Pipeline Definitions + +## Pipeline Diagram + +Issue-based beat pipeline — planner creates EXEC-* tasks at runtime as solutions are completed. + +``` +PLAN-001 ──> [planner] issue-1 solution -> EXEC-001 + issue-2 solution -> EXEC-002 + ... + issue-N solution -> EXEC-00N + all_planned signal + +EXEC-001 ──> [executor] implement issue-1 +EXEC-002 ──> [executor] implement issue-2 +... +EXEC-00N ──> [executor] implement issue-N +``` + +## Beat Cycle + +Event-driven Spawn-and-Stop. Each beat = coordinator wake -> process callback -> spawn next -> STOP. + +``` +Event Coordinator Workers +---------------------------------------------------------------------- +User invokes -------> Phase 1-3: + Parse input + TeamCreate + Create PLAN-001 + Phase 4: + spawn planner ---------> [planner] Phase 1-5 + STOP (idle) | + | +callback <-- planner issue_ready -(per issue)-----------+ + handleCallback: + detect new EXEC-* tasks + spawn executor ---------------------> [executor] Phase 1-5 + STOP (idle) | + | +callback <-- executor impl_complete ---------------------+ + handleCallback: + mark issue done + check next ready EXEC-* + spawn next executor / STOP +``` + +## Task Metadata Registry + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| PLAN-001 | planner | (none) | Requirement decomposition: parse input, create issues, generate solutions, create EXEC-* tasks | +| EXEC-001 | executor | PLAN-001 (created at runtime by planner) | Implement solution for issue #1 | +| EXEC-002 | executor | PLAN-001 (created at runtime by planner) | Implement solution for issue #2 | +| EXEC-00N | executor | PLAN-001 (created at runtime by planner) | Implement solution for issue #N | + +> EXEC-* tasks are created by planner at runtime (per-issue beat), not predefined in the task chain. + +## Execution Method Selection + +| Condition | Execution Method | +|-----------|-----------------| +| `--exec=codex` specified | codex | +| `--exec=gemini` specified | gemini | +| `-y` or `--yes` flag present | Auto (default gemini) | +| No flags (interactive) | AskUserQuestion -> user choice | +| Auto + task_count <= 3 | gemini | +| Auto + task_count > 3 | codex | + +## Input Type Detection + +| Input Pattern | Type | Action | +|--------------|------|--------| +| `ISS-\d{8}-\d{6}` pattern | Issue IDs | Use directly | +| `--text '...'` flag | Text requirement | Create issues via `ccw issue create` | +| `--plan <path>` flag | Plan file | Read file, parse phases, batch create issues | + +## Checkpoints + +| Trigger | Condition | Action | +|---------|-----------|--------| +| Planner complete | all_planned signal received | Wait for remaining EXEC-* executors to finish | +| Pipeline stall | No ready tasks + no running tasks + has pending | Coordinator checks blockedBy chains, escalates to user | +| Executor blocked | blocked > 2 tasks | Coordinator escalates to user | + +## Scope Assessment + +| Factor | Complexity | +|--------|------------| +| Issue count 1-3 | Low | +| Issue count 4-10 | Medium | +| Issue count > 10 | High | +| Cross-cutting concern | +1 level | diff --git a/.claude/skills/team-quality-assurance/SKILL.md b/.claude/skills/team-quality-assurance/SKILL.md index 5fd45d14..e2def671 100644 --- a/.claude/skills/team-quality-assurance/SKILL.md +++ b/.claude/skills/team-quality-assurance/SKILL.md @@ -1,373 +1,74 @@ --- name: team-quality-assurance -description: Unified team skill for quality assurance team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team quality-assurance", "team qa". +description: Unified team skill for quality assurance. Full closed-loop QA combining issue discovery and software testing. Triggers on "team quality-assurance", "team qa". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) --- # Team Quality Assurance -Unified team skill: quality assurance combining issue discovery and software testing into a closed loop of scout -> strategy -> generate -> execute -> analyze. Uses multi-perspective scanning, Generator-Executor pipeline, and shared defect pattern database for progressive quality assurance. All team members invoke with `--role=xxx` to route to role-specific execution. +Orchestrate multi-agent QA: scout -> strategist -> generator -> executor -> analyst. Supports discovery, testing, and full closed-loop modes with parallel generation and GC loops. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-quality-assurance") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-quality-assurance", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-----+-----+-----+-----+-----+ - v v v v v - [tw] [tw] [tw] [tw] [tw] -scout stra- gene- execu- analy- - tegist rator tor st - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+-------+-------+ + v v v v v + [scout] [strat] [gen] [exec] [analyst] + team-worker agents, each loads roles/<role>/role.md ``` -## Command Architecture +## Role Registry -``` -roles/ -├── coordinator/ -│ ├── role.md # Pipeline orchestration (mode selection, task dispatch, monitoring) -│ └── commands/ -│ ├── dispatch.md # Task chain creation -│ └── monitor.md # Progress monitoring -├── scout/ -│ ├── role.md # Multi-perspective issue scanning -│ └── commands/ -│ └── scan.md # Multi-perspective CLI fan-out scanning -├── strategist/ -│ ├── role.md # Test strategy formulation -│ └── commands/ -│ └── analyze-scope.md # Change scope analysis -├── generator/ -│ ├── role.md # Test case generation -│ └── commands/ -│ └── generate-tests.md # Layer-based test code generation -├── executor/ -│ ├── role.md # Test execution and fix cycles -│ └── commands/ -│ └── run-fix-cycle.md # Iterative test-fix loop -└── analyst/ - ├── role.md # Quality analysis reporting - └── commands/ - └── quality-report.md # Defect pattern + coverage analysis -``` - -**Design principle**: role.md retains Phase 1 (Task Discovery) and Phase 5 (Report) inline. Phase 2-4 delegate to `commands/*.md` based on complexity. +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| scout | [roles/scout/role.md](roles/scout/role.md) | SCOUT-* | false | +| strategist | [roles/strategist/role.md](roles/strategist/role.md) | QASTRAT-* | false | +| generator | [roles/generator/role.md](roles/generator/role.md) | QAGEN-* | false | +| executor | [roles/executor/role.md](roles/executor/role.md) | QARUN-* | true | +| analyst | [roles/analyst/role.md](roles/analyst/role.md) | QAANA-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` -> Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` -> Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent -> Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `QA` +- **Session path**: `.workflow/.team/QA-<slug>-<date>/` +- **Team name**: `quality-assurance` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| scout | [role-specs/scout.md](role-specs/scout.md) | SCOUT-* | false | -| strategist | [role-specs/strategist.md](role-specs/strategist.md) | QASTRAT-* | false | -| generator | [role-specs/generator.md](role-specs/generator.md) | QAGEN-* | false | -| executor | [role-specs/executor.md](role-specs/executor.md) | QARUN-* | true | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | QAANA-* | false | +## Worker Spawn Template -> **COMPACT PROTECTION**: Role files are execution documents, not reference material. When context compression occurs and role instructions are reduced to summaries, **you MUST immediately `Read` the corresponding role.md to reload before continuing execution**. Do not execute any Phase based on summaries. - -### 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-quality-assurance", args="<task-description>")` - -**Lifecycle**: -``` -User provides task description - -> coordinator Phase 1-3: Mode detection + requirement clarification -> TeamCreate -> Create task chain - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker executes -> SendMessage callback -> coordinator advances next step - -> Loop until pipeline complete -> Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks -> idle wait -4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete -> skip to Phase 5 report completion -- Artifact incomplete or missing -> normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -#### Output Tagging - -All outputs must carry `[role_name]` prefix. - -#### Coordinator Isolation - -| Allowed | Forbidden | -|---------|-----------| -| Requirement clarification (AskUserQuestion) | Direct test writing | -| Create task chain (TaskCreate) | Direct test execution or scanning | -| Mode selection + quality gating | Direct coverage analysis | -| Monitor progress (message bus) | Bypassing workers | - -#### Worker Isolation - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| Share state via team_msg(type='state_update') | Create tasks for other roles | -| SendMessage to coordinator | Communicate directly with other workers | -| Delegate to commands/ files | Modify resources outside own responsibility | - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | quality-assurance | -| Session directory | `.workflow/.team/QA-<slug>-<date>/` | -| Test layers | L1: Unit (80%), L2: Integration (60%), L3: E2E (40%) | -| Scan perspectives | bug, security, ux, test-coverage, code-quality | - -### Shared Memory - -Cross-role accumulated knowledge stored via team_msg(type='state_update'): - -| Field | Owner | Content | -|-------|-------|---------| -| `discovered_issues` | scout | Multi-perspective scan findings | -| `test_strategy` | strategist | Layer selection, coverage targets, scope | -| `generated_tests` | generator | Test file paths and metadata | -| `execution_results` | executor | Test run results and coverage data | -| `defect_patterns` | analyst | Recurring defect pattern database | -| `quality_score` | analyst | Overall quality assessment | -| `coverage_history` | analyst | Coverage trend over time | - -Each role reads in Phase 2, writes own fields in Phase 5. - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log. - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `mode_selected`, `gc_loop_trigger`, `quality_gate`, `task_unblocked`, `error`, `shutdown` | -| scout | `scan_ready`, `issues_found`, `error` | -| strategist | `strategy_ready`, `error` | -| generator | `tests_generated`, `tests_revised`, `error` | -| executor | `tests_passed`, `tests_failed`, `coverage_report`, `error` | -| analyst | `analysis_ready`, `quality_report`, `error` | - ---- - -## Three-Mode Pipeline Architecture - -### Mode Auto-Detection - -| Condition | Mode | -|-----------|------| -| Explicit `--mode=discovery` flag | discovery | -| Explicit `--mode=testing` flag | testing | -| Explicit `--mode=full` flag | full | -| Task description contains: discovery/scan/issue keywords | discovery | -| Task description contains: test/coverage/TDD keywords | testing | -| No explicit flag and no keyword match | full (default) | - -### Pipeline Diagrams - -``` -Discovery Mode (issue discovery first): - SCOUT-001(multi-perspective scan) -> QASTRAT-001 -> QAGEN-001 -> QARUN-001 -> QAANA-001 - -Testing Mode (skip scout, test first): - QASTRAT-001(change analysis) -> QAGEN-001(L1) -> QARUN-001(L1) -> QAGEN-002(L2) -> QARUN-002(L2) -> QAANA-001 - -Full QA Mode (complete closed loop): - SCOUT-001(scan) -> QASTRAT-001(strategy) - -> [QAGEN-001(L1) || QAGEN-002(L2)](parallel) -> [QARUN-001 || QARUN-002](parallel) - -> QAANA-001(analysis) -> SCOUT-002(regression scan) -``` - -### Generator-Executor Pipeline (GC Loop) - -Generator and executor iterate per test layer until coverage targets are met: - -``` -QAGEN -> QARUN -> (if coverage < target) -> QAGEN-fix -> QARUN-2 - (if coverage >= target) -> next layer or QAANA -``` - -Coordinator monitors GC loop progress. After 3 GC iterations without convergence, accept current coverage with warning. - -In Full QA mode, spawn N generator agents in parallel (one per test layer). Each receives a QAGEN-N task with layer assignment. Use `run_in_background: true` for all spawns, then coordinator stops and waits for callbacks. Similarly spawn N executor agents in parallel for QARUN-N tasks. - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──> ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──> [Worker A] Phase 1-5 - │ (parallel OK) ──┼──> [Worker B] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback <─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat view**: - -``` -Discovery mode (5 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 - │ │ │ │ │ - SCOUT -> STRAT -> GEN -> RUN -> ANA - ▲ ▲ - pipeline pipeline - start done - -S=SCOUT STRAT=QASTRAT GEN=QAGEN RUN=QARUN ANA=QAANA - -Testing mode (6 beats, layer progression) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 - │ │ │ │ │ │ - STRAT -> GEN-L1 -> RUN-L1 -> GEN-L2 -> RUN-L2 -> ANA - ▲ ▲ - no scout analysis - (test only) - -Full QA mode (6 beats, with parallel windows + regression) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 - │ │ ┌────┴────┐ ┌────┴────┐ │ │ - SCOUT -> STRAT -> GEN-L1||GEN-L2 -> RUN-1||RUN-2 -> ANA -> SCOUT-2 - ▲ ▲ - parallel gen regression - scan -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| GC loop limit | QARUN coverage < target | After 3 iterations, accept current coverage with warning | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | -| Regression scan (full mode) | QAANA-001 complete | Trigger SCOUT-002 for regression verification | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| GC loop exceeded | generator/executor iteration > 3 | Terminate loop, output latest coverage report | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| SCOUT-001 | scout | discovery | (none) | Multi-perspective issue scanning | -| QASTRAT-001 | strategist | strategy | SCOUT-001 or (none) | Change scope analysis + test strategy | -| QAGEN-001 | generator | generation | QASTRAT-001 | L1 unit test generation | -| QAGEN-002 | generator | generation | QASTRAT-001 (full mode) | L2 integration test generation | -| QARUN-001 | executor | execution | QAGEN-001 | L1 test execution + fix cycles | -| QARUN-002 | executor | execution | QAGEN-002 (full mode) | L2 test execution + fix cycles | -| QAANA-001 | analyst | analysis | QARUN-001 (+ QARUN-002) | Defect pattern analysis + quality report | -| SCOUT-002 | scout | regression | QAANA-001 (full mode) | Regression scan after fixes | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ - agent_type: "team-worker", + subagent_type: "team-worker", description: "Spawn <role> worker", team_name: "quality-assurance", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-quality-assurance/role-specs/<role>.md +role_spec: .claude/skills/team-quality-assurance/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: quality-assurance @@ -375,56 +76,23 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (executor): Set `inner_loop: true`. +## User Commands -**Single-task roles** (scout, strategist, generator, analyst): Set `inner_loop: false`. - -### Parallel Spawn (N agents for same role) - -> When pipeline has parallel tasks assigned to the same role, spawn N distinct team-worker agents with unique names. - -**Parallel detection**: - -| Condition | Action | -|-----------|--------| -| N parallel tasks for same role prefix | Spawn N agents named `<role>-1`, `<role>-2` ... | -| Single task for role | Standard spawn (single agent) | - -**Parallel spawn template**: - -``` -Agent({ - agent_type: "team-worker", - description: "Spawn <role>-<N> worker", - team_name: "quality-assurance", - name: "<role>-<N>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-quality-assurance/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: quality-assurance -requirement: <task-description> -agent_name: <role>-<N> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery, owner=<role>-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - -**Dispatch must match agent names**: In dispatch, parallel tasks use instance-specific owner: `<role>-<N>`. - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View pipeline status graph | +| `resume` / `continue` | Advance to next step | +| `--mode=discovery` | Force discovery mode | +| `--mode=testing` | Force testing mode | +| `--mode=full` | Force full QA mode | ## Completion Action -When the pipeline completes (all tasks done, coordinator Phase 5): +When pipeline completes, coordinator presents: ``` AskUserQuestion({ @@ -433,55 +101,41 @@ AskUserQuestion({ header: "Completion", multiSelect: false, options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory" } ] }] }) ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-quality-assurance", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - -## Unified Session Directory +## Session Directory ``` -.workflow/.team/QA-<slug>-<YYYY-MM-DD>/ -├── .msg/meta.json # Session state -├── .msg/messages.jsonl # Team message bus -├── .msg/meta.json # Session metadata -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── scan/ # Scout output -│ └── scan-results.json -├── strategy/ # Strategist output -│ └── test-strategy.md -├── tests/ # Generator output -│ ├── L1-unit/ -│ ├── L2-integration/ -│ └── L3-e2e/ -├── results/ # Executor output -│ ├── run-001.json -│ └── coverage-001.json -└── analysis/ # Analyst output - └── quality-report.md +.workflow/.team/QA-<slug>-<date>/ +├── .msg/messages.jsonl # Team message bus +├── .msg/meta.json # Session state + shared memory +├── wisdom/ # Cross-task knowledge +├── scan/ # Scout output +├── strategy/ # Strategist output +├── tests/ # Generator output (L1/, L2/, L3/) +├── results/ # Executor output +└── analysis/ # Analyst output ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry +- [specs/team-config.json](specs/team-config.json) — Team configuration and shared memory schema + ## Error Handling | Scenario | Resolution | |----------|------------| | Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode -> auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>/role.md) | -| Task prefix conflict | Log warning, proceed | -| Coverage never reaches target | After 3 GC loops, accept current with warning | +| Role not found | Error with expected path (roles/<name>/role.md) | +| CLI tool fails | Worker fallback to direct implementation | | Scout finds no issues | Report clean scan, skip to testing mode | -| Test environment broken | Notify user, suggest manual fix | +| GC loop exceeded | Accept current coverage with warning | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-quality-assurance/roles/analyst/role.md b/.claude/skills/team-quality-assurance/roles/analyst/role.md new file mode 100644 index 00000000..4d850f0d --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/analyst/role.md @@ -0,0 +1,80 @@ +--- +role: analyst +prefix: QAANA +inner_loop: false +message_types: + success: analysis_ready + report: quality_report + error: error +--- + +# Quality Analyst + +Analyze defect patterns, coverage gaps, test effectiveness, and generate comprehensive quality reports. Maintain defect pattern database and provide quality scoring. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Discovered issues | meta.json -> discovered_issues | No | +| Test strategy | meta.json -> test_strategy | No | +| Generated tests | meta.json -> generated_tests | No | +| Execution results | meta.json -> execution_results | No | +| Historical patterns | meta.json -> defect_patterns | No | + +1. Extract session path from task description +2. Read .msg/meta.json for all accumulated QA data +3. Read coverage data from `coverage/coverage-summary.json` if available +4. Read layer execution results from `<session>/results/run-*.json` +5. Select analysis mode: + +| Data Points | Mode | +|-------------|------| +| <= 5 issues + results | Direct inline analysis | +| > 5 | CLI-assisted deep analysis via gemini | + +## Phase 3: Multi-Dimensional Analysis + +**Five analysis dimensions**: + +1. **Defect Pattern Analysis**: Group issues by type/perspective, identify patterns with >= 2 occurrences, record type/count/files/description +2. **Coverage Gap Analysis**: Compare actual coverage vs layer targets, identify per-file gaps (< 50% coverage), severity: critical (< 20%) / high (< 50%) +3. **Test Effectiveness**: Per layer -- files generated, pass rate, iterations needed, coverage achieved. Effective = pass_rate >= 95% AND iterations <= 2 +4. **Quality Trend**: Compare against coverage_history. Trend: improving (delta > 5%), declining (delta < -5%), stable +5. **Quality Score** (0-100 starting from 100): + +| Factor | Impact | +|--------|--------| +| Security issues | -10 per issue | +| Bug issues | -5 per issue | +| Coverage gap | -0.5 per gap percentage | +| Test failures | -(100 - pass_rate) * 0.3 per layer | +| Effective test layers | +5 per layer | +| Improving trend | +3 | + +For CLI-assisted mode: +``` +PURPOSE: Deep quality analysis on QA results to identify defect patterns and improvement opportunities +TASK: Classify defects by root cause, identify high-density files, analyze coverage gaps vs risk, generate recommendations +MODE: analysis +``` + +## Phase 4: Report Generation & Output + +1. Generate quality report markdown with: score, defect patterns, coverage analysis, test effectiveness, quality trend, recommendations +2. Write report to `<session>/analysis/quality-report.md` +3. Update `<session>/wisdom/.msg/meta.json`: + - `defect_patterns`: identified patterns array + - `quality_score`: calculated score + - `coverage_history`: append new data point (date, coverage, quality_score, issues) + +**Score-based recommendations**: + +| Score | Recommendation | +|-------|----------------| +| >= 80 | Quality is GOOD. Maintain current testing practices. | +| 60-79 | Quality needs IMPROVEMENT. Focus on coverage gaps and recurring patterns. | +| < 60 | Quality is CONCERNING. Recommend comprehensive review and testing effort. | diff --git a/.claude/skills/team-quality-assurance/roles/coordinator/commands/analyze.md b/.claude/skills/team-quality-assurance/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..87fe921a --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/coordinator/commands/analyze.md @@ -0,0 +1,72 @@ +# Analyze Task + +Parse user task -> detect QA capabilities -> build dependency graph -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| scan, discover, find issues, audit | scout | SCOUT | +| strategy, plan, test layers, coverage | strategist | QASTRAT | +| generate tests, write tests, create tests | generator | QAGEN | +| run tests, execute, fix tests | executor | QARUN | +| analyze, report, quality score | analyst | QAANA | + +## QA Mode Detection + +| Condition | Mode | +|-----------|------| +| Keywords: discovery, scan, issues, bug-finding | discovery | +| Keywords: test, coverage, TDD, unit, integration | testing | +| Both keyword types OR no clear match | full | + +## Dependency Graph + +Natural ordering tiers for QA pipeline: +- Tier 0: scout (issue discovery) +- Tier 1: strategist (strategy requires scout discoveries) +- Tier 2: generator (generation requires strategy) +- Tier 3: executor (execution requires generated tests) +- Tier 4: analyst (analysis requires execution results) + +## Pipeline Definitions + +``` +Discovery Mode: SCOUT -> QASTRAT -> QAGEN(L1) -> QARUN(L1) -> QAANA +Testing Mode: QASTRAT -> QAGEN(L1) -> QARUN(L1) -> QAGEN(L2) -> QARUN(L2) -> QAANA +Full Mode: SCOUT -> QASTRAT -> [QAGEN(L1) || QAGEN(L2)] -> [QARUN(L1) || QARUN(L2)] -> QAANA -> SCOUT(regression) +``` + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per capability | +1 | +| Cross-domain (test + discovery) | +2 | +| Parallel tracks | +1 per track | +| Serial depth > 3 | +1 | + +Results: 1-3 Low, 4-6 Medium, 7+ High + +## Role Minimization + +- Cap at 6 roles (coordinator + 5 workers) +- Merge overlapping capabilities +- Absorb trivial single-step roles + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_mode": "<discovery|testing|full>", + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "gc_loop_enabled": true +} +``` diff --git a/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md b/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md index e01001eb..7140c475 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md @@ -1,167 +1,111 @@ -# Command: dispatch +# Dispatch Tasks -> 任务链创建与依赖管理。根据 QA 模式创建 pipeline 任务链并分配给 worker 角色。 +Create task chains from dependency graph with proper blockedBy relationships. +## Workflow -## When to Use +1. Read task-analysis.json -> extract pipeline_mode and dependency_graph +2. Read specs/pipelines.md -> get task registry for selected pipeline +3. Topological sort tasks (respect blockedBy) +4. Validate all owners exist in role registry (SKILL.md) +5. For each task (in order): + - TaskCreate with structured description (see template below) + - TaskUpdate with blockedBy + owner assignment +6. Update session.json with pipeline.tasks_total +7. Validate chain (no orphans, no cycles, all refs valid) -- Phase 3 of Coordinator -- QA 模式已确定,需要创建任务链 -- 团队已创建,worker 已 spawn - -**Trigger conditions**: -- Coordinator Phase 2 完成后 -- 模式切换需要重建任务链 -- GC 循环需要创建修复任务 - -## Strategy - -### Delegation Mode - -**Mode**: Direct(coordinator 直接操作 TaskCreate/TaskUpdate) - -### Decision Logic - -```javascript -// 根据 qaMode 选择 pipeline -function buildPipeline(qaMode, sessionFolder, taskDescription) { - const pipelines = { - 'discovery': [ - { prefix: 'SCOUT', owner: 'scout', desc: '多视角问题扫描', blockedBy: [] }, - { prefix: 'QASTRAT', owner: 'strategist', desc: '测试策略制定', blockedBy: ['SCOUT'] }, - { prefix: 'QAGEN', owner: 'generator', desc: '测试代码生成 (L1)', meta: 'layer: L1', blockedBy: ['QASTRAT'] }, - { prefix: 'QARUN', owner: 'executor', desc: '测试执行 (L1)', meta: 'layer: L1', blockedBy: ['QAGEN'] }, - { prefix: 'QAANA', owner: 'analyst', desc: '质量分析报告', blockedBy: ['QARUN'] } - ], - 'testing': [ - { prefix: 'QASTRAT', owner: 'strategist', desc: '测试策略制定', blockedBy: [] }, - { prefix: 'QAGEN-L1', owner: 'generator', desc: '测试代码生成 (L1)', meta: 'layer: L1', blockedBy: ['QASTRAT'] }, - { prefix: 'QARUN-L1', owner: 'executor', desc: '测试执行 (L1)', meta: 'layer: L1', blockedBy: ['QAGEN-L1'] }, - { prefix: 'QAGEN-L2', owner: 'generator', desc: '测试代码生成 (L2)', meta: 'layer: L2', blockedBy: ['QARUN-L1'] }, - { prefix: 'QARUN-L2', owner: 'executor', desc: '测试执行 (L2)', meta: 'layer: L2', blockedBy: ['QAGEN-L2'] }, - { prefix: 'QAANA', owner: 'analyst', desc: '质量分析报告', blockedBy: ['QARUN-L2'] } - ], - 'full': [ - { prefix: 'SCOUT', owner: 'scout', desc: '多视角问题扫描', blockedBy: [] }, - { prefix: 'QASTRAT', owner: 'strategist', desc: '测试策略制定', blockedBy: ['SCOUT'] }, - { prefix: 'QAGEN-L1', owner: 'generator-1', desc: '测试代码生成 (L1)', meta: 'layer: L1', blockedBy: ['QASTRAT'] }, - { prefix: 'QAGEN-L2', owner: 'generator-2', desc: '测试代码生成 (L2)', meta: 'layer: L2', blockedBy: ['QASTRAT'] }, - { prefix: 'QARUN-L1', owner: 'executor-1', desc: '测试执行 (L1)', meta: 'layer: L1', blockedBy: ['QAGEN-L1'] }, - { prefix: 'QARUN-L2', owner: 'executor-2', desc: '测试执行 (L2)', meta: 'layer: L2', blockedBy: ['QAGEN-L2'] }, - { prefix: 'QAANA', owner: 'analyst', desc: '质量分析报告', blockedBy: ['QARUN-L1', 'QARUN-L2'] }, - { prefix: 'SCOUT-REG', owner: 'scout', desc: '回归扫描', blockedBy: ['QAANA'] } - ] - } - return pipelines[qaMode] || pipelines['discovery'] -} -``` - -## Execution Steps - -### Step 1: Context Preparation - -```javascript -const pipeline = buildPipeline(qaMode, sessionFolder, taskDescription) -``` - -### Step 2: Execute Strategy - -```javascript -const taskIds = {} - -for (const stage of pipeline) { - // 构建任务描述(包含 session 和层级信息) - const fullDesc = [ - stage.desc, - `\nsession: ${sessionFolder}`, - stage.meta ? `\n${stage.meta}` : '', - `\n\n目标: ${taskDescription}` - ].join('') - - // 创建任务 - TaskCreate({ - subject: `${stage.prefix}-001: ${stage.desc}`, - description: fullDesc, - activeForm: `${stage.desc}进行中` - }) - - // 记录任务 ID(假设 TaskCreate 返回 ID) - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith(`${stage.prefix}-001`)) - taskIds[stage.prefix] = newTask.id - - // 设置 owner 和依赖 - const blockedByIds = stage.blockedBy - .map(dep => taskIds[dep]) - .filter(Boolean) - - TaskUpdate({ - taskId: newTask.id, - owner: stage.owner, - addBlockedBy: blockedByIds - }) -} -``` - -### Step 3: Result Processing - -```javascript -// 验证任务链 -const allTasks = TaskList() -const chainTasks = pipeline.map(s => taskIds[s.prefix]).filter(Boolean) -const chainValid = chainTasks.length === pipeline.length - -if (!chainValid) { - mcp__ccw-tools__team_msg({ - operation: "log", session_id: teamName, from: "coordinator", - to: "user", type: "error", - }) -} -``` - -## GC Loop Task Creation - -当 executor 报告覆盖率不达标时,coordinator 调用此逻辑追加任务: - -```javascript -function createGCLoopTasks(gcIteration, targetLayer, sessionFolder) { - // 创建修复任务 - TaskCreate({ - subject: `QAGEN-fix-${gcIteration}: 修复 ${targetLayer} 测试 (GC #${gcIteration})`, - description: `修复未通过测试并补充覆盖\nsession: ${sessionFolder}\nlayer: ${targetLayer}\ntype: gc-fix`, - activeForm: `GC循环 #${gcIteration} 修复中` - }) - - // 创建重新执行任务 - TaskCreate({ - subject: `QARUN-gc-${gcIteration}: 重新执行 ${targetLayer} (GC #${gcIteration})`, - description: `重新执行测试验证修复\nsession: ${sessionFolder}\nlayer: ${targetLayer}`, - activeForm: `GC循环 #${gcIteration} 执行中` - }) - - // 设置依赖: QARUN-gc 依赖 QAGEN-fix - // ... TaskUpdate addBlockedBy -} -``` - -## Output Format +## Task Description Template ``` -## Task Chain Created - -### Mode: [discovery|testing|full] -### Pipeline Stages: [count] -- [prefix]-001: [description] (owner: [role], blocked by: [deps]) - -### Verification: PASS/FAIL +PURPOSE: <goal> | Success: <criteria> +TASK: + - <step 1> + - <step 2> +CONTEXT: + - Session: <session-folder> + - Layer: <L1-unit|L2-integration|L3-e2e> (if applicable) + - Upstream artifacts: <list> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <artifact path> + <quality criteria> +CONSTRAINTS: <scope limits> +--- +InnerLoop: <true|false> +RoleSpec: .claude/skills/team-quality-assurance/roles/<role>/role.md ``` -## Error Handling +## Pipeline Task Registry -| Scenario | Resolution | -|----------|------------| -| Task creation fails | Retry once, then report to user | -| Dependency cycle detected | Flatten dependencies, warn coordinator | -| Invalid qaMode | Default to 'discovery' mode | -| Agent/CLI failure | Retry once, then fallback to inline execution | -| Timeout (>5 min) | Report partial results, notify coordinator | +### Discovery Mode +``` +SCOUT-001 (scout): Multi-perspective issue scanning + blockedBy: [] +QASTRAT-001 (strategist): Test strategy formulation + blockedBy: [SCOUT-001] +QAGEN-001 (generator): L1 unit test generation + blockedBy: [QASTRAT-001], meta: layer=L1 +QARUN-001 (executor): L1 test execution + fix cycles + blockedBy: [QAGEN-001], inner_loop: true, meta: layer=L1 +QAANA-001 (analyst): Quality analysis report + blockedBy: [QARUN-001] +``` + +### Testing Mode +``` +QASTRAT-001 (strategist): Test strategy formulation + blockedBy: [] +QAGEN-L1-001 (generator): L1 unit test generation + blockedBy: [QASTRAT-001], meta: layer=L1 +QARUN-L1-001 (executor): L1 test execution + fix cycles + blockedBy: [QAGEN-L1-001], inner_loop: true, meta: layer=L1 +QAGEN-L2-001 (generator): L2 integration test generation + blockedBy: [QARUN-L1-001], meta: layer=L2 +QARUN-L2-001 (executor): L2 test execution + fix cycles + blockedBy: [QAGEN-L2-001], inner_loop: true, meta: layer=L2 +QAANA-001 (analyst): Quality analysis report + blockedBy: [QARUN-L2-001] +``` + +### Full Mode +``` +SCOUT-001 (scout): Multi-perspective issue scanning + blockedBy: [] +QASTRAT-001 (strategist): Test strategy formulation + blockedBy: [SCOUT-001] +QAGEN-L1-001 (generator-1): L1 unit test generation + blockedBy: [QASTRAT-001], meta: layer=L1 +QAGEN-L2-001 (generator-2): L2 integration test generation + blockedBy: [QASTRAT-001], meta: layer=L2 +QARUN-L1-001 (executor-1): L1 test execution + fix cycles + blockedBy: [QAGEN-L1-001], inner_loop: true, meta: layer=L1 +QARUN-L2-001 (executor-2): L2 test execution + fix cycles + blockedBy: [QAGEN-L2-001], inner_loop: true, meta: layer=L2 +QAANA-001 (analyst): Quality analysis report + blockedBy: [QARUN-L1-001, QARUN-L2-001] +SCOUT-002 (scout): Regression scan after fixes + blockedBy: [QAANA-001] +``` + +## InnerLoop Flag Rules + +- true: executor roles (run-fix cycles) +- false: scout, strategist, generator, analyst roles + +## Dependency Validation + +- No orphan tasks (all tasks have valid owner) +- No circular dependencies +- All blockedBy references exist +- Session reference in every task description +- RoleSpec reference in every task description + +## Log After Creation + +``` +mcp__ccw-tools__team_msg({ + operation: "log", + session_id: <session-id>, + from: "coordinator", + type: "pipeline_selected", + data: { pipeline: "<mode>", task_count: <N> } +}) +``` diff --git a/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md b/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md index ee73bc13..668c4aac 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md @@ -1,31 +1,31 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, GC loops, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | -|-----|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| WORKER_AGENT | team-worker | -| MAX_GC_ROUNDS | 3 | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 3 -## Phase 2: Context Loading +## Handler Router -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Meta state | <session>/.msg/meta.json | Yes | -| Pipeline definition | From SKILL.md | Yes | +| Source | Handler | +|--------|---------| +| Message contains [scout], [strategist], [generator], [executor], [analyst] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -1. Load session.json for current state, `pipeline_mode`, `gc_rounds` -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## handleCallback -### Role Detection Table +Worker completed. Process and advance. + +1. Parse message to identify role and task ID: | Message Pattern | Role Detection | |----------------|---------------| @@ -35,170 +35,184 @@ Handle all coordinator monitoring events: worker callbacks, status checks, pipel | `[executor]` or task ID `QARUN-*` | executor | | `[analyst]` or task ID `QAANA-*` | analyst | -### Pipeline Stage Order - -``` -SCOUT -> QASTRAT -> QAGEN -> QARUN -> QAANA -``` - -## Phase 3: Event Handlers - -### handleCallback - -Triggered when a worker sends completion message. - -1. Parse message to identify role and task ID using Role Detection Table - -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` - -3. Record completion in session state - -4. **GC Loop Check** (when executor QARUN completes): - -Read `<session>/.msg/meta.json` for execution results. - -| Condition | Action | -|-----------|--------| -| Coverage >= target OR no coverage data | Proceed to handleSpawnNext | -| Coverage < target AND gc_rounds < 3 | Create GC fix tasks, increment gc_rounds | -| Coverage < target AND gc_rounds >= 3 | Accept current coverage, proceed to handleSpawnNext | +2. Check if progress update (inner loop) or final completion +3. Progress -> update session state, STOP +4. Completion -> mark task done via TaskUpdate(status="completed"), remove from active_workers +5. Check for checkpoints: + - QARUN-* completes -> read meta.json for coverage: + - coverage >= target OR gc_rounds >= MAX_GC_ROUNDS -> proceed to handleSpawnNext + - coverage < target AND gc_rounds < MAX_GC_ROUNDS -> create GC fix tasks, increment gc_rounds **GC Fix Task Creation** (when coverage below target): - ``` TaskCreate({ - subject: "QAGEN-fix-<round>", + subject: "QAGEN-fix-<round>: Fix tests for <layer> (GC #<round>)", description: "PURPOSE: Fix failing tests and improve coverage | Success: Coverage meets target TASK: - Load execution results and failing test details - Fix broken tests and add missing coverage - - Re-validate fixes CONTEXT: - Session: <session-folder> - - Upstream artifacts: <session>/.msg/meta.json + - Layer: <layer> + - Previous results: <session>/results/run-<layer>.json EXPECTED: Fixed test files | Improved coverage -CONSTRAINTS: Targeted fixes only | Do not introduce regressions", - blockedBy: [], - status: "pending" +CONSTRAINTS: Only modify test files | No source changes +--- +InnerLoop: false +RoleSpec: .claude/skills/team-quality-assurance/roles/generator/role.md" }) - TaskCreate({ - subject: "QARUN-recheck-<round>", + subject: "QARUN-gc-<round>: Re-execute <layer> (GC #<round>)", description: "PURPOSE: Re-execute tests after fixes | Success: Coverage >= target -TASK: - - Execute test suite on fixed code - - Measure coverage - - Report results +TASK: Execute test suite, measure coverage, report results CONTEXT: - Session: <session-folder> -EXPECTED: Execution results with coverage metrics -CONSTRAINTS: Read-only execution", - blockedBy: ["QAGEN-fix-<round>"], - status: "pending" + - Layer: <layer> +EXPECTED: <session>/results/run-<layer>-gc-<round>.json +CONSTRAINTS: Read-only execution +--- +InnerLoop: false +RoleSpec: .claude/skills/team-quality-assurance/roles/executor/role.md", + blockedBy: ["QAGEN-fix-<round>"] }) ``` -5. Proceed to handleSpawnNext +6. -> handleSpawnNext -### handleSpawnNext +## handleCheck -Find and spawn the next ready tasks. +Read-only status report, then STOP. -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" +Output: +``` +[coordinator] QA Pipeline Status +[coordinator] Mode: <pipeline_mode> +[coordinator] Progress: <done>/<total> (<pct>%) +[coordinator] GC Rounds: <gc_rounds>/3 -2. If no ready tasks and all tasks completed, proceed to handleComplete +[coordinator] Pipeline Graph: + SCOUT-001: <done|run|wait> <summary> + QASTRAT-001: <done|run|wait> <summary> + QAGEN-001: <done|run|wait> <summary> + QARUN-001: <done|run|wait> <summary> + QAANA-001: <done|run|wait> <summary> -3. If no ready tasks but some still in_progress, STOP and wait - -4. For each ready task, determine role from task subject prefix: - -```javascript -const STAGE_WORKER_MAP = { - 'SCOUT': { role: 'scout' }, - 'QASTRAT': { role: 'strategist' }, - 'QAGEN': { role: 'generator' }, - 'QARUN': { role: 'executor' }, - 'QAANA': { role: 'analyst' } -} +[coordinator] Active Workers: <list with elapsed time> +[coordinator] Ready: <pending tasks with resolved deps> +[coordinator] Commands: 'resume' to advance | 'check' to refresh ``` -5. Spawn team-worker (one at a time for sequential pipeline): +Then STOP. + +## handleResume + +1. No active workers -> handleSpawnNext +2. Has active -> check each status + - completed -> mark done via TaskUpdate + - in_progress -> still running +3. Some completed -> handleSpawnNext +4. All running -> report status, STOP + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect from TaskList(): + - completedSubjects: status = completed + - inProgressSubjects: status = in_progress + - readySubjects: status = pending AND all blockedBy in completedSubjects + +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Determine role from task prefix: + +| Prefix | Role | inner_loop | +|--------|------|------------| +| SCOUT-* | scout | false | +| QASTRAT-* | strategist | false | +| QAGEN-* | generator | false | +| QARUN-* | executor | true | +| QAANA-* | analyst | false | + + b. Check if inner loop role with active worker -> skip (worker picks up next task) + c. TaskUpdate -> in_progress + d. team_msg log -> task_unblocked + e. Spawn team-worker: ``` Agent({ - agent_type: "team-worker", - description: "Spawn <role> worker for <task-id>", + subagent_type: "team-worker", + description: "Spawn <role> worker for <subject>", team_name: "quality-assurance", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-quality-assurance/role-specs/<role>.md +role_spec: .claude/skills/team-quality-assurance/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: quality-assurance requirement: <task-description> -inner_loop: false +inner_loop: <true|false> ## Current Task - Task ID: <task-id> -- Task: <task-subject> +- Task: <subject> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -6. STOP after spawning -- wait for next callback + f. Add to active_workers +5. Update session, output summary, STOP -### handleCheck +## handleComplete -Output current pipeline status. +Pipeline done. Generate report and completion action. -``` -Pipeline Status: - [DONE] SCOUT-001 (scout) -> scan complete - [DONE] QASTRAT-001 (strategist) -> strategy ready - [RUN] QAGEN-001 (generator) -> generating tests... - [WAIT] QARUN-001 (executor) -> blocked by QAGEN-001 - [WAIT] QAANA-001 (analyst) -> blocked by QARUN-001 +1. Verify all tasks (including GC fix/recheck tasks) have status "completed" or "deleted" +2. If any tasks incomplete -> return to handleSpawnNext +3. If all complete: + - Read final state from meta.json (quality_score, coverage, gc_rounds) + - Generate summary (deliverables, stats, discussions) +4. Read session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -GC Rounds: 0/3 -Session: <session-id> -``` +## handleAdapt -Output status -- do NOT advance pipeline. +Capability gap reported mid-pipeline. -### handleResume +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 6 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 6 -> merge or pause -Resume pipeline after user pause or interruption. +## Fast-Advance Reconciliation -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext - -### handleComplete - -Triggered when all pipeline tasks are completed. - -1. Verify all tasks (including any GC fix/recheck tasks) have status "completed" -2. If any tasks not completed, return to handleSpawnNext -3. If all completed: - - Read final state from `<session>/.msg/meta.json` - - Compile summary: total tasks, completed, gc_rounds, quality_score, coverage - - Transition to coordinator Phase 5 +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns ## Phase 4: State Persistence After every handler execution: +1. Reconcile active_workers with actual TaskList states +2. Remove entries for completed/deleted tasks +3. Write updated meta.json +4. STOP (wait for next callback) -1. Update session.json with current state (active tasks, gc_rounds, last event) -2. Verify task list consistency -3. STOP and wait for next event +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Session file not found | Error, suggest re-initialization | +| Worker callback from unknown role | Log info, scan for other completions | +| Pipeline stall (no ready, no running, has pending) | Check blockedBy chains, report to user | +| GC loop exceeded | Accept current coverage with warning, proceed | +| Scout finds 0 issues | Skip to testing mode, proceed to QASTRAT | diff --git a/.claude/skills/team-quality-assurance/roles/coordinator/role.md b/.claude/skills/team-quality-assurance/roles/coordinator/role.md index 506608f0..f5c4ec2b 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/role.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/role.md @@ -1,115 +1,62 @@ # Coordinator Role -Orchestrate the Quality Assurance workflow: requirement clarification, mode selection, team creation, task dispatch, progress monitoring, quality gate control, and result reporting. +Orchestrate team-quality-assurance: analyze -> dispatch -> spawn -> monitor -> report. ## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results +- Name: coordinator | Tag: [coordinator] +- Responsibility: Parse requirements -> Mode selection -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST -- All output (SendMessage, team_msg, logs) must carry `[coordinator]` identifier -- Only responsible for requirement clarification, mode selection, task creation/dispatch, progress monitoring, quality gate control, and result reporting -- Create tasks via TaskCreate and assign to worker roles -- Monitor worker progress via message bus and route messages +- Parse task description and detect QA mode +- Create team and spawn team-worker agents in background +- Dispatch tasks with proper dependency chains +- Monitor progress via callbacks and route messages +- Maintain session state +- Handle GC loop (generator-executor coverage cycles) +- Execute completion action when pipeline finishes ### MUST NOT -- Directly execute any business tasks (scanning, testing, analysis, etc.) -- Directly invoke implementation CLI tools (cli-explore-agent, code-developer, etc.) -- Directly modify source code or generated artifact files -- Bypass worker roles to complete delegated work -- Omit `[coordinator]` identifier in any output - -> **Core principle**: coordinator is the orchestrator, not the executor. All actual work must be delegated to worker roles via TaskCreate. - ---- +- Read source code or explore codebase (delegate to workers) +- Execute scan, test, or analysis work directly +- Modify test files or source code +- Spawn workers with general-purpose agent (MUST use team-worker) +- Generate more than 6 worker roles ## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [scout], [strategist], [generator], [executor], [analyst] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) | +| Worker callback | Message contains [scout], [strategist], [generator], [executor], [analyst] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/QA-* | -> Phase 0 | | New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/QA-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/adapt/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -**Objective**: Detect and resume interrupted sessions before creating new ones. - -**Workflow**: -1. Scan session directory 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 state <-> 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 - ---- +1. Scan .workflow/.team/QA-*/session.json for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -**Objective**: Parse user input and gather execution parameters. - -**Workflow**: - -1. **Parse arguments** for explicit settings: mode, scope, focus areas +TEXT-LEVEL ONLY. No source code reading. +1. Parse task description and extract flags 2. **QA Mode Selection**: | Condition | Mode | @@ -121,124 +68,73 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match | Task description contains: test/coverage/TDD keywords | testing | | No explicit flag and no keyword match | full (default) | -3. **Ask for missing parameters** via AskUserQuestion (skip in auto mode with -y/--yes flag): - -| Question | Options | -|----------|---------| -| QA Target description | Custom input / Full project scan / Change testing / Complete QA flow | - -**Success**: All parameters captured, mode finalized. - ---- +3. Clarify if ambiguous (AskUserQuestion: scope, deliverables, constraints) +4. Delegate to commands/analyze.md +5. Output: task-analysis.json +6. CRITICAL: Always proceed to Phase 2, never skip team workflow ## Phase 2: Create Team + Initialize Session -**Objective**: Initialize team, session file, and shared memory. - -**Workflow**: -1. Generate session ID -2. Create session folder -3. Call TeamCreate with team name -4. Initialize meta.json with pipeline metadata and shared state: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<discovery|testing|full>", - pipeline_stages: ["scout", "strategist", "generator", "executor", "analyst"], - roles: ["coordinator", "scout", "strategist", "generator", "executor", "analyst"], - team_name: "quality-assurance", - discovered_issues: [], - test_strategy: {}, - generated_tests: {}, - execution_results: {}, - defect_patterns: [], - coverage_history: [], - quality_score: null - } -}) -``` - -5. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) -6. Write session file with: session_id, mode, scope, status="active" - -**Success**: Team created, session file written, shared memory initialized. - ---- +1. Generate session ID: QA-<slug>-<date> +2. Create session folder structure +3. TeamCreate with team name "quality-assurance" +4. Read specs/pipelines.md -> select pipeline based on mode +5. Register roles in session.json +6. Initialize shared infrastructure (wisdom/*.md) +7. Initialize pipeline via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { + pipeline_mode: "<discovery|testing|full>", + pipeline_stages: [...], + team_name: "quality-assurance", + discovered_issues: [], + test_strategy: {}, + generated_tests: {}, + execution_results: {}, + defect_patterns: [], + coverage_history: [], + quality_score: null + } + }) + ``` +8. Write session.json ## Phase 3: Create Task Chain -**Objective**: Dispatch tasks based on mode with proper dependencies. +Delegate to commands/dispatch.md: +1. Read dependency graph from task-analysis.json +2. Read specs/pipelines.md for selected pipeline's task registry +3. Topological sort tasks +4. Create tasks via TaskCreate with blockedBy +5. Update session.json -Delegate to `commands/dispatch.md` which creates the full task chain. +## Phase 4: Spawn-and-Stop -**Pipeline by Mode**: +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP -| Mode | Pipeline | -|------|----------| -| Discovery | SCOUT-001 -> QASTRAT-001 -> QAGEN-001 -> QARUN-001 -> QAANA-001 | -| Testing | QASTRAT-001 -> QAGEN-001(L1) -> QARUN-001(L1) -> QAGEN-002(L2) -> QARUN-002(L2) -> QAANA-001 | -| Full QA | SCOUT-001 -> QASTRAT-001 -> [QAGEN-001(L1) + QAGEN-002(L2)](parallel) -> [QARUN-001 + QARUN-002](parallel) -> QAANA-001 -> SCOUT-002(regression) | +## Phase 5: Report + Completion Action ---- - -## Phase 4: Coordination Loop - -**Objective**: Spawn workers, monitor progress, advance pipeline. - -> **Design principle (Stop-Wait)**: Model execution has no time concept. No polling with sleep. -> - Use synchronous `Task(run_in_background: false)` calls -> - Worker return = stage completion signal - -Delegate to `commands/monitor.md` for full implementation. - -**Message Handling**: - -| Received Message | Action | -|-----------------|--------| -| `scan_ready` | Mark SCOUT complete -> unlock QASTRAT | -| `strategy_ready` | Mark QASTRAT complete -> unlock QAGEN | -| `tests_generated` | Mark QAGEN complete -> unlock QARUN | -| `tests_passed` | Mark QARUN complete -> unlock QAANA or next layer | -| `tests_failed` | Evaluate coverage -> trigger GC loop (gc_loop_trigger) or continue | -| `analysis_ready` | Mark QAANA complete -> evaluate quality gate | -| Worker: `error` | Evaluate severity -> retry or report to user | - -**GC Loop Trigger Logic**: - -| Condition | Action | -|-----------|--------| -| coverage < targetCoverage AND gcIteration < 3 | Create QAGEN-fix task -> QARUN re-execute, gcIteration++ | -| gcIteration >= 3 | Accept current coverage, continue pipeline, team_msg quality_gate CONDITIONAL | - ---- - -## Phase 5: Report + Persist - -**Objective**: Completion report and follow-up options. - -**Workflow**: -1. Load session state -> count completed tasks, duration -2. Read shared memory for summary -3. List deliverables with output paths -4. Update session status -> "completed" -5. Log via team_msg -6. SendMessage report to user -7. Offer next steps to user (skip in auto mode) - ---- +1. Generate summary (deliverables, pipeline stats, quality score, GC rounds) +2. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean + - auto_keep -> Keep Active ## Error Handling -| Scenario | Resolution | -|----------|------------| -| Teammate unresponsive | Send follow-up, 2x -> respawn | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Dependency cycle | Detect in analysis, halt | | Scout finds nothing | Skip to testing mode | -| GC loop stuck >3 iterations | Accept current coverage, continue pipeline | -| Test environment broken | Notify user, suggest manual fix | -| All tasks completed but quality_score < 60 | Report with WARNING, suggest re-run with deeper analysis | +| GC loop stuck > 3 | Accept current coverage with warning | +| quality_score < 60 | Report with WARNING, suggest re-run | diff --git a/.claude/skills/team-quality-assurance/roles/executor/role.md b/.claude/skills/team-quality-assurance/roles/executor/role.md new file mode 100644 index 00000000..4908be7e --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/executor/role.md @@ -0,0 +1,65 @@ +--- +role: executor +prefix: QARUN +inner_loop: true +additional_prefixes: [QARUN-gc] +message_types: + success: tests_passed + failure: tests_failed + coverage: coverage_report + error: error +--- + +# Test Executor + +Run test suites, collect coverage data, and perform automatic fix cycles when tests fail. Implements the execution side of the Generator-Executor (GC) loop. + +## Phase 2: Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Test strategy | meta.json -> test_strategy | Yes | +| Generated tests | meta.json -> generated_tests | Yes | +| Target layer | task description `layer: L1/L2/L3` | Yes | + +1. Extract session path and target layer from task description +2. Read .msg/meta.json for strategy and generated test file list +3. Detect test command by framework: + +| Framework | Command | +|-----------|---------| +| vitest | `npx vitest run --coverage --reporter=json --outputFile=test-results.json` | +| jest | `npx jest --coverage --json --outputFile=test-results.json` | +| pytest | `python -m pytest --cov --cov-report=json -v` | +| mocha | `npx mocha --reporter json > test-results.json` | +| unknown | `npm test -- --coverage` | + +4. Get test files from `generated_tests[targetLayer].files` + +## Phase 3: Iterative Test-Fix Cycle + +**Max iterations**: 5. **Pass threshold**: 95% or all tests pass. + +Per iteration: +1. Run test command, capture output +2. Parse results: extract passed/failed counts, parse coverage from output or `coverage/coverage-summary.json` +3. If all pass (0 failures) -> exit loop (success) +4. If pass rate >= 95% and iteration >= 2 -> exit loop (good enough) +5. If iteration >= MAX -> exit loop (report current state) +6. Extract failure details (error lines, assertion failures) +7. Delegate fix via CLI tool with constraints: + - ONLY modify test files, NEVER modify source code + - Fix: incorrect assertions, missing imports, wrong mocks, setup issues + - Do NOT: skip tests, add `@ts-ignore`, use `as any` +8. Increment iteration, repeat + +## Phase 4: Result Analysis & Output + +1. Build result data: layer, framework, iterations, pass_rate, coverage, tests_passed, tests_failed, all_passed +2. Save results to `<session>/results/run-<layer>.json` +3. Save last test output to `<session>/results/output-<layer>.txt` +4. Update `<session>/wisdom/.msg/meta.json` under `execution_results[layer]` and top-level `execution_results.pass_rate`, `execution_results.coverage` +5. Message type: `tests_passed` if all_passed, else `tests_failed` diff --git a/.claude/skills/team-quality-assurance/roles/generator/role.md b/.claude/skills/team-quality-assurance/roles/generator/role.md new file mode 100644 index 00000000..efced4b0 --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/generator/role.md @@ -0,0 +1,68 @@ +--- +role: generator +prefix: QAGEN +inner_loop: false +additional_prefixes: [QAGEN-fix] +message_types: + success: tests_generated + revised: tests_revised + error: error +--- + +# Test Generator + +Generate test code according to strategist's strategy and layers. Support L1 unit tests, L2 integration tests, L3 E2E tests. Follow project's existing test patterns and framework conventions. + +## Phase 2: Strategy & Pattern Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Test strategy | meta.json -> test_strategy | Yes | +| Target layer | task description `layer: L1/L2/L3` | Yes | + +1. Extract session path and target layer from task description +2. Read .msg/meta.json for test strategy (layers, coverage targets) +3. Determine if this is a GC fix task (subject contains "fix") +4. Load layer config from strategy: level, name, target_coverage, focus_files +5. Learn existing test patterns -- find 3 similar test files via Glob(`**/*.{test,spec}.{ts,tsx,js,jsx}`) +6. Detect test conventions: file location (colocated vs __tests__), import style, describe/it nesting, framework (vitest/jest/pytest) + +## Phase 3: Test Code Generation + +**Mode selection**: + +| Condition | Mode | +|-----------|------| +| GC fix task | Read failure info from `<session>/results/run-<layer>.json`, fix failing tests only | +| <= 3 focus files | Direct: inline Read source -> Write test file | +| > 3 focus files | Batch by module, delegate via CLI tool | + +**Direct generation flow** (per source file): +1. Read source file content, extract exports +2. Determine test file path following project conventions +3. If test exists -> analyze missing cases -> append new tests via Edit +4. If no test -> generate full test file via Write +5. Include: happy path, edge cases, error cases per export + +**GC fix flow**: +1. Read execution results and failure output from results directory +2. Read each failing test file +3. Fix assertions, imports, mocks, or test setup +4. Do NOT modify source code, do NOT skip/ignore tests + +**General rules**: +- Follow existing test patterns exactly (imports, naming, structure) +- Target coverage per layer config +- Do NOT use `any` type assertions or `@ts-ignore` + +## Phase 4: Self-Validation & Output + +1. Collect generated/modified test files +2. Run syntax check (TypeScript: `tsc --noEmit`, or framework-specific) +3. Auto-fix syntax errors (max 3 attempts) +4. Write test metadata to `<session>/wisdom/.msg/meta.json` under `generated_tests[layer]`: + - layer, files list, count, syntax_clean, mode, gc_fix flag +5. Message type: `tests_generated` for new, `tests_revised` for GC fix iterations diff --git a/.claude/skills/team-quality-assurance/roles/scout/role.md b/.claude/skills/team-quality-assurance/roles/scout/role.md new file mode 100644 index 00000000..99708c5f --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/scout/role.md @@ -0,0 +1,67 @@ +--- +role: scout +prefix: SCOUT +inner_loop: false +message_types: + success: scan_ready + error: error + issues: issues_found +--- + +# Multi-Perspective Scout + +Scan codebase from multiple perspectives (bug, security, test-coverage, code-quality, UX) to discover potential issues. Produce structured scan results with severity-ranked findings. + +## Phase 2: Context & Scope Assessment + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | No | + +1. Extract session path and target scope from task description +2. Determine scan scope: explicit scope from task or `**/*` default +3. Get recent changed files: `git diff --name-only HEAD~5 2>/dev/null || echo ""` +4. Read .msg/meta.json for historical defect patterns (`defect_patterns`) +5. Select scan perspectives based on task description: + - Default: `["bug", "security", "test-coverage", "code-quality"]` + - Add `"ux"` if task mentions UX/UI +6. Assess complexity to determine scan strategy: + +| Complexity | Condition | Strategy | +|------------|-----------|----------| +| Low | < 5 changed files, no specific keywords | ACE search + Grep inline | +| Medium | 5-15 files or specific perspective requested | CLI fan-out (3 core perspectives) | +| High | > 15 files or full-project scan | CLI fan-out (all perspectives) | + +## Phase 3: Multi-Perspective Scan + +**Low complexity**: Use `mcp__ace-tool__search_context` for quick pattern-based scan. + +**Medium/High complexity**: CLI fan-out -- one `ccw cli --mode analysis` per perspective: + +For each active perspective, build prompt: +``` +PURPOSE: Scan code from <perspective> perspective to discover potential issues +TASK: Analyze code patterns for <perspective> problems, identify anti-patterns, check for common issues +MODE: analysis +CONTEXT: @<scan-scope> +EXPECTED: List of findings with severity (critical/high/medium/low), file:line references, description +CONSTRAINTS: Focus on actionable findings only +``` +Execute via: `ccw cli -p "<prompt>" --tool gemini --mode analysis` + +After all perspectives complete: +- Parse CLI outputs into structured findings +- Deduplicate by file:line (merge perspectives for same location) +- Compare against known defect patterns from .msg/meta.json +- Rank by severity: critical > high > medium > low + +## Phase 4: Result Aggregation + +1. Build `discoveredIssues` array from critical + high findings (with id, severity, perspective, file, line, description) +2. Write scan results to `<session>/scan/scan-results.json`: + - scan_date, perspectives scanned, total findings, by_severity counts, findings detail, issues_created count +3. Update `<session>/wisdom/.msg/meta.json`: merge `discovered_issues` field +4. Contribute to wisdom/issues.md if new patterns found diff --git a/.claude/skills/team-quality-assurance/roles/strategist/role.md b/.claude/skills/team-quality-assurance/roles/strategist/role.md new file mode 100644 index 00000000..81c23a50 --- /dev/null +++ b/.claude/skills/team-quality-assurance/roles/strategist/role.md @@ -0,0 +1,71 @@ +--- +role: strategist +prefix: QASTRAT +inner_loop: false +message_types: + success: strategy_ready + error: error +--- + +# Test Strategist + +Analyze change scope, determine test layers (L1-L3), define coverage targets, and generate test strategy document. Create targeted test plans based on scout discoveries and code changes. + +## Phase 2: Context & Change Analysis + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Discovered issues | meta.json -> discovered_issues | No | +| Defect patterns | meta.json -> defect_patterns | No | + +1. Extract session path from task description +2. Read .msg/meta.json for scout discoveries and historical patterns +3. Analyze change scope: `git diff --name-only HEAD~5` +4. Categorize changed files: + +| Category | Pattern | +|----------|---------| +| Source | `\.(ts|tsx|js|jsx|py|java|go|rs)$` | +| Test | `\.(test|spec)\.(ts|tsx|js|jsx)$` or `test_` | +| Config | `\.(json|yaml|yml|toml|env)$` | + +5. Detect test framework from package.json / project files +6. Check existing coverage baseline from `coverage/coverage-summary.json` +7. Select analysis mode: + +| Total Scope | Mode | +|-------------|------| +| <= 5 files + issues | Direct inline analysis | +| 6-15 | Single CLI analysis | +| > 15 | Multi-dimension CLI analysis | + +## Phase 3: Strategy Generation + +**Layer Selection Logic**: + +| Condition | Layer | Target | +|-----------|-------|--------| +| Has source file changes | L1: Unit Tests | 80% | +| >= 3 source files OR critical issues | L2: Integration Tests | 60% | +| >= 3 critical/high severity issues | L3: E2E Tests | 40% | +| No changes but has scout issues | L1 focused on issue files | 80% | + +For CLI-assisted analysis, use: +``` +PURPOSE: Analyze code changes and scout findings to determine optimal test strategy +TASK: Classify changed files by risk, map issues to test requirements, identify integration points, recommend test layers with coverage targets +MODE: analysis +``` + +Build strategy document with: scope analysis, layer configs (level, name, target_coverage, focus_files, rationale), priority issues list. + +**Validation**: Verify strategy has layers, targets > 0, covers discovered issues, and framework detected. + +## Phase 4: Output & Persistence + +1. Write strategy to `<session>/strategy/test-strategy.md` +2. Update `<session>/wisdom/.msg/meta.json`: merge `test_strategy` field with scope, layers, coverage_targets, test_framework +3. Contribute to wisdom/decisions.md with layer selection rationale diff --git a/.claude/skills/team-quality-assurance/specs/pipelines.md b/.claude/skills/team-quality-assurance/specs/pipelines.md new file mode 100644 index 00000000..852dd96b --- /dev/null +++ b/.claude/skills/team-quality-assurance/specs/pipelines.md @@ -0,0 +1,115 @@ +# QA Pipelines + +Pipeline definitions and task registry for team-quality-assurance. + +## Pipeline Modes + +| Mode | Description | Entry Role | +|------|-------------|------------| +| discovery | Scout-first: issue discovery then testing | scout | +| testing | Skip scout, direct test pipeline | strategist | +| full | Complete QA closed loop + regression scan | scout | + +## Pipeline Definitions + +### Discovery Mode (5 tasks, serial) + +``` +SCOUT-001 -> QASTRAT-001 -> QAGEN-001 -> QARUN-001 -> QAANA-001 +``` + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| SCOUT-001 | scout | (none) | Multi-perspective issue scanning | +| QASTRAT-001 | strategist | SCOUT-001 | Change scope analysis + test strategy | +| QAGEN-001 | generator | QASTRAT-001 | L1 unit test generation | +| QARUN-001 | executor | QAGEN-001 | L1 test execution + fix cycles | +| QAANA-001 | analyst | QARUN-001 | Defect pattern analysis + quality report | + +### Testing Mode (6 tasks, progressive layers) + +``` +QASTRAT-001 -> QAGEN-L1-001 -> QARUN-L1-001 -> QAGEN-L2-001 -> QARUN-L2-001 -> QAANA-001 +``` + +| Task ID | Role | Dependencies | Layer | Description | +|---------|------|-------------|-------|-------------| +| QASTRAT-001 | strategist | (none) | — | Test strategy formulation | +| QAGEN-L1-001 | generator | QASTRAT-001 | L1 | L1 unit test generation | +| QARUN-L1-001 | executor | QAGEN-L1-001 | L1 | L1 test execution + fix cycles | +| QAGEN-L2-001 | generator | QARUN-L1-001 | L2 | L2 integration test generation | +| QARUN-L2-001 | executor | QAGEN-L2-001 | L2 | L2 test execution + fix cycles | +| QAANA-001 | analyst | QARUN-L2-001 | — | Quality analysis report | + +### Full Mode (8 tasks, parallel windows + regression) + +``` +SCOUT-001 -> QASTRAT-001 -> [QAGEN-L1-001 || QAGEN-L2-001] -> [QARUN-L1-001 || QARUN-L2-001] -> QAANA-001 -> SCOUT-002 +``` + +| Task ID | Role | Dependencies | Layer | Description | +|---------|------|-------------|-------|-------------| +| SCOUT-001 | scout | (none) | — | Multi-perspective issue scanning | +| QASTRAT-001 | strategist | SCOUT-001 | — | Test strategy formulation | +| QAGEN-L1-001 | generator-1 | QASTRAT-001 | L1 | L1 unit test generation (parallel) | +| QAGEN-L2-001 | generator-2 | QASTRAT-001 | L2 | L2 integration test generation (parallel) | +| QARUN-L1-001 | executor-1 | QAGEN-L1-001 | L1 | L1 test execution + fix cycles (parallel) | +| QARUN-L2-001 | executor-2 | QAGEN-L2-001 | L2 | L2 test execution + fix cycles (parallel) | +| QAANA-001 | analyst | QARUN-L1-001, QARUN-L2-001 | — | Quality analysis report | +| SCOUT-002 | scout | QAANA-001 | — | Regression scan after fixes | + +## GC Loop + +Generator-Executor iterate per test layer until coverage targets are met: + +``` +QAGEN -> QARUN -> (if coverage < target) -> QAGEN-fix -> QARUN-gc + (if coverage >= target) -> next layer or QAANA +``` + +- Max iterations: 3 per layer +- After 3 iterations: accept current coverage with warning + +## Coverage Targets + +| Layer | Name | Default Target | +|-------|------|----------------| +| L1 | Unit Tests | 80% | +| L2 | Integration Tests | 60% | +| L3 | E2E Tests | 40% | + +## Scan Perspectives + +| Perspective | Focus | +|-------------|-------| +| bug | Logic errors, crash paths, null references | +| security | Vulnerabilities, auth bypass, data exposure | +| test-coverage | Untested code paths, missing assertions | +| code-quality | Anti-patterns, complexity, maintainability | +| ux | User-facing issues, accessibility (optional) | + +## Session Directory + +``` +.workflow/.team/QA-<slug>-<YYYY-MM-DD>/ +├── .msg/messages.jsonl # Message bus log +├── .msg/meta.json # Session state + cross-role state +├── wisdom/ # Cross-task knowledge +│ ├── learnings.md +│ ├── decisions.md +│ ├── conventions.md +│ └── issues.md +├── scan/ # Scout output +│ └── scan-results.json +├── strategy/ # Strategist output +│ └── test-strategy.md +├── tests/ # Generator output +│ ├── L1-unit/ +│ ├── L2-integration/ +│ └── L3-e2e/ +├── results/ # Executor output +│ ├── run-001.json +│ └── coverage-001.json +└── analysis/ # Analyst output + └── quality-report.md +``` diff --git a/.claude/skills/team-review/SKILL.md b/.claude/skills/team-review/SKILL.md index c2803d00..be5140b6 100644 --- a/.claude/skills/team-review/SKILL.md +++ b/.claude/skills/team-review/SKILL.md @@ -1,238 +1,72 @@ --- name: team-review -description: "Unified team skill for code review. Uses team-worker agent architecture with role-spec files. 3-role pipeline: scanner, reviewer, fixer. Triggers on team-review." +description: Unified team skill for code review. 3-role pipeline: scanner, reviewer, fixer. Triggers on "team-review". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*) --- # Team Review -Unified team skill: code scanning, vulnerability review, optimization suggestions, and automated fix. All team members invoke with `--role=xxx` to route to role-specific execution. +Orchestrate multi-agent code review: scanner -> reviewer -> fixer. Toolchain + LLM scan, deep analysis with root cause enrichment, and automated fix with rollback-on-failure. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-review") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-review", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+ - v v v - [tw] [tw] [tw] -scann- review- fixer -er er - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+ + v v v + [scan] [review] [fix] + team-worker agents, each loads roles/<role>/role.md ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| scanner | [roles/scanner/role.md](roles/scanner/role.md) | SCAN-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | REV-* | false | +| fixer | [roles/fixer/role.md](roles/fixer/role.md) | FIX-* | true | + ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` -> Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` -> Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `RV` +- **Session path**: `.workflow/.team/RV-<slug>-<date>/` +- **Team name**: `review` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| scanner | [role-specs/scanner.md](role-specs/scanner.md) | SCAN-* | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REV-* | false | -| fixer | [role-specs/fixer.md](role-specs/fixer.md) | FIX-* | true | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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 target description. - -**Invocation**: `Skill(skill="team-review", args="<target-path>")` - -**Lifecycle**: -``` -User provides scan target - → coordinator Phase 1-3: Parse flags → TeamCreate → Create task chain - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until pipeline complete → Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Pipeline (CP-1 Linear) - -``` -coordinator dispatch - → SCAN-* (scanner: toolchain + LLM scan) - → REV-* (reviewer: deep analysis + report) - → [user confirm] - → FIX-* (fixer: plan + execute + verify) -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat view**: - -``` -Review Pipeline (3 beats, linear with user checkpoint) -────────────────────────────────────────────────────────── -Beat 1 2 ⏸ 3 - │ │ │ │ - SCAN → REV ──→ [confirm] → FIX - ▲ ▲ - pipeline pipeline - start done - -SCAN=scanner REV=reviewer FIX=fixer -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Review→Fix transition | REV-* complete | Pause, present review report, wait for user `resume` to confirm fix | -| Quick mode (`-q`) | After SCAN-* | Pipeline ends after scan, no review/fix | -| Fix-only mode (`--fix`) | Entry | Skip scan/review, go directly to fixer | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| SCAN-001 | scanner | scan | (none) | Toolchain + LLM code scanning | -| REV-001 | reviewer | review | SCAN-001 | Deep analysis and review report | -| FIX-001 | fixer | fix | REV-001 + user confirm | Plan + execute + verify fixes | - ---- - -## Shared Infrastructure - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Use tools declared in Toolbox | Create tasks for other roles | -| Delegate to commands/ files | Modify resources outside own responsibility | - -Coordinator additional restrictions: Do not write/modify code directly, do not call implementation CLI tools, do not execute analysis/test/review directly. - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | review | -| Session directory | `.workflow/.team/RV-<slug>-<date>/` | -| Shared memory | `.msg/meta.json` in session dir | -| Team config | `specs/team-config.json` | -| Finding schema | `specs/finding-schema.json` | -| Dimensions | `specs/dimensions.md` | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ - agent_type: "team-worker", + subagent_type: "team-worker", description: "Spawn <role> worker", team_name: "review", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-review/role-specs/<role>.md +role_spec: .claude/skills/team-review/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: review @@ -240,41 +74,25 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (fixer): Set `inner_loop: true`. +## User Commands -**Single-task roles** (scanner, reviewer): Set `inner_loop: false`. - -## Usage - -```bash -# Via coordinator (auto pipeline) -Skill(skill="team-review", args="src/auth/**") # scan + review -Skill(skill="team-review", args="--full src/auth/**") # scan + review + fix -Skill(skill="team-review", args="--fix .review/review-*.json") # fix only -Skill(skill="team-review", args="-q src/auth/**") # quick scan only - -# Direct role invocation -Skill(skill="team-review", args="--role=scanner src/auth/**") -Skill(skill="team-review", args="--role=reviewer --input scan-result.json") -Skill(skill="team-review", args="--role=fixer --input fix-manifest.json") - -# Flags (all modes) ---dimensions=sec,cor,perf,maint # custom dimensions (default: all 4) --y / --yes # skip confirmations --q / --quick # quick scan mode ---full # full pipeline (scan → review → fix) ---fix # fix mode only -``` - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View pipeline status graph | +| `resume` / `continue` | Advance to next step | +| `--full` | Enable scan + review + fix pipeline | +| `--fix` | Fix-only mode (skip scan/review) | +| `-q` / `--quick` | Quick scan only | +| `--dimensions=sec,cor,prf,mnt` | Custom dimensions | +| `-y` / `--yes` | Skip confirmations | ## Completion Action -When the pipeline completes (all tasks done, coordinator Phase 5): +When pipeline completes, coordinator presents: ``` AskUserQuestion({ @@ -283,56 +101,41 @@ AskUserQuestion({ header: "Completion", multiSelect: false, options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory" } ] }] }) ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-review", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- - ## Session Directory ``` -.workflow/.team/RV-<slug>-<YYYY-MM-DD>/ -├── .msg/ -│ ├── messages.jsonl # Message bus log -│ └── meta.json # Session state + cross-role state -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── scan/ # Scanner output -│ └── scan-results.json -├── review/ # Reviewer output -│ └── review-report.json -└── fix/ # Fixer output - └── fix-manifest.json +.workflow/.team/RV-<slug>-<date>/ +├── .msg/messages.jsonl # Team message bus +├── .msg/meta.json # Session state + cross-role state +├── wisdom/ # Cross-task knowledge +├── scan/ # Scanner output +├── review/ # Reviewer output +└── fix/ # Fixer output ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry +- [specs/dimensions.md](specs/dimensions.md) — Review dimension definitions (SEC/COR/PRF/MNT) +- [specs/finding-schema.json](specs/finding-schema.json) — Finding data schema +- [specs/team-config.json](specs/team-config.json) — Team configuration + ## Error Handling | Scenario | Resolution | |----------|------------| | Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected file path (roles/<name>/role.md) | -| Invalid flags | Warn and continue with defaults | -| No target specified (no --role) | AskUserQuestion to clarify | - -## Execution Rules - -1. **Parse first**: Extract --role and flags from $ARGUMENTS before anything else -2. **Progressive loading**: Read ONLY the matched role.md, not all four -3. **Full delegation**: Role.md owns entire execution -- do not add logic here -4. **Self-contained**: Each role.md includes its own message bus, task lifecycle, toolbox -5. **DO NOT STOP**: Continuous execution until role completes all 5 phases +| Role not found | Error with expected path (roles/<name>/role.md) | +| CLI tool fails | Worker fallback to direct implementation | +| Scanner finds 0 findings | Report clean, skip review + fix | +| User declines fix | Delete FIX tasks, complete with review-only results | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-review/roles/coordinator/commands/analyze.md b/.claude/skills/team-review/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..800e6756 --- /dev/null +++ b/.claude/skills/team-review/roles/coordinator/commands/analyze.md @@ -0,0 +1,71 @@ +# Analyze Task + +Parse user task -> detect review capabilities -> build dependency graph -> design pipeline. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| scan, lint, static analysis, toolchain | scanner | SCAN | +| review, analyze, audit, findings | reviewer | REV | +| fix, repair, remediate, patch | fixer | FIX | + +## Pipeline Mode Detection + +| Condition | Mode | +|-----------|------| +| Flag `--fix` | fix-only | +| Flag `--full` | full | +| Flag `-q` or `--quick` | quick | +| (none) | default | + +## Dependency Graph + +Natural ordering for review pipeline: +- Tier 0: scanner (toolchain + semantic scan, no upstream dependency) +- Tier 1: reviewer (deep analysis, requires scan findings) +- Tier 2: fixer (apply fixes, requires reviewed findings + user confirm) + +## Pipeline Definitions + +``` +quick: SCAN(quick=true) +default: SCAN -> REV +full: SCAN -> REV -> [user confirm] -> FIX +fix-only: FIX +``` + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per capability | +1 | +| Large target scope (>20 files) | +2 | +| Multiple dimensions | +1 | +| Fix phase included | +1 | + +Results: 1-2 Low, 3-4 Medium, 5+ High + +## Role Minimization + +- Cap at 4 roles (coordinator + 3 workers) +- Sequential pipeline: scanner -> reviewer -> fixer + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_mode": "<quick|default|full|fix-only>", + "target": "<path>", + "dimensions": ["sec", "cor", "prf", "mnt"], + "auto_confirm": false, + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>" }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."] } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }], + "complexity": { "score": 0, "level": "Low|Medium|High" } +} +``` diff --git a/.claude/skills/team-review/roles/coordinator/commands/dispatch.md b/.claude/skills/team-review/roles/coordinator/commands/dispatch.md index 1d48df65..a7025873 100644 --- a/.claude/skills/team-review/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-review/roles/coordinator/commands/dispatch.md @@ -1,143 +1,91 @@ -# Command: dispatch +# Dispatch Tasks -> Task chain creation based on pipeline mode. Creates SCAN/REV/FIX tasks with dependencies. +Create task chains from pipeline mode with proper blockedBy relationships. -## When to Use +## Workflow -- Phase 3 of Coordinator -- Pipeline mode detected, need to create task chain -- Session initialized +1. Read task-analysis.json -> extract pipeline_mode and parameters +2. Read specs/pipelines.md -> get task registry for selected pipeline +3. Topological sort tasks (respect blockedBy) +4. Validate all owners exist in role registry (SKILL.md) +5. For each task (in order): + - TaskCreate with structured description (see template below) + - TaskUpdate with blockedBy + owner assignment +6. Update session meta.json with pipeline.tasks_total +7. Validate chain (no orphans, no cycles, all refs valid) -**Trigger conditions**: -- Coordinator Phase 2 complete -- Mode switch requires chain rebuild +## Task Description Template -## Strategy - -### Delegation Mode - -**Mode**: Direct (coordinator operates TaskCreate/TaskUpdate directly) - -### Decision Logic - -```javascript -// Build pipeline based on mode -function buildPipeline(pipelineMode) { - const pipelines = { - 'default': [ - { prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Multi-dimension code scan', blockedBy: [], meta: {} }, - { prefix: 'REV', suffix: '001', owner: 'reviewer', desc: 'Deep finding analysis and review', blockedBy: ['SCAN-001'], meta: {} } - ], - 'full': [ - { prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Multi-dimension code scan', blockedBy: [], meta: {} }, - { prefix: 'REV', suffix: '001', owner: 'reviewer', desc: 'Deep finding analysis and review', blockedBy: ['SCAN-001'], meta: {} }, - { prefix: 'FIX', suffix: '001', owner: 'fixer', desc: 'Plan and execute fixes', blockedBy: ['REV-001'], meta: {} } - ], - 'fix-only': [ - { prefix: 'FIX', suffix: '001', owner: 'fixer', desc: 'Execute fixes from manifest', blockedBy: [], meta: {} } - ], - 'quick': [ - { prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Quick scan (fast mode)', blockedBy: [], meta: { quick: true } } - ] - } - return pipelines[pipelineMode] || pipelines['default'] -} +``` +PURPOSE: <goal> | Success: <criteria> +TASK: + - <step 1> + - <step 2> +CONTEXT: + - Session: <session-folder> + - Target: <target> + - Dimensions: <dimensions> + - Upstream artifacts: <list> +EXPECTED: <artifact path> + <quality criteria> +CONSTRAINTS: <scope limits> +--- +InnerLoop: <true|false> +RoleSpec: .claude/skills/team-review/roles/<role>/role.md ``` -## Execution Steps +## Pipeline Task Registry -### Step 1: Session Initialization - -```javascript -// Session directory already created in Phase 2 -// Write pipeline config to shared memory -const sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) -sharedMemory.pipeline_mode = pipelineMode -sharedMemory.pipeline_stages = buildPipeline(pipelineMode).map(s => `${s.prefix}-${s.suffix}`) -Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) +### default Mode +``` +SCAN-001 (scanner): Multi-dimension code scan + blockedBy: [], meta: target=<target>, dimensions=<dims> +REV-001 (reviewer): Deep finding analysis and review + blockedBy: [SCAN-001] ``` -### Step 2: Create Task Chain - -```javascript -const pipeline = buildPipeline(pipelineMode) -const taskIds = {} - -for (const stage of pipeline) { - const taskSubject = `${stage.prefix}-${stage.suffix}: ${stage.desc}` - - // Build task description with session context - const fullDesc = [ - stage.desc, - `\nsession: ${sessionFolder}`, - `\ntarget: ${target}`, - `\ndimensions: ${dimensions.join(',')}`, - stage.meta?.quick ? `\nquick: true` : '', - `\n\nGoal: ${taskDescription || target}` - ].join('') - - // Create task - TaskCreate({ - subject: taskSubject, - description: fullDesc, - activeForm: `${stage.desc} in progress` - }) - - // Record task ID - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith(`${stage.prefix}-${stage.suffix}`)) - taskIds[`${stage.prefix}-${stage.suffix}`] = newTask.id - - // Set owner and dependencies - const blockedByIds = stage.blockedBy - .map(dep => taskIds[dep]) - .filter(Boolean) - - TaskUpdate({ - taskId: newTask.id, - owner: stage.owner, - addBlockedBy: blockedByIds - }) -} +### full Mode +``` +SCAN-001 (scanner): Multi-dimension code scan + blockedBy: [], meta: target=<target>, dimensions=<dims> +REV-001 (reviewer): Deep finding analysis and review + blockedBy: [SCAN-001] +FIX-001 (fixer): Plan and execute fixes + blockedBy: [REV-001] ``` -### Step 3: Verify Chain +### fix-only Mode +``` +FIX-001 (fixer): Execute fixes from manifest + blockedBy: [], meta: input=<fix-manifest> +``` -```javascript -const allTasks = TaskList() -const chainTasks = pipeline.map(s => taskIds[`${s.prefix}-${s.suffix}`]).filter(Boolean) -const chainValid = chainTasks.length === pipeline.length +### quick Mode +``` +SCAN-001 (scanner): Quick scan (fast mode) + blockedBy: [], meta: target=<target>, quick=true +``` -if (!chainValid) { - mcp__ccw-tools__team_msg({ - operation: "log", session_id: sessionId, from: "coordinator", - type: "error", - }) -} +## InnerLoop Flag Rules +- true: fixer role (iterative fix cycles) +- false: scanner, reviewer roles + +## Dependency Validation + +- No orphan tasks (all tasks have valid owner) +- No circular dependencies +- All blockedBy references exist +- Session reference in every task description +- RoleSpec reference in every task description + +## Log After Creation + +``` mcp__ccw-tools__team_msg({ - operation: "log", session_id: sessionId, from: "coordinator", - to: "all", type: "dispatch_ready", + operation: "log", + session_id: <session-id>, + from: "coordinator", + type: "dispatch_ready", + data: { pipeline: "<mode>", task_count: <N>, target: "<target>" } }) ``` - -## Output Format - -``` -## Task Chain Created - -### Mode: [default|full|fix-only|quick] -### Pipeline Stages: [count] -- [prefix]-[suffix]: [description] (owner: [role], blocked by: [deps]) - -### Verification: PASS/FAIL -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| Task creation fails | Retry once, then report to user | -| Dependency cycle | Flatten dependencies, warn coordinator | -| Invalid pipelineMode | Default to 'default' mode | -| Missing session folder | Re-create, log warning | diff --git a/.claude/skills/team-review/roles/coordinator/commands/monitor.md b/.claude/skills/team-review/roles/coordinator/commands/monitor.md index 3a4888f2..5f35ed14 100644 --- a/.claude/skills/team-review/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-review/roles/coordinator/commands/monitor.md @@ -1,276 +1,184 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events for the review pipeline using the async Spawn-and-Stop pattern. One operation per invocation, then STOP and wait for the next callback. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | Description | -|-----|-------|-------------| -| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` | -| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS | -| WORKER_AGENT | team-worker | All workers spawned as team-worker agents | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker -### Role-Worker Map +## Handler Router + +| Source | Handler | +|--------|---------| +| Message contains [scanner], [reviewer], [fixer] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | + +## Role-Worker Map | Prefix | Role | Role Spec | inner_loop | |--------|------|-----------|------------| -| SCAN | scanner | `.claude/skills/team-review/role-specs/scanner.md` | false | -| REV | reviewer | `.claude/skills/team-review/role-specs/reviewer.md` | false | -| FIX | fixer | `.claude/skills/team-review/role-specs/fixer.md` | false | +| SCAN-* | scanner | `.claude/skills/team-review/roles/scanner/role.md` | false | +| REV-* | reviewer | `.claude/skills/team-review/roles/reviewer/role.md` | false | +| FIX-* | fixer | `.claude/skills/team-review/roles/fixer/role.md` | true | -### Pipeline Modes +## handleCallback -| Mode | Stages | -|------|--------| -| scan-only | SCAN-001 | -| default | SCAN-001 -> REV-001 | -| full | SCAN-001 -> REV-001 -> FIX-001 | -| fix-only | FIX-001 | +Worker completed. Verify completion, check pipeline conditions, advance. -## Phase 2: Context Loading +1. Parse message to identify role and task ID: -| Input | Source | Required | -|-------|--------|----------| -| Session file | `<session-folder>/.msg/meta.json` | Yes | -| Task list | `TaskList()` | Yes | -| Active workers | session.active_workers[] | Yes | -| Pipeline mode | session.pipeline_mode | Yes | +| Message Pattern | Role Detection | +|----------------|---------------| +| `[scanner]` or task ID `SCAN-*` | scanner | +| `[reviewer]` or task ID `REV-*` | reviewer | +| `[fixer]` or task ID `FIX-*` | fixer | -``` -Load session state: - 1. Read <session-folder>/.msg/meta.json -> session - 2. TaskList() -> allTasks - 3. Extract pipeline_mode from session - 4. Extract active_workers[] from session (default: []) - 5. Parse $ARGUMENTS to determine trigger event - 6. autoYes = /\b(-y|--yes)\b/.test(args) -``` +2. Check if progress update (inner loop) or final completion +3. Progress -> update session state, STOP +4. Completion -> mark task done via TaskUpdate(status="completed"), remove from active_workers +5. Check for checkpoints: + - scanner completes -> read meta.json for findings_count: + - findings_count === 0 -> delete remaining REV-*/FIX-* tasks -> handleComplete + - findings_count > 0 -> proceed to handleSpawnNext + - reviewer completes AND pipeline_mode === 'full': + - autoYes flag set -> write fix-manifest.json, set fix_scope='all' -> handleSpawnNext + - NO autoYes -> AskUserQuestion: + ``` + question: "<N> findings reviewed. Proceed with fix?" + options: + - "Fix all": set fix_scope='all' + - "Fix critical/high only": set fix_scope='critical,high' + - "Skip fix": delete FIX-* tasks -> handleComplete + ``` + Write fix_scope to meta.json, write fix-manifest.json, -> handleSpawnNext + - fixer completes -> handleSpawnNext (checks for completion naturally) -## Phase 3: Event Handlers +6. -> handleSpawnNext -### Wake-up Source Detection +## handleCheck -Parse `$ARGUMENTS` to determine handler: - -| Priority | Condition | Handler | -|----------|-----------|---------| -| 1 | Message contains `[scanner]`, `[reviewer]`, or `[fixer]` | handleCallback | -| 2 | Contains "check" or "status" | handleCheck | -| 3 | Contains "resume", "continue", or "next" | handleResume | -| 4 | Pipeline detected as complete (no pending, no in_progress) | handleComplete | -| 5 | None of the above (initial spawn after dispatch) | handleSpawnNext | - ---- - -### Handler: handleCallback - -Worker completed a task. Verify completion, check pipeline conditions, advance. - -``` -Receive callback from [<role>] - +- Find matching active worker by role tag - +- Task status = completed? - | +- YES -> remove from active_workers -> update session - | | +- role = scanner? - | | | +- Read session.findings_count from meta.json - | | | +- findings_count === 0? - | | | | +- YES -> Skip remaining stages: - | | | | | Delete all REV-* and FIX-* tasks (TaskUpdate status='deleted') - | | | | | Log: "0 findings, skipping review/fix stages" - | | | | | -> handleComplete - | | | | +- NO -> normal advance - | | | +- -> handleSpawnNext - | | +- role = reviewer? - | | | +- pipeline_mode === 'full'? - | | | | +- YES -> Need fix confirmation gate - | | | | | +- autoYes? - | | | | | | +- YES -> Set fix_scope='all' in meta.json - | | | | | | +- Write fix-manifest.json - | | | | | | +- -> handleSpawnNext - | | | | | +- NO -> AskUserQuestion: - | | | | | question: "<N> findings reviewed. Proceed with fix?" - | | | | | header: "Fix Confirmation" - | | | | | options: - | | | | | - "Fix all": Set fix_scope='all' - | | | | | - "Fix critical/high only": Set fix_scope='critical,high' - | | | | | - "Skip fix": Delete FIX-* tasks -> handleComplete - | | | | | +- Write fix_scope to meta.json - | | | | | +- Write fix-manifest.json: - | | | | | { source: "<session>/review/review-report.json", - | | | | | scope: fix_scope, session: sessionFolder } - | | | | | +- -> handleSpawnNext - | | | | +- NO -> normal advance -> handleSpawnNext - | | +- role = fixer? - | | +- -> handleSpawnNext (checks for completion naturally) - | +- NO -> progress message, do not advance -> STOP - +- No matching worker found - +- Scan all active workers for completed tasks - +- Found completed -> process each -> handleSpawnNext - +- None completed -> STOP -``` - ---- - -### Handler: handleSpawnNext - -Find all ready tasks, spawn one team-worker agent in background, update session, STOP. - -``` -Collect task states from TaskList() - +- completedSubjects: status = completed - +- inProgressSubjects: status = in_progress - +- deletedSubjects: status = deleted - +- readySubjects: status = pending - AND (no blockedBy OR all blockedBy in completedSubjects) - -Ready tasks found? - +- NONE + work in progress -> report waiting -> STOP - +- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete - +- HAS ready tasks -> take first ready task: - +- Determine role from prefix: - | SCAN-* -> scanner - | REV-* -> reviewer - | FIX-* -> fixer - +- TaskUpdate -> in_progress - +- team_msg log -> task_unblocked (team_session_id=<session-id>) - +- Spawn team-worker (see spawn call below) - +- Add to session.active_workers - +- Update session file - +- Output: "[coordinator] Spawned <role> for <subject>" - +- STOP -``` - -**Spawn worker tool call**: - -``` -Agent({ - agent_type: "team-worker", - description: "Spawn <role> worker for <subject>", - team_name: "review", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-review/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: review -requirement: <task-description> -inner_loop: false - -## Current Task -- Task ID: <task-id> -- Task: <subject> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - ---- - -### Handler: handleCheck - -Read-only status report. No pipeline advancement. - -**Output format**: +Read-only status report, then STOP. +Output: ``` [coordinator] Review Pipeline Status [coordinator] Mode: <pipeline_mode> [coordinator] Progress: <completed>/<total> (<percent>%) [coordinator] Pipeline Graph: - SCAN-001: <status-icon> <summary> - REV-001: <status-icon> <summary> - FIX-001: <status-icon> <summary> + SCAN-001: <done|run|wait|deleted> <summary> + REV-001: <done|run|wait|deleted> <summary> + FIX-001: <done|run|wait|deleted> <summary> - done=completed >>>=running o=pending x=deleted .=not created - -[coordinator] Active Workers: - > <subject> (<role>) - running + done=completed >>>=running o=pending x=deleted +[coordinator] Active Workers: <list with elapsed time> [coordinator] Ready to spawn: <subjects> [coordinator] Commands: 'resume' to advance | 'check' to refresh ``` Then STOP. ---- +## handleResume -### Handler: handleResume +1. No active workers -> handleSpawnNext +2. Has active -> check each status + - completed -> mark done via TaskUpdate + - in_progress -> still running + - other -> worker failure -> reset to pending +3. Some completed -> handleSpawnNext +4. All running -> report status, STOP -Check active worker completion, process results, advance pipeline. +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect from TaskList(): + - completedSubjects: status = completed + - inProgressSubjects: status = in_progress + - deletedSubjects: status = deleted + - readySubjects: status = pending AND all blockedBy in completedSubjects + +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> take first ready task: + a. Determine role from prefix (use Role-Worker Map) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker: ``` -Load active_workers from session - +- No active workers -> handleSpawnNext - +- Has active workers -> check each: - +- status = completed -> mark done, remove from active_workers, log - +- status = in_progress -> still running, log - +- other status -> worker failure -> reset to pending - After processing: - +- Some completed -> handleSpawnNext - +- All still running -> report status -> STOP - +- All failed -> handleSpawnNext (retry) +Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <subject>", + team_name: "review", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-review/roles/<role>/role.md +session: <session-folder> +session_id: <session-id> +team_name: review +requirement: <task-description> +inner_loop: <true|false> + +## Current Task +- Task ID: <task-id> +- Task: <subject> + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` +}) ``` ---- + e. Add to active_workers +5. Update session meta.json, output summary, STOP -### Handler: handleComplete +## handleComplete -Pipeline complete. Generate summary and finalize session. +Pipeline done. Generate report and completion action. -``` -All tasks completed or deleted (no pending, no in_progress) - +- Read final session state from meta.json - +- Generate pipeline summary: - | - Pipeline mode - | - Findings count - | - Stages completed - | - Fix results (if applicable) - | - Deliverable paths - | - +- Update session: - | session.pipeline_status = 'complete' - | session.completed_at = <timestamp> - | Write meta.json - | - +- team_msg log -> pipeline_complete - +- Output summary to user - +- STOP -``` +1. All tasks completed or deleted (no pending, no in_progress) +2. Read final session state from meta.json +3. Generate pipeline summary: mode, target, findings_count, stages_completed, fix results (if applicable), deliverable paths +4. Update session: pipeline_status='complete', completed_at=<timestamp> +5. Read session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) ---- +## handleAdapt -### Worker Failure Handling +Capability gap reported mid-pipeline. -When a worker has unexpected status (not completed, not in_progress): +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 4 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 4 -> merge or pause -1. Reset task -> pending via TaskUpdate -2. Remove from active_workers -3. Log via team_msg (type: error) -4. Report to user: task reset, will retry on next resume +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns ## Phase 4: State Persistence -After every handler action, before STOP: - -| Check | Action | -|-------|--------| -| Session state consistent | active_workers matches TaskList in_progress tasks | -| No orphaned tasks | Every in_progress task has an active_worker entry | -| Meta.json updated | Write updated session state | -| Completion detection | readySubjects=0 + inProgressSubjects=0 -> handleComplete | - -``` -Persist: - 1. Reconcile active_workers with actual TaskList states - 2. Remove entries for completed/deleted tasks - 3. Write updated meta.json - 4. Verify consistency - 5. STOP (wait for next callback) -``` +After every handler execution: +1. Reconcile active_workers with actual TaskList states +2. Remove entries for completed/deleted tasks +3. Write updated meta.json +4. STOP (wait for next callback) ## Error Handling @@ -278,7 +186,7 @@ Persist: |----------|------------| | Session file not found | Error, suggest re-initialization | | Worker callback from unknown role | Log info, scan for other completions | -| All workers still running on resume | Report status, suggest check later | -| Pipeline stall (no ready, no running, has pending) | Check blockedBy chains, report to user | | 0 findings after scan | Delete remaining stages, complete pipeline | -| User declines fix | Delete FIX tasks, complete with review-only results | +| User declines fix | Delete FIX-* tasks, complete with review-only results | +| Pipeline stall | Check blockedBy chains, report to user | +| Worker failure | Reset task to pending, respawn on next resume | diff --git a/.claude/skills/team-review/roles/coordinator/role.md b/.claude/skills/team-review/roles/coordinator/role.md index cde363c4..3688ef69 100644 --- a/.claude/skills/team-review/roles/coordinator/role.md +++ b/.claude/skills/team-review/roles/coordinator/role.md @@ -1,152 +1,62 @@ # Coordinator Role -Code review team coordinator. Orchestrates the scan-review-fix pipeline (CP-1 Linear): parse target, detect mode, dispatch task chain, drive sequential stage execution via Stop-Wait, aggregate results. +Orchestrate team-review: parse target -> detect mode -> dispatch task chain -> monitor -> report. ## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Task Prefix**: RC-* (coordinator creates tasks, doesn't receive them) -- **Responsibility**: Orchestration +- Name: coordinator | Tag: [coordinator] +- Responsibility: Target parsing, mode detection, task creation/dispatch, stage monitoring, result aggregation ## Boundaries ### MUST - -- All output (SendMessage, team_msg, logs) prefixed with `[coordinator]` -- Only: target parsing, mode detection, task creation/dispatch, stage monitoring, result aggregation -- Create tasks via TaskCreate and assign to worker roles -- Drive pipeline stages via Stop-Wait (synchronous Skill() calls) -- Parse user requirements and clarify ambiguous inputs via AskUserQuestion -- Maintain session state persistence +- All output prefixed with `[coordinator]` +- Parse task description and detect pipeline mode +- Create team and spawn team-worker agents in background +- Dispatch task chain with proper dependencies +- Monitor progress via callbacks and route messages +- Maintain session state +- Execute completion action when pipeline finishes ### MUST NOT - - Run analysis tools directly (semgrep, eslint, tsc, etc.) - Modify source code files -- Perform code review analysis -- Bypass worker roles to do delegated work -- Omit `[coordinator]` prefix on any output -- Call implementation CLI tools directly - -> **Core principle**: coordinator is the orchestrator, not the executor. All actual work delegated to scanner/reviewer/fixer via task chain. - ---- +- Perform code review or scanning directly +- Bypass worker roles +- Spawn workers with general-purpose agent (MUST use team-worker) ## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [scanner], [reviewer], [fixer] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) | -| New session | None of above | -> Phase 1 (Parse Arguments) | +| Worker callback | Message contains [scanner], [reviewer], [fixer] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/RV-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. +For callback/check/resume/adapt/complete: load commands/monitor.md, execute handler, STOP. -### Router Implementation +## Phase 0: Session Resume Check -1. **Load session context** (if exists): - - Scan `.workflow/.team-review/RC-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode +1. Scan .workflow/.team/RV-*/.msg/meta.json for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords +## Phase 1: Requirement Clarification -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check - - For Phase 1: Execute Parse Arguments below +TEXT-LEVEL ONLY. No source code reading. ---- - -## Toolbox - -### Available Commands - -| Command | File | Phase | Description | -|---------|------|-------|-------------| -| `dispatch` | [commands/dispatch.md](commands/dispatch.md) | Phase 3 | Task chain creation based on mode | -| `monitor` | [commands/monitor.md](commands/monitor.md) | Phase 4 | Stop-Wait stage execution loop | - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `TaskCreate` | Built-in | coordinator | Create tasks for workers | -| `TaskUpdate` | Built-in | coordinator | Update task status | -| `TaskList` | Built-in | coordinator | Check task states | -| `AskUserQuestion` | Built-in | coordinator | Clarify requirements | -| `Skill` | Built-in | coordinator | Spawn workers | -| `SendMessage` | Built-in | coordinator | Receive worker callbacks | -| `team_msg` | MCP | coordinator | Log communication | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `dispatch_ready` | coordinator -> all | Phase 3 done | Task chain created, pipeline ready | -| `stage_transition` | coordinator -> worker | Stage unblocked | Next stage starting | -| `pipeline_complete` | coordinator -> user | All stages done | Pipeline finished, summary ready | -| `error` | coordinator -> user | Stage failure | Blocking issue requiring attention | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: <session-id>, - from: "coordinator", - type: "dispatch_ready" -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --session-id <session-id> --from coordinator --type dispatch_ready --json") -``` - ---- - -## Execution (5-Phase) - -### Phase 1: Parse Arguments & Detect Mode - -**Objective**: Parse user input and gather execution parameters. - -**Workflow**: - -1. **Parse arguments** for explicit settings: +1. Parse arguments for explicit settings: | Flag | Mode | Description | |------|------|-------------| @@ -155,147 +65,65 @@ Bash("ccw team log --session-id <session-id> --from coordinator --type dispatch_ | `-q` / `--quick` | quick | Quick scan only, no review/fix | | (none) | default | scan + review pipeline | -2. **Extract parameters**: +2. Extract parameters: target, dimensions, auto-confirm flag +3. Clarify if ambiguous (AskUserQuestion for target path) +4. Delegate to commands/analyze.md +5. Output: task-analysis.json +6. CRITICAL: Always proceed to Phase 2, never skip team workflow -| Parameter | Extraction Method | Default | -|-----------|-------------------|---------| -| Target | Task description minus flags | `.` | -| Dimensions | `--dimensions=sec,cor,perf,maint` | All 4 | -| Auto-confirm | `-y` / `--yes` flag | false | +## Phase 2: Create Team + Initialize Session -3. **Ask for missing parameters** via AskUserQuestion (if not auto-confirm): +1. Generate session ID: RV-<slug>-<date> +2. Create session folder structure (scan/, review/, fix/, wisdom/) +3. TeamCreate with team name "review" +4. Read specs/pipelines.md -> select pipeline based on mode +5. Initialize pipeline via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { + pipeline_mode: "<default|full|fix-only|quick>", + pipeline_stages: ["scanner", "reviewer", "fixer"], + team_name: "review", + target: "<target>", + dimensions: "<dimensions>", + auto_confirm: "<auto_confirm>" + } + }) + ``` +6. Write session meta.json -| Question | Options | -|----------|---------| -| "What code should be reviewed?" | Custom path, Uncommitted changes, Full project scan | +## Phase 3: Create Task Chain -**Success**: All parameters captured, mode finalized. +Delegate to commands/dispatch.md: +1. Read specs/pipelines.md for selected pipeline's task registry +2. Create tasks via TaskCreate with blockedBy +3. Update session meta.json with pipeline.tasks_total ---- +## Phase 4: Spawn-and-Stop -### Phase 2: Initialize Session +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP -**Objective**: Initialize team, session file, and shared memory. +## Phase 5: Report + Completion Action -**Workflow**: - -1. Generate session ID: `RC-<target-slug>-<date>` -2. Create session folder structure: - -``` -.workflow/.team-review/<workflow_id>/ -├── scan/ -├── review/ -├── fix/ -├── wisdom/ -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── .msg/ -│ ├── messages.jsonl -│ └── meta.json -``` - -3. Initialize .msg/meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<default|full|fix-only|quick>", - pipeline_stages: ["scanner", "reviewer", "fixer"], - roles: ["coordinator", "scanner", "reviewer", "fixer"], - team_name: "review", - target: "<target>", - dimensions: "<dimensions>", - auto_confirm: "<auto_confirm>" - } -}) -``` - -**Success**: Session folder created, shared memory 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. - -**Task Chain by Mode**: - -| Mode | Chain | Description | -|------|-------|-------------| -| default | SCAN-001 -> REV-001 | scan + review | -| full | SCAN-001 -> REV-001 -> FIX-001 | scan + review + fix | -| fix-only | FIX-001 | fix only | -| quick | SCAN-001 (quick=true) | quick scan only | - -**Success**: Task chain created with correct blockedBy dependencies. - ---- - -### Phase 4: Sequential Stage Execution (Stop-Wait) - -**Objective**: Spawn workers sequentially via Skill(), synchronous blocking until return. - -> **Strategy**: Spawn-and-Stop + Callback pattern. -> - Spawn workers with synchronous `Skill()` call -> blocking wait for return -> - Worker return = stage complete. No polling. -> - FORBIDDEN: `while` loop + `sleep` + check status -> - REQUIRED: Synchronous `Skill()` call = natural callback - -**Workflow**: - -1. Load `commands/monitor.md` -2. Find next executable task (pending + blockedBy resolved) -3. Spawn worker via Skill() -4. Wait for worker return -5. Process result -> advance to next stage -6. Repeat until pipeline complete - -**Stage Flow**: - -| Stage | Worker | On Complete | -|-------|--------|-------------| -| SCAN-001 | scanner | Check findings count -> start REV | -| REV-001 | reviewer | Generate review report -> [user confirm] -> start FIX | -| FIX-001 | fixer | Execute fixes -> verify | - ---- - -### Phase 5: Aggregate Results & Report - -> See SKILL.md Shared Infrastructure -> Coordinator Phase 5 - -**Objective**: Completion report and follow-up options. - -**Workflow**: - -1. Load session state -> count completed tasks, duration -2. Calculate fix rate: (fixed_count / findings_count) * 100 -3. Build summary report with: mode, target, dimensions, findings_total, by_severity, by_dimension, fixed_count, fix_rate -4. Log via team_msg -5. SendMessage with `[coordinator]` prefix -6. AskUserQuestion for next steps (unless auto-confirm) - ---- +1. Generate summary (mode, target, findings_total, by_severity, fix_rate if applicable) +2. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Export) + - auto_archive -> Archive & Clean + - auto_keep -> Keep Active ## Error Handling -| Scenario | Resolution | -|----------|------------| +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | | Scanner finds 0 findings | Report clean, skip review + fix stages | -| Worker returns incomplete | Ask user: retry / skip / abort | | Fix verification fails | Log warning, report partial results | -| Session folder missing | Re-create and log warning | | Target path invalid | AskUserQuestion for corrected path | -| Task timeout | Log, mark failed, ask user to retry or skip | -| Worker crash | Respawn worker, reassign task | -| Dependency cycle | Detect, report to user, halt | diff --git a/.claude/skills/team-review/roles/fixer/role.md b/.claude/skills/team-review/roles/fixer/role.md new file mode 100644 index 00000000..3d0bb5c0 --- /dev/null +++ b/.claude/skills/team-review/roles/fixer/role.md @@ -0,0 +1,76 @@ +--- +role: fixer +prefix: FIX +inner_loop: true +message_types: + success: fix_complete + error: fix_failed +--- + +# Code Fixer + +Fix code based on reviewed findings. Load manifest, plan fix groups, apply with rollback-on-failure, verify. Code-generation role -- modifies source files. + +## Phase 2: Context & Scope Resolution + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Fix manifest | <session>/fix/fix-manifest.json | Yes | +| Review report | <session>/review/review-report.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path, input path from task description +2. Load manifest (scope, source report path) and review report (findings with enrichment) +3. Filter fixable findings: severity in scope AND fix_strategy !== 'skip' +4. If 0 fixable -> report complete immediately +5. Detect quick path: findings <= 5 AND no cross-file dependencies +6. Detect verification tools: tsc (tsconfig.json), eslint (package.json), jest (package.json), pytest (pyproject.toml), semgrep (semgrep available) +7. Load wisdom files from `<session>/wisdom/` + +## Phase 3: Plan + Execute + +### 3A: Plan Fixes (deterministic, no CLI) +1. Group findings by primary file +2. Merge groups with cross-file dependencies (union-find) +3. Topological sort within each group (respect fix_dependencies, append cycles at end) +4. Sort groups by max severity (critical first) +5. Determine execution path: quick_path (<=5 findings, <=1 group) or standard +6. Write `<session>/fix/fix-plan.json`: `{plan_id, quick_path, groups[{id, files[], findings[], max_severity}], execution_order[], total_findings, total_groups}` + +### 3B: Execute Fixes +**Quick path**: Single code-developer agent for all findings. +**Standard path**: One code-developer agent per group, in execution_order. + +Agent prompt includes: finding list (dependency-sorted), file contents (truncated 8K), critical rules: +1. Apply each fix using Edit tool in order +2. After each fix, run related tests +3. Tests PASS -> finding is "fixed" +4. Tests FAIL -> `git checkout -- {file}` -> mark "failed" -> continue +5. No retry on failure. Rollback and move on +6. If finding depends on previously failed finding -> mark "skipped" + +Agent returns JSON: `{results:[{id, status: fixed|failed|skipped, file, error?}]}` +Fallback: check git diff per file if no structured output. + +Write `<session>/fix/execution-results.json`: `{fixed[], failed[], skipped[]}` + +## Phase 4: Post-Fix Verification + +1. Run available verification tools on modified files: + +| Tool | Command | Pass Criteria | +|------|---------|---------------| +| tsc | `npx tsc --noEmit` | 0 errors | +| eslint | `npx eslint <files>` | 0 errors | +| jest | `npx jest --passWithNoTests` | Tests pass | +| pytest | `pytest --tb=short` | Tests pass | +| semgrep | `semgrep --config auto <files> --json` | 0 results | + +2. If verification fails critically -> rollback last batch +3. Write `<session>/fix/verify-results.json` +4. Generate `<session>/fix/fix-summary.json`: `{fix_id, fix_date, scope, total, fixed, failed, skipped, fix_rate, verification}` +5. Generate `<session>/fix/fix-summary.md` (human-readable) +6. Update `<session>/.msg/meta.json` with fix results +7. Contribute discoveries to `<session>/wisdom/` files diff --git a/.claude/skills/team-review/roles/reviewer/role.md b/.claude/skills/team-review/roles/reviewer/role.md new file mode 100644 index 00000000..4c9cce73 --- /dev/null +++ b/.claude/skills/team-review/roles/reviewer/role.md @@ -0,0 +1,67 @@ +--- +role: reviewer +prefix: REV +inner_loop: false +message_types: + success: review_complete + error: error +--- + +# Finding Reviewer + +Deep analysis on scan findings: triage, root cause / impact / optimization enrichment via CLI fan-out, cross-correlation, and structured review report generation. Read-only -- never modifies source code. + +## Phase 2: Context & Triage + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Scan results | <session>/scan/scan-results.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path, input path, dimensions from task description +2. Load scan results. If missing or empty -> report clean, complete immediately +3. Load wisdom files from `<session>/wisdom/` +4. Triage findings into two buckets: + +| Bucket | Criteria | Action | +|--------|----------|--------| +| deep_analysis | severity in [critical, high, medium], max 15, sorted critical-first | Enrich with root cause, impact, optimization | +| pass_through | remaining (low, info, or overflow) | Include in report without enrichment | + +If deep_analysis empty -> skip Phase 3, go to Phase 4. + +## Phase 3: Deep Analysis (CLI Fan-out) + +Split deep_analysis into two domain groups, run parallel CLI agents: + +| Group | Dimensions | Focus | +|-------|-----------|-------| +| A | Security + Correctness | Root cause tracing, fix dependencies, blast radius | +| B | Performance + Maintainability | Optimization approaches, refactor tradeoffs | + +If either group empty -> skip that agent. + +Build prompt per group requesting 6 enrichment fields per finding: +- `root_cause`: `{description, related_findings[], is_symptom}` +- `impact`: `{scope: low/medium/high, affected_files[], blast_radius}` +- `optimization`: `{approach, alternative, tradeoff}` +- `fix_strategy`: minimal / refactor / skip +- `fix_complexity`: low / medium / high +- `fix_dependencies`: finding IDs that must be fixed first + +Execute via `ccw cli --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause` (fallback: qwen -> codex). Parse JSON array responses, merge with originals (CLI-enriched replace originals, unenriched get defaults). Write `<session>/review/enriched-findings.json`. + +## Phase 4: Report Generation + +1. Combine enriched + pass_through findings +2. Cross-correlate: + - **Critical files**: file appears in >=2 dimensions -> list with finding_count, severities + - **Root cause groups**: cluster findings sharing related_findings -> identify primary + - **Optimization suggestions**: from root cause groups + standalone enriched findings +3. Compute metrics: by_dimension, by_severity, dimension_severity_matrix, fixable_count, auto_fixable_count +4. Write `<session>/review/review-report.json`: `{review_id, review_date, findings[], critical_files[], optimization_suggestions[], root_cause_groups[], summary}` +5. Write `<session>/review/review-report.md`: Executive summary, metrics matrix (dimension x severity), critical/high findings table, critical files list, optimization suggestions, recommended fix scope +6. Update `<session>/.msg/meta.json` with review summary +7. Contribute discoveries to `<session>/wisdom/` files diff --git a/.claude/skills/team-review/roles/scanner/role.md b/.claude/skills/team-review/roles/scanner/role.md new file mode 100644 index 00000000..28bbda8c --- /dev/null +++ b/.claude/skills/team-review/roles/scanner/role.md @@ -0,0 +1,71 @@ +--- +role: scanner +prefix: SCAN +inner_loop: false +message_types: + success: scan_complete + error: error +--- + +# Code Scanner + +Toolchain + LLM semantic scan producing structured findings. Static analysis tools in parallel, then LLM for issues tools miss. Read-only -- never modifies source code. 4-dimension system: security (SEC), correctness (COR), performance (PRF), maintainability (MNT). + +## Phase 2: Context & Toolchain Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/.msg/meta.json | No | + +1. Extract session path, target, dimensions, quick flag from task description +2. Resolve target files (glob pattern or directory -> `**/*.{ts,tsx,js,jsx,py,go,java,rs}`) +3. If no source files found -> report empty, complete task cleanly +4. Detect toolchain availability: + +| Tool | Detection | Dimension | +|------|-----------|-----------| +| tsc | `tsconfig.json` exists | COR | +| eslint | `.eslintrc*` or `eslint` in package.json | COR/MNT | +| semgrep | `.semgrep.yml` exists | SEC | +| ruff | `pyproject.toml` + ruff available | SEC/COR/MNT | +| mypy | mypy available + `pyproject.toml` | COR | +| npmAudit | `package-lock.json` exists | SEC | + +5. Load wisdom files from `<session>/wisdom/` if they exist + +## Phase 3: Scan Execution + +**Quick mode**: Single CLI call with analysis mode, max 20 findings, skip toolchain. + +**Standard mode** (sequential): + +### 3A: Toolchain Scan +Run detected tools in parallel via Bash backgrounding. Each tool writes to `<session>/scan/tmp/<tool>.{json|txt}`. After `wait`, parse each output into normalized findings: +- tsc: `file(line,col): error TSxxxx: msg` -> dimension=correctness, source=tool:tsc +- eslint: JSON array -> severity 2=correctness/high, else=maintainability/medium +- semgrep: `{results[]}` -> dimension=security, severity from extra.severity +- ruff: `[{code,message,filename}]` -> S*=security, F*/B*=correctness, else=maintainability +- mypy: `file:line: error: msg [code]` -> dimension=correctness +- npm audit: `{vulnerabilities:{}}` -> dimension=security, category=dependency + +Write `<session>/scan/toolchain-findings.json`. + +### 3B: Semantic Scan (LLM via CLI) +Build prompt with target file patterns, toolchain dedup summary, and per-dimension focus areas: +- SEC: Business logic vulnerabilities, privilege escalation, sensitive data flow, auth bypass +- COR: Logic errors, unhandled exception paths, state management bugs, race conditions +- PRF: Algorithm complexity, N+1 queries, unnecessary sync, memory leaks, missing caching +- MNT: Architectural coupling, abstraction leaks, convention violations, dead code + +Execute via `ccw cli --tool gemini --mode analysis --rule analysis-review-code-quality` (fallback: qwen -> codex). Parse JSON array response, validate required fields (dimension, title, location.file), enforce per-dimension limit (max 5 each), filter minimum severity (medium+). Write `<session>/scan/semantic-findings.json`. + +## Phase 4: Aggregate & Output + +1. Merge toolchain + semantic findings, deduplicate (same file + line + dimension = duplicate) +2. Assign dimension-prefixed IDs: SEC-001, COR-001, PRF-001, MNT-001 +3. Write `<session>/scan/scan-results.json` with schema: `{scan_date, target, dimensions, quick_mode, total_findings, by_severity, by_dimension, findings[]}` +4. Each finding: `{id, dimension, category, severity, title, description, location:{file,line}, source, suggested_fix, effort, confidence}` +5. Update `<session>/.msg/meta.json` with scan summary (findings_count, by_severity, by_dimension) +6. Contribute discoveries to `<session>/wisdom/` files diff --git a/.claude/skills/team-review/specs/pipelines.md b/.claude/skills/team-review/specs/pipelines.md new file mode 100644 index 00000000..2d8a88d9 --- /dev/null +++ b/.claude/skills/team-review/specs/pipelines.md @@ -0,0 +1,102 @@ +# Review Pipelines + +Pipeline definitions and task registry for team-review. + +## Pipeline Modes + +| Mode | Description | Tasks | +|------|-------------|-------| +| default | Scan + review | SCAN -> REV | +| full | Scan + review + fix | SCAN -> REV -> [confirm] -> FIX | +| fix-only | Fix from existing manifest | FIX | +| quick | Quick scan only | SCAN (quick=true) | + +## Pipeline Definitions + +### default Mode (2 tasks, linear) + +``` +SCAN-001 -> REV-001 +``` + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| SCAN-001 | scanner | (none) | Multi-dimension code scan (toolchain + LLM) | +| REV-001 | reviewer | SCAN-001 | Deep finding analysis and review report | + +### full Mode (3 tasks, linear with user checkpoint) + +``` +SCAN-001 -> REV-001 -> [user confirm] -> FIX-001 +``` + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| SCAN-001 | scanner | (none) | Multi-dimension code scan (toolchain + LLM) | +| REV-001 | reviewer | SCAN-001 | Deep finding analysis and review report | +| FIX-001 | fixer | REV-001 + user confirm | Plan + execute + verify fixes | + +### fix-only Mode (1 task) + +``` +FIX-001 +``` + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| FIX-001 | fixer | (none) | Execute fixes from existing manifest | + +### quick Mode (1 task) + +``` +SCAN-001 (quick=true) +``` + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| SCAN-001 | scanner | (none) | Quick scan, max 20 findings, skip toolchain | + +## Review Dimensions (4-Dimension System) + +| Dimension | Code | Focus | +|-----------|------|-------| +| Security | SEC | Vulnerabilities, auth, data exposure | +| Correctness | COR | Bugs, logic errors, type safety | +| Performance | PRF | N+1, memory leaks, blocking ops | +| Maintainability | MNT | Coupling, complexity, dead code | + +## Fix Scope Options + +| Scope | Description | +|-------|-------------| +| all | Fix all findings | +| critical,high | Fix critical and high severity only | +| skip | Skip fix phase | + +## Session Directory + +``` +.workflow/.team/RV-<slug>-<YYYY-MM-DD>/ +├── .msg/messages.jsonl # Message bus log +├── .msg/meta.json # Session state + cross-role state +├── wisdom/ # Cross-task knowledge +│ ├── learnings.md +│ ├── decisions.md +│ ├── conventions.md +│ └── issues.md +├── scan/ # Scanner output +│ ├── toolchain-findings.json +│ ├── semantic-findings.json +│ └── scan-results.json +├── review/ # Reviewer output +│ ├── enriched-findings.json +│ ├── review-report.json +│ └── review-report.md +└── fix/ # Fixer output + ├── fix-manifest.json + ├── fix-plan.json + ├── execution-results.json + ├── verify-results.json + ├── fix-summary.json + └── fix-summary.md +``` diff --git a/.claude/skills/team-roadmap-dev/SKILL.md b/.claude/skills/team-roadmap-dev/SKILL.md index af2c7f40..fbe8a607 100644 --- a/.claude/skills/team-roadmap-dev/SKILL.md +++ b/.claude/skills/team-roadmap-dev/SKILL.md @@ -6,311 +6,62 @@ allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), Task # Team Roadmap Dev -Unified team skill: roadmap-driven development with phased execution pipeline. Coordinator discusses roadmap with the user and manages phase transitions. All team members invoke with `--role=xxx` to route to role-specific execution. +Roadmap-driven development with phased execution pipeline. Coordinator discusses roadmap with the user and manages phase transitions. Workers are spawned as team-worker agents. -## Architecture Overview +## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-roadmap-dev") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-roadmap-dev", args="<task-description>") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+ - v v v - [tw] [tw] [tw] -plann- execu- verif- -er tor ier + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- roadmap-discuss -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+ + v v v + [planner] [executor] [verifier] + (team-worker agents) -(tw) = team-worker agent +Pipeline (per phase): + PLAN-N01 -> EXEC-N01 -> VERIFY-N01 (gap closure loop if needed) + +Multi-phase: + Phase 1 -> Phase 2 -> ... -> Phase N -> Complete ``` -## Command Architecture +## Role Registry -``` -roles/ -├── coordinator/ -│ ├── role.md # Orchestrator: roadmap discussion + phase management -│ └── commands/ -│ ├── roadmap-discuss.md # Discuss roadmap with user, generate phase plan -│ ├── dispatch.md # Create task chain per phase -│ ├── monitor.md # Stop-Wait phase execution loop -│ ├── pause.md # Save state and exit cleanly -│ └── resume.md # Resume from paused session -├── planner/ -│ ├── role.md # Research + task JSON generation per phase -│ └── commands/ -│ ├── research.md # Context gathering + codebase exploration -│ └── create-plans.md # action-planning-agent delegation → IMPL-*.json -├── executor/ -│ ├── role.md # Task execution with wave parallelism -│ └── commands/ -│ └── implement.md # Code implementation via code-developer -└── verifier/ - ├── role.md # Goal-backward verification - └── commands/ - └── verify.md # Convergence criteria checking + gap detection -``` +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| planner | [roles/planner/role.md](roles/planner/role.md) | PLAN-* | true | +| executor | [roles/executor/role.md](roles/executor/role.md) | EXEC-* | true | +| verifier | [roles/verifier/role.md](roles/verifier/role.md) | VERIFY-* | true | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). If `--resume` present → coordinator handles resume via commands/resume.md. +## Shared Constants -### Role Registry +- **Session prefix**: `RD` +- **Session path**: `.workflow/.team/RD-<slug>-<date>/` +- **Team name**: `roadmap-dev` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| planner | [role-specs/planner.md](role-specs/planner.md) | PLAN-* | true | -| executor | [role-specs/executor.md](role-specs/executor.md) | EXEC-* | true | -| verifier | [role-specs/verifier.md](role-specs/verifier.md) | VERIFY-* | true | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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-roadmap-dev", args="<task-description>")` - -**Lifecycle**: -``` -User provides task description - → coordinator: Roadmap discussion → TeamCreate → Create phase task chain - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until phase pipeline complete → transition to next phase or complete -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -### Artifact System - -**Fixed Artifacts** (session-level, persist throughout session): - -| Artifact | Path | Created By | Purpose | -|----------|------|------------|---------| -| roadmap.md | `<session>/roadmap.md` | coordinator (roadmap-discuss) | Phase plan with requirements and success criteria | -| state.md | `<session>/state.md` | coordinator | Living memory (<100 lines), updated every significant action | -| config.json | `<session>/config.json` | coordinator | Session settings: mode, depth, gates | - -**Dynamic Artifacts** (per-phase, form execution history): - -| Artifact | Path | Created By | Purpose | -|----------|------|------------|---------| -| context.md | `<session>/phase-N/context.md` | planner (research) | Phase context and requirements | -| IMPL_PLAN.md | `<session>/phase-N/IMPL_PLAN.md` | planner (create-plans) | Implementation overview with task dependency graph | -| IMPL-*.json | `<session>/phase-N/.task/IMPL-*.json` | planner (create-plans) | Task JSON files (unified flat schema with convergence criteria) | -| TODO_LIST.md | `<session>/phase-N/TODO_LIST.md` | planner (create-plans) | Checklist tracking for all tasks | -| summary-{ID}.md | `<session>/phase-N/summary-{IMPL-ID}.md` | executor (implement) | Execution record with requires/provides/convergence-met | -| verification.md | `<session>/phase-N/verification.md` | verifier (verify) | Convergence criteria check results + gap list | - -### Init Prerequisite - -Coordinator **must** ensure `.workflow/project-tech.json` exists before starting. If not found, invoke `/workflow:init`. - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | roadmap-dev | -| Session directory | `.workflow/.team/RD-<slug>-<date>/` | -| Message directory | `.workflow/.team-msg/roadmap-dev/` | - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -#### Output Tagging - -All outputs must carry `[role_name]` prefix. - -#### Coordinator Isolation - -| Allowed | Forbidden | -|---------|-----------| -| Discuss roadmap with user (AskUserQuestion) | Direct code writing/modification | -| Create task chain (TaskCreate) | Calling CLI tools for implementation | -| Dispatch tasks to workers | Direct analysis/testing/verification | -| Monitor progress (message bus) | Bypassing workers | -| Report results to user | Modifying source code | - -#### Worker Isolation - -| Allowed | Forbidden | -|---------|-----------| -| Process own-prefix tasks only | Process other roles' tasks | -| SendMessage to coordinator only | Direct worker-to-worker communication | -| Use Toolbox-declared tools | TaskCreate for other roles | -| Delegate to commands/*.md | Modify resources outside scope | - -### Message Bus & Task Lifecycle - -Each role's role.md contains self-contained Message Bus and Task Lifecycle. See `roles/<role>/role.md`. - ---- - -## Pipeline - -``` -Phase N lifecycle: - Coordinator (roadmap-discuss → dispatch phase N) - → PLAN-N01: Planner (research → action-planning-agent → IMPL-*.json) - → EXEC-N01: Executor (load IMPL-*.json → wave-based code-developer) - → VERIFY-N01: Verifier (convergence criteria check) - → Coordinator (transition: gap closure or next phase) - -Cross-phase flow: - Init → Roadmap Discussion → Phase 1 → Phase 2 → ... → Phase N → Complete - ↑ | - └── gap closure loop ──────┘ - -Session lifecycle: - Running → Pause (save coordinates) → Resume (re-enter monitor at coordinates) -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. Phase beat: PLAN → EXEC → VERIFY per phase. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Phase beat view**: - -``` -Single Phase (3 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 - │ │ │ - PLAN → EXEC ──→ VERIFY - ▲ ▲ - phase phase - start done - -PLAN=planner EXEC=executor VERIFY=verifier - -Multi-Phase (N x 3 beats, with gap closure loop) -────────────────────────────────────────────────────────── -Phase 1: PLAN-101 → EXEC-101 → VERIFY-101 - │ - ⏸ CHECKPOINT ── gap closure or next phase - │ -Phase 2: PLAN-201 → EXEC-201 → VERIFY-201 - │ - ⏸ CHECKPOINT - │ -Phase N: PLAN-N01 → EXEC-N01 → VERIFY-N01 → Complete -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Phase transition | VERIFY-N01 complete | Evaluate gaps: if gaps found → gap closure loop; if clean → next phase | -| Gap closure limit | 3 iterations | Stop iteration, report current state to user | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| Phase verification fails | Gaps detected in VERIFY | Coordinator triggers gap closure loop (max 3 iterations) | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| PLAN-N01 | planner | phase N | (none or previous VERIFY) | Research + context gathering + task JSON generation | -| EXEC-N01 | executor | phase N | PLAN-N01 | Wave-based code implementation following plans | -| VERIFY-N01 | verifier | phase N | EXEC-N01 | Convergence criteria verification + gap detection | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -321,7 +72,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-roadmap-dev/role-specs/<role>.md +role_spec: .claude/skills/team-roadmap-dev/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: roadmap-dev @@ -329,17 +80,48 @@ requirement: <task-description> inner_loop: true Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**All roles** (planner, executor, verifier): Set `inner_loop: true`. +**All worker roles** (planner, executor, verifier): Set `inner_loop: true`. ---- +## User Commands + +| Command | Action | +|---------|--------| +| `check` / `status` | Output execution status graph (phase-grouped), no advancement | +| `resume` / `continue` | Check worker states, advance next step | + +## Session Directory + +``` +.workflow/.team/RD-<slug>-<date>/ ++-- roadmap.md # Phase plan with requirements and success criteria ++-- state.md # Living memory (<100 lines) ++-- config.json # Session settings (mode, depth, gates) ++-- wisdom/ # Cross-task knowledge accumulation +| +-- learnings.md +| +-- decisions.md +| +-- conventions.md +| +-- issues.md ++-- phase-1/ # Per-phase artifacts +| +-- context.md +| +-- IMPL_PLAN.md +| +-- TODO_LIST.md +| +-- .task/IMPL-*.json +| +-- summary-*.md +| +-- verification.md ++-- phase-N/ +| +-- ... ++-- .msg/ + +-- messages.jsonl # Team message bus log + +-- meta.json # Session metadata + shared state +``` ## Completion Action -When the pipeline completes (all phases done, coordinator Phase 5): +When the pipeline completes: ``` AskUserQuestion({ @@ -356,57 +138,18 @@ AskUserQuestion({ }) ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-roadmap-dev", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | +## Specs Reference -## Session Directory - -``` -.workflow/.team/RD-<slug>-<date>/ -├── roadmap.md # Phase plan with requirements -├── state.md # Living memory (<100 lines) -├── config.json # Session settings -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── phase-1/ # Per-phase artifacts -│ ├── context.md -│ ├── IMPL_PLAN.md -│ ├── TODO_LIST.md -│ ├── .task/IMPL-*.json -│ ├── summary-*.md -│ └── verification.md -├── phase-2/ -│ └── ... -├── .msg/ -│ ├── messages.jsonl # Team message bus log -│ └── meta.json # Session metadata + shared state -``` - -## Session Resume - -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan `.workflow/.team/RD-*/` for sessions with status "active" or "paused" -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 +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>/role.md) | +| Unknown --role value | Error with role registry list | +| Role file not found | Error with expected path (roles/{name}/role.md) | | project-tech.json missing | Coordinator invokes /workflow:init | -| Phase verification fails with gaps | Coordinator triggers gap closure loop | +| Phase verification fails with gaps | Coordinator triggers gap closure loop (max 3 iterations) | | Max gap closure iterations (3) | Report to user, ask for guidance | +| Worker crash | Respawn worker, reassign task | +| Session corruption | Attempt recovery, fallback to manual reconciliation | diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/analyze.md b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..47112d2f --- /dev/null +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/analyze.md @@ -0,0 +1,61 @@ +# Analyze Task + +Parse user task description for roadmap-dev domain signals. Detect phase count, depth preference, gate configuration, and pipeline mode. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +### Phase Count + +| Keywords | Inferred Phase Count | +|----------|---------------------| +| "phase 1", "phase 2", ... | Explicit phase count from numbers | +| "milestone", "milestone 1/2/3" | Count milestones | +| "first ... then ... finally" | 3 phases | +| "step 1/2/3" | Count steps | +| No phase keywords | Default: 1 phase | + +### Depth Setting + +| Keywords | Depth | +|----------|-------| +| "quick", "fast", "simple", "minimal" | quick | +| "thorough", "comprehensive", "complete", "full" | comprehensive | +| default | standard | + +### Gate Configuration + +| Keywords | Gate | +|----------|------| +| "review each plan", "approve plan", "check before execute" | plan_check: true | +| "review each phase", "approve phase", "check between phases" | phase_check: true | +| "auto", "automated", "no review", "fully automated" | all gates: false | +| default | plan_check: false, phase_check: false | + +### Pipeline Mode + +| Keywords | Mode | +|----------|------| +| "interactive", "step by step", "with approval" | interactive | +| default | auto | + +## Output + +Write coordinator state to memory (not a file). Structure: + +```json +{ + "pipeline_mode": "auto | interactive", + "phase_count": 1, + "depth": "quick | standard | comprehensive", + "gates": { + "plan_check": false, + "phase_check": false + }, + "task_description": "<original task text>", + "notes": ["<any detected constraints or special requirements>"] +} +``` + +This state is passed to `commands/dispatch.md` and written to `config.json` in the session directory. diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md index 53c56800..5f534eac 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md @@ -15,9 +15,9 @@ Handle all coordinator monitoring events for the roadmap-dev pipeline using the | Prefix | Role | Role Spec | inner_loop | |--------|------|-----------|------------| -| PLAN | planner | `.claude/skills/team-roadmap-dev/role-specs/planner.md` | true (cli_tools: gemini --mode analysis) | -| EXEC | executor | `.claude/skills/team-roadmap-dev/role-specs/executor.md` | true (cli_tools: gemini --mode write) | -| VERIFY | verifier | `.claude/skills/team-roadmap-dev/role-specs/verifier.md` | true | +| PLAN | planner | `.claude/skills/team-roadmap-dev/roles/planner/role.md` | true (cli_tools: gemini --mode analysis) | +| EXEC | executor | `.claude/skills/team-roadmap-dev/roles/executor/role.md` | true (cli_tools: gemini --mode write) | +| VERIFY | verifier | `.claude/skills/team-roadmap-dev/roles/verifier/role.md` | true | ### Pipeline Structure @@ -247,7 +247,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-roadmap-dev/role-specs/<role>.md +role_spec: .claude/skills/team-roadmap-dev/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: roadmap-dev diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/role.md b/.claude/skills/team-roadmap-dev/roles/coordinator/role.md index 22f3b665..582e4a43 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/role.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/role.md @@ -98,6 +98,7 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match | Command | File | Phase | Description | |---------|------|-------|-------------| +| `analyze` | [commands/analyze.md](commands/analyze.md) | Phase 1 | Detect depth/phase-count/gate signals from task description | | `roadmap-discuss` | [commands/roadmap-discuss.md](commands/roadmap-discuss.md) | Phase 2 | Discuss roadmap with user, generate session artifacts | | `dispatch` | [commands/dispatch.md](commands/dispatch.md) | Phase 3 | Create task chain per phase | | `monitor` | [commands/monitor.md](commands/monitor.md) | Phase 4 | Stop-Wait phase execution loop | diff --git a/.claude/skills/team-roadmap-dev/roles/executor/role.md b/.claude/skills/team-roadmap-dev/roles/executor/role.md new file mode 100644 index 00000000..6fcd6438 --- /dev/null +++ b/.claude/skills/team-roadmap-dev/roles/executor/role.md @@ -0,0 +1,72 @@ +--- +role: executor +prefix: EXEC +inner_loop: true +cli_tools: + - gemini --mode write +message_types: + success: exec_complete + progress: exec_progress + error: error +--- + +# Executor + +Wave-based code implementation per phase. Reads IMPL-*.json task files, computes execution waves from the dependency graph, delegates each task to CLI tool for code generation. Produces summary-{IMPL-ID}.md per task. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task JSONs | <session>/phase-{N}/.task/IMPL-*.json | Yes | +| Prior summaries | <session>/phase-{1..N-1}/summary-*.md | No | +| Wisdom | <session>/wisdom/ | No | + +1. Glob `<session>/phase-{N}/.task/IMPL-*.json`, error if none found +2. Parse each task JSON: extract id, description, depends_on, files, convergence, implementation +3. Compute execution waves from dependency graph: + - Wave 1: tasks with no dependencies + - Wave N: tasks whose all deps are in waves 1..N-1 + - Force-assign if circular (break at lowest-numbered task) +4. Load prior phase summaries for cross-task context + +## Phase 3: Wave-Based Implementation + +Execute waves sequentially, tasks within each wave can be parallel. + +**Strategy selection**: + +| Task Count | Strategy | +|------------|----------| +| <= 2 | Direct: inline Edit/Write | +| 3-5 | Single CLI tool call for all | +| > 5 | Batch: one CLI tool call per module group | + +**Per task**: +1. Build prompt from task JSON: description, files, implementation steps, convergence criteria +2. Include prior summaries and wisdom as context +3. Delegate to CLI tool (`run_in_background: false`): + ``` + Bash({ + command: `ccw cli -p "PURPOSE: Implement task ${taskId}: ${description} + TASK: ${implementationSteps} + MODE: write + CONTEXT: @${files.join(' @')} | Memory: ${priorSummaries} + EXPECTED: Working code changes matching convergence criteria + CONSTRAINTS: ${convergenceCriteria}" --tool gemini --mode write`, + run_in_background: false + }) + ``` +4. Write `<session>/phase-{N}/summary-{IMPL-ID}.md` with: task ID, affected files, changes made, status + +**Between waves**: report wave progress via team_msg (type: exec_progress) + +## Phase 4: Self-Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Affected files exist | `test -f <path>` for each file in summary | All present | +| TypeScript syntax | `npx tsc --noEmit` (if tsconfig.json exists) | No errors | +| Lint | `npm run lint` (best-effort) | No critical errors | + +Log errors via team_msg but do NOT fix — verifier handles gap detection. diff --git a/.claude/skills/team-roadmap-dev/roles/planner/role.md b/.claude/skills/team-roadmap-dev/roles/planner/role.md new file mode 100644 index 00000000..620631e7 --- /dev/null +++ b/.claude/skills/team-roadmap-dev/roles/planner/role.md @@ -0,0 +1,78 @@ +--- +role: planner +prefix: PLAN +inner_loop: true +cli_tools: + - gemini --mode analysis +message_types: + success: plan_ready + progress: plan_progress + error: error +--- + +# Planner + +Research and plan creation per roadmap phase. Gathers codebase context via CLI exploration, then generates wave-based execution plans with convergence criteria via CLI planning tool. + +## Phase 2: Context Loading + Research + +| Input | Source | Required | +|-------|--------|----------| +| roadmap.md | <session>/roadmap.md | Yes | +| config.json | <session>/config.json | Yes | +| Prior summaries | <session>/phase-{1..N-1}/summary-*.md | No | +| Wisdom | <session>/wisdom/ | No | + +1. Read roadmap.md, extract phase goal, requirements (REQ-IDs), success criteria +2. Read config.json for depth setting (quick/standard/comprehensive) +3. Load prior phase summaries for dependency context +4. Detect gap closure mode (task description contains "Gap closure") +5. Launch CLI exploration with phase requirements as exploration query: + ``` + Bash({ + command: `ccw cli -p "PURPOSE: Explore codebase for phase requirements + TASK: • Identify files needing modification • Map patterns and dependencies • Assess test infrastructure • Identify risks + MODE: analysis + CONTEXT: @**/* | Memory: Phase goal: ${phaseGoal} + EXPECTED: Structured exploration results with file lists, patterns, risks + CONSTRAINTS: Read-only analysis" --tool gemini --mode analysis`, + run_in_background: false + }) + ``` + - Target: files needing modification, patterns, dependencies, test infrastructure, risks +6. If depth=comprehensive: run Gemini CLI analysis (`--mode analysis --rule analysis-analyze-code-patterns`) +7. Write `<session>/phase-{N}/context.md` combining roadmap requirements + exploration results + +## Phase 3: Plan Creation + +1. Load context.md from Phase 2 +2. Create output directory: `<session>/phase-{N}/.task/` +3. Delegate to CLI planning tool with: + ``` + Bash({ + command: `ccw cli -p "PURPOSE: Generate wave-based execution plan for phase ${phaseNum} + TASK: • Break down requirements into tasks • Define convergence criteria • Build dependency graph • Assign waves + MODE: write + CONTEXT: @${contextMd} | Memory: ${priorSummaries} + EXPECTED: IMPL_PLAN.md + IMPL-*.json files + TODO_LIST.md + CONSTRAINTS: <= 10 tasks | Valid DAG | Measurable convergence criteria" --tool gemini --mode write`, + run_in_background: false + }) + ``` +4. CLI tool produces: `IMPL_PLAN.md`, `.task/IMPL-*.json`, `TODO_LIST.md` +5. If gap closure: only create tasks for gaps, starting from next available ID + +## Phase 4: Self-Validation + +| Check | Pass Criteria | Action on Failure | +|-------|---------------|-------------------| +| Task JSON files exist | >= 1 IMPL-*.json found | Error to coordinator | +| Required fields | id, title, description, files, implementation, convergence | Log warning | +| Convergence criteria | Each task has >= 1 criterion | Log warning | +| No self-dependency | task.id not in task.depends_on | Log error, remove cycle | +| All deps valid | Every depends_on ID exists | Log warning | +| IMPL_PLAN.md exists | File present | Generate minimal version from task JSONs | + +After validation, compute wave structure from dependency graph for reporting: +- Wave count = topological layers of DAG +- Report: task count, wave count, file list diff --git a/.claude/skills/team-roadmap-dev/roles/verifier/role.md b/.claude/skills/team-roadmap-dev/roles/verifier/role.md new file mode 100644 index 00000000..dc230414 --- /dev/null +++ b/.claude/skills/team-roadmap-dev/roles/verifier/role.md @@ -0,0 +1,74 @@ +--- +role: verifier +prefix: VERIFY +inner_loop: true +cli_tools: + - gemini --mode analysis +message_types: + success: verify_passed + failure: gaps_found + error: error +--- + +# Verifier + +Goal-backward verification per phase. Reads convergence criteria from IMPL-*.json task files and checks against actual codebase state. Read-only — never modifies code. Produces verification.md with pass/fail and structured gap lists. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task JSONs | <session>/phase-{N}/.task/IMPL-*.json | Yes | +| Summaries | <session>/phase-{N}/summary-*.md | Yes | +| Wisdom | <session>/wisdom/ | No | + +1. Glob IMPL-*.json files, extract convergence criteria from each task +2. Glob summary-*.md files, parse frontmatter (task, affects, provides) +3. If no task JSONs or summaries found → error to coordinator + +## Phase 3: Goal-Backward Verification + +For each task's convergence criteria, execute appropriate check: + +| Criteria Type | Method | +|---------------|--------| +| File existence | `test -f <path>` | +| Command execution | Run command, check exit code | +| Pattern match | Grep for pattern in specified files | +| Semantic check | Optional: Gemini CLI (`--mode analysis --rule analysis-review-code-quality`) | + +**Per task scoring**: + +| Result | Condition | +|--------|-----------| +| pass | All criteria met | +| partial | Some criteria met | +| fail | No criteria met or critical check failed | + +Collect all gaps from partial/failed tasks with structured format: +- task ID, criteria type, expected value, actual value + +## Phase 4: Compile Results + +1. Aggregate per-task results: count passed, partial, failed +2. Determine overall status: + - `passed` if gaps.length === 0 + - `gaps_found` otherwise +3. Write `<session>/phase-{N}/verification.md`: + +```yaml +--- +phase: <N> +status: passed | gaps_found +tasks_checked: <count> +tasks_passed: <count> +gaps: + - task: "<task-id>" + type: "<criteria-type>" + item: "<description>" + expected: "<expected>" + actual: "<actual>" +--- +``` + +4. Update .msg/meta.json with verification summary diff --git a/.claude/skills/team-roadmap-dev/specs/pipelines.md b/.claude/skills/team-roadmap-dev/specs/pipelines.md new file mode 100644 index 00000000..21d602ee --- /dev/null +++ b/.claude/skills/team-roadmap-dev/specs/pipelines.md @@ -0,0 +1,93 @@ +# Pipeline Definitions — Team Roadmap Dev + +## Pipeline Mode + +### Single Phase Pipeline + +``` +PLAN-101 --> EXEC-101 --> VERIFY-101 +[planner] [executor] [verifier] + | + gap found? + YES (< 3x) + | + PLAN-102 --> EXEC-102 --> VERIFY-102 + | + gap found? + YES (>= 3x) -> AskUser: continue/retry/stop + NO -> Complete +``` + +### Multi-Phase Pipeline + +``` +Phase 1: PLAN-101 --> EXEC-101 --> VERIFY-101 + | + [gap closure loop] + | + Phase 1 passed + | +Phase 2: PLAN-201 --> EXEC-201 --> VERIFY-201 + | + [gap closure loop] + | + Phase 2 passed + | +Phase N: PLAN-N01 --> EXEC-N01 --> VERIFY-N01 + | + [gap closure loop] + | + All phases done -> Complete +``` + +## Task Metadata Registry + +| Task ID | Role | Phase | Dependencies | Description | +|---------|------|-------|-------------|-------------| +| PLAN-N01 | planner | phase N | (none or previous VERIFY) | Context research + IMPL-*.json task generation | +| EXEC-N01 | executor | phase N | PLAN-N01 | Wave-based code implementation following IMPL-*.json plans | +| VERIFY-N01 | verifier | phase N | EXEC-N01 | Convergence criteria check + gap detection | +| PLAN-N02 | planner | phase N (gap closure 1) | VERIFY-N01 | Gap-targeted re-plan | +| EXEC-N02 | executor | phase N (gap closure 1) | PLAN-N02 | Gap fix execution | +| VERIFY-N02 | verifier | phase N (gap closure 1) | EXEC-N02 | Re-verify after gap fixes | + +## Task Naming Rules + +| Type | Pattern | Example | +|------|---------|---------| +| Plan | `PLAN-{phase}01` | PLAN-101, PLAN-201 | +| Execute | `EXEC-{phase}01` | EXEC-101, EXEC-201 | +| Verify | `VERIFY-{phase}01` | VERIFY-101 | +| Gap Plan | `PLAN-{phase}{iteration+1}` | PLAN-102 (gap 1), PLAN-103 (gap 2) | +| Gap Execute | `EXEC-{phase}{iteration+1}` | EXEC-102, EXEC-103 | +| Gap Verify | `VERIFY-{phase}{iteration+1}` | VERIFY-102, VERIFY-103 | + +## Checkpoints + +| Checkpoint | Trigger | Behavior | +|------------|---------|----------| +| Plan gate (optional) | PLAN-N01 complete | If `config.gates.plan_check=true`: AskUser to approve/revise/skip | +| Phase transition | VERIFY-N01 complete, no gaps | If `config.mode=interactive`: AskUser to proceed/review/stop | +| Gap closure | VERIFY-N01 complete, gaps found | Auto-create PLAN-N02/EXEC-N02/VERIFY-N02 (max 3 iterations) | +| Gap limit | gap_iteration >= 3 | AskUser: continue anyway / retry once more / stop | +| Pipeline complete | All phases passed | AskUser: archive & clean / keep active / export results | + +## State Machine Coordinates + +```json +{ + "current_phase": 1, + "total_phases": 3, + "gap_iteration": 0, + "step": "plan | exec | verify | gap_closure | transition", + "status": "running | paused | complete" +} +``` + +## Role-Worker Map + +| Prefix | Role | Role Spec | Inner Loop | +|--------|------|-----------|------------| +| PLAN | planner | `.claude/skills/team-roadmap-dev/roles/planner/role.md` | true | +| EXEC | executor | `.claude/skills/team-roadmap-dev/roles/executor/role.md` | true | +| VERIFY | verifier | `.claude/skills/team-roadmap-dev/roles/verifier/role.md` | true | diff --git a/.claude/skills/team-tech-debt/SKILL.md b/.claude/skills/team-tech-debt/SKILL.md index c956ee73..fcf9afc1 100644 --- a/.claude/skills/team-tech-debt/SKILL.md +++ b/.claude/skills/team-tech-debt/SKILL.md @@ -1,287 +1,74 @@ --- name: team-tech-debt -description: Unified team skill for tech debt identification and cleanup. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team tech-debt", "tech debt cleanup", "技术债务". -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +description: Unified team skill for tech debt identification and remediation. Scans codebase for tech debt, assesses severity, plans and executes fixes with validation. Uses team-worker agent architecture with roles/ for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team tech debt". +allowed-tools: Agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, TaskList, TaskGet, TaskUpdate, TaskCreate, TeamCreate, TeamDelete, SendMessage, mcp__ace-tool__search_context, mcp__ccw-tools__read_file, mcp__ccw-tools__write_file, mcp__ccw-tools__edit_file, mcp__ccw-tools__team_msg --- # Team Tech Debt -技术债务识别与清理团队。融合"债务扫描"、"量化评估"、"治理规划"、"清理执行"、"验证回归"五大能力域,形成"扫描->评估->规划->清理->验证"闭环。通过 Scanner 多维度扫描、Executor-Validator 修复验证循环、共享债务清单数据库,实现渐进式技术债务治理。所有成员通过 `--role=xxx` 路由到角色执行逻辑。 +Systematic tech debt governance: scan -> assess -> plan -> fix -> validate. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from `roles/<role>/role.md`. -## Architecture Overview +## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-tech-debt") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-tech-debt", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-----+-----+-----+-----+-----+ - v v v v v - [tw] [tw] [tw] [tw] [tw] -scann- asses- plan- execu- valid- -er sor ner tor ator - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+-------+ + v v v v v + [team-worker agents, each loads roles/<role>/role.md] + scanner assessor planner executor validator ``` -## Command Architecture +## Role Registry -``` -roles/ -├── coordinator/ -│ ├── role.md # Pipeline 编排(模式选择、任务分发、监控) -│ └── commands/ -│ ├── dispatch.md # 任务链创建 -│ └── monitor.md # 进度监控 -├── scanner/ -│ ├── role.md # 多维度技术债务扫描 -│ └── commands/ -│ └── scan-debt.md # 多维度 CLI Fan-out 扫描 -├── assessor/ -│ ├── role.md # 量化评估与优先级排序 -│ └── commands/ -│ └── evaluate.md # 影响/成本矩阵评估 -├── planner/ -│ ├── role.md # 治理方案规划 -│ └── commands/ -│ └── create-plan.md # 分阶段治理方案生成 -├── executor/ -│ ├── role.md # 债务清理执行 -│ └── commands/ -│ └── remediate.md # 重构/清理/更新执行 -└── validator/ - ├── role.md # 清理结果验证 - └── commands/ - └── verify.md # 回归测试与质量验证 -``` - -**设计原则**: role.md 保留 Phase 1(Task Discovery)和 Phase 5(Report)内联。Phase 2-4 根据复杂度决定内联或委派到 `commands/*.md`。 +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| scanner | [roles/scanner/role.md](roles/scanner/role.md) | TDSCAN-* | false | +| assessor | [roles/assessor/role.md](roles/assessor/role.md) | TDEVAL-* | false | +| planner | [roles/planner/role.md](roles/planner/role.md) | TDPLAN-* | false | +| executor | [roles/executor/role.md](roles/executor/role.md) | TDFIX-* | true | +| validator | [roles/validator/role.md](roles/validator/role.md) | TDVAL-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role` and optional `--agent-name`, `--mode` (scan/remediate/targeted). +## Shared Constants -If no `--role` -> Orchestration Mode (auto route to coordinator). +- **Session prefix**: `TD` +- **Session path**: `.workflow/.team/TD-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` +- **Max GC rounds**: 3 -### Role Registry +## Worker Spawn Template -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| scanner | [role-specs/scanner.md](role-specs/scanner.md) | TDSCAN-* | false | -| assessor | [role-specs/assessor.md](role-specs/assessor.md) | TDEVAL-* | false | -| planner | [role-specs/planner.md](role-specs/planner.md) | TDPLAN-* | false | -| executor | [role-specs/executor.md](role-specs/executor.md) | TDFIX-* | true | -| validator | [role-specs/validator.md](role-specs/validator.md) | TDVAL-* | false | - -> **COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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 -4. Unknown role -> Error with available role list: coordinator, scanner, assessor, planner, executor, validator - -### Orchestration Mode - -当不带 `--role` 调用时,自动进入 coordinator 编排模式。 - -**触发方式**: - -- 用户调用(无 --role): `Skill(skill="team-tech-debt", args="扫描并清理项目中的技术债务")` -- 等价于: `Skill(skill="team-tech-debt", args="--role=coordinator 扫描并清理项目中的技术债务")` - -**完整调用链**: - -``` -用户: Skill(args="任务描述") - │ - ├─ SKILL.md: 无 --role -> Orchestration Mode -> 读取 coordinator role.md - │ - ├─ coordinator Phase 2: TeamCreate + 模式选择 - │ 按 pipeline 阶段逐个 spawn worker(同步阻塞) - │ - ├─ coordinator Phase 3: dispatch 任务链 - │ - ├─ worker 收到任务 -> Skill(args="--role=xxx") -> SKILL.md Role Router -> role.md - │ 每个 worker 自动获取: - │ ├─ 角色定义 (role.md: identity, boundaries, message types) - │ ├─ 可用命令 (commands/*.md) - │ └─ 执行逻辑 (5-phase process) - │ - └─ coordinator Phase 4-5: 监控 -> 结果汇报 -``` - -**User Commands** (唤醒已暂停的 coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | 输出执行状态图,不推进 | -| `resume` / `continue` | 检查 worker 状态,推进下一步 | - ---- - -## Shared Infrastructure - -> 以下为编排级概览。具体实现代码(Message Bus、Task Lifecycle、工具方法)在各 role.md 中自包含。 - -### Team Configuration - -| Key | Value | -|-----|-------| -| name | tech-debt | -| sessionDir | `.workflow/.team/TD-{slug}-{date}/` | -| sharedMemory | team_msg(type="state_update") + .msg/meta.json | -| worktree.basePath | `.worktrees` | -| worktree.branchPrefix | `tech-debt/TD-` | -| worktree.autoCleanup | true (remove worktree after PR creation) | -| debtDimensions | code, architecture, testing, dependency, documentation | -| priorityMatrix.highImpact_lowCost | 立即修复 (Quick Win) | -| priorityMatrix.highImpact_highCost | 战略规划 (Strategic) | -| priorityMatrix.lowImpact_lowCost | 待办处理 (Backlog) | -| priorityMatrix.lowImpact_highCost | 暂缓接受 (Defer) | - -### Role Isolation Rules - -**核心原则**: 每个角色仅能执行自己职责范围内的工作。 - -#### Output Tagging(强制) - -所有角色的输出必须带 `[role_name]` 标识前缀。 - -#### Coordinator 隔离 - -| 允许 | 禁止 | -|------|------| -| 需求澄清 (AskUserQuestion) | 直接扫描代码 | -| 创建任务链 (TaskCreate) | 直接执行重构或清理 | -| 模式选择 + 质量门控 | 直接评估或规划 | -| 监控进度 (消息总线) | 绕过 worker 自行完成 | - -#### Worker 隔离 - -| 允许 | 禁止 | -|------|------| -| 处理自己前缀的任务 | 处理其他角色前缀的任务 | -| Share state via team_msg(type='state_update') | 为其他角色创建任务 | -| SendMessage 给 coordinator | 直接与其他 worker 通信 | - -### 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", session_id=<session-id>, from=`<role>`, type=`<消息类型>`, data={ref: "`<产物路径>`"} - - `to` 和 `summary` 自动生成 -- 无需显式指定 - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: 发送结果给 coordinator -3. **TaskUpdate**: 标记任务 completed -4. **Loop**: 回到 Phase 1 检查下一个任务 - ---- - -## Three-Mode Pipeline Architecture - -``` -Scan Mode (仅扫描评估): - TDSCAN-001(并行多维度扫描+多视角Gemini分析) -> TDEVAL-001(量化评估) -> 报告 - -Remediate Mode (完整闭环): - TDSCAN-001(并行扫描) -> TDEVAL-001(评估) -> TDPLAN-001(规划) -> [Plan Approval] -> [Create Worktree] -> TDFIX-001(修复,worktree) -> TDVAL-001(验证,worktree) -> [Commit+PR] -> 报告 - -Targeted Mode (定向修复): - TDPLAN-001(规划) -> [Plan Approval] -> [Create Worktree] -> TDFIX-001(修复,worktree) -> TDVAL-001(验证,worktree) -> [Commit+PR] -> 报告 -``` - -### TDSCAN Parallel Fan-out Architecture - -``` -TDSCAN-001 内部并行架构: - - ┌────────────────────────────────────────────────────┐ - │ Scanner Worker │ - │ │ - │ Fan-out A: CLI Exploration (parallel CLI explore) │ - │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ - │ │structure │ │patterns │ │deps │ │ - │ │角度 │ │角度 │ │角度 │ │ - │ └─────┬────┘ └─────┬────┘ └─────┬────┘ │ - │ └────────────┼────────────┘ │ - │ ↓ merge │ - │ Fan-out B: CLI Dimension Analysis (并行 gemini) │ - │ ┌──────┐┌────────┐┌───────┐┌──────┐┌─────┐ │ - │ │code ││arch ││testing││deps ││docs │ │ - │ └──┬───┘└───┬────┘└──┬────┘└──┬───┘└──┬──┘ │ - │ └────────┼────────┼────────┘ │ │ - │ ↓ merge │ │ - │ Fan-out C: Multi-Perspective Gemini (并行) │ - │ ┌────────┐┌──────────┐┌───────┐┌─────────┐ │ - │ │security││perform. ││quality││architect│ │ - │ └───┬────┘└────┬─────┘└──┬────┘└────┬────┘ │ - │ └──────────┼─────────┘ │ │ - │ ↓ Fan-in aggregate │ - │ debt-inventory.json │ - └────────────────────────────────────────────────────┘ -``` - -### Mode Auto-Detection - -| Condition | Detected Mode | -|-----------|--------------| -| `--mode=scan` explicitly specified | scan | -| `--mode=remediate` explicitly specified | remediate | -| `--mode=targeted` explicitly specified | targeted | -| Task description contains: 扫描, scan, 审计, audit, 评估, assess | scan | -| Task description contains: 定向, targeted, 指定, specific, 修复已知 | targeted | -| Default (no match) | remediate | - -### Fix-Verify Loop - -``` -TDFIX -> TDVAL -> (if regression or quality drop) -> TDFIX-fix -> TDVAL-2 - (if all pass) -> report -``` - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -> **Note**: This skill uses Stop-Wait coordination (`run_in_background: false`). Each role completes before next spawns. This is intentionally different from the default `run_in_background: true` (Spawn-and-Stop). The Stop-Wait strategy ensures sequential pipeline execution where each phase's output is fully available before the next phase begins -- critical for the scan->assess->plan->execute->validate dependency chain. - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role> worker", + description: "Spawn <role> worker for <task-id>", + team_name: "tech-debt", + name: "<role>", + run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-tech-debt/role-specs/<role>.md +role_spec: .claude/skills/team-tech-debt/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: tech-debt @@ -289,211 +76,47 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`, - run_in_background: false // Stop-Wait: synchronous blocking, wait for worker completion +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (executor): Set `inner_loop: true`. +## User Commands -**Single-task roles** (scanner, assessor, planner, validator): Set `inner_loop: false`. +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | +| `--mode=scan` | Run scan-only pipeline (TDSCAN + TDEVAL) | +| `--mode=targeted` | Run targeted pipeline (TDPLAN + TDFIX + TDVAL) | +| `--mode=remediate` | Run full pipeline (default) | +| `-y` / `--yes` | Skip confirmations | -**Role-specific spawn parameters**: +## Specs Reference -| Role | Prefix | inner_loop | -|------|--------|------------| -| scanner | TDSCAN-* | false | -| assessor | TDEVAL-* | false | -| planner | TDPLAN-* | false | -| executor | TDFIX-* | true | -| validator | TDVAL-* | false | +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): +## Session Directory ``` -AskUserQuestion({ - questions: [{ - question: "Tech Debt pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-tech-debt", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- - -## Cadence Control - -**节拍模型**: Sequential 5-beat -- 扫描->评估->规划->执行->验证,严格串行(Stop-Wait 策略)。 - -``` -Sequential 5-Beat Cycle (Remediate Mode) -=================================================================== - Beat Coordinator Worker -------------------------------------------------------------------- - Beat 1: SCAN ┌─ spawn scanner ──────┐ - │ run_in_background: │ - │ false (阻塞等待) ────┼──> [Scanner] Phase 1-5 - │ scanner 返回 ────────┤ │ - └─ 收到结果 ───────────┘ <──────┘ - │ - Beat 2: ASSESS ┌─ spawn assessor ─────┐ - │ 阻塞等待 ────────────┼──> [Assessor] Phase 1-5 - └─ 收到结果 ───────────┘ <──────┘ - │ - Beat 3: PLAN ┌─ spawn planner ──────┐ - │ 阻塞等待 ────────────┼──> [Planner] Phase 1-5 - └─ 收到结果 ───────────┘ <──────┘ - │ - ⏸ CHECKPOINT ── Plan Approval (用户确认) - │ - Beat 4: FIX ┌─ Create Worktree ────┐ - │ spawn executor ──────┼──> [Executor] Phase 1-5 - │ 阻塞等待 ────────────┤ │ - └─ 收到结果 ───────────┘ <──────┘ - │ - Beat 5: VALIDATE┌─ spawn validator ────┐ - │ 阻塞等待 ────────────┼──> [Validator] Phase 1-5 - └─ 收到结果 ───────────┘ <──────┘ - │ - ┌─ Commit + PR ────────┐ - └─ Final Report ───────┘ -=================================================================== -``` - -**Pipeline 节拍视图 (按模式)**: - -``` -Scan Mode (2 beats) -────────────────────────────────────────────────────────── -Beat 1 2 - │ │ - TDSCAN -> TDEVAL -> 报告 - -Remediate Mode (5 beats, 严格串行 + 检查点) -────────────────────────────────────────────────────────── -Beat 1 2 3 ⏸ 4 5 - │ │ │ │ │ │ - SCAN -> EVAL -> PLAN -> [OK?] -> FIX -> VAL -> Report - ▲ - Plan Approval - -Targeted Mode (3 beats, 跳过扫描评估) -────────────────────────────────────────────────────────── -Beat 1 ⏸ 2 3 - │ │ │ │ - PLAN -> [OK?] -> FIX -> VAL -> Report -``` - -**检查点 (Checkpoint)**: - -| 触发条件 | 位置 | 行为 | -|----------|------|------| -| Plan Approval | TDPLAN 完成后 | 暂停,等待用户确认治理方案 | -| Fix-Verify Loop 上限 | TDVAL max 3 iterations | 超出轮次 -> 停止迭代,escalate to user | -| Pipeline 停滞 | Worker 无响应 | 报告等待中的任务列表 | - -**Stall 检测** (coordinator monitor 时执行): - -| 检查项 | 条件 | 处理 | -|--------|------|------| -| Worker 无响应 | in_progress 任务长时间无返回 | Stop-Wait 下不适用(同步阻塞) | -| Fix-Verify 循环超限 | TDFIX/TDVAL 迭代 > 3 rounds | 终止循环,输出最新验证报告 | -| Scanner 无债务 | debt-inventory 为空 | 报告 clean codebase,跳过后续阶段 | - ---- - -## Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| TDSCAN-001 | scanner | scan | (none) | 多维度技术债务扫描(并行 Fan-out) | -| TDEVAL-001 | assessor | assess | TDSCAN-001 | 量化评估与优先级排序 | -| TDPLAN-001 | planner | plan | TDEVAL-001 (or none in targeted) | 分阶段治理方案规划 | -| TDFIX-001 | executor | fix | TDPLAN-001 + Plan Approval | 债务清理执行(worktree) | -| TDVAL-001 | validator | validate | TDFIX-001 | 回归测试与质量验证 | -| TDFIX-002 | executor | fix (loop) | TDVAL-001 (if regression) | Fix-Verify 循环修复 | -| TDVAL-002 | validator | validate (loop) | TDFIX-002 | Fix-Verify 循环验证 | - ---- - -## 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 文件。 - ---- - -## Unified Session Directory - -``` -.workflow/.team/TD-{slug}-{YYYY-MM-DD}/ +.workflow/.team/TD-<slug>-<date>/ ├── .msg/ -│ ├── messages.jsonl # Team message bus log -│ └── meta.json # Session metadata + shared state -├── scan/ # Scanner output -│ └── debt-inventory.json -├── assessment/ # Assessor output -│ └── priority-matrix.json -├── plan/ # Planner output -│ └── remediation-plan.md -├── fixes/ # Executor output -│ └── fix-log.json -├── validation/ # Validator output -│ └── validation-report.json -└── wisdom/ # Cross-task knowledge - ├── learnings.md - ├── decisions.md - ├── conventions.md - └── issues.md - -# .msg/meta.json worktree 字段(TDFIX 前由 coordinator 写入): -# { -# ... -# "worktree": { -# "path": ".worktrees/TD-{slug}-{date}", -# "branch": "tech-debt/TD-{slug}-{date}" -# } -# } +│ ├── messages.jsonl # Team message bus +│ └── meta.json # Pipeline config + role state snapshot +├── scan/ # Scanner output +├── assessment/ # Assessor output +├── plan/ # Planner output +├── fixes/ # Executor output +├── validation/ # Validator output +└── wisdom/ # Cross-task knowledge ``` ---- - ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list: coordinator, scanner, assessor, planner, executor, validator | -| Missing --role arg | Orchestration Mode -> auto route to coordinator | -| Role file not found | Error with expected path (roles/{name}/role.md) | -| Command file not found | Fall back to inline execution in role.md | -| Task prefix conflict | Log warning, proceed | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| Session corruption | Attempt recovery, fallback to manual | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | | Scanner finds no debt | Report clean codebase, skip to summary | -| Fix introduces regression | Trigger Fix-Verify loop (max 3 iterations) | -| Validation repeatedly fails | Escalate to user with diagnosis | diff --git a/.claude/skills/team-tech-debt/roles/assessor/role.md b/.claude/skills/team-tech-debt/roles/assessor/role.md new file mode 100644 index 00000000..53364c79 --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/assessor/role.md @@ -0,0 +1,69 @@ +--- +role: assessor +prefix: TDEVAL +inner_loop: false +message_types: [state_update] +--- + +# Tech Debt Assessor + +Quantitative evaluator for tech debt items. Score each debt item on business impact (1-5) and fix cost (1-5), classify into priority quadrants, produce priority-matrix.json. + +## Phase 2: Load Debt Inventory + +| Input | Source | Required | +|-------|--------|----------| +| Session path | task description (regex: `session:\s*(.+)`) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Debt inventory | meta.json:debt_inventory OR <session>/scan/debt-inventory.json | Yes | + +1. Extract session path from task description +2. Read .msg/meta.json for team context +3. Load debt_inventory from shared memory or fallback to debt-inventory.json file +4. If debt_inventory is empty -> report empty assessment and exit + +## Phase 3: Evaluate Each Item + +**Strategy selection**: + +| Item Count | Strategy | +|------------|----------| +| <= 10 | Heuristic: severity-based impact + effort-based cost | +| 11-50 | CLI batch: single gemini analysis call | +| > 50 | CLI chunked: batches of 25 items | + +**Impact Score Mapping** (heuristic): + +| Severity | Impact Score | +|----------|-------------| +| critical | 5 | +| high | 4 | +| medium | 3 | +| low | 1 | + +**Cost Score Mapping** (heuristic): + +| Estimated Effort | Cost Score | +|------------------|------------| +| small | 1 | +| medium | 3 | +| large | 5 | +| unknown | 3 | + +**Priority Quadrant Classification**: + +| Impact | Cost | Quadrant | +|--------|------|----------| +| >= 4 | <= 2 | quick-win | +| >= 4 | >= 3 | strategic | +| <= 3 | <= 2 | backlog | +| <= 3 | >= 3 | defer | + +For CLI mode, prompt gemini with full debt summary requesting JSON array of `{id, impact_score, cost_score, risk_if_unfixed, priority_quadrant}`. Unevaluated items fall back to heuristic scoring. + +## Phase 4: Generate Priority Matrix + +1. Build matrix structure: evaluation_date, total_items, by_quadrant (grouped), summary (counts per quadrant) +2. Sort within each quadrant by impact_score descending +3. Write `<session>/assessment/priority-matrix.json` +4. Update .msg/meta.json with `priority_matrix` summary and evaluated `debt_inventory` diff --git a/.claude/skills/team-tech-debt/roles/coordinator/commands/analyze.md b/.claude/skills/team-tech-debt/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..c89a8cea --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/coordinator/commands/analyze.md @@ -0,0 +1,47 @@ +# Analyze Task + +Parse user task -> detect tech debt signals -> assess complexity -> determine pipeline mode and roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Signal | Mode Hint | +|----------|--------|-----------| +| 扫描, scan, 审计, audit | debt-scan | scan | +| 评估, assess, quantify | debt-assess | scan | +| 规划, plan, roadmap | debt-plan | targeted | +| 修复, fix, remediate, clean | debt-fix | remediate | +| 验证, validate, verify | debt-validate | remediate | +| 定向, targeted, specific | debt-targeted | targeted | + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Full codebase scope | +2 | +| Multiple debt dimensions | +1 per dimension (max 3) | +| Large codebase (implied) | +1 | +| Targeted specific items | -1 | + +Results: 1-3 Low (scan mode), 4-6 Medium (remediate), 7+ High (remediate + full pipeline) + +## Pipeline Mode Determination + +| Score + Signals | Mode | +|----------------|------| +| scan/audit keywords | scan | +| targeted/specific keywords | targeted | +| Default | remediate | + +## Output + +Write scope context to coordinator memory: +```json +{ + "pipeline_mode": "<scan|remediate|targeted>", + "scope": "<detected-scope>", + "focus_dimensions": ["code", "architecture", "testing", "dependency", "documentation"], + "complexity": { "score": 0, "level": "Low|Medium|High" } +} +``` diff --git a/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md b/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md index d95b52da..bd064881 100644 --- a/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md @@ -1,163 +1,118 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, fix-verify loops, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. ## Constants -| Key | Value | -|-----|-------| -| SPAWN_MODE | background | -| ONE_STEP_PER_INVOCATION | true | -| WORKER_AGENT | team-worker | -| MAX_GC_ROUNDS | 3 | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 3 -## Phase 2: Context Loading +## Handler Router -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Meta state | <session>/.msg/meta.json | Yes | -| Pipeline definition | From SKILL.md | Yes | +| Source | Handler | +|--------|---------| +| Message contains [scanner], [assessor], [planner], [executor], [validator] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -1. Load session.json for current state, `pipeline_mode`, `gc_rounds` -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## handleCallback -### Role Detection Table +Worker completed. Process and advance. -| Message Pattern | Role Detection | -|----------------|---------------| -| `[scanner]` or task ID `TDSCAN-*` | scanner | -| `[assessor]` or task ID `TDEVAL-*` | assessor | -| `[planner]` or task ID `TDPLAN-*` | planner | -| `[executor]` or task ID `TDFIX-*` | executor | -| `[validator]` or task ID `TDVAL-*` | validator | +1. Find matching worker by role tag in message +2. Check if progress update (inner loop) or final completion +3. Progress update -> update session state, STOP +4. Completion -> mark task done: + ``` + TaskUpdate({ taskId: "<task-id>", status: "completed" }) + ``` +5. Remove from active_workers, record completion in session -### Pipeline Stage Order +6. Check for checkpoints: + - **TDPLAN-001 completes** -> Plan Approval Gate: + ``` + AskUserQuestion({ + questions: [{ question: "Remediation plan generated. Review and decide:", + header: "Plan Review", multiSelect: false, + options: [ + { label: "Approve", description: "Proceed with fix execution" }, + { label: "Revise", description: "Re-run planner with feedback" }, + { label: "Abort", description: "Stop pipeline" } + ] + }] + }) + ``` + - Approve -> Worktree Creation -> handleSpawnNext + - Revise -> Create TDPLAN-revised task -> handleSpawnNext + - Abort -> Log shutdown -> handleComplete + + - **Worktree Creation** (before TDFIX): + ``` + Bash("git worktree add .worktrees/TD-<slug>-<date> -b tech-debt/TD-<slug>-<date>") + ``` + Update .msg/meta.json with worktree info. + + - **TDVAL-* completes** -> GC Loop Check: + Read validation results from .msg/meta.json + + | Condition | Action | + |-----------|--------| + | No regressions | -> handleSpawnNext (pipeline complete) | + | Regressions AND gc_rounds < 3 | Create fix-verify tasks, increment gc_rounds | + | Regressions AND gc_rounds >= 3 | Accept current state -> handleComplete | + + Fix-Verify Task Creation: + ``` + TaskCreate({ subject: "TDFIX-fix-<round>", description: "PURPOSE: Fix regressions | Session: <session>" }) + TaskCreate({ subject: "TDVAL-recheck-<round>", description: "...", blockedBy: ["TDFIX-fix-<round>"] }) + ``` + +7. -> handleSpawnNext + +## handleCheck + +Read-only status report, then STOP. ``` -TDSCAN -> TDEVAL -> TDPLAN -> TDFIX -> TDVAL +Pipeline Status (<mode>): + [DONE] TDSCAN-001 (scanner) -> scan complete + [DONE] TDEVAL-001 (assessor) -> assessment ready + [RUN] TDPLAN-001 (planner) -> planning... + [WAIT] TDFIX-001 (executor) -> blocked by TDPLAN-001 + [WAIT] TDVAL-001 (validator) -> blocked by TDFIX-001 + +GC Rounds: 0/3 +Session: <session-id> +Commands: 'resume' to advance | 'check' to refresh ``` -## Phase 3: Event Handlers +Output status -- do NOT advance pipeline. -### handleCallback +## handleResume -Triggered when a worker sends completion message. +1. Audit task list: + - Tasks stuck in "in_progress" -> reset to "pending" + - Tasks with completed blockers but still "pending" -> include in spawn list +2. -> handleSpawnNext -1. Parse message to identify role and task ID using Role Detection Table +## handleSpawnNext -2. Mark task as completed: +Find ready tasks, spawn workers, STOP. -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` - -3. Record completion in session state - -4. **Plan Approval Gate** (when planner TDPLAN completes): - -Before advancing to TDFIX, present the remediation plan to the user for approval. - -``` -// Read the generated plan -planContent = Read(<session>/plan/remediation-plan.md) - || Read(<session>/plan/remediation-plan.json) - -AskUserQuestion({ - questions: [{ - question: "Remediation plan generated. Review and decide:", - header: "Plan Review", - multiSelect: false, - options: [ - { label: "Approve", description: "Proceed with fix execution" }, - { label: "Revise", description: "Re-run planner with feedback" }, - { label: "Abort", description: "Stop pipeline, no fixes applied" } - ] - }] -}) -``` - -| Decision | Action | -|----------|--------| -| Approve | Proceed to handleSpawnNext (TDFIX becomes ready) | -| Revise | Create TDPLAN-revised task, proceed to handleSpawnNext | -| Abort | Log shutdown, transition to handleComplete | - -5. **GC Loop Check** (when validator TDVAL completes): - -Read `<session>/.msg/meta.json` for validation results. - -| Condition | Action | -|-----------|--------| -| No regressions found | Proceed to handleSpawnNext (pipeline complete) | -| Regressions found AND gc_rounds < 3 | Create fix-verify tasks, increment gc_rounds | -| Regressions found AND gc_rounds >= 3 | Accept current state, proceed to handleComplete | - -**Fix-Verify Task Creation** (when regressions detected): - -``` -TaskCreate({ - subject: "TDFIX-fix-<round>", - description: "PURPOSE: Fix regressions found by validator | Success: All regressions resolved -TASK: - - Load validation report with regression details - - Apply targeted fixes for each regression - - Re-validate fixes locally before completion -CONTEXT: - - Session: <session-folder> - - Upstream artifacts: <session>/.msg/meta.json -EXPECTED: Fixed source files | Regressions resolved -CONSTRAINTS: Targeted fixes only | Do not introduce new regressions", - blockedBy: [], - status: "pending" -}) - -TaskCreate({ - subject: "TDVAL-recheck-<round>", - description: "PURPOSE: Re-validate after regression fixes | Success: Zero regressions -TASK: - - Run full validation suite on fixed code - - Compare debt scores before and after - - Report regression status -CONTEXT: - - Session: <session-folder> -EXPECTED: Validation results with regression count -CONSTRAINTS: Read-only validation", - blockedBy: ["TDFIX-fix-<round>"], - status: "pending" -}) -``` - -6. Proceed to handleSpawnNext - -### handleSpawnNext - -Find and spawn the next ready tasks. - -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" - -2. If no ready tasks and all tasks completed, proceed to handleComplete - -3. If no ready tasks but some still in_progress, STOP and wait - -4. For each ready task, determine role from task subject prefix: - -```javascript -const STAGE_WORKER_MAP = { - 'TDSCAN': { role: 'scanner' }, - 'TDEVAL': { role: 'assessor' }, - 'TDPLAN': { role: 'planner' }, - 'TDFIX': { role: 'executor' }, - 'TDVAL': { role: 'validator' } -} -``` - -5. Spawn team-worker (one at a time for sequential pipeline): +1. Collect: completedSubjects, inProgressSubjects, readySubjects (pending + all blockedBy completed) +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Check inner loop role with active worker -> skip (worker picks up) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker: ``` Agent({ @@ -168,67 +123,54 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-tech-debt/role-specs/<role>.md +role_spec: .claude/skills/team-tech-debt/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: tech-debt requirement: <task-description> -inner_loop: false - -## Current Task -- Task ID: <task-id> -- Task: <task-subject> +inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -6. STOP after spawning -- wait for next callback +Stage-to-role mapping: +| Task Prefix | Role | +|-------------|------| +| TDSCAN | scanner | +| TDEVAL | assessor | +| TDPLAN | planner | +| TDFIX | executor | +| TDVAL | validator | -### handleCheck +5. Add to active_workers, update session, output summary, STOP -Output current pipeline status. +## handleComplete -``` -Pipeline Status: - [DONE] TDSCAN-001 (scanner) -> scan complete - [DONE] TDEVAL-001 (assessor) -> assessment ready - [DONE] TDPLAN-001 (planner) -> plan approved - [RUN] TDFIX-001 (executor) -> fixing... - [WAIT] TDVAL-001 (validator) -> blocked by TDFIX-001 +Pipeline done. Generate report and completion action. -GC Rounds: 0/3 -Session: <session-id> -``` - -Output status -- do NOT advance pipeline. - -### handleResume - -Resume pipeline after user pause or interruption. - -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext - -### handleComplete - -Triggered when all pipeline tasks are completed. - -1. Verify all tasks (including any fix-verify tasks) have status "completed" -2. If any tasks not completed, return to handleSpawnNext +1. Verify all tasks (including fix-verify tasks) have status "completed" +2. If any not completed -> handleSpawnNext 3. If all completed: - - Read final state from `<session>/.msg/meta.json` + - Read final state from .msg/meta.json + - If worktree exists and validation passed: commit, push, gh pr create, cleanup worktree - Compile summary: total tasks, completed, gc_rounds, debt_score_before, debt_score_after - - If worktree exists and validation passed: commit changes, create PR, cleanup worktree - Transition to coordinator Phase 5 -## Phase 4: State Persistence +## handleAdapt -After every handler execution: +Capability gap reported mid-pipeline. -1. Update session.json with current state (active tasks, gc_rounds, last event) -2. Verify task list consistency -3. STOP and wait for next event +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause + +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-tech-debt/roles/coordinator/role.md b/.claude/skills/team-tech-debt/roles/coordinator/role.md index 33b8f53c..2023d552 100644 --- a/.claude/skills/team-tech-debt/roles/coordinator/role.md +++ b/.claude/skills/team-tech-debt/roles/coordinator/role.md @@ -3,8 +3,7 @@ 技术债务治理团队协调者。编排 pipeline:需求澄清 -> 模式选择(scan/remediate/targeted) -> 团队创建 -> 任务分发 -> 监控协调 -> Fix-Verify 循环 -> 债务消减报告。 ## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` +- **Name**: coordinator | **Tag**: [coordinator] - **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries @@ -25,245 +24,65 @@ - Skip dependency validation when creating task chains - Omit `[coordinator]` identifier in any output -> **Core principle**: coordinator is the orchestrator, not the executor. All actual work must be delegated to worker roles via TaskCreate. - ---- - ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): +When coordinator needs to execute a command (analyze, dispatch, monitor): -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [scanner], [assessor], [planner], [executor], [validator] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) | +| Worker callback | Message contains [scanner], [assessor], [planner], [executor], [validator] | -> handleCallback (monitor.md) | +| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) | +| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session exists in .workflow/.team/TD-* | -> Phase 0 | | New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/TD-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- - -## Toolbox - -### Available Commands - -| Command | File | Phase | Description | -|---------|------|-------|-------------| -| `dispatch` | [commands/dispatch.md](commands/dispatch.md) | Phase 3 | 任务链创建与依赖管理 | -| `monitor` | [commands/monitor.md](commands/monitor.md) | Phase 4 | 消息总线轮询与协调循环 | - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `TeamCreate` | Tool | Phase 2 | Team initialization | -| `TaskCreate` | Tool | Phase 3 | Task chain creation | -| `Task` | Tool | Phase 4 | Worker spawning | -| `AskUserQuestion` | Tool | Phase 1 | Requirement clarification | - -> Coordinator does not directly use CLI analysis tools or CLI code generation - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `mode_selected` | coordinator -> all | 模式确定 | scan/remediate/targeted | -| `plan_approval` | coordinator -> user | TDPLAN 完成 | 呈现治理方案供审批 | -| `worktree_created` | coordinator -> user | TDFIX 前 | Worktree 和分支已创建 | -| `pr_created` | coordinator -> user | TDVAL 通过 | PR 已创建,worktree 已清理 | -| `quality_gate` | coordinator -> user | 质量评估 | 通过/不通过/有条件通过 | -| `task_unblocked` | coordinator -> worker | 依赖解除 | 任务可执行 | -| `error` | coordinator -> user | 协调错误 | 阻塞性问题 | -| `shutdown` | coordinator -> all | 团队关闭 | 清理资源 | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: <session-id>, - from: "coordinator", - type: <message-type>, - ref: <artifact-path> -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --session-id <session-id> --from coordinator --type <message-type> --json") -``` - ---- +For callback/check/resume/complete: load `commands/monitor.md`, execute matched handler, STOP. ## Phase 0: Session Resume Check -**Objective**: Detect and resume interrupted sessions before creating new ones. - -**Workflow**: - -1. Scan session directory 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 state <-> 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 - ---- +1. Scan `.workflow/.team/TD-*/.msg/meta.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -**Objective**: Parse user input and gather execution parameters. +TEXT-LEVEL ONLY. No source code reading. -**Workflow**: +1. Parse arguments for explicit settings: mode, scope, focus areas +2. Detect mode: -1. **Parse arguments** for explicit settings: mode, scope, focus areas +| Condition | Mode | +|-----------|------| +| `--mode=scan` or keywords: 扫描, scan, 审计, audit, 评估, assess | scan | +| `--mode=targeted` or keywords: 定向, targeted, 指定, specific, 修复已知 | targeted | +| `-y` or `--yes` specified | Skip confirmations | +| Default | remediate | -2. **Mode Detection**: - -| Detection | Condition | Mode | -|-----------|-----------|------| -| Explicit | `--mode=scan` specified | scan | -| Explicit | `--mode=remediate` specified | remediate | -| Explicit | `--mode=targeted` specified | targeted | -| Keyword | Contains: 扫描, scan, 审计, audit, 评估, assess | scan | -| Keyword | Contains: 定向, targeted, 指定, specific, 修复已知 | targeted | -| Default | No match | remediate | - -3. **Auto mode detection**: - -| Flag | Behavior | -|------|----------| -| `-y` or `--yes` | Skip confirmations | - -4. **Ask for missing parameters** via AskUserQuestion (skip if auto mode): - -| Question | Options | -|----------|---------| -| Tech Debt Target | 自定义 / 全项目扫描 / 完整治理 / 定向修复 | - -5. **Store requirements**: mode, scope, focus, constraints - -**Success**: All parameters captured, mode finalized. - ---- +3. Ask for missing parameters (skip if auto mode): + - AskUserQuestion: Tech Debt Target (自定义 / 全项目扫描 / 完整治理 / 定向修复) +4. Store: mode, scope, focus, constraints +5. Delegate to commands/analyze.md -> output task-analysis context ## Phase 2: Create Team + Initialize Session -**Objective**: Initialize team, session file, and wisdom directory. - -**Workflow**: - -1. Generate session ID: `TD-{slug}-{YYYY-MM-DD}` -2. Create session folder structure: - -``` -<session-folder>/ -├── scan/ -├── assessment/ -├── plan/ -├── fixes/ -├── validation/ -└── wisdom/ - ├── learnings.md - ├── decisions.md - ├── conventions.md - └── issues.md -``` - -3. Initialize .msg/meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<scan|remediate|targeted>", - pipeline_stages: ["scanner", "assessor", "planner", "executor", "validator"], - roles: ["coordinator", "scanner", "assessor", "planner", "executor", "validator"], - team_name: "tech-debt", - debt_inventory: [], - priority_matrix: {}, - remediation_plan: {}, - fix_results: {}, - validation_results: {}, - debt_score_before: null, - debt_score_after: null - } -}) -``` - -4. Call TeamCreate with team name "tech-debt" - -5. **Do NOT spawn workers yet** - Workers are spawned on-demand in Phase 4 (Stop-Wait strategy) - -**Success**: Team created, session file written, wisdom initialized. - ---- +1. Generate session ID: `TD-<slug>-<YYYY-MM-DD>` +2. Create session folder structure (scan/, assessment/, plan/, fixes/, validation/, wisdom/) +3. Initialize .msg/meta.json via team_msg state_update with pipeline metadata +4. TeamCreate(team_name="tech-debt") +5. Do NOT spawn workers yet - deferred to Phase 4 ## 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. - -**Task Chain by Mode**: +Delegate to commands/dispatch.md. Task chain by mode: | Mode | Task Chain | |------|------------| @@ -271,146 +90,22 @@ Delegate to `commands/dispatch.md` which creates the full task chain. | remediate | TDSCAN-001 -> TDEVAL-001 -> TDPLAN-001 -> TDFIX-001 -> TDVAL-001 | | targeted | TDPLAN-001 -> TDFIX-001 -> TDVAL-001 | -**Task Metadata**: +## Phase 4: Spawn-and-Stop -| Task ID | Role | Dependencies | Description | -|---------|------|--------------|-------------| -| TDSCAN-001 | scanner | (none) | 多维度技术债务扫描 | -| TDEVAL-001 | assessor | TDSCAN-001 | 量化评估与优先级排序 | -| TDPLAN-001 | planner | TDEVAL-001 (or none in targeted) | 分阶段治理方案规划 | -| TDFIX-001 | executor | TDPLAN-001 + Plan Approval | 债务清理执行(worktree) | -| TDVAL-001 | validator | TDFIX-001 | 回归测试与质量验证 | - -**Success**: Tasks created with correct dependencies, assigned to appropriate owners. - ---- - -## Phase 4: Sequential Stage Execution (Stop-Wait) - -> **Strategy**: Spawn workers stage-by-stage, synchronous blocking wait. Worker returns = stage complete. No polling needed. - -> **CRITICAL**: Use `Task(run_in_background: false)` for synchronous execution. This is intentionally different from the v3 default Spawn-and-Stop pattern. - -**Workflow**: - -1. Load `commands/monitor.md` if available -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 after spawning (wait for worker callback) - -**Stage Transitions**: - -| Current Stage | Worker | After Completion | -|---------------|--------|------------------| -| TDSCAN-001 | scanner | -> Start TDEVAL | -| TDEVAL-001 | assessor | -> Start TDPLAN | -| TDPLAN-001 | planner | -> [Plan Approval Gate] -> [Create Worktree] -> Start TDFIX | -| TDFIX-001 | executor (worktree) | -> Start TDVAL | -| TDVAL-001 | validator (worktree) | -> Quality Gate -> [Commit+PR] | - -**Worker Spawn Template**: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-tech-debt/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: tech-debt -requirement: <task-description> -inner_loop: false - -## Current Task -- Task ID: <task-id> -- Task: <PREFIX>-<NNN> -- Task Prefix: <PREFIX> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`, - run_in_background: false // Stop-Wait: synchronous blocking -}) -``` - -**Plan Approval Gate** (after TDPLAN completes): - -1. Read remediation plan -2. Present to user via AskUserQuestion: - -| Option | Action | -|--------|--------| -| 批准 | Continue pipeline, create worktree | -| 修订 | Request plan revision from planner | -| 终止 | Stop pipeline, report current status | - -**Worktree Creation** (before TDFIX): - -1. Create worktree: `git worktree add <path> -b <branch>` -2. Update .msg/meta.json with worktree info -3. Notify user via team_msg - -**Fix-Verify Loop** (when TDVAL finds regressions): - -| Condition | Action | -|-----------|--------| -| regressionFound && iteration < 3 | Create TDFIX-fix + TDVAL-verify tasks, continue | -| iteration >= 3 | Accept current state, report with warning | - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Debt Reduction Metrics + PR -**Objective**: Completion report and follow-up options. - -**Workflow**: - -1. **Read shared memory** -> collect all results - -2. **PR Creation** (worktree mode, validation passed): - -| Step | Action | -|------|--------| -| Commit | `cd <worktree> && git add -A && git commit -m "tech-debt: <description>"` | -| Push | `cd <worktree> && git push -u origin <branch>` | -| Create PR | `cd <worktree> && gh pr create --title "Tech Debt: ..." --body "..."` | -| Notify | team_msg with pr_created | -| Cleanup | `git worktree remove <worktree>` (if validation passed) | - -3. **Calculate metrics**: - -| Metric | Calculation | -|--------|-------------| -| debt_items_found | debt_inventory.length | -| items_fixed | fix_results.items_fixed | -| reduction_rate | (items_fixed / debt_items_found) * 100 | - -4. **Generate report**: - -| Field | Value | -|-------|-------| -| mode | scan/remediate/targeted | -| debt_items_found | Count | -| debt_score_before | Initial score | -| debt_score_after | Final score | -| items_fixed | Count | -| items_remaining | Count | -| validation_passed | Boolean | -| regressions | Count | - -5. **Output**: SendMessage with `[coordinator]` prefix + team_msg log - -6. **Ask next steps** (skip if auto mode): - -| Option | Action | -|--------|--------| -| 新目标 | New tech debt target | -| 深度修复 | Continue with remaining high-priority items | -| 关闭团队 | Cleanup and close | - ---- +1. Read shared memory -> collect all results +2. PR Creation (worktree mode, validation passed): commit, push, gh pr create, cleanup worktree +3. Calculate: debt_items_found, items_fixed, reduction_rate +4. Generate report with mode, debt scores, validation status +5. Output with [coordinator] prefix +6. Execute completion action (AskUserQuestion: 新目标 / 深度修复 / 关闭团队) ## Error Handling @@ -421,8 +116,5 @@ Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`, | Dependency cycle | Detect, report to user, halt | | Invalid mode | Reject with error, ask to clarify | | Session corruption | Attempt recovery, fallback to manual reconciliation | -| Teammate unresponsive | Send follow-up, 2x -> respawn | | Scanner finds no debt | Report clean codebase, skip to summary | | Fix-Verify loop stuck >3 iterations | Accept current state, continue pipeline | -| Build/test environment broken | Notify user, suggest manual fix | -| All tasks completed but debt_score_after > debt_score_before | Report with WARNING, suggest re-run | diff --git a/.claude/skills/team-tech-debt/roles/executor/role.md b/.claude/skills/team-tech-debt/roles/executor/role.md new file mode 100644 index 00000000..71919ed6 --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/executor/role.md @@ -0,0 +1,76 @@ +--- +role: executor +prefix: TDFIX +inner_loop: true +message_types: [state_update] +--- + +# Tech Debt Executor + +Debt cleanup executor. Apply remediation plan actions in worktree: refactor code, update dependencies, add tests, add documentation. Batch-delegate to CLI tools, self-validate after each batch. + +## Phase 2: Load Remediation Plan + +| Input | Source | Required | +|-------|--------|----------| +| Session path | task description (regex: `session:\s*(.+)`) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Remediation plan | <session>/plan/remediation-plan.json | Yes | +| Worktree info | meta.json:worktree.path, worktree.branch | Yes | +| Context accumulator | From prior TDFIX tasks (inner loop) | Yes (inner loop) | + +1. Extract session path from task description +2. Read .msg/meta.json for worktree path and branch +3. Read remediation-plan.json, extract all actions from plan phases +4. Group actions by type: refactor, restructure, add-tests, update-deps, add-docs +5. Split large groups (> 10 items) into sub-batches of 10 +6. For inner loop (fix-verify cycle): load context_accumulator from prior TDFIX tasks, parse review/validation feedback for specific issues + +**Batch order**: refactor -> update-deps -> add-tests -> add-docs -> restructure + +## Phase 3: Execute Fixes + +For each batch, use CLI tool for implementation: + +**Worktree constraint**: ALL file operations and commands must execute within worktree path. Use `cd "<worktree-path>" && ...` prefix for all Bash commands. + +**Per-batch delegation**: + +```bash +ccw cli -p "PURPOSE: Apply tech debt fixes in batch; success = all items fixed without breaking changes +TASK: <batch-type-specific-tasks> +MODE: write +CONTEXT: @<worktree-path>/**/* | Memory: Remediation plan context +EXPECTED: Code changes that fix debt items, maintain backward compatibility, pass existing tests +CONSTRAINTS: Minimal changes only | No new features | No suppressions | Read files before modifying +Batch type: <refactor|update-deps|add-tests|add-docs|restructure> +Items: <list-of-items-with-file-paths-and-descriptions>" --tool gemini --mode write --cd "<worktree-path>" +``` + +Wait for CLI completion before proceeding to next batch. + +**Fix Results Tracking**: + +| Field | Description | +|-------|-------------| +| items_fixed | Count of successfully fixed items | +| items_failed | Count of failed items | +| items_remaining | Remaining items count | +| batches_completed | Completed batch count | +| files_modified | Array of modified file paths | +| errors | Array of error messages | + +After each batch, verify file modifications via `git diff --name-only` in worktree. + +## Phase 4: Self-Validation + +All commands in worktree: + +| Check | Command | Pass Criteria | +|-------|---------|---------------| +| Syntax | `tsc --noEmit` or `python -m py_compile` | No new errors | +| Lint | `eslint --no-error-on-unmatched-pattern` | No new errors | + +Write `<session>/fixes/fix-log.json` with fix results. Update .msg/meta.json with `fix_results`. + +Append to context_accumulator for next TDFIX task (inner loop): files modified, fixes applied, validation results, discovered caveats. diff --git a/.claude/skills/team-tech-debt/roles/planner/role.md b/.claude/skills/team-tech-debt/roles/planner/role.md new file mode 100644 index 00000000..8b23c55f --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/planner/role.md @@ -0,0 +1,69 @@ +--- +role: planner +prefix: TDPLAN +inner_loop: false +message_types: [state_update] +--- + +# Tech Debt Planner + +Remediation plan designer. Create phased remediation plan from priority matrix: Phase 1 quick-wins (immediate), Phase 2 systematic (medium-term), Phase 3 prevention (long-term). Produce remediation-plan.md. + +## Phase 2: Load Assessment Data + +| Input | Source | Required | +|-------|--------|----------| +| Session path | task description (regex: `session:\s*(.+)`) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Priority matrix | <session>/assessment/priority-matrix.json | Yes | + +1. Extract session path from task description +2. Read .msg/meta.json for debt_inventory +3. Read priority-matrix.json for quadrant groupings +4. Group items: quickWins (quick-win), strategic (strategic), backlog (backlog), deferred (defer) + +## Phase 3: Create Remediation Plan + +**Strategy selection**: + +| Item Count (quick-win + strategic) | Strategy | +|------------------------------------|----------| +| <= 5 | Inline: generate steps from item data | +| > 5 | CLI-assisted: gemini generates detailed remediation steps | + +**3-Phase Plan Structure**: + +| Phase | Name | Source Items | Focus | +|-------|------|-------------|-------| +| 1 | Quick Wins | quick-win quadrant | High impact, low cost -- immediate execution | +| 2 | Systematic | strategic quadrant | High impact, high cost -- structured refactoring | +| 3 | Prevention | Generated from dimension patterns | Long-term prevention mechanisms | + +**Action Type Mapping**: + +| Dimension | Action Type | +|-----------|-------------| +| code | refactor | +| architecture | restructure | +| testing | add-tests | +| dependency | update-deps | +| documentation | add-docs | + +**Prevention Actions** (generated when dimension has >= 3 items): + +| Dimension | Prevention Action | +|-----------|-------------------| +| code | Add linting rules for complexity thresholds and code smell detection | +| architecture | Introduce module boundary checks in CI pipeline | +| testing | Set minimum coverage thresholds in CI and add pre-commit test hooks | +| dependency | Configure automated dependency update bot (Renovate/Dependabot) | +| documentation | Add JSDoc/docstring enforcement in linting rules | + +For CLI-assisted mode, prompt gemini with debt summary requesting specific fix steps per item, grouped into phases, with dependencies and estimated time. + +## Phase 4: Validate & Save + +1. Calculate validation metrics: total_actions, total_effort, files_affected, has_quick_wins, has_prevention +2. Write `<session>/plan/remediation-plan.md` (markdown with per-item checklists) +3. Write `<session>/plan/remediation-plan.json` (machine-readable) +4. Update .msg/meta.json with `remediation_plan` summary diff --git a/.claude/skills/team-tech-debt/roles/scanner/role.md b/.claude/skills/team-tech-debt/roles/scanner/role.md new file mode 100644 index 00000000..46ef29b4 --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/scanner/role.md @@ -0,0 +1,81 @@ +--- +role: scanner +prefix: TDSCAN +inner_loop: false +message_types: [state_update] +--- + +# Tech Debt Scanner + +Multi-dimension tech debt scanner. Scan codebase across 5 dimensions (code, architecture, testing, dependency, documentation), produce structured debt inventory with severity rankings. + +## Phase 2: Context & Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Scan scope | task description (regex: `scope:\s*(.+)`) | No (default: `**/*`) | +| Session path | task description (regex: `session:\s*(.+)`) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | + +1. Extract session path and scan scope from task description +2. Read .msg/meta.json for team context +3. Detect project type and framework: + +| Signal File | Project Type | +|-------------|-------------| +| package.json + React/Vue/Angular | Frontend Node | +| package.json + Express/Fastify/NestJS | Backend Node | +| pyproject.toml / requirements.txt | Python | +| go.mod | Go | +| No detection | Generic | + +4. Determine scan dimensions (default: code, architecture, testing, dependency, documentation) +5. Detect perspectives from task description: + +| Condition | Perspective | +|-----------|-------------| +| `security\|auth\|inject\|xss` | security | +| `performance\|speed\|optimize` | performance | +| `quality\|clean\|maintain\|debt` | code-quality | +| `architect\|pattern\|structure` | architecture | +| Default | code-quality + architecture | + +6. Assess complexity: + +| Score | Complexity | Strategy | +|-------|------------|----------| +| >= 4 | High | Triple Fan-out: CLI explore + CLI 5 dimensions + multi-perspective Gemini | +| 2-3 | Medium | Dual Fan-out: CLI explore + CLI 3 dimensions | +| 0-1 | Low | Inline: ACE search + Grep | + +## Phase 3: Multi-Dimension Scan + +**Low Complexity** (inline): +- Use `mcp__ace-tool__search_context` for code smells, TODO/FIXME, deprecated APIs, complex functions, dead code, missing tests +- Classify findings into dimensions + +**Medium/High Complexity** (Fan-out): +- Fan-out A: CLI exploration (structure, patterns, dependencies angles) via `ccw cli --tool gemini --mode analysis` +- Fan-out B: CLI dimension analysis (parallel gemini per dimension -- code, architecture, testing, dependency, documentation) +- Fan-out C (High only): Multi-perspective Gemini analysis (security, performance, code-quality, architecture) +- Fan-in: Merge results, cross-deduplicate by file:line, boost severity for multi-source findings + +**Standardize each finding**: + +| Field | Description | +|-------|-------------| +| `id` | `TD-NNN` (sequential) | +| `dimension` | code, architecture, testing, dependency, documentation | +| `severity` | critical, high, medium, low | +| `file` | File path | +| `line` | Line number | +| `description` | Issue description | +| `suggestion` | Fix suggestion | +| `estimated_effort` | small, medium, large, unknown | + +## Phase 4: Aggregate & Save + +1. Deduplicate findings across Fan-out layers (file:line key), merge cross-references +2. Sort by severity (cross-referenced items boosted) +3. Write `<session>/scan/debt-inventory.json` with scan_date, dimensions, total_items, by_dimension, by_severity, items +4. Update .msg/meta.json with `debt_inventory` array and `debt_score_before` count diff --git a/.claude/skills/team-tech-debt/roles/validator/role.md b/.claude/skills/team-tech-debt/roles/validator/role.md new file mode 100644 index 00000000..ee53b15d --- /dev/null +++ b/.claude/skills/team-tech-debt/roles/validator/role.md @@ -0,0 +1,78 @@ +--- +role: validator +prefix: TDVAL +inner_loop: false +message_types: [state_update] +--- + +# Tech Debt Validator + +Cleanup result validator. Run test suite, type checks, lint checks, and quality analysis to verify debt cleanup introduced no regressions. Compare before/after debt scores, produce validation-report.json. + +## Phase 2: Load Context + +| Input | Source | Required | +|-------|--------|----------| +| Session path | task description (regex: `session:\s*(.+)`) | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | +| Fix log | <session>/fixes/fix-log.json | No | + +1. Extract session path from task description +2. Read .msg/meta.json for: worktree.path, debt_inventory, fix_results, debt_score_before +3. Determine command prefix: `cd "<worktree-path>" && ` if worktree exists +4. Read fix-log.json for modified files list +5. Detect available validation tools in worktree: + +| Signal | Tool | Method | +|--------|------|--------| +| package.json + npm | npm test | Test suite | +| pytest available | python -m pytest | Test suite | +| npx tsc available | npx tsc --noEmit | Type check | +| npx eslint available | npx eslint | Lint check | + +## Phase 3: Run Validation Checks + +Execute 4-layer validation (all commands in worktree): + +**1. Test Suite**: +- Run `npm test` or `python -m pytest` in worktree +- PASS if no FAIL/error/failed keywords; FAIL with regression count otherwise +- Skip with "no-tests" if no test runner available + +**2. Type Check**: +- Run `npx tsc --noEmit` in worktree +- Count `error TS` occurrences for error count + +**3. Lint Check**: +- Run `npx eslint --no-error-on-unmatched-pattern <modified-files>` in worktree +- Count error occurrences + +**4. Quality Analysis** (optional, when > 5 modified files): +- Use gemini CLI to compare code quality before/after +- Assess complexity, duplication, naming quality improvements + +**Debt Score Calculation**: +- debt_score_after = debt items NOT in modified files (remaining unfixed items) +- improvement_percentage = ((before - after) / before) * 100 + +**Auto-fix attempt** (when total_regressions <= 3): +- Use CLI tool to fix regressions in worktree: + ``` + Bash({ + command: `cd "${worktreePath}" && ccw cli -p "PURPOSE: Fix regressions found in validation + TASK: ${regressionDetails} + MODE: write + CONTEXT: @${modifiedFiles.join(' @')} + EXPECTED: Fixed regressions + CONSTRAINTS: Fix only regressions | Preserve debt cleanup changes | No suppressions" --tool gemini --mode write`, + run_in_background: false + }) + ``` +- Re-run validation checks after fix attempt + +## Phase 4: Compare & Report + +1. Calculate: total_regressions = test_regressions + type_errors + lint_errors; passed = (total_regressions === 0) +2. Write `<session>/validation/validation-report.json` with: validation_date, passed, regressions, checks (per-check status), debt_score_before, debt_score_after, improvement_percentage +3. Update .msg/meta.json with `validation_results` and `debt_score_after` +4. Select message type: `validation_complete` if passed, `regression_found` if not diff --git a/.claude/skills/team-tech-debt/specs/pipelines.md b/.claude/skills/team-tech-debt/specs/pipelines.md new file mode 100644 index 00000000..9e69e743 --- /dev/null +++ b/.claude/skills/team-tech-debt/specs/pipelines.md @@ -0,0 +1,47 @@ +# Pipeline Definitions + +Tech debt pipeline modes and task registry. + +## Pipeline Modes + +| Mode | Description | Task Chain | +|------|-------------|------------| +| scan | Scan and assess only, no fixes | TDSCAN-001 -> TDEVAL-001 | +| remediate | Full pipeline: scan -> assess -> plan -> fix -> validate | TDSCAN-001 -> TDEVAL-001 -> TDPLAN-001 -> TDFIX-001 -> TDVAL-001 | +| targeted | Skip scan/assess, direct fix path | TDPLAN-001 -> TDFIX-001 -> TDVAL-001 | + +## Task Registry + +| Task ID | Role | Prefix | blockedBy | Description | +|---------|------|--------|-----------|-------------| +| TDSCAN-001 | scanner | TDSCAN | [] | Fan-out multi-dimension codebase scan (code, architecture, testing, dependency, documentation) | +| TDEVAL-001 | assessor | TDEVAL | [TDSCAN-001] | Severity assessment with priority quadrant matrix | +| TDPLAN-001 | planner | TDPLAN | [TDEVAL-001] | 3-phase remediation plan with effort estimates | +| TDFIX-001 | executor | TDFIX | [TDPLAN-001] | Worktree-based incremental fixes (inner_loop: true) | +| TDVAL-001 | validator | TDVAL | [TDFIX-001] | 4-layer validation: syntax, tests, integration, regression | + +## Checkpoints + +| Checkpoint | Trigger | Condition | Action | +|------------|---------|-----------|--------| +| Plan Approval Gate | TDPLAN-001 completes | Always | AskUserQuestion: Approve / Revise / Abort | +| Worktree Creation | Plan approved | Before TDFIX | git worktree add .worktrees/TD-<slug>-<date> | +| Fix-Verify GC Loop | TDVAL-* completes | Regressions found | Create TDFIX-fix-<round> + TDVAL-recheck-<round> (max 3 rounds) | + +## GC Loop Behavior + +| Condition | Action | +|-----------|--------| +| No regressions | Pipeline complete | +| Regressions AND gc_rounds < 3 | Create fix-verify tasks, increment gc_rounds | +| Regressions AND gc_rounds >= 3 | Accept current state, handleComplete | + +## Output Artifacts + +| Task | Output Path | +|------|-------------| +| TDSCAN-001 | <session>/scan/scan-report.json | +| TDEVAL-001 | <session>/assessment/debt-assessment.json | +| TDPLAN-001 | <session>/plan/remediation-plan.md | +| TDFIX-001 | <session>/fixes/ (worktree) | +| TDVAL-001 | <session>/validation/validation-report.md | diff --git a/.claude/skills/team-testing/SKILL.md b/.claude/skills/team-testing/SKILL.md index 5705e713..e37d0365 100644 --- a/.claude/skills/team-testing/SKILL.md +++ b/.claude/skills/team-testing/SKILL.md @@ -1,308 +1,62 @@ --- name: team-testing -description: Unified team skill for testing team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team testing". +description: Unified team skill for testing team. Progressive test coverage through Generator-Critic loops, shared memory, and dynamic layer selection. Triggers on "team testing". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) --- # Team Testing -Unified team skill: progressive test coverage through Generator-Critic loops (generator<->executor), shared memory (defect pattern tracking), and dynamic layer selection. All team members invoke with `--role=xxx` to route to role-specific execution. +Orchestrate multi-agent test pipeline: strategist -> generator -> executor -> analyst. Progressive layer coverage (L1/L2/L3) with Generator-Critic loops for coverage convergence. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-testing") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-testing", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -strate- genera- execu- analyst -gist tor tor - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+-------+ + v v v v + [strat] [gen] [exec] [analyst] + team-worker agents, each loads roles/<role>/role.md ``` -## Command Execution Protocol +## Role Registry -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| strategist | [roles/strategist/role.md](roles/strategist/role.md) | STRATEGY-* | false | +| generator | [roles/generator/role.md](roles/generator/role.md) | TESTGEN-* | true | +| executor | [roles/executor/role.md](roles/executor/role.md) | TESTRUN-* | true | +| analyst | [roles/analyst/role.md](roles/analyst/role.md) | TESTANA-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` -> Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` -> Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `TST` +- **Session path**: `.workflow/.team/TST-<slug>-<date>/` +- **Team name**: `testing` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| strategist | [role-specs/strategist.md](role-specs/strategist.md) | STRATEGY-* | false | -| generator | [role-specs/generator.md](role-specs/generator.md) | TESTGEN-* | true | -| executor | [role-specs/executor.md](role-specs/executor.md) | TESTRUN-* | true | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | TESTANA-* | false | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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-testing", args="<task-description>")` - -**Lifecycle**: -``` -User provides task description - → coordinator Phase 1-3: Change scope analysis → TeamCreate → Create task chain - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until pipeline complete → Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Share state via team_msg(type='state_update') | Create tasks for other roles | -| Delegate to commands/ files | Modify resources outside own responsibility | - -Coordinator additional restrictions: Do not write tests directly, do not execute tests, do not analyze coverage, do not bypass workers. - -### Output Tagging - -All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary. - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: - -**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - -> `to` and `summary` are auto-defaulted by the tool. - -**CLI fallback**: When MCP unavailable → `ccw team log --session-id <session-id> --from <role> --type <type> --json` - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `pipeline_selected`, `gc_loop_trigger`, `quality_gate`, `task_unblocked`, `error`, `shutdown` | -| strategist | `strategy_ready`, `error` | -| generator | `tests_generated`, `tests_revised`, `error` | -| executor | `tests_passed`, `tests_failed`, `coverage_report`, `error` | -| analyst | `analysis_ready`, `error` | - -### Shared State - -All roles share state via `team_msg(type='state_update')` + `meta.json`: - -| Role | Field | -|------|-------| -| strategist | `test_strategy` | -| generator | `generated_tests` | -| executor | `execution_results`, `defect_patterns` | -| analyst | `analysis_report`, `coverage_history` | - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | testing | -| Session directory | `.workflow/.team/TST-<slug>-<date>/` | -| Test layers | L1: Unit (80%), L2: Integration (60%), L3: E2E (40%) | - ---- - -## Three-Pipeline Architecture - -``` -Targeted (small-scope changes): - STRATEGY-001 → TESTGEN-001(L1 unit) → TESTRUN-001 - -Standard (progressive): - STRATEGY-001 → TESTGEN-001(L1) → TESTRUN-001(L1) → TESTGEN-002(L2) → TESTRUN-002(L2) → TESTANA-001 - -Comprehensive (full coverage): - STRATEGY-001 → [TESTGEN-001(L1) + TESTGEN-002(L2)](parallel) → [TESTRUN-001(L1) + TESTRUN-002(L2)](parallel) → TESTGEN-003(L3) → TESTRUN-003(L3) → TESTANA-001 -``` - -### Generator-Critic Loop - -generator <-> executor loop (revise tests when coverage below target): - -``` -TESTGEN → TESTRUN → (if coverage < target) → TESTGEN-fix → TESTRUN-2 - (if coverage >= target) → next layer or TESTANA -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. Testing beat: strategy → generate → execute → analyze. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - │ (parallel OK) ──┼──→ [Worker B] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat views**: - -``` -Targeted (3 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 - │ │ │ - STRATEGY → TESTGEN ──→ TESTRUN - ▲ ▲ - pipeline pipeline - start done - -STRATEGY=strategist TESTGEN=generator TESTRUN=executor - -Standard (6 beats, progressive layers) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 - │ │ │ │ │ │ - STRATEGY → TESTGEN-L1 → TESTRUN-L1 → TESTGEN-L2 → TESTRUN-L2 → TESTANA - │ - coverage check - (< target → GC loop) - -Comprehensive (5+ beats, parallel windows) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 - │ ┌─────┴─────┐ ┌──────┴──────┐ │ │ - STRATEGY → TESTGEN-L1 ∥ TESTGEN-L2 → TESTRUN-L1 ∥ TESTRUN-L2 → TESTGEN-L3 → TESTRUN-L3 → TESTANA - ▲ ▲ ▲ - parallel parallel pipeline - window window done -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Coverage below target | After TESTRUN-* | If coverage < target → create TESTGEN-fix task (GC loop); else proceed | -| GC loop limit | Max 3 rounds per layer | Exceeds limit → accept current coverage with warning | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| GC loop exceeded | generator/executor iteration > 3 rounds | Terminate loop, accept current coverage with warning | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| STRATEGY-001 | strategist | strategy | (none) | Analyze git diff, determine test layers, define coverage targets | -| TESTGEN-001 | generator | generate | STRATEGY-001 | Generate L1 unit tests | -| TESTRUN-001 | executor | execute | TESTGEN-001 | Execute L1 tests, collect coverage | -| TESTGEN-002 | generator | generate | TESTRUN-001 | Generate L2 integration tests (Standard/Comprehensive) | -| TESTRUN-002 | executor | execute | TESTGEN-002 | Execute L2 tests, collect coverage | -| TESTGEN-003 | generator | generate | TESTRUN-002 | Generate L3 E2E tests (Comprehensive only) | -| TESTRUN-003 | executor | execute | TESTGEN-003 | Execute L3 tests, collect coverage | -| TESTANA-001 | analyst | analyze | last TESTRUN-* | Defect pattern analysis, coverage gaps, quality report | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ @@ -313,7 +67,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-testing/role-specs/<role>.md +role_spec: .claude/skills/team-testing/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: testing @@ -321,19 +75,22 @@ requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (generator, executor): Set `inner_loop: true`. The team-worker agent handles the loop internally. +## User Commands -**Single-task roles** (strategist, analyst): Set `inner_loop: false`. - ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View pipeline status graph | +| `resume` / `continue` | Advance to next step | +| `revise <TASK-ID>` | Revise specific task | +| `feedback <text>` | Inject feedback for revision | ## Completion Action -When the pipeline completes (all tasks done, coordinator Phase 5): +When pipeline completes, coordinator presents: ``` AskUserQuestion({ @@ -342,53 +99,39 @@ AskUserQuestion({ header: "Completion", multiSelect: false, options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Deepen Coverage", description: "Add more test layers or increase coverage targets" } ] }] }) ``` -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-testing", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- - -## Unified Session Directory +## Session Directory ``` -.workflow/.team/TST-<slug>-<YYYY-MM-DD>/ -├── .msg/messages.jsonl # Message bus log -├── .msg/meta.json # Session metadata -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── strategy/ # Strategist output -│ └── test-strategy.md -├── tests/ # Generator output -│ ├── L1-unit/ -│ ├── L2-integration/ -│ └── L3-e2e/ -├── results/ # Executor output -│ ├── run-001.json -│ └── coverage-001.json -└── analysis/ # Analyst output - └── quality-report.md +.workflow/.team/TST-<slug>-<date>/ +├── .msg/messages.jsonl # Team message bus +├── .msg/meta.json # Session metadata +├── wisdom/ # Cross-task knowledge +├── strategy/ # Strategist output +├── tests/ # Generator output (L1-unit/, L2-integration/, L3-e2e/) +├── results/ # Executor output +└── analysis/ # Analyst output ``` +## Specs Reference + +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry +- [specs/team-config.json](specs/team-config.json) — Team configuration + ## Error Handling | Scenario | Resolution | |----------|------------| | Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>.md) | -| Task prefix conflict | Log warning, proceed | -| Coverage never reaches target | After 3 GC loops, accept current coverage with warning | -| Test environment broken | Notify user, suggest manual fix | +| Role not found | Error with expected path (roles/<name>/role.md) | +| CLI tool fails | Worker fallback to direct implementation | +| GC loop exceeded | Accept current coverage with warning | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-testing/roles/analyst/role.md b/.claude/skills/team-testing/roles/analyst/role.md new file mode 100644 index 00000000..e1074b94 --- /dev/null +++ b/.claude/skills/team-testing/roles/analyst/role.md @@ -0,0 +1,95 @@ +--- +role: analyst +prefix: TESTANA +inner_loop: false +message_types: + success: analysis_ready + error: error +--- + +# Test Quality Analyst + +Analyze defect patterns, identify coverage gaps, assess GC loop effectiveness, and generate a quality report with actionable recommendations. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Execution results | <session>/results/run-*.json | Yes | +| Test strategy | <session>/strategy/test-strategy.md | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | + +1. Extract session path from task description +2. Read .msg/meta.json for execution context (executor, generator namespaces) +3. Read all execution results: + +``` +Glob("<session>/results/run-*.json") +Read("<session>/results/run-001.json") +``` + +4. Read test strategy: + +``` +Read("<session>/strategy/test-strategy.md") +``` + +5. Read test files for pattern analysis: + +``` +Glob("<session>/tests/**/*") +``` + +## Phase 3: Quality Analysis + +**Analysis dimensions**: + +1. **Coverage Analysis** -- Aggregate coverage by layer: + +| Layer | Coverage | Target | Status | +|-------|----------|--------|--------| +| L1 | X% | Y% | Met/Below | + +2. **Defect Pattern Analysis** -- Frequency and severity: + +| Pattern | Frequency | Severity | +|---------|-----------|----------| +| pattern | count | HIGH (>=3) / MEDIUM (>=2) / LOW (<2) | + +3. **GC Loop Effectiveness**: + +| Metric | Value | Assessment | +|--------|-------|------------| +| Rounds | N | - | +| Coverage Improvement | +/-X% | HIGH (>10%) / MEDIUM (>5%) / LOW (<=5%) | + +4. **Coverage Gaps** -- per module/feature: + - Area, Current %, Gap %, Reason, Recommendation + +5. **Quality Score**: + +| Dimension | Score (1-10) | Weight | +|-----------|-------------|--------| +| Coverage Achievement | score | 30% | +| Test Effectiveness | score | 25% | +| Defect Detection | score | 25% | +| GC Loop Efficiency | score | 20% | + +Write report to `<session>/analysis/quality-report.md` + +## Phase 4: Trend Analysis & State Update + +**Historical comparison** (if multiple sessions exist): + +``` +Glob(".workflow/.team/TST-*/.msg/meta.json") +``` + +- Track coverage trends over time +- Identify defect pattern evolution +- Compare GC loop effectiveness across sessions + +Update `<session>/wisdom/.msg/meta.json` under `analyst` namespace: +- Merge `{ "analyst": { quality_score, coverage_gaps, top_defect_patterns, gc_effectiveness, recommendations } }` diff --git a/.claude/skills/team-testing/roles/coordinator/commands/analyze.md b/.claude/skills/team-testing/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..f92638da --- /dev/null +++ b/.claude/skills/team-testing/roles/coordinator/commands/analyze.md @@ -0,0 +1,70 @@ +# Analyze Task + +Parse user task -> detect testing capabilities -> select pipeline -> design roles. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Prefix | +|----------|------------|--------| +| strategy, plan, layers, scope | strategist | STRATEGY | +| generate tests, write tests, create tests | generator | TESTGEN | +| run tests, execute, coverage | executor | TESTRUN | +| analyze, report, quality, defects | analyst | TESTANA | + +## Pipeline Mode Detection + +| Condition | Pipeline | +|-----------|----------| +| fileCount <= 3 AND moduleCount <= 1 | targeted | +| fileCount <= 10 AND moduleCount <= 3 | standard | +| Otherwise | comprehensive | + +## Dependency Graph + +Natural ordering for testing pipeline: +- Tier 0: strategist (change analysis, no upstream dependency) +- Tier 1: generator (requires strategy) +- Tier 2: executor (requires generated tests; GC loop with generator) +- Tier 3: analyst (requires execution results) + +## Pipeline Definitions + +``` +Targeted: STRATEGY -> TESTGEN(L1) -> TESTRUN(L1) +Standard: STRATEGY -> TESTGEN(L1) -> TESTRUN(L1) -> TESTGEN(L2) -> TESTRUN(L2) -> TESTANA +Comprehensive: STRATEGY -> [TESTGEN(L1) || TESTGEN(L2)] -> [TESTRUN(L1) || TESTRUN(L2)] -> TESTGEN(L3) -> TESTRUN(L3) -> TESTANA +``` + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per test layer | +1 | +| Parallel tracks | +1 per track | +| GC loop enabled | +1 | +| Serial depth > 3 | +1 | + +Results: 1-2 Low, 3-5 Medium, 6+ High + +## Role Minimization + +- Cap at 5 roles (coordinator + 4 workers) +- GC loop: generator <-> executor iterate up to 3 rounds per layer + +## Output + +Write <session>/task-analysis.json: +```json +{ + "task_description": "<original>", + "pipeline_mode": "<targeted|standard|comprehensive>", + "capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }], + "dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "layer": "L1|L2|L3" } }, + "roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": true }], + "complexity": { "score": 0, "level": "Low|Medium|High" }, + "coverage_targets": { "L1": 80, "L2": 60, "L3": 40 }, + "gc_loop_enabled": true +} +``` diff --git a/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md b/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md index 996b71bd..15407b71 100644 --- a/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md @@ -1,33 +1,26 @@ -# Command: Dispatch +# Dispatch Tasks -Create the testing task chain with correct dependencies and structured task descriptions. Supports targeted, standard, and comprehensive pipelines. +Create testing task chains with correct dependencies. Supports targeted, standard, and comprehensive pipelines. -## Phase 2: Context Loading +## Workflow -| Input | Source | Required | -|-------|--------|----------| -| User requirement | From coordinator Phase 1 | Yes | -| Session folder | From coordinator Phase 2 | Yes | -| Pipeline mode | From session.json `pipeline` | Yes | -| Coverage targets | From session.json `coverage_targets` | Yes | +1. Read task-analysis.json -> extract pipeline_mode and dependency_graph +2. Read specs/pipelines.md -> get task registry for selected pipeline +3. Topological sort tasks (respect blockedBy) +4. Validate all owners exist in role registry (SKILL.md) +5. For each task (in order): + - TaskCreate with structured description (see template below) + - TaskUpdate with blockedBy + owner assignment +6. Update session.json with pipeline.tasks_total +7. Validate chain (no orphans, no cycles, all refs valid) -1. Load user requirement and scope from session.json -2. Load pipeline definition from SKILL.md Pipeline Definitions -3. Read `pipeline` mode and `coverage_targets` from session.json - -## Phase 3: Task Chain Creation (Mode-Branched) - -### Task Description Template - -Every task description uses structured format: +## Task Description Template ``` -TaskCreate({ - subject: "<TASK-ID>", - description: "PURPOSE: <what this task achieves> | Success: <measurable criteria> +PURPOSE: <goal> | Success: <criteria> TASK: - - <step 1: specific action> - - <step 2: specific action> + - <step 1> + - <step 2> CONTEXT: - Session: <session-folder> - Scope: <scope> @@ -37,108 +30,72 @@ CONTEXT: EXPECTED: <deliverable path> + <quality criteria> CONSTRAINTS: <scope limits, focus areas> --- -InnerLoop: <true|false>" -}) -TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" }) +InnerLoop: <true|false> +RoleSpec: .claude/skills/team-testing/roles/<role>/role.md ``` -### Mode Router - -| Mode | Action | -|------|--------| -| `targeted` | Create 3 tasks: STRATEGY -> TESTGEN(L1) -> TESTRUN(L1) | -| `standard` | Create 6 tasks: STRATEGY -> TESTGEN(L1) -> TESTRUN(L1) -> TESTGEN(L2) -> TESTRUN(L2) -> TESTANA | -| `comprehensive` | Create 8 tasks with parallel groups | - ---- +## Pipeline Task Registry ### Targeted Pipeline - -**STRATEGY-001** (strategist): ``` -TaskCreate({ - subject: "STRATEGY-001", - description: "PURPOSE: Analyze change scope, define test strategy | Success: Strategy doc with layer recommendations -TASK: - - Analyze git diff for changed files and modules - - Detect test framework and existing patterns - - Define L1 unit test scope and coverage targets -CONTEXT: - - Session: <session-folder> - - Scope: <scope> -EXPECTED: <session>/strategy/test-strategy.md -CONSTRAINTS: Read-only analysis ---- -InnerLoop: false" -}) -TaskUpdate({ taskId: "STRATEGY-001", owner: "strategist" }) -``` - -**TESTGEN-001** (generator, L1): -``` -TaskCreate({ - subject: "TESTGEN-001", - description: "PURPOSE: Generate L1 unit tests | Success: Executable test files covering priority files -TASK: - - Read test strategy for priority files and patterns - - Generate unit tests: happy path, edge cases, error handling - - Validate syntax -CONTEXT: - - Session: <session-folder> - - Layer: L1-unit - - Upstream artifacts: strategy/test-strategy.md -EXPECTED: <session>/tests/L1-unit/ -CONSTRAINTS: Only generate test code, do not modify source ---- -InnerLoop: true" -}) -TaskUpdate({ taskId: "TESTGEN-001", addBlockedBy: ["STRATEGY-001"], owner: "generator" }) -``` - -**TESTRUN-001** (executor, L1): -``` -TaskCreate({ - subject: "TESTRUN-001", - description: "PURPOSE: Execute L1 unit tests, collect coverage | Success: pass_rate >= 0.95 AND coverage >= target -TASK: - - Run tests with coverage collection - - Parse pass rate and coverage metrics - - Auto-fix failures (max 3 iterations) -CONTEXT: - - Session: <session-folder> - - Input: tests/L1-unit - - Coverage target: <L1-target>% -EXPECTED: <session>/results/run-001.json -CONSTRAINTS: Only fix test files, not source code ---- -InnerLoop: true" -}) -TaskUpdate({ taskId: "TESTRUN-001", addBlockedBy: ["TESTGEN-001"], owner: "executor" }) +STRATEGY-001 (strategist): Analyze change scope, define test strategy + blockedBy: [] +TESTGEN-001 (generator): Generate L1 unit tests + blockedBy: [STRATEGY-001], meta: layer=L1-unit +TESTRUN-001 (executor): Execute L1 tests, collect coverage + blockedBy: [TESTGEN-001], inner_loop: true, meta: layer=L1-unit, coverage_target=80% ``` ### Standard Pipeline - -Adds to targeted: - -**TESTGEN-002** (generator, L2): blockedBy ["TESTRUN-001"], Layer: L2-integration -**TESTRUN-002** (executor, L2): blockedBy ["TESTGEN-002"], Input: tests/L2-integration -**TESTANA-001** (analyst): blockedBy ["TESTRUN-002"] +``` +STRATEGY-001 (strategist): Analyze change scope, define test strategy + blockedBy: [] +TESTGEN-001 (generator): Generate L1 unit tests + blockedBy: [STRATEGY-001], meta: layer=L1-unit +TESTRUN-001 (executor): Execute L1 tests, collect coverage + blockedBy: [TESTGEN-001], inner_loop: true, meta: layer=L1-unit, coverage_target=80% +TESTGEN-002 (generator): Generate L2 integration tests + blockedBy: [TESTRUN-001], meta: layer=L2-integration +TESTRUN-002 (executor): Execute L2 tests, collect coverage + blockedBy: [TESTGEN-002], inner_loop: true, meta: layer=L2-integration, coverage_target=60% +TESTANA-001 (analyst): Defect pattern analysis, quality report + blockedBy: [TESTRUN-002] +``` ### Comprehensive Pipeline +``` +STRATEGY-001 (strategist): Analyze change scope, define test strategy + blockedBy: [] +TESTGEN-001 (generator-1): Generate L1 unit tests + blockedBy: [STRATEGY-001], meta: layer=L1-unit +TESTGEN-002 (generator-2): Generate L2 integration tests + blockedBy: [STRATEGY-001], meta: layer=L2-integration +TESTRUN-001 (executor-1): Execute L1 tests, collect coverage + blockedBy: [TESTGEN-001], inner_loop: true, meta: layer=L1-unit, coverage_target=80% +TESTRUN-002 (executor-2): Execute L2 tests, collect coverage + blockedBy: [TESTGEN-002], inner_loop: true, meta: layer=L2-integration, coverage_target=60% +TESTGEN-003 (generator): Generate L3 E2E tests + blockedBy: [TESTRUN-001, TESTRUN-002], meta: layer=L3-e2e +TESTRUN-003 (executor): Execute L3 tests, collect coverage + blockedBy: [TESTGEN-003], inner_loop: true, meta: layer=L3-e2e, coverage_target=40% +TESTANA-001 (analyst): Defect pattern analysis, quality report + blockedBy: [TESTRUN-003] +``` -**Parallel groups**: -- TESTGEN-001 + TESTGEN-002 both blockedBy ["STRATEGY-001"] (parallel generation) -- TESTRUN-001 blockedBy ["TESTGEN-001"], TESTRUN-002 blockedBy ["TESTGEN-002"] (parallel execution) -- TESTGEN-003 blockedBy ["TESTRUN-001", "TESTRUN-002"], Layer: L3-e2e -- TESTRUN-003 blockedBy ["TESTGEN-003"] -- TESTANA-001 blockedBy ["TESTRUN-003"] +## InnerLoop Flag Rules -## Phase 4: Validation +- true: generator, executor roles (GC loop iterations) +- false: strategist, analyst roles -1. Verify all tasks created with correct subjects and dependencies -2. Check no circular dependencies -3. Verify blockedBy references exist -4. Log task chain to team_msg: +## Dependency Validation + +- No orphan tasks (all tasks have valid owner) +- No circular dependencies +- All blockedBy references exist +- Session reference in every task description +- RoleSpec reference in every task description + +## Log After Creation ``` mcp__ccw-tools__team_msg({ diff --git a/.claude/skills/team-testing/roles/coordinator/commands/monitor.md b/.claude/skills/team-testing/roles/coordinator/commands/monitor.md index 65d98653..f0a6b0c9 100644 --- a/.claude/skills/team-testing/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-testing/roles/coordinator/commands/monitor.md @@ -1,27 +1,40 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. -## Phase 2: Context Loading +## Constants -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Pipeline definition | From SKILL.md | Yes | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 3 -1. Load session.json for current state, pipeline mode, gc_rounds, coverage_targets -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## Handler Router -## Phase 3: Event Handlers +| Source | Handler | +|--------|---------| +| Message contains [strategist], [generator], [executor], [analyst] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -### handleCallback +## Role-Worker Map -Triggered when a worker sends completion message. +| Prefix | Role | Role Spec | inner_loop | +|--------|------|-----------|------------| +| STRATEGY-* | strategist | `.claude/skills/team-testing/roles/strategist/role.md` | false | +| TESTGEN-* | generator | `.claude/skills/team-testing/roles/generator/role.md` | true | +| TESTRUN-* | executor | `.claude/skills/team-testing/roles/executor/role.md` | true | +| TESTANA-* | analyst | `.claude/skills/team-testing/roles/analyst/role.md` | false | -1. Parse message to identify role, task ID: +## handleCallback + +Worker completed. Process and advance. + +1. Parse message to identify role and task ID: | Message Pattern | Role Detection | |----------------|---------------| @@ -30,45 +43,19 @@ Triggered when a worker sends completion message. | `[executor]` or task ID `TESTRUN-*` | executor | | `[analyst]` or task ID `TESTANA-*` | analyst | -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` - -3. Record completion in session state - -4. **Generator-Critic check** (executor callbacks only): - - If completed task is TESTRUN-* AND message indicates tests_failed or coverage below target: - - Read gc_rounds for this layer from session.json - - Execute **GC Loop Decision** (see below) - -5. Checkpoints: - -| Completed Task | Checkpoint | Action | -|---------------|------------|--------| -| STRATEGY-001 | CP-1 | Notify user: test strategy ready for review | -| Last TESTRUN-* | CP-2 | Check coverage, decide GC loop or next layer | -| TESTANA-001 | CP-3 | Pipeline complete | - -6. Proceed to handleSpawnNext - -### GC Loop Decision - -When executor reports test results: - -| Condition | Action | -|-----------|--------| -| passRate >= 0.95 AND coverage >= target | Log success, proceed to next stage | -| (passRate < 0.95 OR coverage < target) AND gcRound < maxRounds | Create TESTGEN-fix task, increment gc_round | -| gcRound >= maxRounds | Accept current coverage with warning, proceed | - -**TESTGEN-fix task creation**: +2. Check if progress update (inner loop) or final completion +3. Progress -> update session state, STOP +4. Completion -> mark task done via TaskUpdate(status="completed"), remove from active_workers +5. Check for checkpoints: + - TESTRUN-* completes -> read meta.json for executor.pass_rate and executor.coverage: + - (pass_rate >= 0.95 AND coverage >= target) OR gc_rounds[layer] >= MAX_GC_ROUNDS -> proceed to handleSpawnNext + - (pass_rate < 0.95 OR coverage < target) AND gc_rounds[layer] < MAX_GC_ROUNDS -> create GC fix tasks, increment gc_rounds[layer] +**GC Fix Task Creation** (when coverage below target): ``` TaskCreate({ - subject: "TESTGEN-<layer>-fix-<round>", - description: "PURPOSE: Revise tests to fix failures and improve coverage + subject: "TESTGEN-<layer>-fix-<round>: Revise <layer> tests (GC #<round>)", + description: "PURPOSE: Revise tests to fix failures and improve coverage | Success: pass_rate >= 0.95 AND coverage >= target TASK: - Read previous test results and failure details - Revise tests to address failures @@ -78,109 +65,161 @@ CONTEXT: - Layer: <layer> - Previous results: <session>/results/run-<N>.json EXPECTED: Revised test files in <session>/tests/<layer>/ +CONSTRAINTS: Only modify test files --- -InnerLoop: true" +InnerLoop: true +RoleSpec: .claude/skills/team-testing/roles/generator/role.md" }) -TaskUpdate({ taskId: "TESTGEN-<layer>-fix-<round>", owner: "generator" }) +TaskCreate({ + subject: "TESTRUN-<layer>-fix-<round>: Re-execute <layer> (GC #<round>)", + description: "PURPOSE: Re-execute tests after revision | Success: pass_rate >= 0.95 +CONTEXT: + - Session: <session-folder> + - Layer: <layer> + - Input: tests/<layer> +EXPECTED: <session>/results/run-<N>-gc.json +--- +InnerLoop: true +RoleSpec: .claude/skills/team-testing/roles/executor/role.md", + blockedBy: ["TESTGEN-<layer>-fix-<round>"] +}) +``` +Update session.gc_rounds[layer]++ + +6. -> handleSpawnNext + +## handleCheck + +Read-only status report, then STOP. + +Output: +``` +[coordinator] Testing Pipeline Status +[coordinator] Mode: <pipeline_mode> +[coordinator] Progress: <done>/<total> (<pct>%) +[coordinator] GC Rounds: L1: <n>/3, L2: <n>/3 + +[coordinator] Pipeline Graph: + STRATEGY-001: <done|run|wait> test-strategy.md + TESTGEN-001: <done|run|wait> generating L1... + TESTRUN-001: <done|run|wait> blocked by TESTGEN-001 + TESTGEN-002: <done|run|wait> blocked by TESTRUN-001 + TESTRUN-002: <done|run|wait> blocked by TESTGEN-002 + TESTANA-001: <done|run|wait> blocked by TESTRUN-* + +[coordinator] Active Workers: <list with elapsed time> +[coordinator] Ready: <pending tasks with resolved deps> +[coordinator] Commands: 'resume' to advance | 'check' to refresh ``` -Create TESTRUN-fix blocked on TESTGEN-fix. +Then STOP. -### handleSpawnNext +## handleResume -Find and spawn the next ready tasks. +1. No active workers -> handleSpawnNext +2. Has active -> check each status + - completed -> mark done via TaskUpdate + - in_progress -> still running +3. Some completed -> handleSpawnNext +4. All running -> report status, STOP -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" +## handleSpawnNext -2. For each ready task, determine role from task subject prefix: +Find ready tasks, spawn workers, STOP. -| Prefix | Role | Inner Loop | -|--------|------|------------| -| STRATEGY-* | strategist | false | -| TESTGEN-* | generator | true | -| TESTRUN-* | executor | true | -| TESTANA-* | analyst | false | +1. Collect from TaskList(): + - completedSubjects: status = completed + - inProgressSubjects: status = in_progress + - readySubjects: status = pending AND all blockedBy in completedSubjects -3. Spawn team-worker: +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each ready task: + a. Determine role from prefix (use Role-Worker Map) + b. Check if inner loop role (generator/executor) with active worker -> skip (worker picks up next task) + c. TaskUpdate -> in_progress + d. team_msg log -> task_unblocked + e. Spawn team-worker: ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role> worker for <task-id>", + description: "Spawn <role> worker for <subject>", team_name: "testing", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-testing/role-specs/<role>.md +role_spec: .claude/skills/team-testing/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: testing requirement: <task-description> inner_loop: <true|false> +## Current Task +- Task ID: <task-id> +- Task: <subject> + Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -4. **Parallel spawn** (comprehensive pipeline): + f. Add to active_workers -| Scenario | Spawn Behavior | -|----------|---------------| -| TESTGEN-001 + TESTGEN-002 both unblocked | Spawn both in parallel | -| TESTRUN-001 + TESTRUN-002 both unblocked | Spawn both in parallel | +5. **Parallel spawn** (comprehensive pipeline): + - TESTGEN-001 + TESTGEN-002 both unblocked -> spawn both in parallel (name: "generator-1", "generator-2") + - TESTRUN-001 + TESTRUN-002 both unblocked -> spawn both in parallel (name: "executor-1", "executor-2") -5. STOP after spawning -- wait for next callback +6. Update session.json, output summary, STOP -### handleCheck +## handleComplete -Output current pipeline status. +Pipeline done. Generate report and completion action. -``` -Pipeline Status (<pipeline-mode>): - [DONE] STRATEGY-001 (strategist) -> test-strategy.md - [RUN] TESTGEN-001 (generator) -> generating L1... - [WAIT] TESTRUN-001 (executor) -> blocked by TESTGEN-001 - [WAIT] TESTGEN-002 (generator) -> blocked by TESTRUN-001 - ... +1. Verify all tasks (including any GC fix tasks) have status "completed" or "deleted" +2. If any tasks incomplete -> return to handleSpawnNext +3. If all complete: + - Read final state from meta.json (analyst.quality_score, executor.coverage, gc_rounds) + - Generate summary (deliverables, task count, GC rounds, coverage metrics) +4. Read session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Deepen Coverage) + - auto_archive -> Archive & Clean (status=completed, TeamDelete) + - auto_keep -> Keep Active (status=paused) -GC Rounds: L1: 0/3, L2: 0/3 -Session: <session-id> -``` +## handleAdapt -Output status -- do NOT advance pipeline. +Capability gap reported mid-pipeline. -### handleResume +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/ +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause -Resume pipeline after user pause or interruption. +## Fast-Advance Reconciliation -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext - -### handleComplete - -Triggered when all pipeline tasks are completed and no GC cycles remain. - -**Completion check**: - -| Pipeline | Completion Condition | -|----------|---------------------| -| targeted | STRATEGY-001 + TESTGEN-001 + TESTRUN-001 (+ any fix tasks) completed | -| standard | All 6 tasks (+ any fix tasks) completed | -| comprehensive | All 8 tasks (+ any fix tasks) completed | - -1. If any tasks not completed, return to handleSpawnNext -2. If all completed, transition to coordinator Phase 5 +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns ## Phase 4: State Persistence After every handler execution: +1. Reconcile active_workers with actual TaskList states +2. Remove entries for completed/deleted tasks +3. Write updated session.json +4. STOP (wait for next callback) -1. Update session.json with current state (active tasks, gc_rounds per layer, last event) -2. Verify task list consistency -3. STOP and wait for next event +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Session file not found | Error, suggest re-initialization | +| Worker callback from unknown role | Log info, scan for other completions | +| GC loop exceeded (3 rounds) | Accept current coverage with warning, proceed | +| Pipeline stall | Check blockedBy chains, report to user | +| Coverage tool unavailable | Degrade to pass rate judgment | +| Worker crash | Reset task to pending, respawn | diff --git a/.claude/skills/team-testing/roles/coordinator/role.md b/.claude/skills/team-testing/roles/coordinator/role.md index 0047634c..21ec3170 100644 --- a/.claude/skills/team-testing/roles/coordinator/role.md +++ b/.claude/skills/team-testing/roles/coordinator/role.md @@ -1,15 +1,14 @@ -# Coordinator - Testing Team +# Coordinator Role -**Role**: coordinator -**Type**: Orchestrator -**Team**: testing +Orchestrate team-testing: analyze -> dispatch -> spawn -> monitor -> report. -Orchestrates the testing pipeline: manages task chains, spawns team-worker agents, handles Generator-Critic loops, quality gates, and drives the pipeline to completion. +## Identity +- Name: coordinator | Tag: [coordinator] +- Responsibility: Change scope analysis -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) - Follow Command Execution Protocol for dispatch and monitor commands - Respect pipeline stage dependencies (blockedBy) @@ -18,108 +17,49 @@ Orchestrates the testing pipeline: manages task chains, spawns team-worker agent - Execute completion action in Phase 5 ### MUST NOT - - Implement domain logic (test generation, execution, analysis) -- workers handle this - Spawn workers without creating tasks first - Skip quality gates when coverage is below target - Modify test files or source code directly -- delegate to workers - Force-advance pipeline past failed GC loops ---- - ## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +When coordinator needs to execute a specific phase: +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [strategist], [generator], [executor], [analyst] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Change Scope Analysis) | +| Worker callback | Message contains [strategist], [generator], [executor], [analyst] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) | +| Interrupted session | Active session in .workflow/.team/TST-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/TST-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Change Scope Analysis below - ---- +For callback/check/resume/adapt/complete: load commands/monitor.md, execute handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. +1. Scan .workflow/.team/TST-*/session.json for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection -1. Load session.json from detected session folder -2. Audit task list: +## Phase 1: Requirement Clarification -``` -TaskList() -``` +TEXT-LEVEL ONLY. No source code reading. -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "testing" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- - -## Phase 1: Change Scope Analysis - -1. Parse user task description from $ARGUMENTS +1. Parse task description from $ARGUMENTS 2. Analyze change scope: - -``` -Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached") -``` - -Extract changed files and modules for pipeline selection. - + ``` + Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached") + ``` 3. Select pipeline: | Condition | Pipeline | @@ -128,161 +68,64 @@ Extract changed files and modules for pipeline selection. | fileCount <= 10 AND moduleCount <= 3 | standard | | Otherwise | comprehensive | -4. Ask for missing parameters via AskUserQuestion if scope is unclear +4. Clarify if ambiguous (AskUserQuestion for scope) +5. Delegate to commands/analyze.md +6. Output: task-analysis.json +7. CRITICAL: Always proceed to Phase 2, never skip team workflow -5. Record requirements: mode, scope, focus, constraints +## Phase 2: Create Team + Initialize Session ---- +1. Generate session ID: TST-<slug>-<date> +2. Create session folder structure (strategy/, tests/L1-unit/, tests/L2-integration/, tests/L3-e2e/, results/, analysis/, wisdom/) +3. TeamCreate with team name "testing" +4. Read specs/pipelines.md -> select pipeline based on mode +5. Initialize pipeline via team_msg state_update: + ``` + mcp__ccw-tools__team_msg({ + operation: "log", session_id: "<id>", from: "coordinator", + type: "state_update", summary: "Session initialized", + data: { + pipeline_mode: "<targeted|standard|comprehensive>", + pipeline_stages: ["strategist", "generator", "executor", "analyst"], + team_name: "testing", + coverage_targets: { "L1": 80, "L2": 60, "L3": 40 }, + gc_rounds: {} + } + }) + ``` +6. Write session.json -## Phase 2: Session & Team Setup +## Phase 3: Create Task Chain -1. Create session directory: +Delegate to commands/dispatch.md: +1. Read specs/pipelines.md for selected pipeline's task registry +2. Topological sort tasks +3. Create tasks via TaskCreate with blockedBy +4. Update session.json -``` -Bash("mkdir -p .workflow/.team/TST-<slug>-<date>/strategy .workflow/.team/TST-<slug>-<date>/tests/L1-unit .workflow/.team/TST-<slug>-<date>/tests/L2-integration .workflow/.team/TST-<slug>-<date>/tests/L3-e2e .workflow/.team/TST-<slug>-<date>/results .workflow/.team/TST-<slug>-<date>/analysis .workflow/.team/TST-<slug>-<date>/wisdom") -``` +## Phase 4: Spawn-and-Stop -2. Write session.json: - -```json -{ - "status": "active", - "team_name": "testing", - "requirement": "<requirement>", - "timestamp": "<ISO-8601>", - "pipeline": "<targeted|standard|comprehensive>", - "coverage_targets": { "L1": 80, "L2": 60, "L3": 40 }, - "gc_rounds": {}, - "max_gc_rounds": 3 -} -``` - -3. Initialize .msg/meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<targeted|standard|comprehensive>", - pipeline_stages: ["strategist", "generator", "executor", "analyst"], - roles: ["coordinator", "strategist", "generator", "executor", "analyst"], - team_name: "testing" - } -}) -``` - -4. Create team: - -``` -TeamCreate({ team_name: "testing" }) -``` - -5. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) - ---- - -## Phase 3: Task Chain Creation - -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies - ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn strategist worker", - team_name: "testing", - name: "strategist", - run_in_background: true, - prompt: `## Role Assignment -role: strategist -role_spec: .claude/skills/team-testing/role-specs/strategist.md -session: <session-folder> -session_id: <session-id> -team_name: testing -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to commands/monitor.md#handleSpawnNext: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action -1. Load session state -> count completed tasks, calculate duration -2. List deliverables: - -| Deliverable | Path | -|-------------|------| -| Test Strategy | <session>/strategy/test-strategy.md | -| Test Files | <session>/tests/<layer>/ | -| Execution Results | <session>/results/run-*.json | -| Quality Report | <session>/analysis/quality-report.md | - -3. Output pipeline summary: task count, GC rounds, coverage metrics - -4. **Completion Action** (interactive): - -``` -AskUserQuestion({ - questions: [{ - question: "Testing pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Deepen Coverage", description: "Add more test layers or increase coverage targets" } - ] - }] -}) -``` - -5. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-testing', args='resume')" | -| Deepen Coverage | Create additional TESTGEN+TESTRUN tasks for next layer -> Phase 4 | - ---- +1. Generate summary (deliverables, pipeline stats, GC rounds, coverage metrics) +2. Execute completion action per session.completion_action: + - interactive -> AskUserQuestion (Archive/Keep/Deepen Coverage) + - auto_archive -> Archive & Clean + - auto_keep -> Keep Active ## Error Handling -| Scenario | Resolution | -|----------|------------| -| Teammate no response | Send tracking message, 2 times -> respawn worker | +| Error | Resolution | +|-------|------------| +| Task too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual | +| Worker crash | Reset task to pending, respawn | +| Dependency cycle | Detect in analysis, halt | | GC loop exceeded (3 rounds) | Accept current coverage, log to wisdom, proceed | -| Test environment failure | Report to user, suggest manual fix | -| All tests fail | Check test framework config, notify analyst | | Coverage tool unavailable | Degrade to pass rate judgment | -| Worker crash | Respawn worker, reassign task | -| Dependency cycle | Detect, report to user, halt | diff --git a/.claude/skills/team-testing/roles/executor/role.md b/.claude/skills/team-testing/roles/executor/role.md new file mode 100644 index 00000000..09e20fef --- /dev/null +++ b/.claude/skills/team-testing/roles/executor/role.md @@ -0,0 +1,98 @@ +--- +role: executor +prefix: TESTRUN +inner_loop: true +message_types: + success: tests_passed + failure: tests_failed + coverage: coverage_report + error: error +--- + +# Test Executor + +Execute tests, collect coverage, attempt auto-fix for failures. Acts as the Critic in the Generator-Critic loop. Reports pass rate and coverage for coordinator GC decisions. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Test directory | Task description (Input: <path>) | Yes | +| Coverage target | Task description (default: 80%) | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | No | + +1. Extract session path and test directory from task description +2. Extract coverage target (default: 80%) +3. Read .msg/meta.json for framework info (from strategist namespace) +4. Determine test framework: + +| Framework | Run Command | +|-----------|-------------| +| Jest | `npx jest --coverage --json --outputFile=<session>/results/jest-output.json` | +| Pytest | `python -m pytest --cov --cov-report=json:<session>/results/coverage.json -v` | +| Vitest | `npx vitest run --coverage --reporter=json` | + +5. Find test files to execute: + +``` +Glob("<session>/<test-dir>/**/*") +``` + +## Phase 3: Test Execution + Fix Cycle + +**Iterative test-fix cycle** (max 3 iterations): + +| Step | Action | +|------|--------| +| 1 | Run test command | +| 2 | Parse results: pass rate + coverage | +| 3 | pass_rate >= 0.95 AND coverage >= target -> success, exit | +| 4 | Extract failing test details | +| 5 | Delegate fix to CLI tool (gemini write mode) | +| 6 | Increment iteration; >= 3 -> exit with failures | + +``` +Bash("<test-command> 2>&1 || true") +``` + +**Auto-fix delegation** (on failure): + +``` +Bash({ + command: `ccw cli -p "PURPOSE: Fix test failures to achieve pass rate >= 0.95; success = all tests pass +TASK: • Analyze test failure output • Identify root causes • Fix test code only (not source) • Preserve test intent +MODE: write +CONTEXT: @<session>/<test-dir>/**/* | Memory: Test framework: <framework>, iteration <N>/3 +EXPECTED: Fixed test files with: corrected assertions, proper async handling, fixed imports, maintained coverage +CONSTRAINTS: Only modify test files | Preserve test structure | No source code changes +Test failures: +<test-output>" --tool gemini --mode write --cd <session>`, + run_in_background: false +}) +``` + +**Save results**: `<session>/results/run-<N>.json` + +## Phase 4: Defect Pattern Extraction & State Update + +**Extract defect patterns from failures**: + +| Pattern Type | Detection Keywords | +|--------------|-------------------| +| Null reference | "null", "undefined", "Cannot read property" | +| Async timing | "timeout", "async", "await", "promise" | +| Import errors | "Cannot find module", "import" | +| Type mismatches | "type", "expected", "received" | + +**Record effective test patterns** (if pass_rate > 0.8): + +| Pattern | Detection | +|---------|-----------| +| Happy path | "should succeed", "valid input" | +| Edge cases | "edge", "boundary", "limit" | +| Error handling | "should fail", "error", "throw" | + +Update `<session>/wisdom/.msg/meta.json` under `executor` namespace: +- Merge `{ "executor": { pass_rate, coverage, defect_patterns, effective_patterns, coverage_history_entry } }` diff --git a/.claude/skills/team-testing/roles/generator/role.md b/.claude/skills/team-testing/roles/generator/role.md new file mode 100644 index 00000000..a80d69ca --- /dev/null +++ b/.claude/skills/team-testing/roles/generator/role.md @@ -0,0 +1,97 @@ +--- +role: generator +prefix: TESTGEN +inner_loop: true +message_types: + success: tests_generated + revision: tests_revised + error: error +--- + +# Test Generator + +Generate test code by layer (L1 unit / L2 integration / L3 E2E). Acts as the Generator in the Generator-Critic loop. Supports revision mode for GC loop iterations. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Test strategy | <session>/strategy/test-strategy.md | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | No | + +1. Extract session path and layer from task description +2. Read test strategy: + +``` +Read("<session>/strategy/test-strategy.md") +``` + +3. Read source files to test (from strategy priority_files, limit 20) +4. Read .msg/meta.json for framework and scope context + +5. Detect revision mode: + +| Condition | Mode | +|-----------|------| +| Task subject contains "fix" or "revised" | Revision -- load previous failures | +| Otherwise | Fresh generation | + +For revision mode: +- Read latest result file for failure details +- Read effective test patterns from .msg/meta.json + +6. Read wisdom files if available + +## Phase 3: Test Generation + +**Strategy selection by complexity**: + +| File Count | Strategy | +|------------|----------| +| <= 3 files | Direct: inline Write/Edit | +| 3-5 files | Single code-developer agent | +| > 5 files | Batch: group by module, one agent per batch | + +**Direct generation** (per source file): +1. Generate test path: `<session>/tests/<layer>/<test-file>` +2. Generate test code: happy path, edge cases, error handling +3. Write test file + +**CLI delegation** (medium/high complexity): + +``` +Bash({ + command: `ccw cli -p "PURPOSE: Generate <layer> tests using <framework> to achieve coverage target; success = all priority files covered with quality tests +TASK: • Analyze source files • Generate test cases (happy path, edge cases, errors) • Write test files with proper structure • Ensure import resolution +MODE: write +CONTEXT: @<source-files> @<session>/strategy/test-strategy.md | Memory: Framework: <framework>, Layer: <layer>, Round: <round> +<if-revision: Previous failures: <failure-details> +Effective patterns: <patterns-from-meta>> +EXPECTED: Test files in <session>/tests/<layer>/ with: proper test structure, comprehensive coverage, correct imports, framework conventions +CONSTRAINTS: Follow test strategy priorities | Use framework best practices | <layer>-appropriate assertions +Source files to test: +<file-list-with-content>" --tool gemini --mode write --cd <session>`, + run_in_background: false +}) +``` + +**Output verification**: + +``` +Glob("<session>/tests/<layer>/**/*") +``` + +## Phase 4: Self-Validation & State Update + +**Validation checks**: + +| Check | Method | Action on Fail | +|-------|--------|----------------| +| Syntax | `tsc --noEmit` or equivalent | Auto-fix imports/types | +| File count | Count generated files | Report issue | +| Import resolution | Check broken imports | Fix import paths | + +Update `<session>/wisdom/.msg/meta.json` under `generator` namespace: +- Merge `{ "generator": { test_files, layer, round, is_revision } }` diff --git a/.claude/skills/team-testing/roles/strategist/role.md b/.claude/skills/team-testing/roles/strategist/role.md new file mode 100644 index 00000000..af7f22f2 --- /dev/null +++ b/.claude/skills/team-testing/roles/strategist/role.md @@ -0,0 +1,83 @@ +--- +role: strategist +prefix: STRATEGY +inner_loop: false +message_types: + success: strategy_ready + error: error +--- + +# Test Strategist + +Analyze git diff, determine test layers, define coverage targets, and formulate test strategy with prioritized execution order. + +## Phase 2: Context & Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | No | + +1. Extract session path and scope from task description +2. Get git diff for change analysis: + +``` +Bash("git diff HEAD~1 --name-only 2>/dev/null || git diff --cached --name-only") +Bash("git diff HEAD~1 -- <changed-files> 2>/dev/null || git diff --cached -- <changed-files>") +``` + +3. Detect test framework from project files: + +| Signal File | Framework | Test Pattern | +|-------------|-----------|-------------| +| jest.config.js/ts | Jest | `**/*.test.{ts,tsx,js}` | +| vitest.config.ts/js | Vitest | `**/*.test.{ts,tsx}` | +| pytest.ini / pyproject.toml | Pytest | `**/test_*.py` | +| No detection | Default | Jest patterns | + +4. Scan existing test patterns: + +``` +Glob("**/*.test.*") +Glob("**/*.spec.*") +``` + +5. Read .msg/meta.json if exists for session context + +## Phase 3: Strategy Formulation + +**Change analysis dimensions**: + +| Change Type | Analysis | Priority | +|-------------|----------|----------| +| New files | Need new tests | High | +| Modified functions | Need updated tests | Medium | +| Deleted files | Need test cleanup | Low | +| Config changes | May need integration tests | Variable | + +**Strategy output structure**: + +1. **Change Analysis Table**: File, Change Type, Impact, Priority +2. **Test Layer Recommendations**: + - L1 Unit: Scope, Coverage Target, Priority Files, Patterns + - L2 Integration: Scope, Coverage Target, Integration Points + - L3 E2E: Scope, Coverage Target, User Scenarios +3. **Risk Assessment**: Risk, Probability, Impact, Mitigation +4. **Test Execution Order**: Prioritized sequence + +Write strategy to `<session>/strategy/test-strategy.md` + +**Self-validation**: + +| Check | Criteria | Fallback | +|-------|----------|----------| +| Has L1 scope | L1 scope not empty | Default to all changed files | +| Has coverage targets | L1 target > 0 | Use defaults (80/60/40) | +| Has priority files | List not empty | Use all changed files | + +## Phase 4: Wisdom & State Update + +1. Write discoveries to `<session>/wisdom/conventions.md` (detected framework, patterns) +2. Update `<session>/wisdom/.msg/meta.json` under `strategist` namespace: + - Read existing -> merge `{ "strategist": { framework, layers, coverage_targets, priority_files, risks } }` -> write back diff --git a/.claude/skills/team-testing/specs/pipelines.md b/.claude/skills/team-testing/specs/pipelines.md new file mode 100644 index 00000000..60a7eb86 --- /dev/null +++ b/.claude/skills/team-testing/specs/pipelines.md @@ -0,0 +1,101 @@ +# Testing Pipelines + +Pipeline definitions and task registry for team-testing. + +## Pipeline Selection + +| Condition | Pipeline | +|-----------|----------| +| fileCount <= 3 AND moduleCount <= 1 | targeted | +| fileCount <= 10 AND moduleCount <= 3 | standard | +| Otherwise | comprehensive | + +## Pipeline Definitions + +### Targeted Pipeline (3 tasks, serial) + +``` +STRATEGY-001 -> TESTGEN-001 -> TESTRUN-001 +``` + +| Task ID | Role | Dependencies | Layer | Description | +|---------|------|-------------|-------|-------------| +| STRATEGY-001 | strategist | (none) | — | Analyze changes, define test strategy | +| TESTGEN-001 | generator | STRATEGY-001 | L1 | Generate L1 unit tests | +| TESTRUN-001 | executor | TESTGEN-001 | L1 | Execute L1 tests, collect coverage | + +### Standard Pipeline (6 tasks, progressive layers) + +``` +STRATEGY-001 -> TESTGEN-001 -> TESTRUN-001 -> TESTGEN-002 -> TESTRUN-002 -> TESTANA-001 +``` + +| Task ID | Role | Dependencies | Layer | Description | +|---------|------|-------------|-------|-------------| +| STRATEGY-001 | strategist | (none) | — | Analyze changes, define test strategy | +| TESTGEN-001 | generator | STRATEGY-001 | L1 | Generate L1 unit tests | +| TESTRUN-001 | executor | TESTGEN-001 | L1 | Execute L1 tests, collect coverage | +| TESTGEN-002 | generator | TESTRUN-001 | L2 | Generate L2 integration tests | +| TESTRUN-002 | executor | TESTGEN-002 | L2 | Execute L2 tests, collect coverage | +| TESTANA-001 | analyst | TESTRUN-002 | — | Defect pattern analysis, quality report | + +### Comprehensive Pipeline (8 tasks, parallel windows) + +``` +STRATEGY-001 -> [TESTGEN-001 || TESTGEN-002] -> [TESTRUN-001 || TESTRUN-002] -> TESTGEN-003 -> TESTRUN-003 -> TESTANA-001 +``` + +| Task ID | Role | Dependencies | Layer | Description | +|---------|------|-------------|-------|-------------| +| STRATEGY-001 | strategist | (none) | — | Analyze changes, define test strategy | +| TESTGEN-001 | generator-1 | STRATEGY-001 | L1 | Generate L1 unit tests (parallel) | +| TESTGEN-002 | generator-2 | STRATEGY-001 | L2 | Generate L2 integration tests (parallel) | +| TESTRUN-001 | executor-1 | TESTGEN-001 | L1 | Execute L1 tests (parallel) | +| TESTRUN-002 | executor-2 | TESTGEN-002 | L2 | Execute L2 tests (parallel) | +| TESTGEN-003 | generator | TESTRUN-001, TESTRUN-002 | L3 | Generate L3 E2E tests | +| TESTRUN-003 | executor | TESTGEN-003 | L3 | Execute L3 tests, collect coverage | +| TESTANA-001 | analyst | TESTRUN-003 | — | Defect pattern analysis, quality report | + +## GC Loop (Generator-Critic) + +Generator and executor iterate per test layer: + +``` +TESTGEN -> TESTRUN -> (if pass_rate < 0.95 OR coverage < target) -> TESTGEN-fix -> TESTRUN-fix + (if pass_rate >= 0.95 AND coverage >= target) -> next layer or TESTANA +``` + +- Max iterations: 3 per layer +- After 3 iterations: accept current state with warning + +## Coverage Targets + +| Layer | Name | Default Target | +|-------|------|----------------| +| L1 | Unit Tests | 80% | +| L2 | Integration Tests | 60% | +| L3 | E2E Tests | 40% | + +## Session Directory + +``` +.workflow/.team/TST-<slug>-<YYYY-MM-DD>/ +├── .msg/messages.jsonl # Message bus log +├── .msg/meta.json # Session metadata +├── wisdom/ # Cross-task knowledge +│ ├── learnings.md +│ ├── decisions.md +│ ├── conventions.md +│ └── issues.md +├── strategy/ # Strategist output +│ └── test-strategy.md +├── tests/ # Generator output +│ ├── L1-unit/ +│ ├── L2-integration/ +│ └── L3-e2e/ +├── results/ # Executor output +│ ├── run-001.json +│ └── coverage-001.json +└── analysis/ # Analyst output + └── quality-report.md +``` diff --git a/.claude/skills/team-uidesign/SKILL.md b/.claude/skills/team-uidesign/SKILL.md index 2373a413..b86f839e 100644 --- a/.claude/skills/team-uidesign/SKILL.md +++ b/.claude/skills/team-uidesign/SKILL.md @@ -1,366 +1,73 @@ --- name: team-uidesign -description: Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation. -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), WebFetch(*), WebSearch(*) +description: Unified team skill for UI design team. Research -> design tokens -> audit -> implementation. Uses team-worker agent architecture with roles/ for domain logic. Coordinator orchestrates dual-track pipeline with GC loops and sync points. Triggers on "team ui design", "ui design team". +allowed-tools: Agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, TaskList, TaskGet, TaskUpdate, TaskCreate, TeamCreate, TeamDelete, SendMessage, mcp__ace-tool__search_context, mcp__ccw-tools__read_file, mcp__ccw-tools__write_file, mcp__ccw-tools__edit_file, mcp__ccw-tools__team_msg --- # Team UI Design -Unified team skill: design system analysis, token definition, component specification, accessibility audit, and code implementation via CP-9 Dual-Track (design+implementation). All team members invoke with `--role=xxx` to route to role-specific execution. +Systematic UI design pipeline: research -> design tokens -> review -> implementation. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from `roles/<role>/role.md`. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-uidesign") | -| args="<task-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-uidesign", args="task description") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -resear- design- review- imple- -cher er er menter - -(tw) = team-worker agent + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+-------+ + v v v v + [team-worker agents, each loads roles/<role>/role.md] + researcher designer reviewer implementer ``` -## Command Execution Protocol +## Role Registry -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| researcher | [roles/researcher/role.md](roles/researcher/role.md) | RESEARCH-* | false | +| designer | [roles/designer/role.md](roles/designer/role.md) | DESIGN-* | false | +| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | AUDIT-* | false | +| implementer | [roles/implementer/role.md](roles/implementer/role.md) | BUILD-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator). +## Shared Constants -### Role Registry +- **Session prefix**: `UDS` +- **Session path**: `.workflow/.team/UDS-<slug>-<date>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` +- **Max GC rounds**: 2 -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| researcher | [role-specs/researcher.md](role-specs/researcher.md) | RESEARCH-* | false | -| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | false | -| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | AUDIT-* | false | -| implementer | [role-specs/implementer.md](role-specs/implementer.md) | BUILD-* | false | +## Worker Spawn Template -> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 - -### 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-uidesign", args="<task-description>")` - -**Lifecycle**: -``` -User provides task description - → coordinator Phase 1-3: Scope assessment → TeamCreate → Create task chain (dual-track) - → coordinator Phase 4: spawn first batch workers (background) → STOP - → Worker executes → SendMessage callback → coordinator advances next step - → Loop until pipeline complete → Phase 5 report -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Every worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty -3. No tasks → idle wait -4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after resume): -- Check whether this task's output artifact already exists -- Artifact complete → skip to Phase 5 report completion -- Artifact incomplete or missing → normal Phase 2-4 execution - -### Worker Phase 5: Report (shared by all workers) - -Standard reporting flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues -``` - -**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Forbidden | -|---------|-----------| -| Process tasks with own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Share state via team_msg(type='state_update') | Create tasks for other roles | -| Delegate to commands/ files | Modify resources outside own responsibility | - -Coordinator additional restrictions: Do not write/modify code directly, do not spawn implementation workers directly, do not execute analysis/audits, do not bypass workers. - -### Output Tagging - -All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary. - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: - -**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - -> `to` and `summary` are auto-defaulted by the tool. - -**CLI fallback**: When MCP unavailable → `ccw team log --session-id <session-id> --from <role> --type <type> --json` - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `task_unblocked`, `sync_checkpoint`, `fix_required`, `error`, `shutdown` | -| researcher | `research_ready`, `research_progress`, `error` | -| designer | `design_ready`, `design_revision`, `design_progress`, `error` | -| reviewer | `audit_result`, `audit_passed`, `fix_required`, `error` | -| implementer | `build_complete`, `build_progress`, `error` | - -### Shared State - -All roles share state via `team_msg(type='state_update')` + `meta.json`: - -| Role | Field | -|------|-------| -| researcher | `design_intelligence`, `component_inventory`, `industry_context` | -| designer | `design_token_registry`, `style_decisions` | -| reviewer | `audit_history`, `accessibility_patterns` | -| implementer | (reads all fields, writes build artifacts to session dir) | - -### Design Intelligence (ui-ux-pro-max) - -Researcher obtains design intelligence via `Skill(skill="ui-ux-pro-max", args="...")`, writes to `design-intelligence.json`. Downstream roles consume: - -``` -researcher (Stream 4) - | Skill("ui-ux-pro-max", args="<industry> <keywords> --design-system") - | Skill("ui-ux-pro-max", args="accessibility animation responsive --domain ux") - | Skill("ui-ux-pro-max", args="<keywords> --stack <detected-stack>") - ↓ -design-intelligence.json - |-> designer: recommended colors/typography/style → token values, anti-patterns → component specs - |-> reviewer: anti-patterns → Industry Compliance audit dimension (20% weight) - |-> implementer: stack guidelines → code generation, anti-patterns → validation -``` - -**Data flow**: -- `design_system.colors/typography/style` → designer token defaults (recommended-first mode) -- `recommendations.anti_patterns[]` → reviewer compliance check, designer/implementer avoidance -- `stack_guidelines` → implementer code generation constraints -- `ux_guidelines[]` → designer component spec implementation hints - -**Degradation strategy**: When ui-ux-pro-max unavailable, use LLM general knowledge for defaults, mark `_source` as `"llm-general-knowledge"`. - -### Team Configuration - -| Setting | Value | -|---------|-------| -| Team name | uidesign | -| Session directory | `.workflow/.team/UDS-<slug>-<date>/` | - ---- - -## Three-Pipeline Architecture - -### CP-9 Dual-Track Concept - -``` -Track A (Design): RESEARCH → DESIGN(tokens) → DESIGN(components) → ... - | | - Sync Point 1 Sync Point 2 - | | -Track B (Build): BUILD(tokens) ──→ BUILD(components) → ... -``` - -Design and implementation proceed in parallel after sync checkpoints. Each sync point validates that design artifacts are stable enough for implementation to consume. - -### Pipeline Modes - -``` -component (single component): - RESEARCH-001 → DESIGN-001 → AUDIT-001 → BUILD-001 - -system (design system - dual-track): - Track A: RESEARCH-001 → DESIGN-001(tokens) → DESIGN-002(components) - Sync-1: AUDIT-001 (token audit) - Track B: BUILD-001(tokens, blockedBy AUDIT-001) || DESIGN-002(components) - Sync-2: AUDIT-002 (component audit) - Track B: BUILD-002(components, blockedBy AUDIT-002) - -full-system (complete design system): - RESEARCH-001 → DESIGN-001(tokens) → AUDIT-001 - → [DESIGN-002(components) + BUILD-001(tokens)](parallel, blockedBy AUDIT-001) - → AUDIT-002 → BUILD-002(components) → AUDIT-003(final) -``` - -### Generator-Critic Loop - -designer <-> reviewer loop, ensuring design consistency and accessibility: - -``` -DESIGN → AUDIT → (if audit.score < 8 or critical_count > 0) → DESIGN-fix → AUDIT-2 - (if audit.score >= 8 and critical_count === 0) → next stage or BUILD - -Convergence: audit.score >= 8 && audit.critical_count === 0 -Max 2 rounds -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. UI Design beat: research → design → review → implement. - -``` -Beat Cycle (single beat) -═══════════════════════════════════════════════════════════ - Event Coordinator Workers -─────────────────────────────────────────────────────────── - callback/resume ──→ ┌─ handleCallback ─┐ - │ mark completed │ - │ check pipeline │ - ├─ handleSpawnNext ─┤ - │ find ready tasks │ - │ spawn workers ───┼──→ [Worker A] Phase 1-5 - │ (parallel OK) ──┼──→ [Worker B] Phase 1-5 - └─ STOP (idle) ─────┘ │ - │ - callback ←─────────────────────────────────────────┘ - (next beat) SendMessage + TaskUpdate(completed) -═══════════════════════════════════════════════════════════ -``` - -**Pipeline beat views**: - -``` -Component (4 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 - | | | | - RESEARCH → DESIGN → AUDIT ──→ BUILD - ^ ^ - pipeline pipeline - start done - -RESEARCH=researcher DESIGN=designer AUDIT=reviewer BUILD=implementer - -System (dual-track, 5-6 beats with parallel windows) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 - | | | ┌────┴────┐ | | - RESEARCH → DESIGN-tokens → AUDIT-1 → BUILD-tokens ∥ DESIGN-comp → AUDIT-2 → BUILD-comp - ^ ^ - sync point 1 sync point 2 - -Full-system (7+ beats with dual-track parallel) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 7 - | | | ┌────┴────┐ | | | - RESEARCH → DESIGN-tokens → AUDIT-1 → DESIGN-comp ∥ BUILD-tokens → AUDIT-2 → BUILD-comp → AUDIT-3 - ^ ^ - parallel final - window audit -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Sync Point (token audit) | After AUDIT on tokens | If passed → unblock BUILD(tokens) + DESIGN(components); else GC loop | -| Sync Point (component audit) | After AUDIT on components | If passed → unblock BUILD(components); else GC loop | -| GC loop limit | Max 2 rounds | Exceeds limit → coordinator escalates to user | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall Detection** (coordinator `handleCheck` executes): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` | -| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point | -| GC loop exceeded | designer/reviewer iteration > 2 rounds | Terminate loop, escalate to user | -| Dual-track sync failure | BUILD waiting on AUDIT that never completes | Fall back to single-track sequential execution | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| RESEARCH-001 | researcher | research | (none) | Design system analysis, component inventory, accessibility audit | -| DESIGN-001 | designer | design | RESEARCH-001 | Design token definition (colors, typography, spacing) | -| AUDIT-001 | reviewer | review | DESIGN-001 | Token design consistency and accessibility audit | -| BUILD-001 | implementer | implement | AUDIT-001 | Token code implementation (CSS variables, JS constants) | -| DESIGN-002 | designer | design | AUDIT-001 | Component specification and layout design | -| AUDIT-002 | reviewer | review | DESIGN-002 | Component design audit | -| BUILD-002 | implementer | implement | AUDIT-002 | Component code implementation | -| AUDIT-003 | reviewer | review | BUILD-002 | Final integrated audit (full-system only) | - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role> worker", + description: "Spawn <role> worker for <task-id>", team_name: "uidesign", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-uidesign/role-specs/<role>.md +role_spec: .claude/skills/team-uidesign/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: uidesign @@ -368,81 +75,52 @@ requirement: <task-description> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**All roles** (researcher, designer, reviewer, implementer): Set `inner_loop: false`. +## User Commands ---- +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | -## Completion Action +## Specs Reference -When the pipeline completes (all tasks done, coordinator Phase 5): +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry + +## Session Directory ``` -AskUserQuestion({ - questions: [{ - question: "UI Design pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-uidesign", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- - -## Unified Session Directory - -``` -.workflow/.team/UDS-<slug>-<YYYY-MM-DD>/ -├── .msg/messages.jsonl # Message bus log -├── .msg/meta.json # Session metadata -├── wisdom/ # Cross-task knowledge -│ ├── learnings.md -│ ├── decisions.md -│ ├── conventions.md -│ └── issues.md -├── research/ # Researcher output +.workflow/.team/UDS-<slug>-<date>/ +├── .msg/ +│ ├── messages.jsonl # Team message bus +│ └── meta.json # Pipeline config + GC state +├── research/ # Researcher output │ ├── design-system-analysis.json │ ├── component-inventory.json │ ├── accessibility-audit.json -│ ├── design-intelligence.json # ui-ux-pro-max design intelligence -│ └── design-intelligence-raw.md # ui-ux-pro-max raw output -├── design/ # Designer output +│ └── design-intelligence.json +├── design/ # Designer output │ ├── design-tokens.json │ ├── component-specs/ -│ │ └── {component-name}.md │ └── layout-specs/ -│ └── {layout-name}.md -├── audit/ # Reviewer output -│ └── audit-{NNN}.md -└── build/ # Implementer output - ├── token-files/ - └── component-files/ +├── audit/ # Reviewer output +│ └── audit-*.md +├── build/ # Implementer output +│ ├── token-files/ +│ └── component-files/ +└── wisdom/ # Cross-task knowledge ``` ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode → auto route to coordinator | -| Role file not found | Error with expected path (roles/<name>.md) | -| AUDIT score < 6 after 2 GC rounds | Coordinator escalates to user | -| Dual-track sync failure | Fall back to single-track sequential execution | -| Design token conflict | Reviewer arbitrates, coordinator intervenes | -| BUILD cannot find design files | Wait for Sync Point or escalate | -| ui-ux-pro-max unavailable | Degrade to LLM general knowledge, `_source: "llm-general-knowledge"` | -| Industry anti-pattern check failure | Reviewer marks Industry Compliance dimension as N/A | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| Session corruption | Attempt recovery, fallback to manual | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | +| GC loop stuck > 2 rounds | Escalate to user: accept / retry / terminate | diff --git a/.claude/skills/team-uidesign/roles/coordinator/commands/analyze.md b/.claude/skills/team-uidesign/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..91ea6920 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/coordinator/commands/analyze.md @@ -0,0 +1,59 @@ +# Analyze Task + +Parse user task -> detect UI design scope -> build dependency graph -> design pipeline mode. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Capability | Pipeline Hint | +|----------|------------|---------------| +| component, button, card, input, modal | component | component | +| design system, token, theme | system | system | +| complete, full, all components, redesign | full | full-system | +| accessibility, a11y, wcag | accessibility | component or system | +| implement, build, code | implementation | component | + +## Scope Determination + +| Signal | Pipeline Mode | +|--------|---------------| +| Single component mentioned | component | +| Multiple components or "design system" | system | +| "Full design system" or "complete redesign" | full-system | +| Unclear | ask user | + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Single component | +1 | +| Component system | +2 | +| Full design system | +3 | +| Accessibility required | +1 | +| Multiple industries/constraints | +1 | + +Results: 1-2 Low (component), 3-4 Medium (system), 5+ High (full-system) + +## Industry Detection + +| Keywords | Industry | +|----------|----------| +| saas, dashboard, analytics | SaaS/Tech | +| shop, cart, checkout, e-commerce | E-commerce | +| medical, patient, healthcare | Healthcare | +| bank, finance, payment | Finance | +| edu, course, learning | Education/Content | +| Default | SaaS/Tech | + +## Output + +Write scope context to coordinator memory: +```json +{ + "pipeline_mode": "<component|system|full-system>", + "scope": "<description>", + "industry": "<detected-industry>", + "complexity": { "score": 0, "level": "Low|Medium|High" } +} +``` diff --git a/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md b/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md index 4f50f655..807b6114 100644 --- a/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md @@ -12,7 +12,7 @@ Create the UI design task chain with correct dependencies and structured task de | Industry config | From session.json `industry` | Yes | 1. Load user requirement and design scope from session.json -2. Load pipeline stage definitions from SKILL.md Task Metadata Registry +2. Load pipeline stage definitions from specs/pipelines.md 3. Read `pipeline` and `industry` from session.json ## Phase 3: Task Chain Creation (Mode-Branched) diff --git a/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md b/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md index d782df2f..0e706cb2 100644 --- a/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md @@ -1,71 +1,122 @@ -# Command: Monitor +# Monitor Pipeline -Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, and completion. Supports component, system, and full-system pipeline modes with sync point and Generator-Critic loop management. +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. -## Phase 2: Context Loading +## Constants -| Input | Source | Required | -|-------|--------|----------| -| Session state | <session>/session.json | Yes | -| Task list | TaskList() | Yes | -| Trigger event | From Entry Router detection | Yes | -| Pipeline definition | From SKILL.md | Yes | +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_GC_ROUNDS: 2 -1. Load session.json for current state, `pipeline`, `gc_state`, `sync_points` -2. Run TaskList() to get current task statuses -3. Identify trigger event type from Entry Router +## Handler Router -## Phase 3: Event Handlers +| Source | Handler | +|--------|---------| +| Message contains [researcher], [designer], [reviewer], [implementer] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -### handleCallback +## handleCallback -Triggered when a worker sends completion message. +Worker completed. Process and advance. 1. Parse message to identify role and task ID: -| Message Pattern | Role Detection | -|----------------|---------------| -| `[researcher]` or task ID `RESEARCH-*` | researcher | -| `[designer]` or task ID `DESIGN-*` | designer | -| `[reviewer]` or task ID `AUDIT-*` | reviewer | -| `[implementer]` or task ID `BUILD-*` | implementer | - -2. Mark task as completed: - -``` -TaskUpdate({ taskId: "<task-id>", status: "completed" }) -``` +| Message Pattern | Role | +|----------------|------| +| `[researcher]` or `RESEARCH-*` | researcher | +| `[designer]` or `DESIGN-*` | designer | +| `[reviewer]` or `AUDIT-*` | reviewer | +| `[implementer]` or `BUILD-*` | implementer | +2. Mark task completed: `TaskUpdate({ taskId: "<task-id>", status: "completed" })` 3. Record completion in session state -4. Check if checkpoint feedback is configured for this stage: +4. Check checkpoint for completed task: | Completed Task | Checkpoint | Action | |---------------|------------|--------| | RESEARCH-001 | - | Notify user: research complete | | DESIGN-001 (tokens) | - | Proceed to AUDIT-001 | -| AUDIT-001 | Sync Point 1 | Check audit signal -> GC loop or unblock parallel (see below) | -| DESIGN-002 (components) | - | Proceed to AUDIT-002 | -| AUDIT-002 | Sync Point 2 | Check audit signal -> GC loop or unblock BUILD-002 | +| AUDIT-* | QUALITY-001: Sync Point | Check audit signal -> GC loop or unblock parallel | | BUILD-001 (tokens) | - | Check if BUILD-002 ready | | BUILD-002 (components) | - | Check if AUDIT-003 exists (full-system) or handleComplete | -| AUDIT-003 | Final | Notify user: final audit complete | 5. **Sync Point handling** (AUDIT task completed): - - Read audit signal from message: `audit_passed`, `audit_result`, or `fix_required` - - Route to GC loop control (see below) + Read audit signal from message: `audit_passed`, `audit_result`, or `fix_required` -6. Proceed to handleSpawnNext + | Signal | Condition | Action | + |--------|-----------|--------| + | `audit_passed` | Score >= 8, critical === 0 | GC converged -> record sync_point -> unblock downstream | + | `audit_result` | Score 6-7, no critical | gc_rounds < max -> create DESIGN-fix task | + | `fix_required` | Score < 6 or critical > 0 | gc_rounds < max -> create DESIGN-fix task (CRITICAL) | + | Any | gc_rounds >= max | Escalate to user | -### handleSpawnNext + **GC Fix Task Creation**: + ``` + TaskCreate({ subject: "DESIGN-fix-<round>", + description: "PURPOSE: Address audit feedback | Success: All critical/high issues resolved + TASK: + - Parse audit feedback for specific issues + - Apply targeted fixes + CONTEXT: + - Session: <session-folder> + - Upstream artifacts: audit/audit-<NNN>.md" }) + TaskUpdate({ taskId: "DESIGN-fix-<round>", owner: "designer" }) + ``` + Then create new AUDIT task blocked by fix. Increment gc_state.round. -Find and spawn the next ready tasks. + **GC Escalation Options** (when max rounds exceeded): + 1. Accept current design - skip review, continue implementation + 2. Try one more round + 3. Terminate -1. Scan task list for tasks where: - - Status is "pending" - - All blockedBy tasks have status "completed" +6. -> handleSpawnNext -2. For each ready task, spawn team-worker: +## handleCheck + +Read-only status report, then STOP. + +``` +Pipeline Status (<pipeline-mode>): + [DONE] RESEARCH-001 (researcher) -> research/*.json + [DONE] DESIGN-001 (designer) -> design-tokens.json + [RUN] AUDIT-001 (reviewer) -> auditing tokens... + [WAIT] BUILD-001 (implementer) -> blocked by AUDIT-001 + [WAIT] DESIGN-002 (designer) -> blocked by AUDIT-001 + +GC Rounds: 0/2 +Sync Points: 0/<expected> +Session: <session-id> +Commands: 'resume' to advance | 'check' to refresh +``` + +Output status -- do NOT advance pipeline. + +## handleResume + +1. Audit task list for inconsistencies: + - Tasks stuck in "in_progress" -> reset to "pending" + - Tasks with completed blockers but still "pending" -> include in spawn list +2. -> handleSpawnNext + +## handleSpawnNext + +Find ready tasks, spawn workers, STOP. + +1. Collect: completedSubjects, inProgressSubjects, readySubjects (pending + all blockedBy completed) +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Check inner loop role with active worker -> skip (worker picks up) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker: ``` Agent({ @@ -76,7 +127,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-uidesign/role-specs/<role>.md +role_spec: .claude/skills/team-uidesign/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: uidesign @@ -84,119 +135,50 @@ requirement: <task-description> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -3. **Parallel spawn rules by mode**: +**Parallel spawn rules by mode**: | Mode | Scenario | Spawn Behavior | |------|----------|---------------| -| Component | Sequential | One task at a time | -| System | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel | -| System | After Sync Point 2 | Spawn BUILD-002 | -| Full-system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel | -| Full-system | After BUILD-002 | Spawn AUDIT-003 | +| component | Sequential | One task at a time | +| system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel | +| system | After Sync Point 2 | Spawn BUILD-002 | +| full-system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel | +| full-system | After BUILD-002 | Spawn AUDIT-003 | -4. STOP after spawning -- wait for next callback +5. Add to active_workers, update session, output summary, STOP -### Generator-Critic Loop Control +## handleComplete -When AUDIT task completes, check signal: - -| Signal | Condition | Action | -|--------|-----------|--------| -| `audit_passed` | Score >= 8, critical === 0 | GC converged -> record sync_point -> unblock downstream tasks | -| `audit_result` | Score 6-7, critical === 0 | GC round < max -> create DESIGN-fix task | -| `fix_required` | Score < 6 or critical > 0 | GC round < max -> create DESIGN-fix task (CRITICAL) | -| Any | GC round >= max | Escalate to user | - -**GC Fix Task Creation**: -``` -TaskCreate({ - subject: "DESIGN-fix-<round>", - description: "PURPOSE: Address audit feedback from AUDIT-<NNN> | Success: All critical/high issues resolved -TASK: - - Parse audit feedback for specific issues - - Re-read affected design artifacts - - Apply fixes: token adjustments, missing states, accessibility gaps - - Re-write affected files -CONTEXT: - - Session: <session-folder> - - Upstream artifacts: audit/audit-<NNN>.md - - Shared memory: <session>/wisdom/.msg/meta.json -EXPECTED: Updated design artifacts | All flagged issues addressed -CONSTRAINTS: Targeted fixes only" -}) -TaskUpdate({ taskId: "DESIGN-fix-<round>", owner: "designer" }) -``` - -After fix completes, create new AUDIT task blocked by the fix task. Increment gc_state.round. - -**GC Escalation Options**: -1. Accept current design - Skip remaining review, continue implementation -2. Try one more round - Extra GC loop opportunity -3. Terminate - Stop and handle manually - -### Dual-Track Sync Point Management - -**When AUDIT at sync point passes (audit_passed)**: -1. Record sync point in session.sync_points -2. Unblock parallel tasks on both tracks -3. team_msg log(sync_checkpoint) - -**Dual-track failure fallback**: -- Convert remaining parallel tasks to sequential -- Remove parallel dependencies, add sequential blockedBy -- team_msg log(error): "Dual-track sync failed, falling back to sequential" - -### handleCheck - -Output current pipeline status. - -``` -Pipeline Status (<pipeline-mode>): - [DONE] RESEARCH-001 (researcher) -> research/*.json - [DONE] DESIGN-001 (designer) -> design-tokens.json - [RUN] AUDIT-001 (reviewer) -> auditing tokens... - [WAIT] BUILD-001 (implementer) -> blocked by AUDIT-001 - [WAIT] DESIGN-002 (designer) -> blocked by AUDIT-001 - -GC Rounds: 0/2 -Sync Points: 0/<expected> -Session: <session-id> -``` - -Output status -- do NOT advance pipeline. - -### handleResume - -Resume pipeline after user pause or interruption. - -1. Audit task list for inconsistencies: - - Tasks stuck in "in_progress" -> reset to "pending" - - Tasks with completed blockers but still "pending" -> include in spawn list -2. Proceed to handleSpawnNext - -### handleComplete - -Triggered when all pipeline tasks are completed. +Pipeline done. Generate report and completion action. **Completion check by mode**: | Mode | Completion Condition | |------|---------------------| -| Component | All 4 tasks (+ any fix/retry tasks) have status "completed" | -| System | All 7 tasks (+ any fix/retry tasks) have status "completed" | -| Full-system | All 8 tasks (+ any fix/retry tasks) have status "completed" | +| component | All 4 tasks (+ fix tasks) completed | +| system | All 7 tasks (+ fix tasks) completed | +| full-system | All 8 tasks (+ fix tasks) completed | -If any tasks not completed, return to handleSpawnNext. -If all completed, transition to coordinator Phase 5. +1. If any tasks not completed -> handleSpawnNext +2. If all completed -> transition to coordinator Phase 5 -## Phase 4: State Persistence +## handleAdapt -After every handler execution: +Capability gap reported mid-pipeline. -1. Update session.json with current state (active tasks, gc_state, sync_points, last event) -2. Verify task list consistency -3. STOP and wait for next event +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role spec +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause + +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-uidesign/roles/coordinator/role.md b/.claude/skills/team-uidesign/roles/coordinator/role.md index dc347adf..7dac8352 100644 --- a/.claude/skills/team-uidesign/roles/coordinator/role.md +++ b/.claude/skills/team-uidesign/roles/coordinator/role.md @@ -1,253 +1,131 @@ -# Coordinator - UI Design Team +# Coordinator Role -**Role**: coordinator -**Type**: Orchestrator -**Team**: uidesign +UI Design Team coordinator. Orchestrate pipeline: analyze -> dispatch -> spawn -> monitor -> report. Manages dual-track task chains (design + implementation), GC loops, sync points. -Orchestrates the UI design pipeline: manages dual-track task chains (design + implementation), spawns team-worker agents, handles Generator-Critic loops between designer and reviewer, manages sync points, and drives the pipeline to completion. +## Identity +- **Name**: coordinator | **Tag**: [coordinator] +- **Responsibility**: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - +- All output (SendMessage, team_msg, logs) must carry `[coordinator]` identifier - Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) -- Follow Command Execution Protocol for dispatch and monitor commands -- Respect pipeline stage dependencies (blockedBy) -- Stop after spawning workers -- wait for callbacks +- Dispatch tasks with proper dependency chains and blockedBy +- Monitor worker progress via message bus and route messages - Handle Generator-Critic loops with max 2 iterations -- Execute completion action in Phase 5 +- Maintain session state persistence ### MUST NOT - - Implement domain logic (researching, designing, auditing, building) -- workers handle this - Spawn workers without creating tasks first - Skip sync points when configured - Force-advance pipeline past failed audit - Modify source code or design artifacts directly -- delegate to workers - ---- +- Omit `[coordinator]` identifier in any output ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): +When coordinator needs to execute a command (analyze, dispatch, monitor): -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** -- NOT separate agents or subprocesses -4. **Execute synchronously** -- complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [researcher], [designer], [reviewer], [implementer] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [researcher], [designer], [reviewer], [implementer] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session exists in .workflow/.team/UDS-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/UDS-*/.msg/meta.json` for active/paused sessions - - If found, extract session folder path, status, and pipeline mode - -2. **Parse $ARGUMENTS** for detection keywords: - - Check for role name tags in message content - - Check for "check", "status", "resume", "continue" keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/adapt/complete: load `commands/monitor.md`, execute matched handler, STOP. ## Phase 0: Session Resume Check -Triggered when an active/paused session is detected on coordinator entry. - -1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - -3. Reconcile session state vs task status: - -| Task Status | Session Expects | Action | -|-------------|----------------|--------| -| in_progress | Should be running | Reset to pending (worker was interrupted) | -| completed | Already tracked | Skip | -| pending + unblocked | Ready to run | Include in spawn list | - -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "uidesign" }) -``` - -5. Spawn workers for ready tasks -> Phase 4 coordination loop - ---- +1. Scan `.workflow/.team/UDS-*/.msg/meta.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -1. Parse user task description from $ARGUMENTS -2. Identify design scope: +TEXT-LEVEL ONLY. No source code reading. -| Signal | Target | -|--------|--------| -| Single component mentioned | Component pipeline | -| Multiple components or "design system" | System pipeline | -| Full redesign or "complete design system" | Full-system pipeline | +1. Parse task description from arguments +2. Detect design scope: -3. If scope is unclear, ask for clarification: +| Signal | Pipeline Mode | +|--------|---------------| +| Single component mentioned | component | +| Multiple components or "design system" | system | +| "Full design system" or "complete redesign" | full-system | +| Unclear | ask user | -``` -AskUserQuestion({ - questions: [ - { question: "UI design scope?", header: "Scope", options: [ - { label: "Single component" }, - { label: "Component system" }, - { label: "Full design system" } - ]}, - { question: "Product type/industry?", header: "Industry", options: [ - { label: "SaaS/Tech" }, - { label: "E-commerce" }, - { label: "Healthcare/Finance" }, - { label: "Education/Content" }, - { label: "Other" } - ]} - ] -}) -``` +3. Ask for missing parameters if scope unclear: + ``` + AskUserQuestion({ + questions: [ + { question: "UI design scope?", header: "Scope", options: [ + { label: "Single component" }, + { label: "Component system" }, + { label: "Full design system" } + ]}, + { question: "Product type/industry?", header: "Industry", options: [ + { label: "SaaS/Tech" }, { label: "E-commerce" }, + { label: "Healthcare/Finance" }, { label: "Education/Content" }, { label: "Other" } + ]} + ] + }) + ``` +4. Delegate to `commands/analyze.md` -> output scope context +5. Record: pipeline_mode, industry, complexity -4. Map scope to pipeline: component / system / full-system -5. Record requirement with scope, industry, and pipeline mode +## Phase 2: Create Team + Initialize Session ---- +1. Generate session ID: `UDS-<slug>-<YYYY-MM-DD>` +2. Create session folder structure: + ``` + .workflow/.team/UDS-<slug>-<date>/research/ + .workflow/.team/UDS-<slug>-<date>/design/component-specs/ + .workflow/.team/UDS-<slug>-<date>/design/layout-specs/ + .workflow/.team/UDS-<slug>-<date>/audit/ + .workflow/.team/UDS-<slug>-<date>/build/token-files/ + .workflow/.team/UDS-<slug>-<date>/build/component-files/ + .workflow/.team/UDS-<slug>-<date>/wisdom/ + .workflow/.team/UDS-<slug>-<date>/.msg/ + ``` +3. Initialize `.msg/meta.json` via team_msg state_update with pipeline metadata +4. TeamCreate(team_name="uidesign") +5. Do NOT spawn workers yet - deferred to Phase 4 -## Phase 2: Session & Team Setup +## Phase 3: Create Task Chain -1. Create session directory: +Delegate to `commands/dispatch.md`. Task chains by mode: -``` -Bash("mkdir -p .workflow/.team/UDS-<slug>-<date>/research .workflow/.team/UDS-<slug>-<date>/design/component-specs .workflow/.team/UDS-<slug>-<date>/design/layout-specs .workflow/.team/UDS-<slug>-<date>/audit .workflow/.team/UDS-<slug>-<date>/build/token-files .workflow/.team/UDS-<slug>-<date>/build/component-files .workflow/.team/UDS-<slug>-<date>/wisdom .workflow/.team/UDS-<slug>-<date>/.msg") -``` +| Mode | Task Chain | +|------|------------| +| component | RESEARCH-001 -> DESIGN-001 -> AUDIT-001 -> BUILD-001 | +| system | RESEARCH-001 -> DESIGN-001 -> AUDIT-001 -> [DESIGN-002 + BUILD-001] -> AUDIT-002 -> BUILD-002 | +| full-system | system chain + AUDIT-003 after BUILD-002 | -2. Write session.json: +## Phase 4: Spawn-and-Stop -```json -{ - "status": "active", - "team_name": "uidesign", - "requirement": "<requirement>", - "timestamp": "<ISO-8601>", - "pipeline": "<component|system|full-system>", - "industry": "<industry>", - "sync_points": [], - "gc_state": { "round": 0, "max_rounds": 2, "converged": false }, - "fix_cycles": {} -} -``` - -3. Initialize .msg/meta.json with pipeline metadata: -```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json -mcp__ccw-tools__team_msg({ - operation: "log", - session_id: "<session-id>", - from: "coordinator", - type: "state_update", - summary: "Session initialized", - data: { - pipeline_mode: "<component|system|full-system>", - pipeline_stages: ["researcher", "designer", "reviewer", "implementer"], - roles: ["coordinator", "researcher", "designer", "reviewer", "implementer"], - team_name: "uidesign" - } -}) -``` - -4. Create team: - -``` -TeamCreate({ team_name: "uidesign" }) -``` - ---- - -## Phase 3: Task Chain Creation - -Execute `commands/dispatch.md` inline (Command Execution Protocol): - -1. Read `roles/coordinator/commands/dispatch.md` -2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) -3. Result: all pipeline tasks created with correct blockedBy dependencies - ---- - -## Phase 4: Spawn & Coordination Loop - -### Initial Spawn - -Find first unblocked task and spawn its worker: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn researcher worker", - team_name: "uidesign", - name: "researcher", - run_in_background: true, - prompt: `## Role Assignment -role: researcher -role_spec: .claude/skills/team-uidesign/role-specs/researcher.md -session: <session-folder> -session_id: <session-id> -team_name: uidesign -requirement: <requirement> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` - -**STOP** after spawning. Wait for worker callback. - -### Coordination (via monitor.md handlers) - -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 - ---- +Delegate to `commands/monitor.md#handleSpawnNext`: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action -1. Load session state -> count completed tasks, calculate duration +1. Read session state -> collect all results 2. List deliverables: | Deliverable | Path | @@ -262,29 +140,26 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger | Token Files | <session>/build/token-files/* | | Component Files | <session>/build/component-files/* | -3. Output pipeline summary: task count, duration, GC rounds, sync points passed, final audit score +3. Calculate: completed_tasks, gc_rounds, sync_points_passed, final_audit_score +4. Output pipeline summary with [coordinator] prefix +5. Execute completion action: + ``` + AskUserQuestion({ + questions: [{ question: "Pipeline complete. What next?", header: "Completion", options: [ + { label: "Archive & Clean", description: "Archive session and clean up team resources" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to specified location" } + ]}] + }) + ``` -4. **Completion Action** (interactive): +## Error Handling -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -5. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-uidesign', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | +| Error | Resolution | +|-------|------------| +| Task timeout | Log, mark failed, ask user to retry or skip | +| Worker crash | Reset task to pending, respawn worker | +| Dependency cycle | Detect, report to user, halt | +| Invalid scope | Reject with error, ask to clarify | +| Session corruption | Attempt recovery, fallback to manual reconciliation | +| GC loop stuck > 2 rounds | Escalate to user: accept / try one more / terminate | diff --git a/.claude/skills/team-uidesign/roles/designer/role.md b/.claude/skills/team-uidesign/roles/designer/role.md new file mode 100644 index 00000000..3c56d9b6 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/designer/role.md @@ -0,0 +1,69 @@ +--- +role: designer +prefix: DESIGN +inner_loop: false +message_types: [state_update] +--- + +# Design Token & Component Spec Author + +Define visual language through design tokens (W3C Design Tokens Format) and component specifications. Consume design intelligence from researcher. Act as Generator in the designer<->reviewer Generator-Critic loop. + +## Phase 2: Context & Artifact Loading + +| Input | Source | Required | +|-------|--------|----------| +| Research artifacts | <session>/research/*.json | Yes | +| Design intelligence | <session>/research/design-intelligence.json | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | +| Audit feedback | <session>/audit/audit-*.md | Only for GC fix tasks | + +1. Extract session path from task description +2. Read research findings: design-system-analysis.json, component-inventory.json, accessibility-audit.json +3. Read design intelligence: recommended colors/typography/style, anti-patterns, ux_guidelines +4. Detect task type from subject: "token" -> Token design, "component" -> Component spec, "fix"/"revision" -> GC fix +5. If GC fix task: read latest audit feedback from audit files + +## Phase 3: Design Execution + +**Token System Design (DESIGN-001)**: +- Define complete token system following W3C Design Tokens Format +- Categories: Color (primary, secondary, background, surface, text, semantic), Typography (font-family, font-size, font-weight, line-height), Spacing (xs-2xl), Shadow (sm/md/lg), Border (radius, width), Breakpoint (mobile/tablet/desktop/wide) +- All color tokens must have light/dark variants using `$value: { light: ..., dark: ... }` +- Integrate design intelligence: recommended.colors -> color tokens, recommended.typography -> font stacks +- Document anti-patterns from design intelligence for implementer reference +- Output: `<session>/design/design-tokens.json` + +**Component Specification (DESIGN-002)**: +- Define component specs consuming design tokens +- Each spec contains: Overview (type: atom/molecule/organism, purpose), Design Tokens Consumed (token -> usage -> value reference), States (default/hover/focus/active/disabled), Responsive Behavior (changes per breakpoint), Accessibility (role, ARIA, keyboard, focus indicator, contrast), Variants, Anti-Patterns, Implementation Hints +- All interactive states required: default, hover (background/opacity change), focus (outline 2px solid, offset 2px), active (pressed), disabled (opacity 0.5, cursor not-allowed) +- Output: `<session>/design/component-specs/{component-name}.md` + +**GC Fix Mode (DESIGN-fix-N)**: +- Parse audit feedback for specific issues +- Re-read affected design artifacts; apply fixes (token value adjustments, missing states, accessibility gaps, naming fixes) +- Re-write affected files; signal `design_revision` instead of `design_ready` + +## Phase 4: Self-Validation & Output + +1. Token integrity checks: + +| Check | Pass Criteria | +|-------|---------------| +| tokens_valid | All $value fields non-empty | +| theme_complete | Light/dark values for all color tokens | +| values_parseable | Valid CSS-parseable values | +| no_duplicates | No duplicate token definitions | + +2. Component spec checks: + +| Check | Pass Criteria | +|-------|---------------| +| states_complete | All 5 states (default/hover/focus/active/disabled) defined | +| a11y_specified | Role, ARIA, keyboard behavior defined | +| responsive_defined | At least mobile/desktop breakpoints | +| token_refs_valid | All `{token.path}` references resolve to defined tokens | + +3. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace: + - Read existing -> merge `{ "designer": { task_type, token_categories, component_count, style_decisions } }` -> write back diff --git a/.claude/skills/team-uidesign/roles/implementer/role.md b/.claude/skills/team-uidesign/roles/implementer/role.md new file mode 100644 index 00000000..269656a9 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/implementer/role.md @@ -0,0 +1,72 @@ +--- +role: implementer +prefix: BUILD +inner_loop: false +message_types: [state_update] +--- + +# Component Code Builder + +Translate design tokens and component specifications into production code. Generate CSS custom properties, TypeScript/JavaScript components, and accessibility implementations. Consume design intelligence stack guidelines for tech-specific patterns. + +## Phase 2: Context & Artifact Loading + +| Input | Source | Required | +|-------|--------|----------| +| Design tokens | <session>/design/design-tokens.json | Yes (token build) | +| Component specs | <session>/design/component-specs/*.md | Yes (component build) | +| Design intelligence | <session>/research/design-intelligence.json | Yes | +| Latest audit report | <session>/audit/audit-*.md | No | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | + +1. Extract session path from task description +2. Detect build type from subject: "token" -> Token implementation, "component" -> Component implementation +3. Read design artifacts: design-tokens.json (token build), component-specs/*.md (component build) +4. Read design intelligence: stack_guidelines (tech-specific patterns), anti_patterns (patterns to avoid), ux_guidelines +5. Read latest audit report for approved changes and feedback +6. Detect project tech stack from package.json + +## Phase 3: Implementation Execution + +**Token Implementation (BUILD-001)**: +- Convert design tokens to production code +- Output files in `<session>/build/token-files/`: + - `tokens.css`: CSS custom properties with `:root` (light) and `[data-theme="dark"]` selectors, plus `@media (prefers-color-scheme: dark)` fallback + - `tokens.ts`: TypeScript constants and types for programmatic access with autocomplete support + - `README.md`: Token usage guide +- All color tokens must have both light and dark values +- Semantic token names must match design token definitions + +**Component Implementation (BUILD-002)**: +- Implement component code from design specifications +- Per-component output in `<session>/build/component-files/`: + - `{ComponentName}.tsx`: React/Vue/Svelte component (match detected stack) + - `{ComponentName}.css`: Styles consuming tokens via `var(--token-name)` only + - `{ComponentName}.test.tsx`: Basic render + state tests + - `index.ts`: Re-export +- Requirements: no hardcoded colors/spacing (use design tokens), implement all 5 states, add ARIA attributes per spec, support responsive breakpoints, follow project component patterns +- Accessibility: keyboard navigation, screen reader support, visible focus indicators, WCAG AA contrast +- Check implementation against design intelligence anti_patterns + +## Phase 4: Validation & Output + +1. Token build validation: + +| Check | Pass Criteria | +|-------|---------------| +| File existence | tokens.css and tokens.ts exist | +| Token coverage | All defined tokens present in CSS | +| Theme support | Light/dark variants exist | + +2. Component build validation: + +| Check | Pass Criteria | +|-------|---------------| +| File existence | At least 3 files per component (component, style, index) | +| No hardcoded values | No `#xxx` or `rgb()` in component CSS (only in tokens.css) | +| Focus styles | `:focus` or `:focus-visible` defined | +| Responsive | `@media` queries present | +| Anti-pattern clean | No violations of design intelligence anti_patterns | + +3. Update `<session>/wisdom/.msg/meta.json` under `implementer` namespace: + - Read existing -> merge `{ "implementer": { build_type, file_count, output_dir, components_built } }` -> write back diff --git a/.claude/skills/team-uidesign/roles/researcher/role.md b/.claude/skills/team-uidesign/roles/researcher/role.md new file mode 100644 index 00000000..73d2e8f1 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/researcher/role.md @@ -0,0 +1,82 @@ +--- +role: researcher +prefix: RESEARCH +inner_loop: false +message_types: [state_update] +--- + +# Design System Researcher + +Analyze existing design system, build component inventory, assess accessibility baseline, and retrieve industry-specific design intelligence via ui-ux-pro-max. Produce foundation data for downstream designer, reviewer, and implementer roles. + +## Phase 2: Context & Environment Detection + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | No | + +1. Extract session path and target scope from task description +2. Detect project type and tech stack from package.json or equivalent: + +| Package | Detected Stack | +|---------|---------------| +| next | nextjs | +| react | react | +| vue | vue | +| svelte | svelte | +| @shadcn/ui | shadcn | +| (default) | html-tailwind | + +3. Use CLI tools (e.g., `ccw cli -p "..." --tool gemini --mode analysis`) or direct tools (Glob, Grep, mcp__ace-tool__search_context) to scan for existing design tokens, component files, styling patterns +4. Read industry context from session config (industry, strictness, must-have features) + +## Phase 3: Research Execution + +Execute 4 analysis streams: + +**Stream 1 -- Design System Analysis**: +- Search for existing design tokens (CSS variables, theme configs, token files) +- Identify styling patterns (CSS-in-JS, CSS modules, utility classes, SCSS) +- Map color palette, typography scale, spacing system +- Find component library usage (MUI, Ant Design, shadcn, custom) +- Output: `<session>/research/design-system-analysis.json` + +**Stream 2 -- Component Inventory**: +- Find all UI component files; identify props/API surface +- Identify states supported (hover, focus, disabled, etc.) +- Check accessibility attributes (ARIA labels, roles) +- Map inter-component dependencies and usage counts +- Output: `<session>/research/component-inventory.json` + +**Stream 3 -- Accessibility Baseline**: +- Check ARIA attribute usage patterns, keyboard navigation support +- Assess color contrast ratios (if design tokens found) +- Find focus management and semantic HTML patterns +- Output: `<session>/research/accessibility-audit.json` + +**Stream 4 -- Design Intelligence (ui-ux-pro-max)**: +- Call `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` for design system recommendations +- Call `Skill(skill="ui-ux-pro-max", args="accessibility animation responsive --domain ux")` for UX guidelines +- Call `Skill(skill="ui-ux-pro-max", args="<keywords> --stack <detected-stack>")` for stack guidelines +- Degradation: when unavailable, use LLM general knowledge, mark `_source: "llm-general-knowledge"` +- Output: `<session>/research/design-intelligence.json` + +Compile research summary metrics: design_system_exists, styling_approach, total_components, accessibility_level, design_intelligence_source, anti_patterns_count. + +## Phase 4: Validation & Output + +1. Verify all 4 output files exist and contain valid JSON with required fields: + +| File | Required Fields | +|------|----------------| +| design-system-analysis.json | existing_tokens, styling_approach | +| component-inventory.json | components array | +| accessibility-audit.json | wcag_level | +| design-intelligence.json | _source, design_system | + +2. If any file missing or invalid, re-run corresponding stream + +3. Update `<session>/wisdom/.msg/meta.json` under `researcher` namespace: + - Read existing -> merge `{ "researcher": { detected_stack, component_count, wcag_level, di_source, scope } }` -> write back diff --git a/.claude/skills/team-uidesign/roles/reviewer/role.md b/.claude/skills/team-uidesign/roles/reviewer/role.md new file mode 100644 index 00000000..497c1704 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/reviewer/role.md @@ -0,0 +1,67 @@ +--- +role: reviewer +prefix: AUDIT +inner_loop: false +message_types: [state_update] +--- + +# Design Auditor + +Audit design tokens and component specs for consistency, accessibility compliance, completeness, quality, and industry best-practice adherence. Act as Critic in the designer<->reviewer Generator-Critic loop. Serve as sync point gatekeeper in dual-track pipelines. + +## Phase 2: Context & Artifact Loading + +| Input | Source | Required | +|-------|--------|----------| +| Design artifacts | <session>/design/*.json, <session>/design/component-specs/*.md | Yes | +| Design intelligence | <session>/research/design-intelligence.json | Yes | +| Audit history | .msg/meta.json -> reviewer namespace | No | +| Build artifacts | <session>/build/**/* | Only for final audit | +| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes | + +1. Extract session path from task description +2. Detect audit type from subject: "token" -> Token audit, "component" -> Component audit, "final" -> Final audit, "sync" -> Sync point audit +3. Read design intelligence for anti-patterns and ux_guidelines +4. Read design artifacts: design-tokens.json (token/component audit), component-specs/*.md (component/final audit), build/**/* (final audit only) +5. Load audit_history from meta.json for trend analysis + +## Phase 3: Audit Execution + +Score 5 dimensions on 1-10 scale: + +| Dimension | Weight | Focus | +|-----------|--------|-------| +| Consistency | 20% | Token usage, naming conventions, visual uniformity | +| Accessibility | 25% | WCAG AA compliance, ARIA attributes, keyboard nav, contrast | +| Completeness | 20% | All states defined, responsive specs, edge cases | +| Quality | 15% | Token reference integrity, documentation clarity, maintainability | +| Industry Compliance | 20% | Anti-pattern avoidance, UX best practices, design intelligence adherence | + +**Token Audit**: Naming convention (kebab-case, semantic names), value patterns (consistent units), theme completeness (light+dark for all colors), contrast ratios (text on background >= 4.5:1), minimum font sizes (>= 12px), all categories present, W3C $type metadata, no duplicates. + +**Component Audit**: Token references resolve, naming matches convention, ARIA roles defined, keyboard behavior specified, focus indicator defined, all 5 states present, responsive breakpoints specified, variants documented, clear descriptions. + +**Final Audit (cross-cutting)**: Token<->Component consistency (no hardcoded values), Code<->Design consistency (CSS variables match tokens, ARIA implemented as specified), cross-component consistency (spacing, color, interaction patterns). + +**Score calculation**: `overallScore = round(consistency*0.20 + accessibility*0.25 + completeness*0.20 + quality*0.15 + industryCompliance*0.20)` + +**Signal determination**: + +| Condition | Signal | +|-----------|--------| +| Score >= 8 AND critical_count === 0 | `audit_passed` (GC CONVERGED) | +| Score >= 6 AND critical_count === 0 | `audit_result` (GC REVISION NEEDED) | +| Score < 6 OR critical_count > 0 | `fix_required` (CRITICAL FIX NEEDED) | + +## Phase 4: Report & Output + +1. Write audit report to `<session>/audit/audit-{NNN}.md`: + - Summary: overall score, signal, critical/high/medium counts + - Sync Point Status (if applicable): PASSED/BLOCKED + - Dimension Scores table (score/weight/weighted per dimension) + - Critical/High/Medium issues with descriptions, locations, fix suggestions + - GC Loop Status: signal, action required + - Trend analysis (if audit_history exists): improving/stable/declining + +2. Update `<session>/wisdom/.msg/meta.json` under `reviewer` namespace: + - Read existing -> merge `{ "reviewer": { audit_id, score, critical_count, signal, is_sync_point, audit_type, timestamp } }` -> write back diff --git a/.claude/skills/team-uidesign/specs/pipelines.md b/.claude/skills/team-uidesign/specs/pipelines.md new file mode 100644 index 00000000..6c3ea056 --- /dev/null +++ b/.claude/skills/team-uidesign/specs/pipelines.md @@ -0,0 +1,76 @@ +# Pipeline Definitions + +UI design pipeline modes and task registry. + +## Pipeline Modes + +| Mode | Description | Task Count | +|------|-------------|------------| +| component | Single component: research -> design -> audit -> build | 4 tasks | +| system | Design system: dual-track with 2 sync points | 7 tasks | +| full-system | Full design system + final integrated audit | 8 tasks | + +## Component Pipeline Task Registry + +| Task ID | Role | blockedBy | Description | +|---------|------|-----------|-------------| +| RESEARCH-001 | researcher | [] | Design system analysis, component inventory, accessibility baseline | +| DESIGN-001 | designer | [RESEARCH-001] | Design tokens + component spec with all 5 interactive states | +| AUDIT-001 | reviewer | [DESIGN-001] | 5-dimension audit: consistency, accessibility, completeness, quality, compliance | +| BUILD-001 | implementer | [AUDIT-001] | CSS custom properties + component code + ARIA + keyboard navigation | + +## System Pipeline Task Registry + +| Task ID | Role | blockedBy | Description | +|---------|------|-----------|-------------| +| RESEARCH-001 | researcher | [] | Design system analysis across all components | +| DESIGN-001 | designer | [RESEARCH-001] | Token system design | +| AUDIT-001 | reviewer | [DESIGN-001] | Token audit [Sync Point 1: QUALITY-001] | +| DESIGN-002 | designer | [AUDIT-001] | Component specification (parallel) | +| BUILD-001 | implementer | [AUDIT-001] | Token code implementation (parallel) | +| AUDIT-002 | reviewer | [DESIGN-002] | Component audit [Sync Point 2] | +| BUILD-002 | implementer | [AUDIT-002, BUILD-001] | Component code implementation | + +## Full-System Pipeline Task Registry + +Same as System pipeline, plus: + +| Task ID | Role | blockedBy | Description | +|---------|------|-----------|-------------| +| AUDIT-003 | reviewer | [BUILD-002] | Final integrated audit (cross-cutting) | + +## Checkpoints / Sync Points + +| Checkpoint | Task | Condition | Action | +|------------|------|-----------|--------| +| QUALITY-001: Sync Point 1 | AUDIT-001 completes | Score >= 8, critical == 0 | Unblock DESIGN-002 + BUILD-001 (parallel) | +| QUALITY-001: GC Loop | AUDIT-* completes | Score < 8 or critical > 0 | Create DESIGN-fix task, new AUDIT task (max 2 rounds) | + +## GC Loop Behavior + +| Signal | Condition | Action | +|--------|-----------|--------| +| audit_passed | Score >= 8, critical == 0 | GC converged -> record sync_point -> unblock downstream | +| audit_result | Score 6-7, no critical | gc_rounds < max -> create DESIGN-fix task | +| fix_required | Score < 6 or critical > 0 | gc_rounds < max -> create DESIGN-fix task (CRITICAL) | +| Any | gc_rounds >= max | Escalate to user: accept / try one more / terminate | + +## Parallel Spawn Rules + +| Mode | After | Spawn Behavior | +|------|-------|----------------| +| component | Sequential | One task at a time | +| system | Sync Point 1 (AUDIT-001) | Spawn DESIGN-002 + BUILD-001 in parallel | +| system | AUDIT-002 | Spawn BUILD-002 | +| full-system | Sync Point 1 (AUDIT-001) | Spawn DESIGN-002 + BUILD-001 in parallel | +| full-system | BUILD-002 | Spawn AUDIT-003 | + +## Output Artifacts + +| Task | Output Path | +|------|-------------| +| RESEARCH-001 | <session>/research/*.json | +| DESIGN-001 | <session>/design/design-tokens.json + component-specs/*.md | +| AUDIT-* | <session>/audit/audit-<NNN>.md | +| BUILD-001 | <session>/build/token-files/* | +| BUILD-002 | <session>/build/component-files/* | diff --git a/.claude/skills/team-ultra-analyze/SKILL.md b/.claude/skills/team-ultra-analyze/SKILL.md index a9eef8f3..a10b7b3f 100644 --- a/.claude/skills/team-ultra-analyze/SKILL.md +++ b/.claude/skills/team-ultra-analyze/SKILL.md @@ -1,362 +1,70 @@ --- name: team-ultra-analyze -description: Unified team skill for deep collaborative analysis. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team ultra-analyze", "team analyze". +description: Deep collaborative analysis team skill. All roles route via this SKILL.md. Beat model is coordinator-only (monitor.md). Structure is roles/ + specs/. Triggers on "team ultra-analyze", "team analyze". allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) --- # Team Ultra Analyze -Deep collaborative analysis team skill. Splits monolithic analysis into 5-role collaboration: explore -> analyze -> discuss -> synthesize. Supports Quick/Standard/Deep pipeline modes with configurable depth (N parallel agents). Discussion loops enable user-guided progressive understanding. All members route via `--role=xxx`. +Deep collaborative analysis: explore -> analyze -> discuss -> synthesize. Supports Quick/Standard/Deep pipeline modes with configurable depth (N parallel agents). Discussion loops enable user-guided progressive understanding. ## Architecture ``` -+---------------------------------------------------+ -| Skill(skill="team-ultra-analyze") | -| args="<topic-description>" | -+-------------------+-------------------------------+ +Skill(skill="team-ultra-analyze", args="<topic>") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+ - v v v v - [tw] [tw] [tw] [tw] -explor- analy- discu- synthe- -er st ssant sizer + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze -> dispatch -> spawn workers -> STOP + | + +-------+-------+-------+-------+ + v v v v + [team-worker agents, each loads roles/<role>/role.md] -(tw) = team-worker agent +Pipeline (Standard mode): + [EXPLORE-1..N](parallel) -> [ANALYZE-1..N](parallel) -> DISCUSS-001 -> SYNTH-001 + +Pipeline (Deep mode): + [EXPLORE-1..N] -> [ANALYZE-1..N] -> DISCUSS-001 -> ANALYZE-fix -> DISCUSS-002 -> ... -> SYNTH-001 + +Pipeline (Quick mode): + EXPLORE-001 -> ANALYZE-001 -> SYNTH-001 ``` -## Command Architecture +## Role Registry -``` -roles/ -+-- coordinator/ -| +-- role.md # Orchestration: topic clarification, pipeline selection, discussion loop, reporting -| +-- commands/ -| +-- dispatch.md # Task chain creation and dependency management -| +-- monitor.md # Progress monitoring + discussion loop -+-- explorer/ -| +-- role.md # Codebase exploration -| +-- commands/ -| +-- explore.md # cli-explore-agent parallel exploration -+-- analyst/ -| +-- role.md # Deep analysis -| +-- commands/ -| +-- analyze.md # CLI multi-perspective analysis -+-- discussant/ -| +-- role.md # Discussion processing + direction adjustment -| +-- commands/ -| +-- deepen.md # Deep-dive exploration -+-- synthesizer/ - +-- role.md # Synthesis and conclusions - +-- commands/ - +-- synthesize.md # Cross-perspective integration -``` - -**Design principle**: role.md retains Phase 1 (Task Discovery) and Phase 5 (Report) inline. Phase 2-4 delegate to `commands/*.md` based on complexity. +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| explorer | [roles/explorer/role.md](roles/explorer/role.md) | EXPLORE-* | false | +| analyst | [roles/analyst/role.md](roles/analyst/role.md) | ANALYZE-* | false | +| discussant | [roles/discussant/role.md](roles/discussant/role.md) | DISCUSS-* | false | +| synthesizer | [roles/synthesizer/role.md](roles/synthesizer/role.md) | SYNTH-* | false | ## Role Router -### Input Parsing +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -Parse `$ARGUMENTS` to extract `--role` and optional `--agent-name`. If `--role` is absent, enter Orchestration Mode (auto route to coordinator). The `--agent-name` parameter supports parallel instances (e.g., explorer-1, analyst-2) and is passed through to role.md for task discovery filtering. +## Shared Constants -### Role Registry +- **Session prefix**: `UAN` +- **Session path**: `.workflow/.team/UAN-<slug>-<date>/` +- **Team name**: `ultra-analyze` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` -| Role | Spec | Task Prefix | Inner Loop | -|------|------|-------------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - | -| explorer | [role-specs/explorer.md](role-specs/explorer.md) | EXPLORE-* | false | -| analyst | [role-specs/analyst.md](role-specs/analyst.md) | ANALYZE-* | false | -| discussant | [role-specs/discussant.md](role-specs/discussant.md) | DISCUSS-* | false | -| synthesizer | [role-specs/synthesizer.md](role-specs/synthesizer.md) | SYNTH-* | false | +## Worker Spawn Template -> **COMPACT PROTECTION**: Role files are execution documents, not reference material. When context compression occurs and role instructions are reduced to summaries, you **must immediately `Read` the corresponding role.md to reload before continuing execution**. Never execute any Phase based on compressed summaries alone. - -### 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 the analysis topic. - -**Invocation**: `Skill(skill="team-ultra-analyze", args="analysis topic description")` - -**Lifecycle**: -``` -User provides analysis topic - -> coordinator Phase 1-3: topic clarification -> TeamCreate -> pipeline selection -> create task chain - -> coordinator Phase 4: spawn depth explorers in parallel (background) -> STOP - -> Explorers execute -> SendMessage callback -> coordinator spawns analysts - -> Analysts execute -> SendMessage callback -> coordinator spawns discussant - -> Discussion loop (Deep mode: user feedback -> deepen -> re-analyze -> repeat) - -> coordinator spawns synthesizer -> final conclusions -> Phase 5 report -``` - -**User Commands** (wake suspended coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status diagram, do not advance pipeline | -| `resume` / `continue` | Check worker status, advance to next pipeline step | - ---- - -## Shared Infrastructure - -The following templates apply to all worker roles. Each role.md only needs to define **Phase 2-4** role-specific logic. - -### Worker Phase 1: Task Discovery (shared by all workers) - -Each worker executes the same task discovery flow on startup: - -1. Call `TaskList()` to get all tasks -2. Filter: subject matches this role's prefix + owner matches this agent's name + status is pending + blockedBy is empty -3. No tasks -> idle wait -4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress - -**Resume Artifact Check** (prevent duplicate output after recovery): -- Check if this task's output artifacts already exist -- Artifacts complete -> skip to Phase 5 report completion -- Artifacts incomplete or missing -> execute Phase 2-4 normally - -### Worker Phase 5: Report (shared by all workers) - -Standard report flow after task completion: - -1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} - - `to` and `summary` auto-defaulted -- do NOT specify explicitly - - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -2. **SendMessage**: Send result to coordinator (both content and summary prefixed with `[<role>]`) -3. **TaskUpdate**: Mark task completed -4. **Loop**: Return to Phase 1 to check for next task - -### Wisdom Accumulation (all roles) - -Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory during session initialization. - -**Directory**: -``` -<session-folder>/wisdom/ -+-- learnings.md # Patterns and insights -+-- decisions.md # Analysis direction decisions -+-- conventions.md # Codebase conventions discovered -+-- issues.md # Known risks and issues -``` - -**Worker load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files. -**Worker contribute** (Phase 4/5): Write discoveries from this task into corresponding wisdom files. - -### Role Isolation Rules - -| Allowed | Prohibited | -|---------|-----------| -| Process tasks matching own prefix | Process tasks with other role prefixes | -| SendMessage to coordinator | Communicate directly with other workers | -| Share state via team_msg(type='state_update') | Create tasks for other roles | -| Delegate to commands/*.md | Modify resources outside own responsibility | - -Coordinator additionally prohibited: directly executing code exploration or analysis, directly calling cli-explore-agent or CLI analysis tools, bypassing workers to complete work. - -### Cross-Role State - -Cross-role state managed via `team_msg(type='state_update')`, stored in `.msg/meta.json.role_state`. Each role reads all states but writes only to its own designated field: - -| Role | State Field | -|------|-------------| -| explorer | `explorations` | -| analyst | `analyses` | -| discussant | `discussions` | -| synthesizer | `synthesis` | -| coordinator | `decision_trail` + `current_understanding` | - -On startup, read role states via `team_msg(operation="get_state", session_id=<session-id>)`. After completing work, share results via `team_msg(operation="log", session_id=<session-id>, from=<role>, type="state_update", data={...})`. - -### Message Bus (All Roles) - -All roles log messages before sending via SendMessage. Call `mcp__ccw-tools__team_msg` with: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<file-path>"}. `to` and `summary` are auto-defaulted. - - - -| Role | Types | -|------|-------| -| coordinator | `pipeline_selected`, `discussion_round`, `direction_adjusted`, `task_unblocked`, `error`, `shutdown` | -| explorer | `exploration_ready`, `error` | -| analyst | `analysis_ready`, `error` | -| discussant | `discussion_processed`, `error` | -| synthesizer | `synthesis_ready`, `error` | - -**CLI fallback**: When MCP unavailable -> `ccw team log --session-id <session-id> --from <role> --type <type> --json` - - ---- - -## Three-Mode Pipeline Architecture - -``` -Quick: EXPLORE-001 -> ANALYZE-001 -> SYNTH-001 -Standard: [EXPLORE-001..depth](parallel) -> [ANALYZE-001..depth](parallel) -> DISCUSS-001 -> SYNTH-001 -Deep: [EXPLORE-001..depth] -> [ANALYZE-001..depth] -> DISCUSS-001 -> ANALYZE-fix -> DISCUSS-002 -> ... -> SYNTH-001 -``` - -### Mode Auto-Detection - -Parse `--mode` from arguments first. If not specified, auto-detect from topic description: - -| Condition | Mode | Depth | -|-----------|------|-------| -| `--mode=quick` explicit or topic contains "quick/overview/fast" | Quick | 1 | -| `--mode=deep` explicit or topic contains "deep/thorough/detailed/comprehensive" | Deep | N (from perspectives) | -| Default (no match) | Standard | N (from perspectives) | - -**Depth** is determined by the number of selected analysis perspectives (e.g., architecture, implementation, performance, security, concept, comparison, decision). Quick mode always uses depth=1. Standard/Deep mode uses depth = number of selected perspectives. - -### Discussion Loop (Deep Mode) - -``` -coordinator(AskUser) -> DISCUSS-N(deepen) -> [optional ANALYZE-fix] -> coordinator(AskUser) -> ... -> SYNTH -``` - -Maximum 5 discussion rounds. If exceeded, force synthesis and offer continuation option. - -## Decision Recording Protocol - -**CRITICAL**: Inherited from the original analyze-with-file command. During analysis, the following must be immediately recorded to discussion.md: - -| Trigger | What to Record | Target Section | -|---------|---------------|----------------| -| **Direction choice** | What was chosen, why, which alternatives were rejected | `#### Decision Log` | -| **Key finding** | Discovery content, impact scope, confidence level | `#### Key Findings` | -| **Assumption change** | Old assumption -> new understanding, reason for change, impact | `#### Corrected Assumptions` | -| **User feedback** | User's raw input, adoption/adjustment rationale | `#### User Input` | - -## Cadence Control - -**Beat model**: Event-driven. Each beat = coordinator wakes -> processes callback -> spawns next phase -> STOP. - -``` -Beat Cycle (single beat) -===================================================================== - Event Coordinator Workers ---------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [Worker A] Phase 1-5 - | (parallel OK) --+--> [Worker B] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -===================================================================== -``` - -**Discussion Loop Beat (Deep mode with configurable depth)**: - -``` -Phase 1 (explore): Spawn depth explorers simultaneously - EXPLORE-1, EXPLORE-2, ..., EXPLORE-depth (all parallel) - -> All complete -> coordinator wakes - -Phase 2 (analyze): Spawn depth analysts simultaneously - ANALYZE-1, ANALYZE-2, ..., ANALYZE-depth (all parallel) - -> All complete -> coordinator wakes - -Phase 3 (discuss): Spawn 1 discussant - DISCUSS-001 - -> Complete -> coordinator asks user for direction - -Phase 3a (loop): If user requests deeper analysis (Deep mode only): - -> Spawn ANALYZE-fix tasks -> DISCUSS-002 -> ask user -> repeat - -> Maximum 5 rounds - -Phase 4 (synth): Spawn 1 synthesizer - SYNTHESIZE-001 - -> Complete -> coordinator reports to user -``` - -**Pipeline Beat Views**: - -``` -Quick (3 beats, serial) ------------------------------------------------------- -Beat 1 2 3 - | | | - EXPLORE -> ANALYZE -> SYNTH - -Standard (4 beats, parallel windows) ------------------------------------------------------- -Beat 1 2 3 4 - +----- ... ----+ +----- ... ----+ | | - E1 || E2 || EN A1 || A2 || AN -> DISCUSS -> SYNTH - +---- parallel ---+ +---- parallel ---+ - -Deep (4+ beats, with discussion loop) ------------------------------------------------------- -Beat 1 2 3 3a... 4 - +-...-+ +-...-+ | +-- loop --+ | - E1||EN A1||AN -> DISC -> A-fix->DISC -> SYNTH - (max 5 rounds) -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Discussion round (Deep mode) | After DISCUSS-N completes | Pause, AskUser for direction/continuation | -| Discussion loop limit | >5 rounds | Force synthesis, offer continuation | -| Pipeline stall | No ready + no running | Check missing tasks, report to user | - -**Stall detection** (coordinator `handleCheck`): - -| Check | Condition | Resolution | -|-------|-----------|------------| -| Worker unresponsive | in_progress task with no callback | Report waiting tasks, suggest user `resume` | -| Pipeline deadlock | No ready + no running + has pending | Check blockedBy chain, report blockage | -| Discussion loop over limit | DISCUSS round > 5 | Terminate loop, output latest discussion state | - -## Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| EXPLORE-1..depth | explorer | explore | (none) | Parallel codebase exploration, one per perspective | -| ANALYZE-1..depth | analyst | analyze | EXPLORE-1..depth (all complete) | Parallel deep analysis, one per perspective | -| DISCUSS-001 | discussant | discuss | ANALYZE-1..depth (all complete) | Process analysis results, identify gaps | -| ANALYZE-fix-N | analyst | discuss-loop | DISCUSS-N | Re-analysis for specific areas (Deep mode only) | -| DISCUSS-002..N | discussant | discuss-loop | ANALYZE-fix-N | Subsequent discussion rounds (Deep mode, max 5) | -| SYNTHESIZE-001 | synthesizer | synthesize | Last DISCUSS-N | Cross-perspective integration and conclusions | - -**Dynamic task creation**: Coordinator creates EXPLORE-1 through EXPLORE-depth and ANALYZE-1 through ANALYZE-depth based on the number of selected perspectives. Discussion loop tasks (ANALYZE-fix-N, DISCUSS-002+) are created dynamically in Deep mode based on user feedback. - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path. The coordinator determines depth (number of parallel agents) based on selected perspectives. - -**Phase 1 - Spawn Explorers**: Create depth explorer team-worker agents in parallel (EXPLORE-1 through EXPLORE-depth). Each receives its assigned perspective/domain and agent name for task matching. - -**Phase 2 - Spawn Analysts**: After all explorers complete, create depth analyst team-worker agents in parallel (ANALYZE-1 through ANALYZE-depth). - -**Phase 3 - Spawn Discussant**: After all analysts complete, create 1 discussant. Coordinator stops. - -**Phase 3a - Discussion Loop** (Deep mode only): Based on user feedback, coordinator may create additional ANALYZE-fix and DISCUSS tasks. - -**Phase 4 - Spawn Synthesizer**: After final discussion round, create 1 synthesizer. - -**Quick mode exception**: When depth=1, spawn single explorer, single analyst, single discussant, single synthesizer without numbered suffixes. - -**Single spawn template** (worker template used for all roles): +Coordinator spawns workers using this template: ``` Agent({ @@ -367,7 +75,7 @@ Agent({ run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-ultra-analyze/role-specs/<role>.md +role_spec: .claude/skills/team-ultra-analyze/roles/<role>/role.md session: <session-folder> session_id: <session-id> team_name: ultra-analyze @@ -376,37 +84,34 @@ agent_name: <agent-name> inner_loop: false Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery, owner=<agent-name>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery, owner=<agent-name>) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -## Team Configuration +## User Commands -| Setting | Value | -|---------|-------| -| Team name | ultra-analyze | -| Session directory | .workflow/.team/UAN-{slug}-{date}/ | +| Command | Action | +|---------|--------| +| `check` / `status` | Output execution status diagram, do not advance pipeline | +| `resume` / `continue` | Check worker status, advance to next pipeline step | -| Analysis dimensions | architecture, implementation, performance, security, concept, comparison, decision | -| Max discussion rounds | 5 | - -## Unified Session Directory +## Session Directory ``` .workflow/.team/UAN-{slug}-{YYYY-MM-DD}/ +-- .msg/messages.jsonl # Message bus log -+-- .msg/meta.json # Session metadata -+-- discussion.md # Understanding evolution and discussion timeline -+-- explorations/ # Explorer output ++-- .msg/meta.json # Session metadata + cross-role state ++-- discussion.md # Understanding evolution and discussion timeline ++-- explorations/ # Explorer output | +-- exploration-001.json | +-- exploration-002.json -+-- analyses/ # Analyst output ++-- analyses/ # Analyst output | +-- analysis-001.json | +-- analysis-002.json -+-- discussions/ # Discussant output ++-- discussions/ # Discussant output | +-- discussion-round-001.json -+-- conclusions.json # Synthesizer output -+-- wisdom/ # Cross-task knowledge ++-- conclusions.json # Synthesizer output ++-- wisdom/ # Cross-task knowledge | +-- learnings.md | +-- decisions.md | +-- conventions.md @@ -415,7 +120,7 @@ Execute built-in Phase 1 (task discovery, owner=<agent-name>) -> role-spec Phase ## Completion Action -When the pipeline completes (all tasks done, coordinator Phase 5): +When pipeline completes, coordinator presents: ``` AskUserQuestion({ @@ -435,29 +140,21 @@ AskUserQuestion({ | Choice | Action | |--------|--------| | Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-ultra-analyze", args="resume")` | +| Keep Active | Update session status="paused" -> output resume instructions | | Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | -## Session Resume +## Specs Reference -Coordinator supports `--resume` / `--continue` for interrupted sessions: - -1. Scan `.workflow/.team/UAN-*/` for active/paused sessions -2. Multiple matches -> AskUserQuestion for selection -3. Audit TaskList -> reconcile session state with 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 +- [specs/team-config.json](specs/team-config.json) — Team configuration and pipeline settings ## Error Handling | Scenario | Resolution | |----------|------------| -| Unknown --role value | Error with available role list | -| Missing --role arg | Orchestration Mode -> coordinator | +| Unknown --role value | Error with role registry list | | Role file not found | Error with expected path (roles/{name}/role.md) | -| Task prefix conflict | Log warning, proceed | | Discussion loop stuck >5 rounds | Force synthesis, offer continuation | | CLI tool unavailable | Fallback chain: gemini -> codex -> manual analysis | | Explorer agent fails | Continue with available context, note limitation | +| Fast-advance conflict | Coordinator reconciles on next callback | +| Completion action fails | Default to Keep Active | diff --git a/.claude/skills/team-ultra-analyze/roles/analyst/role.md b/.claude/skills/team-ultra-analyze/roles/analyst/role.md new file mode 100644 index 00000000..f4dbaaa4 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/roles/analyst/role.md @@ -0,0 +1,90 @@ +--- +role: analyst +prefix: ANALYZE +inner_loop: false +additional_prefixes: [ANALYZE-fix] +message_types: + success: analysis_ready + error: error +--- + +# Deep Analyst + +Perform deep multi-perspective analysis on exploration results via CLI tools. Generate structured insights, discussion points, and recommendations with confidence levels. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Exploration results | `<session>/explorations/*.json` | Yes | + +1. Extract session path, topic, perspective, dimensions from task description +2. Detect direction-fix mode: `type:\s*direction-fix` with `adjusted_focus:\s*(.+)` +3. Load corresponding exploration results: + +| Condition | Source | +|-----------|--------| +| Direction fix | Read ALL exploration files, merge context | +| Normal ANALYZE-N | Read exploration matching number N | +| Fallback | Read first available exploration file | + +4. Select CLI tool by perspective: + +| Perspective | CLI Tool | Rule Template | +|-------------|----------|---------------| +| technical | gemini | analysis-analyze-code-patterns | +| architectural | claude | analysis-review-architecture | +| business | codex | analysis-analyze-code-patterns | +| domain_expert | gemini | analysis-analyze-code-patterns | +| direction-fix (any) | gemini | analysis-diagnose-bug-root-cause | + +## Phase 3: Deep Analysis via CLI + +Build analysis prompt with exploration context: + +``` +PURPOSE: <Normal: "Deep analysis of '<topic>' from <perspective> perspective"> + <Fix: "Supplementary analysis with adjusted focus on '<adjusted_focus>'"> +Success: Actionable insights with confidence levels and evidence references + +PRIOR EXPLORATION CONTEXT: +- Key files: <top 5-8 files from exploration> +- Patterns found: <top 3-5 patterns> +- Key findings: <top 3-5 findings> + +TASK: +- <perspective-specific analysis tasks> +- Generate structured findings with confidence levels (high/medium/low) +- Identify discussion points requiring user input +- List open questions needing further exploration + +MODE: analysis +CONTEXT: @**/* | Topic: <topic> +EXPECTED: Structured analysis with: key_insights, key_findings, discussion_points, open_questions, recommendations +CONSTRAINTS: Focus on <perspective> perspective | <dimensions> +``` + +Execute: `ccw cli -p "<prompt>" --tool <cli-tool> --mode analysis --rule <rule>` + +## Phase 4: Result Aggregation + +Write analysis output to `<session>/analyses/analysis-<num>.json`: + +```json +{ + "perspective": "<perspective>", + "dimensions": ["<dim1>", "<dim2>"], + "is_direction_fix": false, + "key_insights": [{"insight": "...", "confidence": "high", "evidence": "file:line"}], + "key_findings": [{"finding": "...", "file_ref": "...", "impact": "..."}], + "discussion_points": ["..."], + "open_questions": ["..."], + "recommendations": [{"action": "...", "rationale": "...", "priority": "high"}], + "_metadata": {"cli_tool": "...", "cli_rule": "...", "perspective": "...", "timestamp": "..."} +} +``` + +Update `<session>/wisdom/.msg/meta.json` under `analyst` namespace: +- Read existing -> merge `{ "analyst": { perspective, insight_count, finding_count, is_direction_fix } }` -> write back diff --git a/.claude/skills/team-ultra-analyze/roles/coordinator/commands/analyze.md b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..a1e82f94 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/analyze.md @@ -0,0 +1,73 @@ +# Analyze Task + +Parse topic -> detect pipeline mode and perspectives -> output analysis config. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +### Pipeline Mode Detection + +Parse `--mode` from arguments first. If not specified, auto-detect from topic description: + +| Condition | Mode | Depth | +|-----------|------|-------| +| `--mode=quick` or topic contains "quick/overview/fast" | Quick | 1 | +| `--mode=deep` or topic contains "deep/thorough/detailed/comprehensive" | Deep | N (from perspectives) | +| Default (no match) | Standard | N (from perspectives) | + +### Dimension Detection + +Scan topic keywords to select analysis perspectives: + +| Dimension | Keywords | +|-----------|----------| +| architecture | architecture, design, structure | +| implementation | implement, code, source | +| performance | performance, optimize, speed | +| security | security, auth, vulnerability | +| concept | concept, theory, principle | +| comparison | compare, vs, difference | +| decision | decision, choice, tradeoff | + +**Depth** = number of selected perspectives. Quick mode always uses depth=1. + +## Pipeline Mode Rules + +| Mode | Task Structure | +|------|----------------| +| quick | EXPLORE-001 -> ANALYZE-001 -> SYNTH-001 (serial, depth=1) | +| standard | EXPLORE-001..N (parallel) -> ANALYZE-001..N (parallel) -> DISCUSS-001 -> SYNTH-001 | +| deep | Same as standard but SYNTH-001 omitted (created dynamically after discussion loop) | + +## Output + +Write analysis config to coordinator state (not a file), to be used by dispatch.md: + +```json +{ + "pipeline_mode": "<quick|standard|deep>", + "depth": <number>, + "perspectives": ["<perspective1>", "<perspective2>"], + "topic": "<original topic>", + "dimensions": ["<dim1>", "<dim2>"] +} +``` + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Per perspective | +1 | +| Deep mode | +2 | +| Cross-domain (3+ perspectives) | +1 | + +Results: 1-3 Quick, 4-6 Standard, 7+ Deep (if not explicitly set) + +## Discussion Loop Configuration + +| Mode | Max Discussion Rounds | +|------|----------------------| +| quick | 0 | +| standard | 1 | +| deep | 5 | diff --git a/.claude/skills/team-ultra-analyze/roles/coordinator/role.md b/.claude/skills/team-ultra-analyze/roles/coordinator/role.md index 4e93c520..cb26e511 100644 --- a/.claude/skills/team-ultra-analyze/roles/coordinator/role.md +++ b/.claude/skills/team-ultra-analyze/roles/coordinator/role.md @@ -36,16 +36,6 @@ When coordinator needs to execute a command (dispatch, monitor): 3. **Commands are inline execution guides** -- NOT separate agents or subprocesses 4. **Execute synchronously** -- complete the command workflow before proceeding -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - --- ## Entry Router @@ -54,12 +44,12 @@ When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains role tag [explorer], [analyst], [discussant], [synthesizer] | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Pipeline complete | All tasks have status "completed" | -> handleComplete | -| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) | -| New session | None of above | -> Phase 1 (Topic Understanding) | +| Worker callback | Message contains role tag [explorer], [analyst], [discussant], [synthesizer] | -> handleCallback (monitor.md) | +| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) | +| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session exists | -> Phase 0 | +| New session | None of above | -> Phase 1 | For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. @@ -85,12 +75,7 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match Triggered when an active/paused session is detected on coordinator entry. 1. Load session.json from detected session folder -2. Audit task list: - -``` -TaskList() -``` - +2. Audit task list: `TaskList()` 3. Reconcile session state vs task status: | Task Status | Session Expects | Action | @@ -99,42 +84,19 @@ TaskList() | completed | Already tracked | Skip | | pending + unblocked | Ready to run | Include in spawn list | -4. Rebuild team if not active: - -``` -TeamCreate({ team_name: "ultra-analyze" }) -``` - +4. Rebuild team if not active: `TeamCreate({ team_name: "ultra-analyze" })` 5. Spawn workers for ready tasks -> Phase 4 coordination loop --- ## Phase 1: Topic Understanding & Requirement Clarification +TEXT-LEVEL ONLY. No source code reading. + 1. Parse user task description from $ARGUMENTS 2. Extract explicit settings: `--mode`, scope, focus areas - -3. **Pipeline mode selection**: - -| Condition | Mode | Depth | -|-----------|------|-------| -| `--mode=quick` or topic contains "quick/overview/fast" | Quick | 1 | -| `--mode=deep` or topic contains "deep/thorough/detailed/comprehensive" | Deep | N (from perspectives) | -| Default | Standard | N (from perspectives) | - -4. **Dimension detection** (from topic keywords): - -| Dimension | Keywords | -|-----------|----------| -| architecture | architecture, design, structure | -| implementation | implement, code | -| performance | performance, optimize | -| security | security, auth | -| concept | concept, theory | -| comparison | compare, vs | -| decision | decision, choice | - -5. **Interactive clarification** (non-auto mode): AskUserQuestion for focus, perspectives, depth. +3. Delegate to `commands/analyze.md` for signal detection and pipeline mode selection +4. **Interactive clarification** (non-auto mode): AskUserQuestion for focus, perspectives, depth. --- @@ -156,9 +118,8 @@ TeamCreate({ team_name: "ultra-analyze" }) ``` 3. Write session.json with mode, requirement, timestamp -4. Initialize .msg/meta.json with pipeline metadata: +4. Initialize .msg/meta.json with pipeline metadata via team_msg: ```typescript -// Use team_msg to write pipeline metadata to .msg/meta.json mcp__ccw-tools__team_msg({ operation: "log", session_id: "<session-id>", @@ -173,7 +134,6 @@ mcp__ccw-tools__team_msg({ } }) ``` - 5. Call `TeamCreate({ team_name: "ultra-analyze" })` --- @@ -181,7 +141,6 @@ mcp__ccw-tools__team_msg({ ## Phase 3: Create Task Chain Execute `commands/dispatch.md` inline (Command Execution Protocol): - 1. Read `roles/coordinator/commands/dispatch.md` 2. Follow dispatch Phase 2 -> Phase 3 -> Phase 4 3. Result: all pipeline tasks created with correct blockedBy dependencies @@ -192,38 +151,16 @@ Execute `commands/dispatch.md` inline (Command Execution Protocol): ### Initial Spawn -Find first unblocked tasks and spawn their workers: - -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn explorer worker", - team_name: "ultra-analyze", - name: "explorer", - run_in_background: true, - prompt: `## Role Assignment -role: explorer -role_spec: .claude/skills/team-ultra-analyze/role-specs/explorer.md -session: <session-folder> -session_id: <session-id> -team_name: ultra-analyze -requirement: <topic-description> -inner_loop: false - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` -}) -``` +Find first unblocked tasks and spawn their workers. Use SKILL.md Worker Spawn Template with: +- `role_spec: .claude/skills/team-ultra-analyze/roles/<role>/role.md` +- `team_name: ultra-analyze` +- `inner_loop: false` **STOP** after spawning. Wait for worker callback. ### Coordination (via monitor.md handlers) -All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: - -- handleCallback -> mark task done -> check pipeline -> handleSpawnNext -- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP -- handleComplete -> all done -> Phase 5 +All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks. --- @@ -247,7 +184,7 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger ``` AskUserQuestion({ questions: [{ - question: "Team pipeline complete. What would you like to do?", + question: "Ultra-Analyze pipeline complete. What would you like to do?", header: "Completion", multiSelect: false, options: [ @@ -259,13 +196,7 @@ AskUserQuestion({ }) ``` -6. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions | -| Export Results | AskUserQuestion for target directory -> copy artifacts -> Archive & Clean | +6. Handle user choice per SKILL.md Completion Action section. --- diff --git a/.claude/skills/team-ultra-analyze/roles/discussant/role.md b/.claude/skills/team-ultra-analyze/roles/discussant/role.md new file mode 100644 index 00000000..44c37372 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/roles/discussant/role.md @@ -0,0 +1,107 @@ +--- +role: discussant +prefix: DISCUSS +inner_loop: false +message_types: + success: discussion_processed + error: error +--- + +# Discussant + +Process analysis results and user feedback. Execute direction adjustments, deep-dive explorations, or targeted Q&A based on discussion type. Update discussion timeline. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| Analysis results | `<session>/analyses/*.json` | Yes | +| Exploration results | `<session>/explorations/*.json` | No | + +1. Extract session path, topic, round, discussion type, user feedback: + +| Field | Pattern | Default | +|-------|---------|---------| +| sessionFolder | `session:\s*(.+)` | required | +| topic | `topic:\s*(.+)` | required | +| round | `round:\s*(\d+)` | 1 | +| discussType | `type:\s*(.+)` | "initial" | +| userFeedback | `user_feedback:\s*(.+)` | empty | + +2. Read all analysis and exploration results +3. Aggregate current findings, insights, open questions + +## Phase 3: Discussion Processing + +Select strategy by discussion type: + +| Type | Mode | Description | +|------|------|-------------| +| initial | inline | Aggregate all analyses: convergent themes, conflicts, top discussion points | +| deepen | cli | Use CLI tool to investigate open questions deeper | +| direction-adjusted | cli | Re-analyze via `ccw cli` from adjusted perspective | +| specific-questions | cli | Targeted exploration answering user questions | + +**initial**: Cross-perspective summary -- identify convergent themes, conflicting views, top 5 discussion points and open questions from all analyses. + +**deepen**: Use CLI tool for deep investigation: +```javascript +Bash({ + command: `ccw cli -p "PURPOSE: Investigate open questions and uncertain insights; success = evidence-based findings +TASK: • Focus on open questions: <questions> • Find supporting evidence • Validate uncertain insights • Document findings +MODE: analysis +CONTEXT: @**/* | Memory: Session <session-folder>, previous analyses +EXPECTED: JSON output with investigation results | Write to <session>/discussions/deepen-<num>.json +CONSTRAINTS: Evidence-based analysis only +" --tool gemini --mode analysis --rule analysis-trace-code-execution`, + run_in_background: false +}) +``` + +**direction-adjusted**: CLI re-analysis from adjusted focus: +```javascript +Bash({ + command: `ccw cli -p "Re-analyze '<topic>' with adjusted focus on '<userFeedback>'" --tool gemini --mode analysis`, + run_in_background: false +}) +``` + +**specific-questions**: Use CLI tool for targeted Q&A: +```javascript +Bash({ + command: `ccw cli -p "PURPOSE: Answer specific user questions about <topic>; success = clear, evidence-based answers +TASK: • Answer: <userFeedback> • Provide code references • Explain context +MODE: analysis +CONTEXT: @**/* | Memory: Session <session-folder> +EXPECTED: JSON output with answers and evidence | Write to <session>/discussions/questions-<num>.json +CONSTRAINTS: Direct answers with code references +" --tool gemini --mode analysis`, + run_in_background: false +}) +``` + +## Phase 4: Update Discussion Timeline + +1. Write round content to `<session>/discussions/discussion-round-<num>.json`: +```json +{ + "round": 1, "type": "initial", "user_feedback": "...", + "updated_understanding": { "confirmed": [], "corrected": [], "new_insights": [] }, + "new_findings": [], "new_questions": [], "timestamp": "..." +} +``` + +2. Append round section to `<session>/discussion.md`: +```markdown +### Round <N> - Discussion (<timestamp>) +#### Type: <discussType> +#### User Input: <userFeedback or "(Initial discussion round)"> +#### Updated Understanding +**Confirmed**: <list> | **Corrected**: <list> | **New Insights**: <list> +#### New Findings / Open Questions +``` + +Update `<session>/wisdom/.msg/meta.json` under `discussant` namespace: +- Read existing -> merge `{ "discussant": { round, type, new_insight_count, corrected_count } }` -> write back diff --git a/.claude/skills/team-ultra-analyze/roles/explorer/role.md b/.claude/skills/team-ultra-analyze/roles/explorer/role.md new file mode 100644 index 00000000..994eb140 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/roles/explorer/role.md @@ -0,0 +1,74 @@ +--- +role: explorer +prefix: EXPLORE +inner_loop: false +message_types: + success: exploration_ready + error: error +--- + +# Codebase Explorer + +Explore codebase structure through cli-explore-agent, collecting structured context (files, patterns, findings) for downstream analysis. One explorer per analysis perspective. + +## Phase 2: Context & Scope Assessment + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | + +1. Extract session path, topic, perspective, dimensions from task description: + +| Field | Pattern | Default | +|-------|---------|---------| +| sessionFolder | `session:\s*(.+)` | required | +| topic | `topic:\s*(.+)` | required | +| perspective | `perspective:\s*(.+)` | "general" | +| dimensions | `dimensions:\s*(.+)` | "general" | + +2. Determine exploration number from task subject (EXPLORE-N) +3. Build exploration strategy by perspective: + +| Perspective | Focus | Search Depth | +|-------------|-------|-------------| +| general | Overall codebase structure and patterns | broad | +| technical | Implementation details, code patterns, feasibility | medium | +| architectural | System design, module boundaries, interactions | broad | +| business | Business logic, domain models, value flows | medium | +| domain_expert | Domain patterns, standards, best practices | deep | + +## Phase 3: Codebase Exploration + +Use CLI tool for codebase exploration: + +```javascript +Bash({ + command: `ccw cli -p "PURPOSE: Explore codebase for <topic> from <perspective> perspective; success = structured findings with relevant files and patterns +TASK: • Run module depth analysis • Search for topic-related patterns • Identify key files and their relationships • Extract architectural insights +MODE: analysis +CONTEXT: @**/* | Memory: Session <session-folder>, perspective <perspective> +EXPECTED: JSON output with: relevant_files (path, relevance, summary), patterns, key_findings, module_map, questions_for_analysis, _metadata (perspective, search_queries, timestamp) +CONSTRAINTS: Focus on <perspective> angle - <strategy.focus> | Write to <session>/explorations/exploration-<num>.json +" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, + run_in_background: false +}) +``` + +**ACE fallback** (when CLI produces no output): +```javascript +mcp__ace-tool__search_context({ project_root_path: ".", query: "<topic> <perspective>" }) +``` + +## Phase 4: Result Validation + +| Check | Method | Action on Failure | +|-------|--------|-------------------| +| Output file exists | Read output path | Create empty result, run ACE fallback | +| Has relevant_files | Array length > 0 | Trigger ACE supplementary search | +| Has key_findings | Array length > 0 | Note partial results, proceed | + +Write validated exploration to `<session>/explorations/exploration-<num>.json`. + +Update `<session>/wisdom/.msg/meta.json` under `explorer` namespace: +- Read existing -> merge `{ "explorer": { perspective, file_count, finding_count } }` -> write back diff --git a/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md b/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md new file mode 100644 index 00000000..e6c799ad --- /dev/null +++ b/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md @@ -0,0 +1,78 @@ +--- +role: synthesizer +prefix: SYNTH +inner_loop: false +message_types: + success: synthesis_ready + error: error +--- + +# Synthesizer + +Integrate all explorations, analyses, and discussions into final conclusions. Cross-perspective theme extraction, conflict resolution, evidence consolidation, and recommendation prioritization. Pure integration role -- no external tools or CLI calls. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | From task subject/description | Yes | +| Session path | Extracted from task description | Yes | +| All artifacts | `<session>/explorations/*.json`, `analyses/*.json`, `discussions/*.json` | Yes | +| Decision trail | From wisdom/.msg/meta.json | No | + +1. Extract session path and topic from task description +2. Read all exploration, analysis, and discussion round files +3. Load decision trail and current understanding from meta.json +4. Select synthesis strategy: + +| Condition | Strategy | +|-----------|----------| +| Single analysis, no discussions | simple (Quick mode summary) | +| Multiple analyses, >2 discussion rounds | deep (track evolution) | +| Default | standard (cross-perspective integration) | + +## Phase 3: Cross-Perspective Synthesis + +Execute synthesis across four dimensions: + +**1. Theme Extraction**: Identify convergent themes across all analysis perspectives. Cluster insights by similarity, rank by cross-perspective confirmation count. + +**2. Conflict Resolution**: Identify contradictions between perspectives. Present both sides with trade-off analysis when irreconcilable. + +**3. Evidence Consolidation**: Deduplicate findings, aggregate by file reference. Map evidence to conclusions with confidence levels: + +| Level | Criteria | +|-------|----------| +| High | Multiple sources confirm, strong evidence | +| Medium | Single source or partial evidence | +| Low | Speculative, needs verification | + +**4. Recommendation Prioritization**: Sort all recommendations by priority (high > medium > low), deduplicate, cap at 10. + +Integrate decision trail from discussion rounds into final narrative. + +## Phase 4: Write Conclusions + +1. Write `<session>/conclusions.json`: +```json +{ + "session_id": "...", "topic": "...", "completed": "ISO-8601", + "summary": "Executive summary...", + "key_conclusions": [{"point": "...", "evidence": "...", "confidence": "high"}], + "recommendations": [{"action": "...", "rationale": "...", "priority": "high"}], + "open_questions": ["..."], + "decision_trail": [{"round": 1, "decision": "...", "context": "..."}], + "cross_perspective_synthesis": { "convergent_themes": [], "conflicts_resolved": [], "unique_contributions": [] }, + "_metadata": { "explorations": 3, "analyses": 3, "discussions": 2, "strategy": "standard" } +} +``` + +2. Append conclusions section to `<session>/discussion.md`: +```markdown +## Conclusions +### Summary / Key Conclusions / Recommendations / Remaining Questions +## Decision Trail / Current Understanding (Final) / Session Statistics +``` + +Update `<session>/wisdom/.msg/meta.json` under `synthesizer` namespace: +- Read existing -> merge `{ "synthesizer": { conclusion_count, recommendation_count, open_question_count } }` -> write back diff --git a/.claude/skills/team-ultra-analyze/specs/pipelines.md b/.claude/skills/team-ultra-analyze/specs/pipelines.md new file mode 100644 index 00000000..dea42eea --- /dev/null +++ b/.claude/skills/team-ultra-analyze/specs/pipelines.md @@ -0,0 +1,64 @@ +# Pipeline Definitions — Team Ultra Analyze + +## Pipeline Modes + +### Quick Mode (3 tasks, serial) + +``` +EXPLORE-001 -> ANALYZE-001 -> SYNTH-001 +``` + +| Task | Role | Dependencies | +|------|------|-------------| +| EXPLORE-001 | explorer | (none) | +| ANALYZE-001 | analyst | EXPLORE-001 | +| SYNTH-001 | synthesizer | ANALYZE-001 | + +### Standard Mode (2N+2 tasks, parallel windows) + +``` +[EXPLORE-001..N](parallel) -> [ANALYZE-001..N](parallel) -> DISCUSS-001 -> SYNTH-001 +``` + +| Task | Role | Dependencies | +|------|------|-------------| +| EXPLORE-001..N | explorer | (none, parallel) | +| ANALYZE-001..N | analyst | corresponding EXPLORE-N | +| DISCUSS-001 | discussant | all ANALYZE tasks | +| SYNTH-001 | synthesizer | DISCUSS-001 | + +### Deep Mode (2N+1 tasks initially, dynamic loop) + +Same as Standard but SYNTH-001 is omitted at dispatch. Created dynamically after discussion loop completes. + +Dynamic tasks created during discussion loop: +- `DISCUSS-N` (round N) — created based on user feedback +- `ANALYZE-fix-N` (direction fix) — created when user requests adjusted focus +- `SYNTH-001` — created after final discussion round + +## Task Metadata Registry + +| Task ID | Role | Dependencies | Description | +|---------|------|-------------|-------------| +| EXPLORE-1..depth | explorer | (none) | Parallel codebase exploration, one per perspective | +| ANALYZE-1..depth | analyst | EXPLORE-1..depth (all) | Parallel deep analysis, one per perspective | +| DISCUSS-001 | discussant | ANALYZE-1..depth (all) | Process analysis results, identify gaps | +| ANALYZE-fix-N | analyst | DISCUSS-N | Re-analysis for adjusted focus (Deep mode) | +| DISCUSS-002..N | discussant | ANALYZE-fix-N | Subsequent discussion rounds (Deep mode, max 5) | +| SYNTH-001 | synthesizer | Last DISCUSS-N | Cross-perspective integration and conclusions | + +## Discussion Loop Control + +| Mode | Max Rounds | Trigger | +|------|-----------|---------| +| quick | 0 | No discussion | +| standard | 1 | After DISCUSS-001 | +| deep | 5 | After each DISCUSS-N | + +## Checkpoints + +| Trigger | Location | Behavior | +|---------|----------|----------| +| Discussion round (Deep mode) | After DISCUSS-N completes | Pause, AskUser for direction/continuation | +| Discussion loop limit | >5 rounds | Force synthesis, offer continuation | +| Pipeline stall | No ready + no running | Check missing tasks, report to user | diff --git a/.claude/skills/team-ux-improve/SKILL.md b/.claude/skills/team-ux-improve/SKILL.md index 5c595d74..db7bad68 100644 --- a/.claude/skills/team-ux-improve/SKILL.md +++ b/.claude/skills/team-ux-improve/SKILL.md @@ -1,289 +1,135 @@ --- name: team-ux-improve -description: Unified team skill for UX improvement. Systematically discovers and fixes UI/UX interaction issues including unresponsive buttons, missing feedback, and state refresh problems. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team ux improve". +description: Unified team skill for UX improvement. Systematically discovers and fixes UI/UX interaction issues including unresponsive buttons, missing feedback, and state refresh problems. Uses team-worker agent architecture with roles/ for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team ux improve". allowed-tools: Agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, TaskList, TaskGet, TaskUpdate, TaskCreate, TeamCreate, TeamDelete, SendMessage, mcp__ace-tool__search_context, mcp__ccw-tools__read_file, mcp__ccw-tools__write_file, mcp__ccw-tools__edit_file, mcp__ccw-tools__team_msg --- # Team UX Improve -Unified team skill for systematically discovering and fixing UI/UX interaction issues. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. +Systematic UX improvement pipeline: scan -> diagnose -> design -> implement -> test. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from `roles/<role>/role.md`. ## Architecture ``` -+-------------------------------------------------------------------+ -| Skill(skill="team-ux-improve") | -| args="<project-path> [--framework react|vue]" | -+-------------------+-----------------------------------------------+ +Skill(skill="team-ux-improve", args="<project-path> [--framework react|vue]") | - Orchestration Mode (auto -> coordinator) + SKILL.md (this file) = Router | - Coordinator (inline) - Phase 0-5 orchestration - | - +-------+-------+-------+-------+-------+ - v v v v v v - [team-worker agents, each loaded with a role-spec] - scanner diagnoser designer implementer tester - - Utility Members (spawned by coordinator for utility work): - [explorer] + +--------------+--------------+ + | | + no --role flag --role <name> + | | + Coordinator Worker + roles/coordinator/role.md roles/<name>/role.md + | + +-- analyze → dispatch → spawn workers → STOP + | + +-------+-------+-------+-------+ + v v v v v + [team-worker agents, each loads roles/<role>/role.md] + scanner diagnoser designer implementer tester ``` +## Role Registry + +| Role | Path | Prefix | Inner Loop | +|------|------|--------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — | +| scanner | [roles/scanner/role.md](roles/scanner/role.md) | SCAN-* | false | +| diagnoser | [roles/diagnoser/role.md](roles/diagnoser/role.md) | DIAG-* | false | +| designer | [roles/designer/role.md](roles/designer/role.md) | DESIGN-* | false | +| implementer | [roles/implementer/role.md](roles/implementer/role.md) | IMPL-* | true | +| tester | [roles/tester/role.md](roles/tester/role.md) | TEST-* | false | + +## Utility Member Registry + +**Coordinator-only**: Utility members can only be spawned by Coordinator. Workers CANNOT call Agent() to spawn utility members. + +| Utility Member | Path | Callable By | Purpose | +|----------------|------|-------------|---------| +| explorer | [roles/explorer/role.md](roles/explorer/role.md) | Coordinator only | Explore codebase for UI component patterns and framework-specific patterns | + ## Role Router -This skill is **coordinator-only**. Workers do NOT invoke this skill — they are spawned as `team-worker` agents directly. +Parse `$ARGUMENTS`: +- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4 +- No `--role` → Read `roles/coordinator/role.md`, execute entry router -### Input Parsing +## Shared Constants -Parse `$ARGUMENTS`. No `--role` needed — always routes to coordinator. +- **Session prefix**: `ux-improve` +- **Session path**: `.workflow/.team/ux-improve-<timestamp>/` +- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications) +- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)` +- **Max test iterations**: 5 -### Role Registry +## Worker Spawn Template -| Role | Spec | Task Prefix | Type | Inner Loop | -|------|------|-------------|------|------------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | -| scanner | [role-specs/scanner.md](role-specs/scanner.md) | SCAN-* | worker | false | -| diagnoser | [role-specs/diagnoser.md](role-specs/diagnoser.md) | DIAG-* | worker | false | -| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | worker | false | -| implementer | [role-specs/implementer.md](role-specs/implementer.md) | IMPL-* | worker | true | -| tester | [role-specs/tester.md](role-specs/tester.md) | TEST-* | worker | false | - -### Utility Member Registry - -**⚠️ COORDINATOR ONLY**: Utility members can only be spawned by Coordinator. Workers CANNOT call Agent() to spawn utility members. Workers must use CLI tools instead. - -| Utility Member | Spec | Callable By | Purpose | -|----------------|------|-------------|---------| -| explorer | [role-specs/explorer.md](role-specs/explorer.md) | **Coordinator only** | Explore codebase for UI component patterns, state management conventions, and framework-specific patterns | - -### Worker Alternatives - -Workers needing similar capabilities must use CLI tools: - -| Capability | CLI Command | Example | -|------------|-------------|---------| -| Codebase exploration | `ccw cli --tool gemini --mode analysis` | Explore architecture patterns | -| Multi-perspective critique | Parallel CLI calls | Security + performance + quality reviews | -| Document generation | `ccw cli --tool gemini --mode write` | Generate implementation guide | - -### Dispatch - -Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. - -### Orchestration Mode - -User provides project path and optional framework flag. - -**Invocation**: `Skill(skill="team-ux-improve", args="<project-path> [--framework react|vue]")` - -**Lifecycle**: -``` -User provides project path - -> coordinator Phase 1-3: Requirement clarification -> TeamCreate -> Create task chain - -> coordinator Phase 4: spawn first batch workers (background) -> STOP - -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances - -> Loop until pipeline complete -> Phase 5 report + completion action -``` - -**User Commands** (wake paused coordinator): - -| Command | Action | -|---------|--------| -| `check` / `status` | Output execution status graph, no advancement | -| `resume` / `continue` | Check worker states, advance next step | - ---- - -## Command Execution Protocol - -When coordinator needs to execute a command (dispatch, monitor): - -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** - NOT separate agents or subprocesses -4. **Execute synchronously** - complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- - -## Coordinator Spawn Template - -### v5 Worker Spawn (all roles) - -When coordinator spawns workers, use `team-worker` agent with role-spec path: +Coordinator spawns workers using this template: ``` Agent({ subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: <team-name>, + description: "Spawn <role> worker for <task-id>", + team_name: "ux-improve", name: "<role>", run_in_background: true, prompt: `## Role Assignment role: <role> -role_spec: .claude/skills/team-ux-improve/role-specs/<role>.md +role_spec: .claude/skills/team-ux-improve/roles/<role>/role.md session: <session-folder> session_id: <session-id> -team_name: <team-name> +team_name: ux-improve requirement: <task-description> inner_loop: <true|false> Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` }) ``` -**Inner Loop roles** (implementer): Set `inner_loop: true`. The team-worker agent handles the loop internally. +## User Commands -**Single-task roles** (scanner, diagnoser, designer, tester): Set `inner_loop: false`. +| Command | Action | +|---------|--------| +| `check` / `status` | View execution status graph | +| `resume` / `continue` | Advance to next step | ---- +## Specs Reference -## Pipeline Definitions - -### Pipeline Diagram - -``` -scanner (SCAN) → diagnoser (DIAG) → designer (DESIGN) → implementer (IMPL) → tester (TEST) - -Stage 1: UI Scanning - └─ scanner: Scan UI components for interaction issues - -Stage 2: Root Cause Diagnosis - └─ diagnoser: Diagnose root causes of identified issues - -Stage 3: Solution Design - └─ designer: Design feedback mechanisms and state management solutions - -Stage 4: Code Implementation - └─ implementer: Generate fix code with proper state handling - -Stage 5: Test Validation - └─ tester: Generate and run tests to verify fixes -``` - -### Cadence Control - -**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. - -``` -Beat Cycle (single beat) -====================================================================== - Event Coordinator Workers ----------------------------------------------------------------------- - callback/resume --> +- handleCallback -+ - | mark completed | - | check pipeline | - +- handleSpawnNext -+ - | find ready tasks | - | spawn workers ---+--> [team-worker scanner] Phase 1-5 - | (parallel OK) --+--> [team-worker diagnoser] Phase 1-5 - +- STOP (idle) -----+ | - | - callback <-----------------------------------------+ - (next beat) SendMessage + TaskUpdate(completed) -====================================================================== - - Fast-Advance (skips coordinator for simple linear successors) -====================================================================== - [Worker scanner] Phase 5 complete - +- 1 ready task? simple successor? - | --> spawn team-worker diagnoser directly - | --> log fast_advance to message bus (coordinator syncs on next wake) - +- complex case? --> SendMessage to coordinator -====================================================================== -``` - -**Checkpoints**: - -| Checkpoint | Trigger | Location | Behavior | -|------------|---------|----------|----------| -| Pipeline complete | All tasks completed | coordinator Phase 5 | Execute completion action | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| SCAN-001 | scanner | 2-4 | [] | Scan UI components for interaction issues | -| DIAG-001 | diagnoser | 2-4 | [SCAN-001] | Diagnose root causes of identified issues | -| DESIGN-001 | designer | 2-4 | [DIAG-001] | Design feedback mechanisms and state management solutions | -| IMPL-001 | implementer | 2-4 | [DESIGN-001] | Generate fix code with proper state handling | -| TEST-001 | tester | 2-4 | [IMPL-001] | Generate and run tests to verify fixes | - ---- - -## Completion Action - -When the pipeline completes (all tasks done, coordinator Phase 5): - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -| Choice | Action | -|--------|--------| -| Archive & Clean | Update session status="completed" -> TeamDelete(ux-improve) -> output final summary | -| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-ux-improve", args="resume")` | -| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | - ---- +- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry ## Session Directory ``` .workflow/.team/ux-improve-<timestamp>/ ├── .msg/ -│ ├── messages.jsonl ← Messages + state_update audit log -│ └── meta.json ← Pipeline config + role state snapshot -├── artifacts/ ← Role deliverables -│ ├── scan-report.md ← scanner output -│ ├── diagnosis.md ← diagnoser output -│ ├── design-guide.md ← designer output -│ ├── fixes/ ← implementer output -│ └── test-report.md ← tester output -├── explorations/ ← explorer cache +│ ├── messages.jsonl # Team message bus +│ └── meta.json # Pipeline config + role state snapshot +├── artifacts/ # Role deliverables +│ ├── scan-report.md # Scanner output +│ ├── diagnosis.md # Diagnoser output +│ ├── design-guide.md # Designer output +│ ├── fixes/ # Implementer output +│ └── test-report.md # Tester output +├── explorations/ # Explorer cache │ └── cache-index.json -└── wisdom/ ← Session knowledge base - ├── contributions/ ← Worker contributions (write-only for workers) - ├── principles/ ← Core principles - │ └── general-ux.md - ├── patterns/ ← Solution patterns - │ ├── ui-feedback.md - │ └── state-management.md - └── anti-patterns/ ← Issues to avoid - └── common-ux-pitfalls.md +└── wisdom/ # Session knowledge base + ├── contributions/ # Worker contributions (write-only for workers) + ├── principles/ + ├── patterns/ + └── anti-patterns/ ``` ## Error Handling | Scenario | Resolution | |----------|------------| -| Role spec file not found | Error with expected path (role-specs/<name>.md) | -| Command file not found | Fallback to inline execution in coordinator role.md | -| Utility member spec not found | Error with expected path (role-specs/explorer.md) | -| Fast-advance orphan detected | Coordinator resets task to pending on next check | -| team-worker agent unavailable | Error: requires .claude/agents/team-worker.md | -| Completion action timeout | Default to Keep Active | -| Framework detection fails | Prompt user for framework selection | -| No UI issues found | Complete with empty fix list | +| Unknown command | Error with available command list | +| Role not found | Error with role registry | +| Project path invalid | Re-prompt user for valid path | +| Framework detection fails | AskUserQuestion for framework selection | +| Session corruption | Attempt recovery, fallback to manual | +| Fast-advance conflict | Coordinator reconciles on next callback | +| No UI issues found | Complete with empty fix list, generate clean bill report | +| Test iterations exceeded | Accept current state, continue to completion | diff --git a/.claude/skills/team-ux-improve/roles/coordinator/commands/analyze.md b/.claude/skills/team-ux-improve/roles/coordinator/commands/analyze.md new file mode 100644 index 00000000..b96dc228 --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/coordinator/commands/analyze.md @@ -0,0 +1,62 @@ +# Analyze Task + +Parse user task -> detect UX improvement scope -> assess complexity -> determine pipeline configuration. + +**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration. + +## Signal Detection + +| Keywords | Signal | Pipeline Hint | +|----------|--------|---------------| +| button, click, tap, unresponsive | interaction-issues | standard | +| loading, spinner, feedback, progress | feedback-missing | standard | +| state, refresh, update, stale | state-issues | standard | +| form, input, validation, error | input-issues | standard | +| accessibility, a11y, keyboard, screen reader | accessibility | standard | +| performance, slow, lag, freeze | performance | standard | +| all, full, complete, comprehensive | full-scope | standard | + +## Framework Detection + +| Keywords | Framework | +|----------|-----------| +| react, jsx, tsx, useState, useEffect | React | +| vue, .vue, ref(), reactive(), v-model | Vue | +| angular, ng-, @Component | Angular | +| Default | auto-detect | + +## Complexity Scoring + +| Factor | Points | +|--------|--------| +| Single component scope | +1 | +| Multiple components | +2 | +| Full project scope | +3 | +| Accessibility required | +1 | +| Performance issues | +1 | +| Complex state management | +1 | + +Results: 1-2 Low (targeted fix), 3-4 Medium (standard pipeline), 5+ High (full pipeline) + +## Scope Determination + +| Signal | Pipeline Mode | +|--------|---------------| +| Specific component or file mentioned | targeted | +| Multiple issues or general project | standard | +| "Full audit" or "complete scan" | standard | +| Unclear | ask user | + +## Output + +Write scope context to coordinator memory: +```json +{ + "pipeline_mode": "standard", + "project_path": "<detected-or-provided-path>", + "framework": "<react|vue|angular|auto>", + "scope": "<detected-scope>", + "issue_signals": ["interaction", "feedback", "state"], + "complexity": { "score": 0, "level": "Low|Medium|High" } +} +``` diff --git a/.claude/skills/team-ux-improve/roles/coordinator/commands/dispatch.md b/.claude/skills/team-ux-improve/roles/coordinator/commands/dispatch.md index 3ff79f7b..1f09e5f0 100644 --- a/.claude/skills/team-ux-improve/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-ux-improve/roles/coordinator/commands/dispatch.md @@ -47,8 +47,7 @@ CONSTRAINTS: <scope limits, focus areas> --- InnerLoop: <true|false> <additional-metadata-fields>", - blockedBy: [<dependency-list>], - status: "pending" + blockedBy: [<dependency-list>] }) ``` diff --git a/.claude/skills/team-ux-improve/roles/coordinator/commands/monitor.md b/.claude/skills/team-ux-improve/roles/coordinator/commands/monitor.md index 0255458c..eff2e10d 100644 --- a/.claude/skills/team-ux-improve/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-ux-improve/roles/coordinator/commands/monitor.md @@ -1,131 +1,154 @@ -# Monitor Command +# Monitor Pipeline -## Purpose +Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP. -Handle worker callbacks, status checks, pipeline advancement, and completion detection. +## Constants ---- +- SPAWN_MODE: background +- ONE_STEP_PER_INVOCATION: true +- FAST_ADVANCE_AWARE: true +- WORKER_AGENT: team-worker +- MAX_TEST_ITERATIONS: 5 -## Handlers +## Handler Router -### handleCallback +| Source | Handler | +|--------|---------| +| Message contains [scanner], [diagnoser], [designer], [implementer], [tester] | handleCallback | +| "capability_gap" | handleAdapt | +| "check" or "status" | handleCheck | +| "resume" or "continue" | handleResume | +| All tasks completed | handleComplete | +| Default | handleSpawnNext | -**Trigger**: Worker SendMessage with `[scanner]`, `[diagnoser]`, `[designer]`, `[implementer]`, or `[tester]` tag. +## handleCallback -1. Parse worker role from message tag -2. Mark corresponding task as completed: `TaskUpdate({ taskId: <task-id>, status: "completed" })` -3. Log completion to message bus: +Worker completed. Process and advance. + +1. Parse message to identify role and task ID: + +| Message Pattern | Role | +|----------------|------| +| `[scanner]` or `SCAN-*` | scanner | +| `[diagnoser]` or `DIAG-*` | diagnoser | +| `[designer]` or `DESIGN-*` | designer | +| `[implementer]` or `IMPL-*` | implementer | +| `[tester]` or `TEST-*` | tester | + +2. Check if progress update (inner loop) or final completion +3. Progress update -> update session state, STOP +4. Completion -> mark task done: ``` - team_msg(operation="log", session_id=<session-id>, from="coordinator", - type="task_complete", data={ role: <role>, task_id: <task-id> }) + TaskUpdate({ taskId: "<task-id>", status: "completed" }) ``` -4. Check if all tasks completed -> handleComplete -5. Otherwise -> handleSpawnNext +5. Remove from active_workers, record completion in session -### handleCheck +6. Check for checkpoints: + - **TEST-001 completes** -> Validation Gate: + Read test results from `.msg/meta.json` -**Trigger**: User "check" or "status" command. + | Condition | Action | + |-----------|--------| + | pass_rate >= 95% | -> handleSpawnNext (pipeline likely complete) | + | pass_rate < 95% AND iterations < max | Log warning, still -> handleSpawnNext | + | pass_rate < 95% AND iterations >= max | Accept current state -> handleComplete | -1. Load TaskList -2. Build status graph: - ``` - Pipeline Status: - ✅ SCAN-001 (scanner) - completed - ✅ DIAG-001 (diagnoser) - completed - 🔄 DESIGN-001 (designer) - in_progress - ⏳ IMPL-001 (implementer) - pending [blocked by DESIGN-001] - ⏳ TEST-001 (tester) - pending [blocked by IMPL-001] - ``` -3. Output status graph, do NOT advance pipeline -4. STOP +7. -> handleSpawnNext -### handleResume +## handleCheck -**Trigger**: User "resume" or "continue" command. +Read-only status report, then STOP. -1. Load TaskList -2. Check for fast-advance orphans: - - Tasks with status "in_progress" but no active worker - - Reset orphans to "pending" -3. -> handleSpawnNext +``` +Pipeline Status (standard): + [DONE] SCAN-001 (scanner) -> artifacts/scan-report.md + [DONE] DIAG-001 (diagnoser) -> artifacts/diagnosis.md + [RUN] DESIGN-001 (designer) -> designing solutions... + [WAIT] IMPL-001 (implementer) -> blocked by DESIGN-001 + [WAIT] TEST-001 (tester) -> blocked by IMPL-001 -### handleSpawnNext +Session: <session-id> +Commands: 'resume' to advance | 'check' to refresh +``` -**Trigger**: After handleCallback or handleResume. +Output status -- do NOT advance pipeline. -1. Load TaskList -2. Find ready tasks: - - status = "pending" - - All blockedBy tasks have status "completed" -3. For each ready task: - - Extract role from task owner - - Extract inner_loop from task description metadata - - Spawn team-worker agent: - ``` - Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: "ux-improve", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment - role: <role> - role_spec: .claude/skills/team-ux-improve/role-specs/<role>.md - session: <session-folder> - session_id: <session-id> - team_name: ux-improve - requirement: <task-description> - inner_loop: <inner-loop-value> +## handleResume - Read role_spec file to load Phase 2-4 domain instructions. - Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` - }) - ``` -4. STOP (wait for next callback) +1. Audit task list for inconsistencies: + - Tasks stuck in "in_progress" -> reset to "pending" + - Tasks with completed blockers but still "pending" -> include in spawn list +2. -> handleSpawnNext -### handleConsensus +## handleSpawnNext -**Trigger**: consensus_blocked message from worker. +Find ready tasks, spawn workers, STOP. -Route by severity: +1. Collect: completedSubjects, inProgressSubjects, readySubjects (pending + all blockedBy completed) +2. No ready + work in progress -> report waiting, STOP +3. No ready + nothing in progress -> handleComplete +4. Has ready -> for each: + a. Check inner loop role with active worker -> skip (worker picks up) + b. TaskUpdate -> in_progress + c. team_msg log -> task_unblocked + d. Spawn team-worker: -| Severity | Action | -|----------|--------| -| HIGH | Pause pipeline, AskUserQuestion for resolution | -| MEDIUM | Log warning, continue pipeline | -| LOW | Log info, continue pipeline | +``` +Agent({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <task-id>", + team_name: "ux-improve", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-ux-improve/roles/<role>/role.md +session: <session-folder> +session_id: <session-id> +team_name: ux-improve +requirement: <task-description> +inner_loop: <true|false> -### handleComplete +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` +}) +``` -**Trigger**: All tasks have status "completed". +Stage-to-role mapping: +| Task Prefix | Role | +|-------------|------| +| SCAN | scanner | +| DIAG | diagnoser | +| DESIGN | designer | +| IMPL | implementer | +| TEST | tester | -1. Verify all tasks completed via TaskList -2. Generate pipeline summary: - - Total tasks: 5 - - Duration: <calculated> - - Deliverables: list artifact paths -3. Execute completion action (see coordinator Phase 5) +Inner loop roles: implementer (inner_loop: true) +Single-task roles: scanner, diagnoser, designer, tester (inner_loop: false) ---- +5. Add to active_workers, update session, output summary, STOP -## Fast-Advance Detection +## handleComplete -When handleCallback detects a completed task: +Pipeline done. Generate report and completion action. -| Condition | Action | -|-----------|--------| -| Exactly 1 ready successor, simple linear | Worker already fast-advanced, log sync | -| Multiple ready successors | Coordinator spawns all | -| No ready successors, all done | -> handleComplete | -| No ready successors, some pending | Wait (blocked tasks) | +1. Verify all tasks (including any fix-verify iterations) have status "completed" +2. If any tasks not completed -> handleSpawnNext +3. If all completed -> transition to coordinator Phase 5 ---- +## handleAdapt -## Error Handling +Capability gap reported mid-pipeline. -| Scenario | Resolution | -|----------|------------| -| Worker callback with unknown role | Log warning, ignore | -| Task not found for callback | Log error, check TaskList | -| Spawn fails | Mark task as failed, log error, try next ready task | -| All tasks failed | Report failure, execute completion action | +1. Parse gap description +2. Check if existing role covers it -> redirect +3. Role count < 5 -> generate dynamic role spec +4. Create new task, spawn worker +5. Role count >= 5 -> merge or pause + +## Fast-Advance Reconciliation + +On every coordinator wake: +1. Read team_msg entries with type="fast_advance" +2. Sync active_workers with spawned successors +3. No duplicate spawns diff --git a/.claude/skills/team-ux-improve/roles/coordinator/role.md b/.claude/skills/team-ux-improve/roles/coordinator/role.md index 61c7427c..dbfd827b 100644 --- a/.claude/skills/team-ux-improve/roles/coordinator/role.md +++ b/.claude/skills/team-ux-improve/roles/coordinator/role.md @@ -1,263 +1,139 @@ # Coordinator Role -## Identity +UX Improvement Team coordinator. Orchestrate pipeline: analyze -> dispatch -> spawn -> monitor -> report. Systematically discovers and fixes UI/UX interaction issues. -- **Name**: coordinator -- **Type**: Orchestration -- **Responsibility**: Orchestrate UX improvement pipeline, spawn workers, monitor progress, handle completion +## Identity +- **Name**: coordinator | **Tag**: [coordinator] +- **Responsibility**: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results ## Boundaries ### MUST - -- Parse user requirements (project path, framework) -- Create team and session structure -- Generate task chain via dispatch.md -- Spawn team-worker agents with correct role-spec paths -- Monitor worker callbacks and advance pipeline -- Execute completion action when pipeline finishes -- Handle user commands (check, resume) +- All output (SendMessage, team_msg, logs) must carry `[coordinator]` identifier +- Use `team-worker` agent type for all worker spawns (NOT `general-purpose`) +- Parse project_path and framework from arguments +- Dispatch tasks with proper dependency chains and blockedBy +- Monitor worker progress via message bus and route messages +- Handle wisdom initialization and consolidation +- Maintain session state persistence ### MUST NOT - -- Execute worker domain logic directly +- Execute worker domain logic directly (scanning, diagnosing, designing, implementing, testing) +- Spawn workers without creating tasks first - Skip completion action -- Spawn workers as general-purpose agents (must use team-worker) - ---- +- Modify source code directly -- delegate to implementer +- Omit `[coordinator]` identifier in any output ## Command Execution Protocol -When coordinator needs to execute a command (dispatch, monitor): +When coordinator needs to execute a command (analyze, dispatch, monitor): -1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` -2. **Follow the workflow** defined in the command file (Phase 2-4 structure) -3. **Commands are inline execution guides** - NOT separate agents or subprocesses -4. **Execute synchronously** - complete the command workflow before proceeding - -Example: -``` -Phase 3 needs task dispatch - -> Read roles/coordinator/commands/dispatch.md - -> Execute Phase 2 (Context Loading) - -> Execute Phase 3 (Task Chain Creation) - -> Execute Phase 4 (Validation) - -> Continue to Phase 4 -``` - ---- +1. Read `commands/<command>.md` +2. Follow the workflow defined in the command +3. Commands are inline execution guides, NOT separate agents +4. Execute synchronously, complete before proceeding ## Entry Router -When coordinator is invoked, detect invocation type: - | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[scanner]`, `[diagnoser]`, etc. | -> handleCallback | -| Status check | Arguments contain "check" or "status" | -> handleCheck | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | -| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | -| New session | None of above | -> Phase 1 (Requirement Clarification) | +| Worker callback | Message contains [scanner], [diagnoser], [designer], [implementer], [tester] | -> handleCallback (monitor.md) | +| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) | +| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) | +| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) | +| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) | +| Interrupted session | Active/paused session exists in .workflow/.team/ux-improve-* | -> Phase 0 | +| New session | None of above | -> Phase 1 | -For callback/check/resume: load `commands/monitor.md` and execute handler, then STOP. - -### Router Implementation - -1. **Load session context** (if exists): - - Scan `.workflow/.team/ux-improve-*/.msg/meta.json` for active/paused sessions - - If found, extract known worker roles from meta.json or SKILL.md Role Registry - -2. **Parse $ARGUMENTS** for detection keywords - -3. **Route to handler**: - - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP - - For Phase 0: Execute Session Resume Check below - - For Phase 1: Execute Requirement Clarification below - ---- +For callback/check/resume/adapt/complete: load `commands/monitor.md`, execute matched handler, STOP. ## Phase 0: Session Resume Check -**Trigger**: Interrupted session detected (active/paused session exists) - -1. Load session meta.json -2. Audit TaskList -> reconcile session state vs task status -3. Reset in_progress tasks -> pending (interrupted tasks) -4. Check for fast-advance orphans (tasks spawned but not in TaskList) -5. AskUserQuestion: "Resume session <session-id>? [Yes/No/New]" - - Yes -> Phase 4 (coordination loop) - - No -> Archive old session -> Phase 1 - - New -> Keep old session paused -> Phase 1 - ---- +1. Scan `.workflow/.team/ux-improve-*/.msg/meta.json` for active/paused sessions +2. No sessions -> Phase 1 +3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) +4. Multiple -> AskUserQuestion for selection ## Phase 1: Requirement Clarification -1. Parse $ARGUMENTS for project path and framework flag +TEXT-LEVEL ONLY. No source code reading. + +1. Parse `$ARGUMENTS` for project path and framework flag: + - `<project-path>` (required) + - `--framework react|vue` (optional, auto-detect if omitted) 2. If project path missing -> AskUserQuestion for path -3. If framework not specified -> detect from package.json or ask user -4. Validate project path exists -5. Store: project_path, framework (react|vue) +3. Delegate to `commands/analyze.md` -> output scope context +4. Store: project_path, framework, pipeline_mode, issue_signals ---- - -## Phase 2: Team Creation +## Phase 2: Create Team + Initialize Session 1. Generate session ID: `ux-improve-<timestamp>` -2. Create session directory structure: +2. Create session folder structure: ``` - .workflow/.team/<session-id>/ + .workflow/.team/ux-improve-<timestamp>/ ├── .msg/ ├── artifacts/ ├── explorations/ - └── wisdom/ + └── wisdom/contributions/ ``` -3. TeamCreate(team_name="ux-improve") -4. Initialize meta.json with pipeline config: +3. **Wisdom Initialization**: Copy `.claude/skills/team-ux-improve/wisdom/` to `<session>/wisdom/` +4. Initialize `.msg/meta.json` via team_msg state_update with pipeline metadata +5. TeamCreate(team_name="ux-improve") +6. Do NOT spawn workers yet - deferred to Phase 4 -### Wisdom Initialization +## Phase 3: Create Task Chain -After creating session directory, initialize wisdom from skill's permanent knowledge base: +Delegate to `commands/dispatch.md`. Standard pipeline: -1. Copy `.claude/skills/team-ux-improve/wisdom/` contents to `<session>/wisdom/` -2. Create `<session>/wisdom/contributions/` directory if not exists -3. This provides workers with initial patterns, principles, and anti-patterns +SCAN-001 -> DIAG-001 -> DESIGN-001 -> IMPL-001 -> TEST-001 -Example: -```bash -# Copy permanent wisdom to session -cp -r .claude/skills/team-ux-improve/wisdom/* <session>/wisdom/ -mkdir -p <session>/wisdom/contributions/ -``` +## Phase 4: Spawn-and-Stop -5. Initialize meta.json with pipeline config: - ``` - team_msg(operation="log", session_id=<session-id>, from="coordinator", - type="state_update", - data={ - pipeline_mode: "standard", - pipeline_stages: ["scan", "diagnose", "design", "implement", "test"], - project_path: <path>, - framework: <framework> - }) - ``` - ---- - -## Phase 3: Task Chain Creation - -Delegate to dispatch.md: - -1. Read `roles/coordinator/commands/dispatch.md` -2. Execute Phase 2 (Context Loading) -3. Execute Phase 3 (Task Chain Creation) -4. Execute Phase 4 (Validation) - ---- - -## Phase 4: Spawn-and-Stop Coordination - -1. Find ready tasks (status=pending, no blockedBy or all blockedBy completed) -2. For each ready task: - - Extract role from task owner - - Spawn team-worker agent with role-spec path - - Use spawn template from SKILL.md -3. STOP (idle, wait for worker callbacks) - -**Spawn template**: -``` -Agent({ - subagent_type: "team-worker", - description: "Spawn <role> worker", - team_name: "ux-improve", - name: "<role>", - run_in_background: true, - prompt: `## Role Assignment -role: <role> -role_spec: .claude/skills/team-ux-improve/role-specs/<role>.md -session: <session-folder> -session_id: <session-id> -team_name: ux-improve -requirement: <task-description> -inner_loop: <true|false> - -Read role_spec file to load Phase 2-4 domain instructions. -Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` -}) -``` - -**Inner loop roles**: implementer (inner_loop: true) - ---- +Delegate to `commands/monitor.md#handleSpawnNext`: +1. Find ready tasks (pending + blockedBy resolved) +2. Spawn team-worker agents (see SKILL.md Spawn Template) +3. Output status summary +4. STOP ## Phase 5: Report + Completion Action -1. Load session state -> count completed tasks, duration -2. List deliverables with output paths: - - artifacts/scan-report.md - - artifacts/diagnosis.md - - artifacts/design-guide.md - - artifacts/fixes/ - - artifacts/test-report.md +1. Read session state -> collect all results +2. List deliverables: -### Wisdom Consolidation +| Deliverable | Path | +|-------------|------| +| Scan Report | <session>/artifacts/scan-report.md | +| Diagnosis | <session>/artifacts/diagnosis.md | +| Design Guide | <session>/artifacts/design-guide.md | +| Fix Files | <session>/artifacts/fixes/ | +| Test Report | <session>/artifacts/test-report.md | -Before pipeline completion, handle knowledge contributions: +3. **Wisdom Consolidation**: Check `<session>/wisdom/contributions/` for worker contributions + - If contributions exist -> AskUserQuestion to merge to permanent wisdom + - If approved -> copy to `.claude/skills/team-ux-improve/wisdom/` -1. Check if `<session>/wisdom/contributions/` has any files -2. If contributions exist: - - Summarize contributions for user review - - Use AskUserQuestion to ask if user wants to merge valuable contributions back to permanent wisdom - - If approved, copy selected contributions to `.claude/skills/team-ux-improve/wisdom/` (classify into patterns/, anti-patterns/, etc.) - -Example interaction: -``` -AskUserQuestion({ - questions: [{ - question: "Workers contributed new knowledge during this session. Merge to permanent wisdom?", - header: "Knowledge", - options: [ - { label: "Merge All", description: "Add all contributions to permanent wisdom" }, - { label: "Review First", description: "Show contributions before deciding" }, - { label: "Skip", description: "Keep contributions in session only" } - ] - }] -}) -``` - -3. **Completion Action** (interactive mode): - -``` -AskUserQuestion({ - questions: [{ - question: "Team pipeline complete. What would you like to do?", - header: "Completion", - multiSelect: false, - options: [ - { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, - { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, - { label: "Export Results", description: "Export deliverables to a specified location, then clean" } - ] - }] -}) -``` - -4. Handle user choice: - -| Choice | Steps | -|--------|-------| -| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("ux-improve") -> output final summary with artifact paths | -| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-ux-improve', args='resume')" | -| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | - ---- +4. Calculate: completed_tasks, total_issues_found, issues_fixed, test_pass_rate +5. Output pipeline summary with [coordinator] prefix +6. Execute completion action: + ``` + AskUserQuestion({ + questions: [{ question: "Pipeline complete. What next?", header: "Completion", options: [ + { label: "Archive & Clean", description: "Archive session and clean up team resources" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to specified location" } + ]}] + }) + ``` ## Error Handling -| Scenario | Resolution | -|----------|------------| +| Error | Resolution | +|-------|------------| | Project path invalid | Re-prompt user for valid path | | Framework detection fails | AskUserQuestion for framework selection | -| Worker spawn fails | Log error, mark task as failed, continue with other tasks | -| TeamCreate fails | Error: cannot proceed without team | -| Completion action timeout (5 min) | Default to Keep Active | +| Task timeout | Log, mark failed, ask user to retry or skip | +| Worker crash | Reset task to pending, respawn worker | +| Dependency cycle | Detect, report to user, halt | +| Session corruption | Attempt recovery, fallback to manual reconciliation | +| No UI issues found | Complete with empty fix list, generate clean bill report | +| Test iterations exceeded | Accept current state, continue to completion | diff --git a/.claude/skills/team-ux-improve/roles/designer/role.md b/.claude/skills/team-ux-improve/roles/designer/role.md new file mode 100644 index 00000000..3e856a44 --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/designer/role.md @@ -0,0 +1,122 @@ +--- +role: designer +prefix: DESIGN +inner_loop: false +message_types: [state_update] +--- + +# UX Designer + +Design feedback mechanisms (loading/error/success states) and state management patterns (React/Vue reactive updates). + +## Phase 2: Context & Pattern Loading + +1. Load diagnosis report from `<session>/artifacts/diagnosis.md` +2. Load diagnoser state via `team_msg(operation="get_state", session_id=<session-id>, role="diagnoser")` +3. Detect framework from project structure +4. Load framework-specific patterns: + +| Framework | State Pattern | Event Pattern | +|-----------|---------------|---------------| +| React | useState, useRef | onClick, onChange | +| Vue | ref, reactive | @click, @change | + +### Wisdom Input + +1. Read `<session>/wisdom/patterns/ui-feedback.md` for established feedback design patterns +2. Read `<session>/wisdom/patterns/state-management.md` for state handling patterns +3. Read `<session>/wisdom/principles/general-ux.md` for UX design principles +4. Apply patterns when designing solutions for identified issues + +### Complex Design (use CLI) + +For complex multi-component solutions: + +``` +Bash(`ccw cli -p "PURPOSE: Design comprehensive feedback mechanism for multi-step form +CONTEXT: @<component-files> +EXPECTED: Complete design with state flow diagram and code patterns +CONSTRAINTS: Must support React hooks" --tool gemini --mode analysis`) +``` + +## Phase 3: Solution Design + +For each diagnosed issue, design solution: + +### Feedback Mechanism Design + +| Issue Type | Solution Design | +|------------|-----------------| +| Missing loading | Add loading state + UI indicator (spinner, disabled button) | +| Missing error | Add error state + error message display | +| Missing success | Add success state + confirmation toast/message | +| No empty state | Add conditional rendering for empty data | + +### State Management Design + +**React Pattern**: +```typescript +const [isLoading, setIsLoading] = useState(false); +const [error, setError] = useState<string | null>(null); + +const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsLoading(true); + setError(null); + try { + const response = await fetch('/api/upload', { method: 'POST', body: formData }); + if (!response.ok) throw new Error('Upload failed'); + } catch (err: any) { + setError(err.message || 'An error occurred'); + } finally { + setIsLoading(false); + } +}; +``` + +**Vue Pattern**: +```typescript +const isLoading = ref(false); +const error = ref<string | null>(null); + +const handleSubmit = async () => { + isLoading.value = true; + error.value = null; + try { + const response = await fetch('/api/upload', { method: 'POST', body: formData }); + if (!response.ok) throw new Error('Upload failed'); + } catch (err: any) { + error.value = err.message || 'An error occurred'; + } finally { + isLoading.value = false; + } +}; +``` + +### Input Control Design + +| Issue | Solution | +|-------|----------| +| Text input for file path | Add file picker: `<input type="file" />` | +| Text input for folder path | Add directory picker: `<input type="file" webkitdirectory />` | +| No validation | Add validation rules and error messages | + +## Phase 4: Design Document Generation + +1. Generate implementation guide for each issue and write to `<session>/artifacts/design-guide.md` + +### Wisdom Contribution + +If novel design patterns created: +1. Write new patterns to `<session>/wisdom/contributions/designer-pattern-<timestamp>.md` +2. Format: Problem context, solution design, implementation hints, trade-offs + +3. Share state via team_msg: + ``` + team_msg(operation="log", session_id=<session-id>, from="designer", + type="state_update", data={ + designed_solutions: <count>, + framework: <framework>, + patterns_used: [<pattern-list>] + }) + ``` diff --git a/.claude/skills/team-ux-improve/roles/diagnoser/role.md b/.claude/skills/team-ux-improve/roles/diagnoser/role.md new file mode 100644 index 00000000..1c71a2a6 --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/diagnoser/role.md @@ -0,0 +1,93 @@ +--- +role: diagnoser +prefix: DIAG +inner_loop: false +message_types: [state_update] +--- + +# State Diagnoser + +Diagnose root causes of UI issues: state management problems, event binding failures, async handling errors. + +## Phase 2: Context & Complexity Assessment + +1. Load scan report from `<session>/artifacts/scan-report.md` +2. Load scanner state via `team_msg(operation="get_state", session_id=<session-id>, role="scanner")` + +### Wisdom Input + +1. Read `<session>/wisdom/patterns/ui-feedback.md` and `<session>/wisdom/patterns/state-management.md` if available +2. Use patterns to identify root causes of UI interaction issues +3. Reference `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` for common causes + +3. Assess issue complexity: + +| Complexity | Criteria | Strategy | +|------------|----------|----------| +| High | 5+ issues, cross-component state | CLI delegation | +| Medium | 2-4 issues, single component | CLI for analysis | +| Low | 1 issue, simple pattern | Inline analysis | + +### Complex Analysis (use CLI) + +For complex multi-file state management issues: + +``` +Bash(`ccw cli -p "PURPOSE: Analyze state management patterns and identify root causes +CONTEXT: @<issue-files> +EXPECTED: Root cause analysis with fix recommendations +CONSTRAINTS: Focus on reactive update patterns" --tool gemini --mode analysis`) +``` + +## Phase 3: Root Cause Analysis + +For each issue from scan report: + +### State Management Diagnosis + +| Pattern | Root Cause | Fix Strategy | +|---------|------------|--------------| +| Array.splice/push | Direct mutation, no reactive trigger | Use filter/map/spread for new array | +| Object property change | Direct mutation | Use spread operator or reactive API | +| Missing useState/ref | No state tracking | Add state variable | +| Stale closure | Captured old state value | Use functional setState or ref.current | + +### Event Binding Diagnosis + +| Pattern | Root Cause | Fix Strategy | +|---------|------------|--------------| +| onClick without handler | Missing event binding | Add event handler function | +| Async without await | Unhandled promise | Add async/await or .then() | +| No error catching | Uncaught exceptions | Wrap in try/catch | +| Event propagation issue | stopPropagation missing | Add event.stopPropagation() | + +### Async Handling Diagnosis + +| Pattern | Root Cause | Fix Strategy | +|---------|------------|--------------| +| No loading state | Missing async state tracking | Add isLoading state | +| No error handling | Missing catch block | Add try/catch with error state | +| Race condition | Multiple concurrent requests | Add request cancellation or debounce | + +## Phase 4: Diagnosis Report + +1. Generate root cause analysis for each issue and write to `<session>/artifacts/diagnosis.md` + +### Wisdom Contribution + +If new root cause patterns discovered: +1. Write diagnosis patterns to `<session>/wisdom/contributions/diagnoser-patterns-<timestamp>.md` +2. Format: Symptom, root cause, detection method, fix approach + +3. Share state via team_msg: + ``` + team_msg(operation="log", session_id=<session-id>, from="diagnoser", + type="state_update", data={ + diagnosed_issues: <count>, + pattern_types: { + state_management: <count>, + event_binding: <count>, + async_handling: <count> + } + }) + ``` diff --git a/.claude/skills/team-ux-improve/roles/explorer/role.md b/.claude/skills/team-ux-improve/roles/explorer/role.md new file mode 100644 index 00000000..02c1f5fd --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/explorer/role.md @@ -0,0 +1,77 @@ +--- +role: explorer +prefix: EXPLORE +inner_loop: false +message_types: [state_update] +--- + +# Codebase Explorer + +Explore codebase for UI component patterns, state management conventions, and framework-specific patterns. Callable by coordinator only. + +## Phase 2: Exploration Scope + +1. Parse exploration request from task description +2. Determine file patterns based on framework: + +### Wisdom Input + +1. Read `<session>/wisdom/patterns/ui-feedback.md` and `<session>/wisdom/patterns/state-management.md` if available +2. Use known patterns as reference when exploring codebase for component structures +3. Check `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` to identify problematic patterns during exploration + +| Framework | Patterns | +|-----------|----------| +| React | `**/*.tsx`, `**/*.jsx`, `**/use*.ts`, `**/store*.ts` | +| Vue | `**/*.vue`, `**/composables/*.ts`, `**/stores/*.ts` | + +3. Check exploration cache: `<session>/explorations/cache-index.json` + - If cache hit and fresh -> return cached results + - If cache miss or stale -> proceed to Phase 3 + +## Phase 3: Codebase Exploration + +Use ACE search for semantic queries: + +``` +mcp__ace-tool__search_context( + project_root_path="<project-path>", + query="<exploration-query>" +) +``` + +Exploration dimensions: + +| Dimension | Query | Purpose | +|-----------|-------|---------| +| Component patterns | "UI components with user interactions" | Find interactive components | +| State management | "State management patterns useState ref reactive" | Identify state conventions | +| Event handling | "Event handlers onClick onChange onSubmit" | Map event patterns | +| Error handling | "Error handling try catch error state" | Find error patterns | +| Feedback mechanisms | "Loading state spinner progress indicator" | Find existing feedback | + +For each dimension, collect: +- File paths +- Pattern examples +- Convention notes + +## Phase 4: Exploration Summary + +1. Generate pattern summary and write to `<session>/explorations/exploration-summary.md` +2. Cache results to `<session>/explorations/cache-index.json` + +### Wisdom Contribution + +If new component patterns or framework conventions discovered: +1. Write pattern summaries to `<session>/wisdom/contributions/explorer-patterns-<timestamp>.md` +2. Format: Pattern Name, Framework, Use Case, Code Example, Adoption + +4. Share state via team_msg: + ``` + team_msg(operation="log", session_id=<session-id>, from="explorer", + type="state_update", data={ + framework: <framework>, + components_found: <count>, + patterns_identified: [<pattern-list>] + }) + ``` diff --git a/.claude/skills/team-ux-improve/roles/implementer/role.md b/.claude/skills/team-ux-improve/roles/implementer/role.md new file mode 100644 index 00000000..76237552 --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/implementer/role.md @@ -0,0 +1,102 @@ +--- +role: implementer +prefix: IMPL +inner_loop: true +message_types: [state_update] +--- + +# Code Implementer + +Generate executable fix code with proper state management, event handling, and UI feedback bindings. + +## Phase 2: Task & Design Loading + +1. Extract session path from task description +2. Read design guide: `<session>/artifacts/design-guide.md` +3. Extract implementation tasks from design guide +4. **Wisdom Input**: + - Read `<session>/wisdom/patterns/state-management.md` for state handling patterns + - Read `<session>/wisdom/patterns/ui-feedback.md` for UI feedback implementation patterns + - Read `<session>/wisdom/principles/general-ux.md` for implementation principles + - Load framework-specific conventions if available + - Apply these patterns and principles when generating code to ensure consistency and quality +5. **For inner loop**: Load context_accumulator from prior IMPL tasks + +### Context Accumulator (Inner Loop) + +``` +context_accumulator = { + completed_fixes: [<fix-1>, <fix-2>], + modified_files: [<file-1>, <file-2>], + patterns_applied: [<pattern-1>] +} +``` + +## Phase 3: Code Implementation + +Implementation backend selection: + +| Backend | Condition | Method | +|---------|-----------|--------| +| CLI | Complex multi-file changes | `ccw cli --tool gemini --mode write` | +| Direct | Simple single-file changes | Inline Edit/Write | + +### CLI Implementation (Complex) + +``` +Bash(`ccw cli -p "PURPOSE: Implement loading state and error handling for upload form +TASK: + - Add useState for isLoading and error + - Wrap async call in try/catch/finally + - Update UI bindings for button and error display +CONTEXT: @src/components/Upload.tsx +EXPECTED: Modified Upload.tsx with complete implementation +CONSTRAINTS: Maintain existing code style" --tool gemini --mode write`) +``` + +### Direct Implementation (Simple) + +For simple state variable additions or UI binding changes use Edit/Write tools directly. + +### Implementation Steps + +For each fix in design guide: +1. Read target file +2. Determine complexity (simple vs complex) +3. Apply fix using appropriate backend +4. Verify syntax (no compilation errors) +5. Append to context_accumulator + +## Phase 4: Self-Validation + +| Check | Method | Pass Criteria | +|-------|--------|---------------| +| Syntax | IDE diagnostics or tsc --noEmit | No errors | +| File existence | Verify planned files exist | All present | +| Acceptance criteria | Match against design guide | All met | + +Validation steps: +1. Run syntax check on modified files +2. Verify all files from design guide exist +3. Check acceptance criteria from design guide +4. If validation fails -> attempt auto-fix (max 2 attempts) + +### Context Accumulator Update + +Append to context_accumulator and write summary to `<session>/artifacts/fixes/README.md`. + +Share state via team_msg: +``` +team_msg(operation="log", session_id=<session-id>, from="implementer", + type="state_update", data={ + completed_fixes: <count>, + modified_files: [<file-list>], + validation_passed: true + }) +``` + +### Wisdom Contribution + +If reusable code patterns or snippets created: +1. Write code snippets to `<session>/wisdom/contributions/implementer-snippets-<timestamp>.md` +2. Format: Use case, code snippet with comments, framework compatibility notes diff --git a/.claude/skills/team-ux-improve/roles/scanner/role.md b/.claude/skills/team-ux-improve/roles/scanner/role.md new file mode 100644 index 00000000..491700c3 --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/scanner/role.md @@ -0,0 +1,93 @@ +--- +role: scanner +prefix: SCAN +inner_loop: false +message_types: [state_update] +--- + +# UI Scanner + +Scan UI components to identify interaction issues: unresponsive buttons, missing feedback mechanisms, state not refreshing. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Project path | Task description CONTEXT | Yes | +| Framework | Task description CONTEXT | Yes | +| Scan scope | Task description CONSTRAINTS | Yes | + +1. Extract session path and project path from task description +2. Detect framework from project structure: + +| Signal | Framework | +|--------|-----------| +| package.json has "react" | React | +| package.json has "vue" | Vue | +| *.tsx files present | React | +| *.vue files present | Vue | + +3. Build file pattern list for scanning: + - React: `**/*.tsx`, `**/*.jsx`, `**/use*.ts` + - Vue: `**/*.vue`, `**/composables/*.ts` + +### Wisdom Input + +1. Read `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` if available +2. Use anti-patterns to identify known UX issues during scanning +3. Check `<session>/wisdom/patterns/ui-feedback.md` for expected feedback patterns + +### Complex Analysis (use CLI) + +For large projects with many components: + +``` +Bash(`ccw cli -p "PURPOSE: Discover all UI components with user interactions +CONTEXT: @<project-path>/**/*.tsx @<project-path>/**/*.vue +EXPECTED: Component list with interaction types (click, submit, input, select) +CONSTRAINTS: Focus on interactive components only" --tool gemini --mode analysis`) +``` + +## Phase 3: Component Scanning + +Scan strategy: + +| Category | Detection Pattern | Severity | +|----------|-------------------|----------| +| Unresponsive actions | onClick/\@click without async handling or error catching | High | +| Missing loading state | Form submit without isLoading/loading ref | High | +| State not refreshing | Array.splice/push without reactive reassignment | High | +| Missing error feedback | try/catch without error state or user notification | Medium | +| Missing success feedback | API call without success confirmation | Medium | +| No empty state | Data list without empty state placeholder | Low | +| Input without validation | Form input without validation rules | Low | +| Missing file selector | Text input for file/folder path without picker | Medium | + +For each component file: +1. Read file content +2. Scan for interaction patterns using Grep +3. Check for feedback mechanisms (loading, error, success states) +4. Check state update patterns (mutation vs reactive) +5. Record issues with file:line references + +## Phase 4: Issue Report Generation + +1. Classify issues by severity (High/Medium/Low) +2. Group by category (unresponsive, missing feedback, state issues, input UX) +3. Generate structured report and write to `<session>/artifacts/scan-report.md` +4. Share state via team_msg: + ``` + team_msg(operation="log", session_id=<session-id>, from="scanner", + type="state_update", data={ + total_issues: <count>, + high: <count>, medium: <count>, low: <count>, + categories: [<category-list>], + scanned_files: <count> + }) + ``` + +### Wisdom Contribution + +If novel UX issues discovered that aren't in anti-patterns: +1. Write findings to `<session>/wisdom/contributions/scanner-issues-<timestamp>.md` +2. Format: Issue description, detection criteria, affected components diff --git a/.claude/skills/team-ux-improve/roles/tester/role.md b/.claude/skills/team-ux-improve/roles/tester/role.md new file mode 100644 index 00000000..93617aaa --- /dev/null +++ b/.claude/skills/team-ux-improve/roles/tester/role.md @@ -0,0 +1,84 @@ +--- +role: tester +prefix: TEST +inner_loop: false +message_types: [state_update] +--- + +# Test Engineer + +Generate and run tests to verify fixes (loading states, error handling, state updates). + +## Phase 2: Environment Detection + +1. Detect test framework from project files: + +| Signal | Framework | +|--------|-----------| +| package.json has "jest" | Jest | +| package.json has "vitest" | Vitest | +| package.json has "@testing-library/react" | React Testing Library | +| package.json has "@vue/test-utils" | Vue Test Utils | + +2. Get changed files from implementer state: + ``` + team_msg(operation="get_state", session_id=<session-id>, role="implementer") + ``` + +3. Load test strategy from design guide + +### Wisdom Input + +1. Read `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` for common issues to test +2. Read `<session>/wisdom/patterns/ui-feedback.md` for expected feedback behaviors to verify +3. Use wisdom to design comprehensive test cases covering known edge cases + +## Phase 3: Test Generation & Execution + +### Test Generation + +For each modified file, generate test cases covering loading states, error handling, state updates, and accessibility. + +### Test Execution + +Iterative test-fix cycle (max 5 iterations): + +1. Run tests: `npm test` or `npm run test:unit` +2. Parse results -> calculate pass rate +3. If pass rate >= 95% -> exit (success) +4. If pass rate < 95% and iterations < 5: + - Analyze failures + - Use CLI to generate fixes: + ``` + Bash(`ccw cli -p "PURPOSE: Fix test failures + CONTEXT: @<test-file> @<source-file> + EXPECTED: Fixed code that passes tests + CONSTRAINTS: Maintain existing functionality" --tool gemini --mode write`) + ``` + - Increment iteration counter + - Loop to step 1 +5. If iterations >= 5 -> send fix_required message + +## Phase 4: Test Report + +### Wisdom Contribution + +If new edge cases or test patterns discovered: +1. Write test findings to `<session>/wisdom/contributions/tester-edge-cases-<timestamp>.md` +2. Format: Edge case description, test scenario, expected behavior, actual behavior + +Write report to `<session>/artifacts/test-report.md`. + +Share state via team_msg: +``` +team_msg(operation="log", session_id=<session-id>, from="tester", + type="state_update", data={ + total_tests: <count>, + passed: <count>, + failed: <count>, + pass_rate: <percentage>, + fix_iterations: <count> + }) +``` + +If pass rate < 95%, send fix_required message to coordinator. diff --git a/.claude/skills/team-ux-improve/specs/pipelines.md b/.claude/skills/team-ux-improve/specs/pipelines.md new file mode 100644 index 00000000..fa5c5b34 --- /dev/null +++ b/.claude/skills/team-ux-improve/specs/pipelines.md @@ -0,0 +1,54 @@ +# Pipeline Definitions + +UX improvement pipeline modes and task registry. + +## Pipeline Modes + +| Mode | Description | Task Chain | +|------|-------------|------------| +| standard | Full UX improvement pipeline | SCAN-001 -> DIAG-001 -> DESIGN-001 -> IMPL-001 -> TEST-001 | + +## Standard Pipeline Task Registry + +| Task ID | Role | blockedBy | Inner Loop | Description | +|---------|------|-----------|------------|-------------| +| SCAN-001 | scanner | [] | false | Scan UI components for interaction issues (unresponsive buttons, missing feedback, state problems) | +| DIAG-001 | diagnoser | [SCAN-001] | false | Root cause diagnosis with fix recommendations | +| DESIGN-001 | designer | [DIAG-001] | false | Feedback mechanism and state management solution design | +| IMPL-001 | implementer | [DESIGN-001] | true | Code implementation with proper state handling | +| TEST-001 | tester | [IMPL-001] | false | Test generation and validation (pass rate >= 95%, max 5 iterations) | + +## Checkpoints + +| Checkpoint | Trigger | Condition | Action | +|------------|---------|-----------|--------| +| Pipeline complete | TEST-001 completes | All tasks done | Coordinator Phase 5: wisdom consolidation + completion action | + +## Test Iteration Behavior + +| Condition | Action | +|-----------|--------| +| pass_rate >= 95% | Pipeline complete | +| pass_rate < 95% AND iterations < 5 | Tester generates fixes, re-runs (inner loop within TEST-001) | +| pass_rate < 95% AND iterations >= 5 | Accept current state, report to coordinator | + +## Output Artifacts + +| Task | Output Path | +|------|-------------| +| SCAN-001 | <session>/artifacts/scan-report.md | +| DIAG-001 | <session>/artifacts/diagnosis.md | +| DESIGN-001 | <session>/artifacts/design-guide.md | +| IMPL-001 | <session>/artifacts/fixes/ | +| TEST-001 | <session>/artifacts/test-report.md | + +## Wisdom System + +Workers contribute learnings to `<session>/wisdom/contributions/`. On pipeline completion, coordinator asks user to merge approved contributions to permanent wisdom at `.claude/skills/team-ux-improve/wisdom/`. + +| Directory | Purpose | +|-----------|---------| +| wisdom/principles/ | Core UX principles | +| wisdom/patterns/ | Solution patterns (ui-feedback, state-management) | +| wisdom/anti-patterns/ | Issues to avoid (common-ux-pitfalls) | +| wisdom/contributions/ | Session worker contributions (pending review) | diff --git a/ccw/src/services/deepwiki-service.ts b/ccw/src/services/deepwiki-service.ts index 1fc4aeeb..503fc1ab 100644 --- a/ccw/src/services/deepwiki-service.ts +++ b/ccw/src/services/deepwiki-service.ts @@ -7,7 +7,7 @@ import { homedir } from 'os'; import { join } from 'path'; -import { existsSync } from 'fs'; +import { existsSync, readFileSync } from 'fs'; import Database from 'better-sqlite3'; // Default database path (same as Python DeepWikiStore) @@ -251,6 +251,122 @@ export class DeepWikiService { } } + /** + * Get all symbols for multiple source file paths (batch query) + * @param paths - Array of source file paths + * @returns Map of normalized path to array of symbol info + */ + public getSymbolsForPaths(paths: string[]): Map<string, Array<{ + name: string; + type: string; + doc_file: string; + anchor: string; + start_line: number; + end_line: number; + staleness_score: number; + }>> { + const db = this.getConnection(); + if (!db) { + return new Map(); + } + + try { + const result = new Map<string, Array<{ + name: string; + type: string; + doc_file: string; + anchor: string; + start_line: number; + end_line: number; + staleness_score: number; + }>>(); + + const stmt = db.prepare(` + SELECT name, type, doc_file, anchor, start_line, end_line, staleness_score + FROM deepwiki_symbols + WHERE source_file = ? + ORDER BY start_line + `); + + for (const filePath of paths) { + const normalizedPath = filePath.replace(/\\/g, '/'); + const rows = stmt.all(normalizedPath) as Array<{ + name: string; + type: string; + doc_file: string; + anchor: string; + start_line: number; + end_line: number; + staleness_score: number; + }>; + + if (rows.length > 0) { + result.set(normalizedPath, rows); + } + } + + return result; + } catch (error) { + console.error('[DeepWiki] Error getting symbols for paths:', error); + return new Map(); + } + } + + /** + * Check which files have stale documentation by comparing content hashes + * @param files - Array of {path, hash} to check + * @returns Array of file paths where stored hash differs from provided hash + */ + public getStaleFiles(files: Array<{ path: string; hash: string }>): Array<{ + path: string; + stored_hash: string | null; + current_hash: string; + }> { + const db = this.getConnection(); + if (!db) { + return []; + } + + try { + const stmt = db.prepare('SELECT content_hash FROM deepwiki_files WHERE path = ?'); + const stale: Array<{ path: string; stored_hash: string | null; current_hash: string }> = []; + + for (const file of files) { + const normalizedPath = file.path.replace(/\\/g, '/'); + const row = stmt.get(normalizedPath) as { content_hash: string } | undefined; + + if (row && row.content_hash !== file.hash) { + stale.push({ path: file.path, stored_hash: row.content_hash, current_hash: file.hash }); + } else if (!row) { + stale.push({ path: file.path, stored_hash: null, current_hash: file.hash }); + } + } + + return stale; + } catch (error) { + console.error('[DeepWiki] Error checking stale files:', error); + return []; + } + } + + /** + * Read symbol documentation file content + * @param docFile - Path to the documentation file (relative to .deepwiki/) + * @returns Documentation content string or null + */ + public getSymbolDocContent(docFile: string): string | null { + try { + const fullPath = join(homedir(), '.codexlens', 'deepwiki', docFile); + if (!existsSync(fullPath)) { + return null; + } + return readFileSync(fullPath, 'utf-8'); + } catch (error) { + console.error('[DeepWiki] Error reading doc content:', error); + return null; + } + } + /** * Get storage statistics * @returns Statistics object with counts @@ -293,3 +409,58 @@ export function getDeepWikiService(): DeepWikiService { } return deepWikiService; } + +/** + * Handle DeepWiki API routes + * @returns true if route was handled, false otherwise + */ +export async function handleDeepWikiRoutes(ctx: { + pathname: string; + req: any; + res: any; +}): Promise<boolean> { + const { pathname, req, res } = ctx; + const service = getDeepWikiService(); + + if (pathname === '/api/deepwiki/symbols-for-paths' && req.method === 'POST') { + const body = await readJsonBody(req); + const paths: string[] = body?.paths || []; + const result = service.getSymbolsForPaths(paths); + // Convert Map to plain object for JSON serialization + const obj: Record<string, any> = {}; + for (const [key, value] of result) { + obj[key] = value; + } + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(obj)); + return true; + } + + if (pathname === '/api/deepwiki/stale-files' && req.method === 'POST') { + const body = await readJsonBody(req); + const files: Array<{ path: string; hash: string }> = body?.files || []; + const result = service.getStaleFiles(files); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(result)); + return true; + } + + return false; +} + +/** + * Read JSON body from request + */ +function readJsonBody(req: any): Promise<any> { + return new Promise((resolve) => { + let body = ''; + req.on('data', (chunk: string) => { body += chunk; }); + req.on('end', () => { + try { + resolve(JSON.parse(body)); + } catch { + resolve(null); + } + }); + }); +} diff --git a/ccw/src/tools/cli-executor-core.ts b/ccw/src/tools/cli-executor-core.ts index 65adc6e3..ff70444c 100644 --- a/ccw/src/tools/cli-executor-core.ts +++ b/ccw/src/tools/cli-executor-core.ts @@ -35,50 +35,46 @@ import { saveConversation } from './cli-executor-state.js'; -// Track current running child process for cleanup on interruption -let currentChildProcess: ChildProcess | null = null; -let killTimeout: NodeJS.Timeout | null = null; -let killTimeoutProcess: ChildProcess | null = null; +// Track all running child processes for cleanup on interruption (multi-process support) +const runningChildProcesses = new Set<ChildProcess>(); /** - * Kill the current running CLI child process + * Kill all running CLI child processes * Called when parent process receives SIGINT/SIGTERM */ -export function killCurrentCliProcess(): boolean { - const child = currentChildProcess; - if (!child || child.killed) return false; +export function killAllCliProcesses(): boolean { + if (runningChildProcesses.size === 0) return false; - debugLog('KILL', 'Killing current child process', { pid: child.pid }); + const processesToKill = Array.from(runningChildProcesses); + debugLog('KILL', `Killing ${processesToKill.length} child process(es)`, { pids: processesToKill.map(p => p.pid) }); - try { - child.kill('SIGTERM'); - } catch { - // Ignore kill errors (process may already be gone) + // 1. SIGTERM for graceful shutdown + for (const child of processesToKill) { + if (!child.killed) { + try { child.kill('SIGTERM'); } catch { /* Ignore kill errors */ } + } } - if (killTimeout) { - clearTimeout(killTimeout); - killTimeout = null; - killTimeoutProcess = null; - } - - // Force kill after 2 seconds if still running. - killTimeoutProcess = child; - killTimeout = setTimeout(() => { - const target = killTimeoutProcess; - if (!target || target !== currentChildProcess) return; - if (target.killed) return; - - try { - target.kill('SIGKILL'); - } catch { - // Ignore kill errors (process may already be gone) + // 2. SIGKILL after 2s timeout + const killTimeout = setTimeout(() => { + for (const child of processesToKill) { + if (!child.killed) { + try { child.kill('SIGKILL'); } catch { /* Ignore kill errors */ } + } } }, 2000); + killTimeout.unref(); + runningChildProcesses.clear(); return true; } +/** + * Backward compatibility alias + * @deprecated Use killAllCliProcesses() instead + */ +export const killCurrentCliProcess = killAllCliProcesses; + // LiteLLM integration import { executeLiteLLMEndpoint } from './litellm-executor.js'; import { findEndpointById } from '../config/litellm-api-config-manager.js'; @@ -242,8 +238,8 @@ async function executeClaudeWithSettings(params: ClaudeWithSettingsParams): Prom stdio: ['ignore', 'pipe', 'pipe'] }); - // Track current child process for cleanup - currentChildProcess = child; + // Track child process for cleanup (multi-process support) + runningChildProcesses.add(child); let stdout = ''; let stderr = ''; @@ -282,7 +278,7 @@ async function executeClaudeWithSettings(params: ClaudeWithSettingsParams): Prom }); child.on('close', (code) => { - currentChildProcess = null; + runningChildProcesses.delete(child); const endTime = Date.now(); const duration = endTime - startTime; @@ -338,7 +334,7 @@ async function executeClaudeWithSettings(params: ClaudeWithSettingsParams): Prom }); child.on('error', (error) => { - currentChildProcess = null; + runningChildProcesses.delete(child); reject(new Error(`Failed to spawn claude: ${error.message}`)); }); }); @@ -999,8 +995,8 @@ async function executeCliTool( env: spawnEnv }); - // Track current child process for cleanup on interruption - currentChildProcess = child; + // Track child process for cleanup on interruption (multi-process support) + runningChildProcesses.add(child); debugLog('SPAWN', `Process spawned`, { pid: child.pid }); @@ -1050,14 +1046,8 @@ async function executeCliTool( // Handle completion child.on('close', async (code) => { - if (killTimeout && killTimeoutProcess === child) { - clearTimeout(killTimeout); - killTimeout = null; - killTimeoutProcess = null; - } - - // Clear current child process reference - currentChildProcess = null; + // Remove from running processes + runningChildProcesses.delete(child); // Flush remaining buffer from parser const remainingUnits = parser.flush(); @@ -1319,6 +1309,9 @@ async function executeCliTool( // Handle errors child.on('error', (error) => { + // Remove from running processes + runningChildProcesses.delete(child); + errorLog('SPAWN', `Failed to spawn process`, error, { tool, command, diff --git a/codex-lens/src/codexlens/storage/deepwiki_models.py b/codex-lens/src/codexlens/storage/deepwiki_models.py index 2ee33b78..e86665c8 100644 --- a/codex-lens/src/codexlens/storage/deepwiki_models.py +++ b/codex-lens/src/codexlens/storage/deepwiki_models.py @@ -7,7 +7,7 @@ for the DeepWiki documentation generation system. from __future__ import annotations from datetime import datetime -from typing import List, Optional, Tuple +from typing import Any, List, Optional, Tuple from pydantic import BaseModel, Field, field_validator @@ -30,6 +30,10 @@ class DeepWikiSymbol(BaseModel): ) created_at: Optional[datetime] = Field(default=None, description="Record creation timestamp") updated_at: Optional[datetime] = Field(default=None, description="Record update timestamp") + staleness_score: float = Field(default=0.0, ge=0.0, le=1.0, description="Staleness score (0.0=fresh, 1.0=stale)") + last_checked_commit: Optional[str] = Field(default=None, description="Git commit hash at last freshness check") + last_checked_at: Optional[float] = Field(default=None, description="Timestamp of last freshness check") + staleness_factors: Optional[dict[str, Any]] = Field(default=None, description="JSON factors contributing to staleness score") @field_validator("line_range") @classmethod @@ -101,6 +105,10 @@ class DeepWikiFile(BaseModel): ) symbols_count: int = Field(default=0, ge=0, description="Number of symbols indexed from this file") docs_generated: bool = Field(default=False, description="Whether documentation has been generated") + staleness_score: float = Field(default=0.0, ge=0.0, le=1.0, description="Staleness score (0.0=fresh, 1.0=stale)") + last_checked_commit: Optional[str] = Field(default=None, description="Git commit hash at last freshness check") + last_checked_at: Optional[float] = Field(default=None, description="Timestamp of last freshness check") + staleness_factors: Optional[dict[str, Any]] = Field(default=None, description="JSON factors contributing to staleness score") @field_validator("path", "content_hash") @classmethod diff --git a/codex-lens/src/codexlens/storage/deepwiki_store.py b/codex-lens/src/codexlens/storage/deepwiki_store.py index 0934b71d..763c0e4c 100644 --- a/codex-lens/src/codexlens/storage/deepwiki_store.py +++ b/codex-lens/src/codexlens/storage/deepwiki_store.py @@ -14,13 +14,13 @@ from __future__ import annotations import hashlib import json import logging -import platform +import math # noqa: F401 - used in calculate_staleness_score import sqlite3 import threading import time from datetime import datetime from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional from codexlens.errors import StorageError from codexlens.storage.deepwiki_models import DeepWikiDoc, DeepWikiFile, DeepWikiSymbol @@ -40,7 +40,7 @@ class DeepWikiStore: """ DEFAULT_DB_PATH = Path.home() / ".codexlens" / "deepwiki_index.db" - SCHEMA_VERSION = 1 + SCHEMA_VERSION = 2 def __init__(self, db_path: Path | None = None) -> None: """Initialize DeepWiki store. @@ -130,7 +130,11 @@ class DeepWikiStore: content_hash TEXT NOT NULL, last_indexed REAL NOT NULL, symbols_count INTEGER DEFAULT 0, - docs_generated INTEGER DEFAULT 0 + docs_generated INTEGER DEFAULT 0, + staleness_score REAL DEFAULT 0.0, + last_checked_commit TEXT, + last_checked_at REAL, + staleness_factors TEXT ) """ ) @@ -172,6 +176,10 @@ class DeepWikiStore: end_line INTEGER NOT NULL, created_at REAL, updated_at REAL, + staleness_score REAL DEFAULT 0.0, + last_checked_commit TEXT, + last_checked_at REAL, + staleness_factors TEXT, UNIQUE(name, source_file) ) """ @@ -226,6 +234,23 @@ class DeepWikiStore: (self.SCHEMA_VERSION, time.time()), ) + # Schema v2 migration: add staleness columns + staleness_columns = [ + ("deepwiki_files", "staleness_score", "REAL DEFAULT 0.0"), + ("deepwiki_files", "last_checked_commit", "TEXT"), + ("deepwiki_files", "last_checked_at", "REAL"), + ("deepwiki_files", "staleness_factors", "TEXT"), + ("deepwiki_symbols", "staleness_score", "REAL DEFAULT 0.0"), + ("deepwiki_symbols", "last_checked_commit", "TEXT"), + ("deepwiki_symbols", "last_checked_at", "REAL"), + ("deepwiki_symbols", "staleness_factors", "TEXT"), + ] + for table, col, col_type in staleness_columns: + try: + conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {col_type}") + except sqlite3.OperationalError: + pass # Column already exists + conn.commit() except sqlite3.DatabaseError as exc: raise StorageError( @@ -355,6 +380,70 @@ class DeepWikiStore: ) conn.commit() + def update_file_staleness( + self, + file_path: str | Path, + staleness_score: float, + commit: str | None = None, + factors: Dict[str, Any] | None = None, + ) -> None: + """Update staleness data for a tracked file. + + Args: + file_path: Path to the source file. + staleness_score: Staleness score (0.0-1.0). + commit: Git commit hash at check time. + factors: Dict of factors contributing to the score. + """ + with self._lock: + conn = self._get_connection() + path_str = self._normalize_path(file_path) + now = time.time() + factors_json = json.dumps(factors) if factors else None + + conn.execute( + """ + UPDATE deepwiki_files + SET staleness_score=?, last_checked_commit=?, last_checked_at=?, staleness_factors=? + WHERE path=? + """, + (staleness_score, commit, now, factors_json, path_str), + ) + conn.commit() + + def update_symbol_staleness( + self, + name: str, + source_file: str | Path, + staleness_score: float, + commit: str | None = None, + factors: Dict[str, Any] | None = None, + ) -> None: + """Update staleness data for a symbol. + + Args: + name: Symbol name. + source_file: Path to the source file. + staleness_score: Staleness score (0.0-1.0). + commit: Git commit hash at check time. + factors: Dict of factors contributing to the score. + """ + with self._lock: + conn = self._get_connection() + path_str = self._normalize_path(source_file) + now = time.time() + factors_json = json.dumps(factors) if factors else None + + conn.execute( + """ + UPDATE deepwiki_symbols + SET staleness_score=?, last_checked_commit=?, last_checked_at=?, staleness_factors=? + WHERE name=? AND source_file=? + """, + (staleness_score, commit, now, factors_json, name, path_str), + ) + conn.commit() + def remove_file(self, file_path: str | Path) -> bool: """Remove a tracked file and its associated symbols. @@ -722,6 +811,121 @@ class DeepWikiStore: return sha256.hexdigest() + @staticmethod + def calculate_staleness_score( + days_since_update: float, + commits_since: int = 0, + files_changed: int = 0, + lines_changed: int = 0, + proportion_changed: float = 0.0, + is_deleted: bool = False, + weights: tuple[float, float, float] = (0.1, 0.4, 0.5), + decay_k: float = 0.05, + ) -> float: + """Calculate staleness score using three-factor formula. + + S = min(1.0, w_t * T + w_c * C + w_s * M) + + Args: + days_since_update: Days since last documentation update. + commits_since: Number of commits since last check. + files_changed: Number of files changed. + lines_changed: Total lines changed. + proportion_changed: Proportion of symbol body changed (0.0-1.0). + is_deleted: Whether the symbol was deleted. + weights: (w_t, w_c, w_s) weights for time, churn, symbol factors. + decay_k: Time decay constant (default 0.05, ~14 days to 50%). + + Returns: + Staleness score between 0.0 and 1.0. + """ + w_t, w_c, w_s = weights + + # T: Time decay factor + T = 1 - math.exp(-decay_k * max(0, days_since_update)) + + # C: Code churn factor (sigmoid normalization) + churn_raw = ( + math.log1p(commits_since) + + math.log1p(files_changed) + + math.log1p(lines_changed) + ) + C = 1 / (1 + math.exp(-churn_raw + 3)) # sigmoid centered at 3 + + # M: Symbol modification factor + if is_deleted: + M = 1.0 + else: + M = min(1.0, max(0.0, proportion_changed)) + + return min(1.0, w_t * T + w_c * C + w_s * M) + + def get_stale_files( + self, files: list[dict[str, str]] + ) -> list[dict[str, str]]: + """Check which files have stale documentation by comparing hashes. + + Args: + files: List of dicts with 'path' and 'hash' keys. + + Returns: + List of file dicts where stored hash differs from provided hash. + """ + with self._lock: + conn = self._get_connection() + stale = [] + for f in files: + path_str = self._normalize_path(f["path"]) + row = conn.execute( + "SELECT content_hash FROM deepwiki_files WHERE path=?", + (path_str,), + ).fetchone() + if row and row["content_hash"] != f["hash"]: + stale.append({ + "path": f["path"], + "stored_hash": row["content_hash"], + "current_hash": f["hash"], + }) + elif not row: + stale.append({ + "path": f["path"], + "stored_hash": None, + "current_hash": f["hash"], + }) + return stale + + def get_symbols_for_paths( + self, paths: list[str | Path] + ) -> dict[str, list[DeepWikiSymbol]]: + """Get all symbols for multiple source files. + + Args: + paths: List of source file paths. + + Returns: + Dict mapping normalized path to list of DeepWikiSymbol records. + """ + with self._lock: + conn = self._get_connection() + result: dict[str, list[DeepWikiSymbol]] = {} + + for path in paths: + path_str = self._normalize_path(path) + rows = conn.execute( + """ + SELECT * FROM deepwiki_symbols + WHERE source_file=? + ORDER BY start_line + """, + (path_str,), + ).fetchall() + if rows: + result[path_str] = [ + self._row_to_deepwiki_symbol(row) for row in rows + ] + + return result + def stats(self) -> Dict[str, Any]: """Get storage statistics. @@ -914,6 +1118,14 @@ class DeepWikiStore: def _row_to_deepwiki_file(self, row: sqlite3.Row) -> DeepWikiFile: """Convert database row to DeepWikiFile.""" + staleness_factors = None + try: + factors_str = row["staleness_factors"] + if factors_str: + staleness_factors = json.loads(factors_str) + except (KeyError, IndexError): + pass + return DeepWikiFile( id=int(row["id"]), path=row["path"], @@ -923,6 +1135,10 @@ class DeepWikiStore: else datetime.utcnow(), symbols_count=int(row["symbols_count"]) if row["symbols_count"] else 0, docs_generated=bool(row["docs_generated"]), + staleness_score=float(row["staleness_score"]) if row["staleness_score"] else 0.0, + last_checked_commit=row["last_checked_commit"] if "last_checked_commit" in row.keys() else None, + last_checked_at=row["last_checked_at"] if "last_checked_at" in row.keys() else None, + staleness_factors=staleness_factors, ) def _row_to_deepwiki_symbol(self, row: sqlite3.Row) -> DeepWikiSymbol: @@ -935,6 +1151,14 @@ class DeepWikiStore: if row["updated_at"]: updated_at = datetime.fromtimestamp(row["updated_at"]) + staleness_factors = None + try: + factors_str = row["staleness_factors"] + if factors_str: + staleness_factors = json.loads(factors_str) + except (KeyError, IndexError): + pass + return DeepWikiSymbol( id=int(row["id"]), name=row["name"], @@ -945,6 +1169,10 @@ class DeepWikiStore: line_range=(int(row["start_line"]), int(row["end_line"])), created_at=created_at, updated_at=updated_at, + staleness_score=float(row["staleness_score"]) if row["staleness_score"] else 0.0, + last_checked_commit=row["last_checked_commit"] if "last_checked_commit" in row.keys() else None, + last_checked_at=row["last_checked_at"] if "last_checked_at" in row.keys() else None, + staleness_factors=staleness_factors, ) def _row_to_deepwiki_doc(self, row: sqlite3.Row) -> DeepWikiDoc: diff --git a/codex-lens/src/codexlens/tools/deepwiki_generator.py b/codex-lens/src/codexlens/tools/deepwiki_generator.py index 8cac50c7..87981643 100644 --- a/codex-lens/src/codexlens/tools/deepwiki_generator.py +++ b/codex-lens/src/codexlens/tools/deepwiki_generator.py @@ -605,7 +605,12 @@ Keep it minimal. Format as clean Markdown.""" symbol=symbol, ) - def should_regenerate(self, symbol: DeepWikiSymbol, source_code: str) -> bool: + def should_regenerate( + self, + symbol: DeepWikiSymbol, + source_code: str, + staleness_threshold: float = 0.7, + ) -> bool: """Check if symbol needs regeneration. Conditions for regeneration: @@ -613,10 +618,12 @@ Keep it minimal. Format as clean Markdown.""" 2. Symbol not in database (new) 3. Source code hash changed 4. Previous generation failed + 5. Staleness score exceeds threshold Args: symbol: Symbol to check. source_code: Source code of the symbol. + staleness_threshold: Score above which regeneration is triggered. Returns: True if regeneration needed, False otherwise. @@ -639,6 +646,11 @@ Keep it minimal. Format as clean Markdown.""" if progress.get("status") == "failed": return True # Retry failed + # Check staleness score from DeepWiki index + db_symbol = self.db.get_symbol(symbol.name, symbol.source_file) + if db_symbol and db_symbol.staleness_score >= staleness_threshold: + return True # Stale documentation + return False # Skip def _fallback_generate(