From 26bda9c634990bfbfe8a6a853c087715a46f9eb0 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Tue, 3 Mar 2026 23:35:41 +0800 Subject: [PATCH] feat: Add coordinator commands and role specifications for UI design team - Implemented the 'monitor' command for coordinator role to handle monitoring events, task completion, and pipeline management. - Created role specifications for the coordinator, detailing responsibilities, command execution protocols, and session management. - Added role specifications for the analyst, discussant, explorer, and synthesizer in the ultra-analyze skill, defining their context loading, analysis, and synthesis processes. --- .claude/agents/team-worker.md | 14 +- .../skills/ccw-help/index/all-commands.json | 4 +- .claude/skills/ccw-help/index/all-skills.json | 74 ++- .../ccw-help/index/command-relationships.json | 105 +--- .../ccw-help/index/skills-by-category.json | 74 ++- .claude/skills/team-arch-opt/SKILL.md | 6 +- .../team-arch-opt/role-specs/analyzer.md | 4 +- .../team-arch-opt/role-specs/designer.md | 6 +- .../team-arch-opt/role-specs/refactorer.md | 4 +- .../team-arch-opt/role-specs/reviewer.md | 6 +- .../team-arch-opt/role-specs/validator.md | 8 +- .../roles/coordinator/commands/dispatch.md | 26 +- .../roles/coordinator/commands/monitor.md | 6 +- .../team-arch-opt/roles/coordinator/role.md | 6 +- .claude/skills/team-brainstorm/SKILL.md | 185 +++--- .../team-brainstorm/role-specs/challenger.md | 63 +++ .../team-brainstorm/role-specs/evaluator.md | 58 ++ .../team-brainstorm/role-specs/ideator.md | 71 +++ .../team-brainstorm/role-specs/synthesizer.md | 59 ++ .../team-brainstorm/roles/challenger.md | 20 +- .../team-brainstorm/roles/coordinator.md | 20 +- .../roles/coordinator/commands/dispatch.md | 220 ++++++++ .../roles/coordinator/commands/monitor.md | 165 ++++++ .../team-brainstorm/roles/coordinator/role.md | 317 +++++++++++ .../skills/team-brainstorm/roles/evaluator.md | 16 +- .../skills/team-brainstorm/roles/ideator.md | 28 +- .../team-brainstorm/roles/synthesizer.md | 20 +- .claude/skills/team-coordinate-v2/SKILL.md | 5 +- .../roles/coordinator/commands/dispatch.md | 4 +- .../roles/coordinator/commands/monitor.md | 2 +- .../roles/coordinator/role.md | 6 +- .../specs/role-spec-template.md | 45 +- .../roles/executor/commands/monitor.md | 2 +- .../team-executor-v2/specs/session-schema.md | 8 +- .claude/skills/team-frontend/SKILL.md | 529 +++++++----------- .../team-frontend/role-specs/analyst.md | 92 +++ .../team-frontend/role-specs/architect.md | 86 +++ .../team-frontend/role-specs/developer.md | 93 +++ .claude/skills/team-frontend/role-specs/qa.md | 79 +++ .../analyst/commands/design-intelligence.md | 150 ----- .../team-frontend/roles/analyst/role.md | 225 -------- .../team-frontend/roles/architect/role.md | 219 -------- .../roles/coordinator/commands/dispatch.md | 202 +++++++ .../roles/coordinator/commands/monitor.md | 185 ++++++ .../team-frontend/roles/coordinator/role.md | 455 +++++++-------- .../team-frontend/roles/developer/role.md | 238 -------- .../qa/commands/pre-delivery-checklist.md | 116 ---- .claude/skills/team-frontend/roles/qa/role.md | 257 --------- .claude/skills/team-issue/SKILL.md | 20 +- .../skills/team-issue/role-specs/explorer.md | 105 ++++ .../team-issue/role-specs/implementer.md | 89 +++ .../team-issue/role-specs/integrator.md | 94 ++++ .../skills/team-issue/role-specs/planner.md | 85 +++ .../skills/team-issue/role-specs/reviewer.md | 89 +++ .../skills/team-issue/roles/coordinator.md | 12 +- .../roles/coordinator/commands/dispatch.md | 375 +++++++++++++ .../roles/coordinator/commands/monitor.md | 202 +++++++ .../team-issue/roles/coordinator/role.md | 277 +++++++++ .claude/skills/team-issue/roles/explorer.md | 8 +- .../skills/team-issue/roles/implementer.md | 12 +- .claude/skills/team-issue/roles/integrator.md | 16 +- .claude/skills/team-issue/roles/planner.md | 16 +- .claude/skills/team-issue/roles/reviewer.md | 8 +- .claude/skills/team-iterdev/SKILL.md | 34 +- .../team-iterdev/role-specs/architect.md | 64 +++ .../team-iterdev/role-specs/developer.md | 73 +++ .../team-iterdev/role-specs/reviewer.md | 65 +++ .../skills/team-iterdev/role-specs/tester.md | 74 +++ .../skills/team-iterdev/roles/architect.md | 25 +- .../skills/team-iterdev/roles/coordinator.md | 21 +- .../roles/coordinator/commands/dispatch.md | 248 ++++++++ .../team-iterdev/roles/coordinator/role.md | 269 +++++++++ .../skills/team-iterdev/roles/developer.md | 25 +- .claude/skills/team-iterdev/roles/reviewer.md | 25 +- .claude/skills/team-iterdev/roles/tester.md | 25 +- .claude/skills/team-perf-opt/SKILL.md | 3 +- .../team-perf-opt/role-specs/benchmarker.md | 6 +- .../team-perf-opt/role-specs/optimizer.md | 2 +- .../team-perf-opt/role-specs/profiler.md | 4 +- .../team-perf-opt/role-specs/reviewer.md | 6 +- .../team-perf-opt/role-specs/strategist.md | 6 +- .../roles/coordinator/commands/dispatch.md | 22 +- .../roles/coordinator/commands/monitor.md | 2 +- .../team-perf-opt/roles/coordinator/role.md | 6 +- .claude/skills/team-planex/SKILL.md | 10 +- .../skills/team-planex/role-specs/executor.md | 3 +- .../skills/team-planex/role-specs/planner.md | 1 - .../roles/coordinator/commands/monitor.md | 2 +- .../team-planex/roles/coordinator/role.md | 6 +- .../skills/team-quality-assurance/SKILL.md | 17 +- .../role-specs/analyst.md | 80 +++ .../role-specs/executor.md | 65 +++ .../role-specs/generator.md | 68 +++ .../role-specs/scout.md | 67 +++ .../role-specs/strategist.md | 71 +++ .../roles/analyst/commands/quality-report.md | 4 +- .../roles/analyst/role.md | 11 +- .../roles/coordinator/commands/dispatch.md | 4 +- .../roles/coordinator/commands/monitor.md | 75 +-- .../roles/coordinator/role.md | 52 +- .../roles/executor/commands/run-fix-cycle.md | 2 +- .../roles/executor/role.md | 12 +- .../generator/commands/generate-tests.md | 2 +- .../roles/generator/role.md | 11 +- .../roles/scout/role.md | 10 +- .../roles/strategist/role.md | 11 +- .claude/skills/team-review/SKILL.md | 9 +- .../skills/team-review/role-specs/fixer.md | 75 +++ .../skills/team-review/role-specs/reviewer.md | 66 +++ .../skills/team-review/role-specs/scanner.md | 70 +++ .../roles/coordinator/commands/dispatch.md | 12 +- .../roles/coordinator/commands/monitor.md | 40 +- .../team-review/roles/coordinator/role.md | 64 ++- .../roles/fixer/commands/execute-fixes.md | 3 +- .../roles/fixer/commands/plan-fixes.md | 3 +- .../skills/team-review/roles/fixer/role.md | 8 +- .../skills/team-review/roles/reviewer/role.md | 8 +- .../skills/team-review/roles/scanner/role.md | 8 +- .claude/skills/team-roadmap-dev/SKILL.md | 11 +- .../team-roadmap-dev/role-specs/executor.md | 60 ++ .../team-roadmap-dev/role-specs/planner.md | 60 ++ .../team-roadmap-dev/role-specs/verifier.md | 72 +++ .../roles/coordinator/commands/dispatch.md | 3 +- .../roles/coordinator/commands/monitor.md | 83 ++- .../roles/coordinator/commands/pause.md | 3 +- .../roles/coordinator/commands/resume.md | 3 +- .../roles/coordinator/role.md | 55 +- .../roles/executor/commands/implement.md | 10 +- .../team-roadmap-dev/roles/executor/role.md | 7 +- .../roles/planner/commands/create-plans.md | 35 +- .../team-roadmap-dev/roles/planner/role.md | 12 +- .../team-roadmap-dev/roles/verifier/role.md | 7 +- .claude/skills/team-tech-debt/SKILL.md | 20 +- .../team-tech-debt/role-specs/assessor.md | 70 +++ .../team-tech-debt/role-specs/executor.md | 68 +++ .../team-tech-debt/role-specs/planner.md | 71 +++ .../team-tech-debt/role-specs/scanner.md | 84 +++ .../team-tech-debt/role-specs/validator.md | 70 +++ .../team-tech-debt/roles/assessor/role.md | 14 +- .../roles/coordinator/commands/dispatch.md | 5 +- .../roles/coordinator/commands/monitor.md | 103 ++-- .../team-tech-debt/roles/coordinator/role.md | 60 +- .../team-tech-debt/roles/executor/role.md | 12 +- .../team-tech-debt/roles/planner/role.md | 12 +- .../team-tech-debt/roles/scanner/role.md | 12 +- .../team-tech-debt/roles/validator/role.md | 12 +- .../team-tech-debt/specs/team-config.json | 2 +- .claude/skills/team-testing/SKILL.md | 70 +-- .../skills/team-testing/role-specs/analyst.md | 94 ++++ .../team-testing/role-specs/executor.md | 92 +++ .../team-testing/role-specs/generator.md | 92 +++ .../team-testing/role-specs/strategist.md | 82 +++ .claude/skills/team-testing/roles/analyst.md | 50 +- .../skills/team-testing/roles/coordinator.md | 55 +- .../roles/coordinator/commands/dispatch.md | 156 ++++++ .../roles/coordinator/commands/monitor.md | 188 +++++++ .../team-testing/roles/coordinator/role.md | 276 +++++++++ .claude/skills/team-testing/roles/executor.md | 64 +-- .../skills/team-testing/roles/generator.md | 52 +- .../skills/team-testing/roles/strategist.md | 48 +- .claude/skills/team-uidesign/SKILL.md | 23 +- .../team-uidesign/role-specs/designer.md | 72 +++ .../team-uidesign/role-specs/implementer.md | 74 +++ .../team-uidesign/role-specs/researcher.md | 85 +++ .../team-uidesign/role-specs/reviewer.md | 70 +++ .../skills/team-uidesign/roles/coordinator.md | 35 +- .../roles/coordinator/commands/dispatch.md | 190 +++++++ .../roles/coordinator/commands/monitor.md | 203 +++++++ .../team-uidesign/roles/coordinator/role.md | 278 +++++++++ .../skills/team-uidesign/roles/designer.md | 10 +- .../skills/team-uidesign/roles/implementer.md | 10 +- .../skills/team-uidesign/roles/researcher.md | 12 +- .../skills/team-uidesign/roles/reviewer.md | 10 +- .claude/skills/team-ultra-analyze/SKILL.md | 28 +- .../team-ultra-analyze/role-specs/analyst.md | 90 +++ .../role-specs/discussant.md | 90 +++ .../team-ultra-analyze/role-specs/explorer.md | 90 +++ .../role-specs/synthesizer.md | 78 +++ .../team-ultra-analyze/roles/analyst/role.md | 12 +- .../roles/coordinator/commands/dispatch.md | 477 +++++++++------- .../roles/coordinator/commands/monitor.md | 80 +-- .../roles/coordinator/role.md | 406 ++++++-------- .../roles/discussant/role.md | 12 +- .../team-ultra-analyze/roles/explorer/role.md | 12 +- .../roles/synthesizer/role.md | 12 +- ccw/src/cli.ts | 2 +- ccw/src/commands/team.ts | 38 +- ccw/src/tools/team-msg.ts | 44 +- 188 files changed, 9332 insertions(+), 3512 deletions(-) create mode 100644 .claude/skills/team-brainstorm/role-specs/challenger.md create mode 100644 .claude/skills/team-brainstorm/role-specs/evaluator.md create mode 100644 .claude/skills/team-brainstorm/role-specs/ideator.md create mode 100644 .claude/skills/team-brainstorm/role-specs/synthesizer.md create mode 100644 .claude/skills/team-brainstorm/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-brainstorm/roles/coordinator/role.md create mode 100644 .claude/skills/team-frontend/role-specs/analyst.md create mode 100644 .claude/skills/team-frontend/role-specs/architect.md create mode 100644 .claude/skills/team-frontend/role-specs/developer.md create mode 100644 .claude/skills/team-frontend/role-specs/qa.md delete mode 100644 .claude/skills/team-frontend/roles/analyst/commands/design-intelligence.md delete mode 100644 .claude/skills/team-frontend/roles/analyst/role.md delete mode 100644 .claude/skills/team-frontend/roles/architect/role.md create mode 100644 .claude/skills/team-frontend/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-frontend/roles/coordinator/commands/monitor.md delete mode 100644 .claude/skills/team-frontend/roles/developer/role.md delete mode 100644 .claude/skills/team-frontend/roles/qa/commands/pre-delivery-checklist.md delete mode 100644 .claude/skills/team-frontend/roles/qa/role.md create mode 100644 .claude/skills/team-issue/role-specs/explorer.md create mode 100644 .claude/skills/team-issue/role-specs/implementer.md create mode 100644 .claude/skills/team-issue/role-specs/integrator.md create mode 100644 .claude/skills/team-issue/role-specs/planner.md create mode 100644 .claude/skills/team-issue/role-specs/reviewer.md create mode 100644 .claude/skills/team-issue/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-issue/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-issue/roles/coordinator/role.md create mode 100644 .claude/skills/team-iterdev/role-specs/architect.md create mode 100644 .claude/skills/team-iterdev/role-specs/developer.md create mode 100644 .claude/skills/team-iterdev/role-specs/reviewer.md create mode 100644 .claude/skills/team-iterdev/role-specs/tester.md create mode 100644 .claude/skills/team-iterdev/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-iterdev/roles/coordinator/role.md create mode 100644 .claude/skills/team-quality-assurance/role-specs/analyst.md create mode 100644 .claude/skills/team-quality-assurance/role-specs/executor.md create mode 100644 .claude/skills/team-quality-assurance/role-specs/generator.md create mode 100644 .claude/skills/team-quality-assurance/role-specs/scout.md create mode 100644 .claude/skills/team-quality-assurance/role-specs/strategist.md create mode 100644 .claude/skills/team-review/role-specs/fixer.md create mode 100644 .claude/skills/team-review/role-specs/reviewer.md create mode 100644 .claude/skills/team-review/role-specs/scanner.md create mode 100644 .claude/skills/team-roadmap-dev/role-specs/executor.md create mode 100644 .claude/skills/team-roadmap-dev/role-specs/planner.md create mode 100644 .claude/skills/team-roadmap-dev/role-specs/verifier.md create mode 100644 .claude/skills/team-tech-debt/role-specs/assessor.md create mode 100644 .claude/skills/team-tech-debt/role-specs/executor.md create mode 100644 .claude/skills/team-tech-debt/role-specs/planner.md create mode 100644 .claude/skills/team-tech-debt/role-specs/scanner.md create mode 100644 .claude/skills/team-tech-debt/role-specs/validator.md create mode 100644 .claude/skills/team-testing/role-specs/analyst.md create mode 100644 .claude/skills/team-testing/role-specs/executor.md create mode 100644 .claude/skills/team-testing/role-specs/generator.md create mode 100644 .claude/skills/team-testing/role-specs/strategist.md create mode 100644 .claude/skills/team-testing/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-testing/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-testing/roles/coordinator/role.md create mode 100644 .claude/skills/team-uidesign/role-specs/designer.md create mode 100644 .claude/skills/team-uidesign/role-specs/implementer.md create mode 100644 .claude/skills/team-uidesign/role-specs/researcher.md create mode 100644 .claude/skills/team-uidesign/role-specs/reviewer.md create mode 100644 .claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-uidesign/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-uidesign/roles/coordinator/role.md create mode 100644 .claude/skills/team-ultra-analyze/role-specs/analyst.md create mode 100644 .claude/skills/team-ultra-analyze/role-specs/discussant.md create mode 100644 .claude/skills/team-ultra-analyze/role-specs/explorer.md create mode 100644 .claude/skills/team-ultra-analyze/role-specs/synthesizer.md diff --git a/.claude/agents/team-worker.md b/.claude/agents/team-worker.md index 167dd858..cdb5e8d8 100644 --- a/.claude/agents/team-worker.md +++ b/.claude/agents/team-worker.md @@ -35,7 +35,7 @@ Parse the following fields from your prompt: | `role` | Yes | Role name (analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa) | | `role_spec` | Yes | Path to role-spec .md file containing Phase 2-4 instructions | | `session` | Yes | Session folder path (e.g., `.workflow/.team/TLS-xxx-2026-02-27`) | -| `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`) | +| `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`). Used directly as `session_id` param for all message bus operations | | `team_name` | Yes | Team name for SendMessage | | `requirement` | Yes | Original task/requirement description | | `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks | @@ -256,7 +256,7 @@ After Phase 4 completes, determine Phase 5 variant (see Execution Flow for decis ``` mcp__ccw-tools__team_msg( operation="log", - team_session_id=, + session_id=, from=, type="state_update", data={ @@ -336,7 +336,7 @@ After spawning, MUST log to message bus (passive log, NOT a SendMessage): ``` mcp__ccw-tools__team_msg( operation="log", - team_session_id=, + session_id=, from=, type="fast_advance", summary="[] fast-advanced → spawned for " @@ -393,7 +393,7 @@ Always use `mcp__ccw-tools__team_msg` for team communication. | Param | Value | |-------|-------| | operation | "log" | -| team_session_id | `` (NOT team_name) | +| session_id | `` (NOT team_name) | | from | `` | | type | "state_update" for completion; or role_spec message_types for non-state messages | | data | structured state payload (auto-synced to meta.json when type="state_update"). Use `data.ref` for artifact paths | @@ -406,7 +406,7 @@ Always use `mcp__ccw-tools__team_msg` for team communication. ``` mcp__ccw-tools__team_msg( operation="get_state", - team_session_id=, + session_id=, role= // omit to get ALL role states ) ``` @@ -418,7 +418,7 @@ Returns `role_state[]` from meta.json. ``` mcp__ccw-tools__team_msg( operation="broadcast", - team_session_id=, + session_id=, from=, type= ) @@ -428,7 +428,7 @@ Equivalent to `log` with `to="all"`. Summary auto-generated. **CLI fallback** (if MCP tool unavailable): ``` -ccw team log --team --from --type --json +ccw team log --session-id --from --type --json ``` --- diff --git a/.claude/skills/ccw-help/index/all-commands.json b/.claude/skills/ccw-help/index/all-commands.json index 2e1ee0ed..21d3e15b 100644 --- a/.claude/skills/ccw-help/index/all-commands.json +++ b/.claude/skills/ccw-help/index/all-commands.json @@ -46,8 +46,8 @@ { "name": "flow-create", "command": "/flow-create", - "description": "", - "arguments": "", + "description": "Flow Template Generator - Generate workflow templates for meta-skill/flow-coordinator with interactive 3-phase workflow", + "arguments": "[template-name] [--output ]", "category": "general", "subcategory": null, "usage_scenario": "implementation", diff --git a/.claude/skills/ccw-help/index/all-skills.json b/.claude/skills/ccw-help/index/all-skills.json index 722024cd..ec392b2f 100644 --- a/.claude/skills/ccw-help/index/all-skills.json +++ b/.claude/skills/ccw-help/index/all-skills.json @@ -9,6 +9,16 @@ "version": "", "source": "../../../skills/brainstorm/SKILL.md" }, + { + "name": "ccw-help", + "description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".", + "category": "utility", + "is_team": false, + "has_phases": false, + "has_role_specs": false, + "version": "8.0.0", + "source": "../../../skills/ccw-help/SKILL.md" + }, { "name": "command-generator", "description": "Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on \"create command\", \"new command\", \"command generator\".", @@ -99,6 +109,16 @@ "version": "", "source": "../../../skills/spec-generator/SKILL.md" }, + { + "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\".", + "category": "team", + "is_team": true, + "has_phases": false, + "has_role_specs": true, + "version": "", + "source": "../../../skills/team-arch-opt/SKILL.md" + }, { "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\".", @@ -109,16 +129,6 @@ "version": "", "source": "../../../skills/team-brainstorm/SKILL.md" }, - { - "name": "team-coordinate", - "description": "Universal team coordination skill with dynamic role generation. Only coordinator is built-in -- all worker roles are generated at runtime based on task analysis. Beat/cadence model for orchestration. Triggers on \"team coordinate\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-coordinate/SKILL.md" - }, { "name": "team-coordinate-v2", "description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"team coordinate v2\".", @@ -129,16 +139,6 @@ "version": "", "source": "../../../skills/team-coordinate-v2/SKILL.md" }, - { - "name": "team-executor", - "description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-executor/SKILL.md" - }, { "name": "team-executor-v2", "description": "Lightweight session execution skill. Resumes existing team-coordinate-v2 sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor v2\".", @@ -179,26 +179,6 @@ "version": "", "source": "../../../skills/team-iterdev/SKILL.md" }, - { - "name": "team-lifecycle-v3", - "description": "Unified team skill for full lifecycle - spec/impl/test. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-lifecycle-v3/SKILL.md" - }, - { - "name": "team-lifecycle-v4", - "description": "Unified team skill for full lifecycle - spec/impl/test. Optimized cadence with inline discuss subagent and shared explore. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-lifecycle-v4/SKILL.md" - }, { "name": "team-lifecycle-v5", "description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".", @@ -209,6 +189,16 @@ "version": "", "source": "../../../skills/team-lifecycle-v5/SKILL.md" }, + { + "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\".", + "category": "team", + "is_team": true, + "has_phases": false, + "has_role_specs": true, + "version": "", + "source": "../../../skills/team-perf-opt/SKILL.md" + }, { "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\".", @@ -340,7 +330,7 @@ "source": "../../../skills/workflow-skill-designer/SKILL.md" }, { - "name": "workflow-tdd-plan-plan", + "name": "workflow-tdd-plan", "description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".", "category": "workflow", "is_team": false, @@ -359,4 +349,4 @@ "version": "", "source": "../../../skills/workflow-test-fix/SKILL.md" } -] \ No newline at end of file +] diff --git a/.claude/skills/ccw-help/index/command-relationships.json b/.claude/skills/ccw-help/index/command-relationships.json index 039acd81..56e10aeb 100644 --- a/.claude/skills/ccw-help/index/command-relationships.json +++ b/.claude/skills/ccw-help/index/command-relationships.json @@ -1,49 +1,40 @@ { "workflow-plan": { "calls_internally": [ - "workflow:session:start", - "workflow:tools:context-gather", - "workflow:tools:conflict-resolution", - "workflow:tools:task-generate-agent" + "workflow:session:start" ], "next_steps": [ "workflow-plan-verify", - "workflow:status", - "workflow-execute" - ], - "alternatives": [ - "workflow-tdd-plan" + "workflow:session:list", + "workflow:unified-execute-with-file" ], + "alternatives": [], "prerequisites": [] }, "workflow-tdd-plan": { "calls_internally": [ - "workflow:session:start", - "workflow:tools:context-gather", - "workflow:tools:task-generate-tdd" + "workflow:session:start" ], "next_steps": [ "workflow-tdd-verify", - "workflow:status", - "workflow-execute" - ], - "alternatives": [ - "workflow-plan" + "workflow:session:list", + "workflow:unified-execute-with-file" ], + "alternatives": [], "prerequisites": [] }, - "workflow-execute": { + "workflow:unified-execute-with-file": { "prerequisites": [ "workflow-plan", "workflow-tdd-plan" ], "related": [ - "workflow:status", - "workflow:resume" + "workflow:session:list", + "workflow:session:resume" ], "next_steps": [ - "workflow:review", - "workflow-tdd-verify" + "review-cycle", + "workflow-test-fix" ] }, "workflow-plan-verify": { @@ -51,24 +42,22 @@ "workflow-plan" ], "next_steps": [ - "workflow-execute" + "workflow:unified-execute-with-file" ], "related": [ - "workflow:status" + "workflow:session:list" ] }, "workflow-tdd-verify": { "prerequisites": [ - "workflow-execute" + "workflow:unified-execute-with-file" ], - "related": [ - "workflow:tools:tdd-coverage-analysis" - ] + "related": [] }, "workflow:session:start": { "next_steps": [ "workflow-plan", - "workflow-execute" + "workflow:unified-execute-with-file" ], "related": [ "workflow:session:list", @@ -76,71 +65,27 @@ ] }, "workflow:session:resume": { - "alternatives": [ - "workflow:resume" - ], + "alternatives": [], "related": [ - "workflow:session:list", - "workflow:status" + "workflow:session:list" ] }, "workflow-lite-planex": { "calls_internally": [], "next_steps": [ - "workflow:status" + "workflow:session:list" ], "alternatives": [ "workflow-plan" ], "prerequisites": [] }, - "workflow:lite-fix": { - "next_steps": [ - "workflow:status" - ], - "alternatives": [ - "workflow-lite-planex" + "review-cycle": { + "prerequisites": [ + "workflow:unified-execute-with-file" ], "related": [ "workflow-test-fix" ] - }, - "workflow:review-session-cycle": { - "prerequisites": [ - "workflow-execute" - ], - "next_steps": [ - "workflow:review-fix" - ], - "related": [ - "workflow:review-module-cycle" - ] - }, - "workflow:review-fix": { - "prerequisites": [ - "workflow:review-module-cycle", - "workflow:review-session-cycle" - ], - "related": [ - "workflow-test-fix" - ] - }, - "memory:docs": { - "calls_internally": [ - "workflow:session:start", - "workflow:tools:context-gather" - ], - "next_steps": [ - "workflow-execute" - ] - }, - "memory:skill-memory": { - "next_steps": [ - "workflow-plan", - "cli:analyze" - ], - "related": [ - "memory:load-skill-memory" - ] } -} \ No newline at end of file +} diff --git a/.claude/skills/ccw-help/index/skills-by-category.json b/.claude/skills/ccw-help/index/skills-by-category.json index bd2b77de..dc2ba65e 100644 --- a/.claude/skills/ccw-help/index/skills-by-category.json +++ b/.claude/skills/ccw-help/index/skills-by-category.json @@ -54,6 +54,16 @@ } ], "utility": [ + { + "name": "ccw-help", + "description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".", + "category": "utility", + "is_team": false, + "has_phases": false, + "has_role_specs": false, + "version": "8.0.0", + "source": "../../../skills/ccw-help/SKILL.md" + }, { "name": "issue-manage", "description": "Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on \"manage issue\", \"list issues\", \"edit issue\", \"delete issue\", \"bulk update\", \"issue dashboard\", \"issue history\", \"completed issues\".", @@ -108,6 +118,16 @@ } ], "team": [ + { + "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\".", + "category": "team", + "is_team": true, + "has_phases": false, + "has_role_specs": true, + "version": "", + "source": "../../../skills/team-arch-opt/SKILL.md" + }, { "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\".", @@ -118,16 +138,6 @@ "version": "", "source": "../../../skills/team-brainstorm/SKILL.md" }, - { - "name": "team-coordinate", - "description": "Universal team coordination skill with dynamic role generation. Only coordinator is built-in -- all worker roles are generated at runtime based on task analysis. Beat/cadence model for orchestration. Triggers on \"team coordinate\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-coordinate/SKILL.md" - }, { "name": "team-coordinate-v2", "description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"team coordinate v2\".", @@ -138,16 +148,6 @@ "version": "", "source": "../../../skills/team-coordinate-v2/SKILL.md" }, - { - "name": "team-executor", - "description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-executor/SKILL.md" - }, { "name": "team-executor-v2", "description": "Lightweight session execution skill. Resumes existing team-coordinate-v2 sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor v2\".", @@ -188,26 +188,6 @@ "version": "", "source": "../../../skills/team-iterdev/SKILL.md" }, - { - "name": "team-lifecycle-v3", - "description": "Unified team skill for full lifecycle - spec/impl/test. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-lifecycle-v3/SKILL.md" - }, - { - "name": "team-lifecycle-v4", - "description": "Unified team skill for full lifecycle - spec/impl/test. Optimized cadence with inline discuss subagent and shared explore. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".", - "category": "team", - "is_team": true, - "has_phases": false, - "has_role_specs": false, - "version": "", - "source": "../../../skills/team-lifecycle-v4/SKILL.md" - }, { "name": "team-lifecycle-v5", "description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".", @@ -218,6 +198,16 @@ "version": "", "source": "../../../skills/team-lifecycle-v5/SKILL.md" }, + { + "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\".", + "category": "team", + "is_team": true, + "has_phases": false, + "has_role_specs": true, + "version": "", + "source": "../../../skills/team-perf-opt/SKILL.md" + }, { "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\".", @@ -351,7 +341,7 @@ "source": "../../../skills/workflow-skill-designer/SKILL.md" }, { - "name": "workflow-tdd-plan-plan", + "name": "workflow-tdd-plan", "description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".", "category": "workflow", "is_team": false, @@ -371,4 +361,4 @@ "source": "../../../skills/workflow-test-fix/SKILL.md" } ] -} \ No newline at end of file +} diff --git a/.claude/skills/team-arch-opt/SKILL.md b/.claude/skills/team-arch-opt/SKILL.md index 598ad887..950a3d1d 100644 --- a/.claude/skills/team-arch-opt/SKILL.md +++ b/.claude/skills/team-arch-opt/SKILL.md @@ -384,7 +384,9 @@ AskUserQuestion({ | +-- .md # Cached exploration results +-- wisdom/ | +-- patterns.md # Discovered patterns and conventions -| +-- shared-memory.json # Cross-role structured data ++-- .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 @@ -468,7 +470,7 @@ Coordinator supports `--resume` / `--continue` for interrupted sessions: | 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 | -| Shared-memory concurrent writes | Each worker writes only its own namespace key (e.g., `refactorer.B01`) | +| 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 | diff --git a/.claude/skills/team-arch-opt/role-specs/analyzer.md b/.claude/skills/team-arch-opt/role-specs/analyzer.md index 561be243..49fb58de 100644 --- a/.claude/skills/team-arch-opt/role-specs/analyzer.md +++ b/.claude/skills/team-arch-opt/role-specs/analyzer.md @@ -17,7 +17,7 @@ Analyze codebase architecture to identify structural issues: dependency cycles, |-------|--------|----------| | Task description | From task subject/description | Yes | | Session path | Extracted from task description | Yes | -| shared-memory.json | /wisdom/shared-memory.json | No | +| .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: @@ -76,5 +76,5 @@ Execute analysis based on detected project type: - Evidence summary per issue - Detected project type and analysis methods used -3. Update `/wisdom/shared-memory.json` under `analyzer` namespace: +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/role-specs/designer.md b/.claude/skills/team-arch-opt/role-specs/designer.md index 3a9660db..ede2d042 100644 --- a/.claude/skills/team-arch-opt/role-specs/designer.md +++ b/.claude/skills/team-arch-opt/role-specs/designer.md @@ -18,13 +18,13 @@ Analyze architecture reports and baseline metrics to design a prioritized refact |-------|--------|----------| | Architecture report | /artifacts/architecture-report.md | Yes | | Architecture baseline | /artifacts/architecture-baseline.json | Yes | -| shared-memory.json | /wisdom/shared-memory.json | Yes | +| .msg/meta.json | /wisdom/.msg/meta.json | Yes | | Wisdom files | /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 shared-memory.json for analyzer findings (project_type, scope) +4. Load .msg/meta.json for analyzer findings (project_type, scope) 5. Assess overall refactoring complexity: | Issue Count | Severity Mix | Complexity | @@ -91,7 +91,7 @@ Define measurable success criteria per refactoring (target metric improvement or - 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 `/wisdom/shared-memory.json` under `designer` namespace: +2. Update `/wisdom/.msg/meta.json` under `designer` namespace: - Read existing -> merge -> write back: ```json { diff --git a/.claude/skills/team-arch-opt/role-specs/refactorer.md b/.claude/skills/team-arch-opt/role-specs/refactorer.md index e1db48c0..a0701c01 100644 --- a/.claude/skills/team-arch-opt/role-specs/refactorer.md +++ b/.claude/skills/team-arch-opt/role-specs/refactorer.md @@ -28,7 +28,7 @@ Implement architecture refactoring changes following the design plan. For FIX ta | Branch refactoring detail | /artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) | | Pipeline refactoring plan | /artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) | | Review/validation feedback | From task description | Yes (FIX) | -| shared-memory.json | /wisdom/shared-memory.json | Yes | +| .msg/meta.json | /wisdom/.msg/meta.json | Yes | | Wisdom files | /wisdom/patterns.md | No | | Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) | @@ -50,7 +50,7 @@ Implement architecture refactoring changes following the design plan. For FIX ta 5. Use `explore` subagent to load implementation context for target files 6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks -**Shared-memory namespace**: +**Meta.json namespace**: - Single: write to `refactorer` namespace - Fan-out: write to `refactorer.B{NN}` namespace - Independent: write to `refactorer.{P}` namespace diff --git a/.claude/skills/team-arch-opt/role-specs/reviewer.md b/.claude/skills/team-arch-opt/role-specs/reviewer.md index 287463e2..86244065 100644 --- a/.claude/skills/team-arch-opt/role-specs/reviewer.md +++ b/.claude/skills/team-arch-opt/role-specs/reviewer.md @@ -21,7 +21,7 @@ Review refactoring code changes for correctness, pattern consistency, completene | 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 | -| shared-memory.json | /wisdom/shared-memory.json | Yes | +| .msg/meta.json | /wisdom/.msg/meta.json | Yes | 1. Extract session path from task description 2. **Detect branch/pipeline context** from task description: @@ -37,7 +37,7 @@ Review refactoring code changes for correctness, pattern consistency, completene - Fan-out branch: Read `/artifacts/branches/B{NN}/refactoring-detail.md` - Independent: Read `/artifacts/pipelines/{P}/refactoring-plan.md` -4. Load shared-memory.json for scoped refactorer namespace: +4. Load .msg/meta.json for scoped refactorer namespace: - Single: `refactorer` namespace - Fan-out: `refactorer.B{NN}` namespace - Independent: `refactorer.{P}` namespace @@ -108,7 +108,7 @@ Classify overall verdict based on findings: - Independent: `/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 `/wisdom/shared-memory.json` under scoped namespace: +2. Update `/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 } }` diff --git a/.claude/skills/team-arch-opt/role-specs/validator.md b/.claude/skills/team-arch-opt/role-specs/validator.md index cc5662ab..c22949d0 100644 --- a/.claude/skills/team-arch-opt/role-specs/validator.md +++ b/.claude/skills/team-arch-opt/role-specs/validator.md @@ -17,7 +17,7 @@ Validate refactoring changes by running build checks, test suites, dependency me |-------|--------|----------| | Architecture baseline | /artifacts/architecture-baseline.json (shared) | Yes | | Refactoring plan / detail | Varies by mode (see below) | Yes | -| shared-memory.json | /wisdom/shared-memory.json | Yes | +| .msg/meta.json | /wisdom/.msg/meta.json | Yes | 1. Extract session path from task description 2. **Detect branch/pipeline context** from task description: @@ -37,7 +37,7 @@ Validate refactoring changes by running build checks, test suites, dependency me - Fan-out branch: Read `/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria - Independent: Read `/artifacts/pipelines/{P}/refactoring-plan.md` -5. Load shared-memory.json for project type and refactoring scope +5. Load .msg/meta.json for project type and refactoring scope 6. Detect available validation tools from project: | Signal | Validation Tool | Method | @@ -50,7 +50,7 @@ Validate refactoring changes by running build checks, test suites, dependency me | Makefile with test target | Custom tests | make test | | No tooling detected | Manual validation | File existence + import grep checks | -7. Get changed files scope from shared-memory: +7. Get changed files scope from .msg/meta.json: - Single: `refactorer` namespace - Fan-out: `refactorer.B{NN}` namespace - Independent: `refactorer.{P}` namespace @@ -108,7 +108,7 @@ Compare against baseline and plan criteria: - Independent: `/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 `/wisdom/shared-memory.json` under scoped namespace: +2. Update `/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 } }` diff --git a/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md b/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md index 1e634166..c68cf64f 100644 --- a/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md @@ -38,7 +38,7 @@ CONTEXT: - Scope: - Branch: - Upstream artifacts: , - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: + CONSTRAINTS: --- @@ -77,7 +77,7 @@ CONTEXT: - Session: - Scope: - Branch: none - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: /artifacts/architecture-baseline.json + /artifacts/architecture-report.md | Quantified metrics with evidence CONSTRAINTS: Focus on | Analyze before any changes --- @@ -101,7 +101,7 @@ CONTEXT: - Scope: - Branch: none - Upstream artifacts: architecture-baseline.json, architecture-report.md - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: /artifacts/refactoring-plan.md | Priority-ordered with structural improvement targets, discrete REFACTOR-IDs CONSTRAINTS: Focus on highest-impact refactorings | Risk assessment required | Non-overlapping file targets per REFACTOR-ID --- @@ -126,7 +126,7 @@ CONTEXT: - Scope: - Branch: none - Upstream artifacts: refactoring-plan.md - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: Modified source files + validation passing | Refactorings applied without regressions CONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions --- @@ -152,7 +152,7 @@ CONTEXT: - Scope: - Branch: none - Upstream artifacts: architecture-baseline.json, refactoring-plan.md - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: /artifacts/validation-results.json | Per-dimension validation with verdicts CONSTRAINTS: Must compare against baseline | Flag any regressions or broken imports --- @@ -176,7 +176,7 @@ CONTEXT: - Scope: - Branch: none - Upstream artifacts: refactoring-plan.md, validation-results.json (if available) - - Shared memory: /wisdom/shared-memory.json + - Shared memory: /wisdom/.msg/meta.json EXPECTED: /artifacts/review-report.md | Per-dimension findings with severity CONSTRAINTS: Focus on refactoring changes only | Provide specific file:line references --- @@ -220,7 +220,7 @@ TaskCreate({ subject: "REVIEW-

01", ... }) // blockedBy: ["REFACTOR-

Task descriptions follow same template as single mode, with additions: - `Pipeline:

` in CONTEXT - Artifact paths use `/artifacts/pipelines/

/` instead of `/artifacts/` -- Shared-memory namespace uses `.

` (e.g., `analyzer.A`, `refactorer.B`) +- Meta.json namespace uses `.

` (e.g., `analyzer.A`, `refactorer.B`) - Each pipeline's scope is its specific target from `independent_targets[i]` Example for pipeline A with target "refactor auth module": @@ -236,7 +236,7 @@ CONTEXT: - Session: - Scope: refactor auth module - Pipeline: A - - Shared memory: /wisdom/shared-memory.json (namespace: analyzer.A) + - Shared memory: /wisdom/.msg/meta.json (namespace: analyzer.A) EXPECTED: /artifacts/pipelines/A/architecture-baseline.json + architecture-report.md CONSTRAINTS: Focus on auth module scope --- @@ -255,7 +255,7 @@ PipelineId: A", **Procedure**: 1. Read `/artifacts/refactoring-plan.md` to count REFACTOR-IDs -2. Read `shared-memory.json` -> `designer.refactoring_count` +2. Read `.msg/meta.json` -> `designer.refactoring_count` 3. **Auto mode decision**: | Refactoring Count | Decision | @@ -293,7 +293,7 @@ CONTEXT: - Session: - Branch: B{NN} - Upstream artifacts: branches/B{NN}/refactoring-detail.md - - Shared memory: /wisdom/shared-memory.json (namespace: refactorer.B{NN}) + - Shared memory: /wisdom/.msg/meta.json (namespace: refactorer.B{NN}) EXPECTED: Modified source files for REFACTOR-{NNN} only CONSTRAINTS: Only implement this branch's refactoring | Do not touch files outside REFACTOR-{NNN} scope --- @@ -314,7 +314,7 @@ CONTEXT: - Session: - Branch: B{NN} - Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md - - Shared memory: /wisdom/shared-memory.json (namespace: validator.B{NN}) + - Shared memory: /wisdom/.msg/meta.json (namespace: validator.B{NN}) EXPECTED: /artifacts/branches/B{NN}/validation-results.json CONSTRAINTS: Only validate this branch's changes --- @@ -328,14 +328,14 @@ TaskCreate({ subject: "REVIEW-B{NN}", description: "PURPOSE: Review branch B{NN} refactoring code | Success: Code quality verified for REFACTOR-{NNN} TASK: - - Load modified files from refactorer.B{NN} shared-memory namespace + - Load modified files from refactorer.B{NN} namespace in .msg/meta.json - Review across 5 dimensions for this branch's changes only - Issue verdict: APPROVE, REVISE, or REJECT CONTEXT: - Session: - Branch: B{NN} - Upstream artifacts: branches/B{NN}/refactoring-detail.md - - Shared memory: /wisdom/shared-memory.json (namespace: reviewer.B{NN}) + - Shared memory: /wisdom/.msg/meta.json (namespace: reviewer.B{NN}) EXPECTED: /artifacts/branches/B{NN}/review-report.md CONSTRAINTS: Only review this branch's changes --- 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 7dfe7871..cea2bf92 100644 --- a/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md @@ -104,8 +104,8 @@ Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` When both VALIDATE-001 and REVIEW-001 are completed: -1. Read validation verdict from shared-memory (validator namespace) -2. Read review verdict from shared-memory (reviewer namespace) +1. Read validation verdict from .msg/meta.json (validator namespace) +2. Read review verdict from .msg/meta.json (reviewer namespace) | Validate Verdict | Review Verdict | Action | |-----------------|----------------|--------| @@ -166,7 +166,7 @@ CONTEXT: - Session: - Branch: B{NN} - Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/validation-results.json - - Shared memory: /wisdom/shared-memory.json (namespace: refactorer.B{NN}) + - 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 --- diff --git a/.claude/skills/team-arch-opt/roles/coordinator/role.md b/.claude/skills/team-arch-opt/roles/coordinator/role.md index 36e37ba4..4f6b6b80 100644 --- a/.claude/skills/team-arch-opt/roles/coordinator/role.md +++ b/.claude/skills/team-arch-opt/roles/coordinator/role.md @@ -69,7 +69,7 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match ### Router Implementation 1. **Load session context** (if exists): - - Scan `.workflow/.team/ARCH-OPT-*/team-session.json` for active/paused sessions + - 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: @@ -186,10 +186,10 @@ Bash("mkdir -p .workflow//artifacts/pipelines/A .workflow//wisdom/shared-memory.json", { "session_id": "", "requirement": "", "parallel_mode": "" }) +Write("/wisdom/.msg/meta.json", { "session_id": "", "requirement": "", "parallel_mode": "" }) ``` 4. Create team: diff --git a/.claude/skills/team-brainstorm/SKILL.md b/.claude/skills/team-brainstorm/SKILL.md index eb1f5b33..6ba599ac 100644 --- a/.claude/skills/team-brainstorm/SKILL.md +++ b/.claude/skills/team-brainstorm/SKILL.md @@ -11,23 +11,23 @@ Unified team skill: multi-angle brainstorming via Generator-Critic loops, shared ## Architecture ``` -┌───────────────────────────────────────────────────┐ -│ Skill(skill="team-brainstorm") │ -│ args="" or args="--role=xxx" │ -└───────────────────┬───────────────────────────────┘ - │ Role Router - ┌──── --role present? ────┐ - │ NO │ YES - ↓ ↓ - Orchestration Mode Role Dispatch - (auto → coordinator) (route to role.md) - │ - ┌────┴────┬───────────┬───────────┬───────────┐ - ↓ ↓ ↓ ↓ ↓ -┌──────────┐┌─────────┐┌──────────┐┌──────────┐┌─────────┐ -│coordinator││ ideator ││challenger││synthesizer││evaluator│ -│ ││ IDEA-* ││CHALLENGE-*││ SYNTH-* ││ EVAL-* │ -└──────────┘└─────────┘└──────────┘└──────────┘└─────────┘ ++---------------------------------------------------+ +| Skill(skill="team-brainstorm") | +| args="" | ++-------------------+-------------------------------+ + | + Orchestration Mode (auto -> coordinator) + | + 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 ``` ## Role Router @@ -38,13 +38,13 @@ Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto r ### Role Registry -| Role | File | Task Prefix | Type | Compact | -|------|------|-------------|------|---------| -| coordinator | [roles/coordinator.md](roles/coordinator.md) | (none) | orchestrator | **⚠️ 压缩后必须重读** | -| ideator | [roles/ideator.md](roles/ideator.md) | IDEA-* | pipeline | 压缩后必须重读 | -| challenger | [roles/challenger.md](roles/challenger.md) | CHALLENGE-* | pipeline | 压缩后必须重读 | -| synthesizer | [roles/synthesizer.md](roles/synthesizer.md) | SYNTH-* | pipeline | 压缩后必须重读 | -| evaluator | [roles/evaluator.md](roles/evaluator.md) | EVAL-* | pipeline | 压缩后必须重读 | +| 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 | > **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 @@ -101,10 +101,10 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=****, from=, to="coordinator", type=, summary="[]

", ref= - - **CLI fallback**: When MCP unavailable → `ccw team log --team --from --to coordinator --type --summary "[] ..." --json` - - **Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description. -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[]`) + - Parameters: operation="log", session_id=, from=, type=, data={ref: ""} + - `to` and `summary` auto-defaulted -- do NOT specify explicitly + - **CLI fallback**: `ccw team log --session-id --from --type --json` +2. **SendMessage**: Send result to coordinator 3. **TaskUpdate**: Mark task completed 4. **Loop**: Return to Phase 1 to check next task @@ -130,7 +130,7 @@ Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at se |---------|-----------| | Process tasks with own prefix | Process tasks with other role prefixes | | SendMessage to coordinator | Communicate directly with other workers | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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. @@ -143,11 +143,12 @@ All outputs must carry `[role_name]` prefix in both SendMessage content/summary Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: -**Parameters**: operation="log", team=****, from=, to="coordinator", type=, summary="[] ", ref= +**Parameters**: operation="log", session_id=, from=, type=, data={ref: ""} -**CLI fallback**: When MCP unavailable → `ccw team log --team --from --to coordinator --type --summary "[] ..." --json` +`to` and `summary` auto-defaulted -- do NOT specify explicitly. + +**CLI fallback**: `ccw team log --session-id --from --type --json` -**Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description. **Message types by role**: @@ -159,12 +160,12 @@ Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: | synthesizer | `synthesis_ready`, `error` | | evaluator | `evaluation_ready`, `error` | -### Shared Memory +### Shared State -All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: +Cross-role state is shared via `team_msg(type="state_update")` messages, persisted in `.msg/meta.json`: -| Role | Field | -|------|-------| +| Role | State Key | +|------|-----------| | ideator | `generated_ideas` | | challenger | `critique_insights` | | synthesizer | `synthesis_themes` | @@ -176,7 +177,7 @@ All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: |---------|-------| | Team name | brainstorm | | Session directory | `.workflow/.team/BRS--/` | -| Shared memory | `shared-memory.json` in session dir | +| Message store | `.msg/messages.jsonl` + `.msg/meta.json` in session dir | --- @@ -291,79 +292,61 @@ Beat 1 2 3-4 5 6 ## Coordinator Spawn Template -When coordinator spawns workers, use background mode (Spawn-and-Stop). +### v5 Worker Spawn (all roles) -**Standard spawn** (single agent per role): For Quick/Deep pipeline, spawn one ideator. Challenger, synthesizer, and evaluator are always single agents. - -**Parallel spawn** (Full pipeline): For Full pipeline with N idea angles, spawn N ideator agents in parallel (`ideator-1`, `ideator-2`, ...) with `run_in_background: true`. Each parallel ideator only processes tasks where owner matches its agent name. After all parallel ideators complete, proceed with single challenger for batch critique. - -**Spawn template**: +When coordinator spawns workers, use `team-worker` agent with role-spec path: ``` Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: "Spawn worker", team_name: "brainstorm", name: "", run_in_background: true, - prompt: `You are team "brainstorm" . + prompt: `## Role Assignment +role: +role_spec: .claude/skills/team-brainstorm/role-specs/.md +session: +session_id: +team_name: brainstorm +requirement: +inner_loop: -## Primary Directive -All your work must be executed through Skill to load role definition: -Skill(skill="team-brainstorm", args="--role=") - -Current topic: -Session: - -## Role Guidelines -- Only process -* tasks, do not execute other role work -- All output prefixed with [] identifier -- Only communicate with coordinator -- Do not use TaskCreate for other roles -- Call mcp__ccw-tools__team_msg before every SendMessage - -## Workflow -1. Call Skill -> load role definition and execution logic -2. Follow role.md 5-Phase flow -3. team_msg + SendMessage results to coordinator -4. TaskUpdate completed -> check next task` +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).` }) ``` +**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 agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name. +> 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 agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` | -| Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` agent | +| 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 | ``` Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: "Spawn ideator- worker", team_name: "brainstorm", name: "ideator-", run_in_background: true, - prompt: `You are team "brainstorm" IDEATOR (ideator-). -Your agent name is "ideator-", use this name for task discovery owner matching. + prompt: `## Role Assignment +role: ideator +role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md +session: +session_id: +team_name: brainstorm +requirement: +agent_name: ideator- +inner_loop: false -## Primary Directive -Skill(skill="team-brainstorm", args="--role=ideator --agent-name=ideator-") - -Current topic: -Session: - -## Role Guidelines -- Only process tasks where owner === "ideator-" with IDEA-* prefix -- All output prefixed with [ideator] identifier - -## Workflow -1. TaskList -> find tasks where owner === "ideator-" with IDEA-* prefix -2. Skill -> execute role definition -3. team_msg + SendMessage results to coordinator -4. TaskUpdate completed -> check next task` +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery, owner=ideator-) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` }) ``` @@ -371,12 +354,40 @@ Session: --- +## Completion Action + +When the pipeline completes (all tasks done, coordinator Phase 5): + +``` +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(brainstorm) -> 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--/ -├── team-session.json # Session state -├── shared-memory.json # Cumulative: generated_ideas / critique_insights / synthesis_themes / evaluation_scores +├── .msg/ +│ ├── messages.jsonl # Message bus log +│ └── meta.json # Session state + cross-role state ├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md diff --git a/.claude/skills/team-brainstorm/role-specs/challenger.md b/.claude/skills/team-brainstorm/role-specs/challenger.md new file mode 100644 index 00000000..5506c3e2 --- /dev/null +++ b/.claude/skills/team-brainstorm/role-specs/challenger.md @@ -0,0 +1,63 @@ +--- +prefix: CHALLENGE +inner_loop: false +subagents: [] +message_types: + success: critique_ready + error: error +--- + +# 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 | /ideas/*.md files | Yes | +| Previous critiques | /.msg/meta.json critique_insights | No | + +1. Extract session path from task description (match "Session: ") +2. Glob idea files from /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 `/critiques/critique-.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/role-specs/evaluator.md b/.claude/skills/team-brainstorm/role-specs/evaluator.md new file mode 100644 index 00000000..2479bc7b --- /dev/null +++ b/.claude/skills/team-brainstorm/role-specs/evaluator.md @@ -0,0 +1,58 @@ +--- +prefix: EVAL +inner_loop: false +subagents: [] +message_types: + success: evaluation_ready + error: error +--- + +# 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 | /synthesis/*.md files | Yes | +| All ideas | /ideas/*.md files | No (for context) | +| All critiques | /critiques/*.md files | No (for context) | + +1. Extract session path from task description (match "Session: ") +2. Glob synthesis files from /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 `/evaluation/evaluation-.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/role-specs/ideator.md b/.claude/skills/team-brainstorm/role-specs/ideator.md new file mode 100644 index 00000000..d6522adf --- /dev/null +++ b/.claude/skills/team-brainstorm/role-specs/ideator.md @@ -0,0 +1,71 @@ +--- +prefix: IDEA +inner_loop: false +subagents: [] +message_types: + success: ideas_ready + error: error +--- + +# 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 | /.msg/meta.json | Yes | +| Angles | /.msg/meta.json | Yes | +| GC Round | /.msg/meta.json | Yes | +| Previous critique | /critiques/*.md | For revision tasks only | +| Previous ideas | /.msg/meta.json generated_ideas | No | + +1. Extract session path from task description (match "Session: ") +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 /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 `/ideas/idea-.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/role-specs/synthesizer.md b/.claude/skills/team-brainstorm/role-specs/synthesizer.md new file mode 100644 index 00000000..48ff2bdd --- /dev/null +++ b/.claude/skills/team-brainstorm/role-specs/synthesizer.md @@ -0,0 +1,59 @@ +--- +prefix: SYNTH +inner_loop: false +subagents: [] +message_types: + success: synthesis_ready + error: error +--- + +# 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 | /ideas/*.md files | Yes | +| All critiques | /critiques/*.md files | Yes | +| GC rounds completed | /.msg/meta.json gc_round | Yes | + +1. Extract session path from task description (match "Session: ") +2. Glob all idea files from /ideas/ +3. Glob all critique files from /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 `/synthesis/synthesis-.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/roles/challenger.md b/.claude/skills/team-brainstorm/roles/challenger.md index 8e9984cc..97637180 100644 --- a/.claude/skills/team-brainstorm/roles/challenger.md +++ b/.claude/skills/team-brainstorm/roles/challenger.md @@ -15,7 +15,7 @@ - 仅处理 `CHALLENGE-*` 前缀的任务 - 所有输出必须带 `[challenger]` 标识 - 仅通过 SendMessage 与 coordinator 通信 -- Phase 2 读取 shared-memory.json,Phase 5 写入 critique_insights +- Phase 2 读取 .msg/meta.json,Phase 5 写入 critique_insights - 为每个创意标记挑战严重度 (LOW/MEDIUM/HIGH/CRITICAL) ### MUST NOT @@ -23,7 +23,7 @@ - 生成创意、综合想法或评估排序 - 直接与其他 worker 角色通信 - 为其他角色创建任务 -- 修改 shared-memory.json 中不属于自己的字段 +- 修改 .msg/meta.json 中不属于自己的字段 - 在输出中省略 `[challenger]` 标识 --- @@ -37,7 +37,7 @@ | `TaskList` | Built-in | Phase 1 | Discover pending CHALLENGE-* tasks | | `TaskGet` | Built-in | Phase 1 | Get task details | | `TaskUpdate` | Built-in | Phase 1/5 | Update task status | -| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files | +| `Read` | Built-in | Phase 2 | Read .msg/meta.json, idea files | | `Write` | Built-in | Phase 3/5 | Write critique files, update shared memory | | `Glob` | Built-in | Phase 2 | Find idea files | | `SendMessage` | Built-in | Phase 5 | Report to coordinator | @@ -59,19 +59,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: ****, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field. + session_id: , from: "challenger", - to: "coordinator", type: "critique_ready", - summary: "[challenger] Critique complete: C/H/M/L -- Signal: ", - ref: + data: {ref: } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team --from challenger --to coordinator --type critique_ready --summary \"[challenger] Critique complete\" --ref --json") +Bash("ccw team log --session-id --from challenger --type critique_ready --json") ``` --- @@ -90,14 +88,14 @@ Standard task discovery flow: TaskList -> filter by prefix `CHALLENGE-*` + owner |-------|--------|----------| | Session folder | Task description (Session: line) | Yes | | Ideas | ideas/*.md files | Yes | -| Previous critiques | shared-memory.json.critique_insights | No (avoid repeating) | +| Previous critiques | .msg/meta.json.critique_insights | No (avoid repeating) | **Loading steps**: 1. Extract session path from task description (match "Session: ") 2. Glob idea files from session folder 3. Read all idea files for analysis -4. Read shared-memory.json.critique_insights to avoid repeating +4. Read .msg/meta.json.critique_insights to avoid repeating ### Phase 3: Critical Analysis @@ -151,7 +149,7 @@ Standard task discovery flow: TaskList -> filter by prefix `CHALLENGE-*` + owner Standard report flow: team_msg log -> SendMessage with `[challenger]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. **Shared Memory Update**: -1. Append challenges to shared-memory.json.critique_insights +1. Append challenges to .msg/meta.json.critique_insights 2. Each entry: idea, severity, key_challenge, round --- diff --git a/.claude/skills/team-brainstorm/roles/coordinator.md b/.claude/skills/team-brainstorm/roles/coordinator.md index 239a3556..db7944e4 100644 --- a/.claude/skills/team-brainstorm/roles/coordinator.md +++ b/.claude/skills/team-brainstorm/roles/coordinator.md @@ -47,20 +47,16 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: ****, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field. + session_id: , from: "coordinator", - to: , type: , - summary: "[coordinator] complete: ", - ref: + data: {ref: } }) ``` -**CLI fallback** (when MCP unavailable): +`to` and `summary` auto-defaulted -- do NOT specify explicitly. -``` -Bash("ccw team log --team --from coordinator --to --type --summary \"[coordinator] complete\" --ref --json") -``` +**CLI fallback**: `ccw team log --session-id --from coordinator --type --json` --- @@ -147,8 +143,8 @@ For callback/check/resume: load monitor logic and execute the appropriate handle 2. Create session folder structure 3. Call TeamCreate with team name 4. Initialize subdirectories: ideas/, critiques/, synthesis/, evaluation/ -5. Initialize shared-memory.json with: topic, pipeline, angles, gc_round, generated_ideas, critique_insights, synthesis_themes, evaluation_scores -6. Write team-session.json with: session_id, team_name, topic, pipeline, status="active", created_at, updated_at +5. Initialize .msg/meta.json with: topic, pipeline, angles, gc_round, generated_ideas, critique_insights, synthesis_themes, evaluation_scores +6. Write .msg/meta.json with: session_id, team_name, topic, pipeline, status="active", created_at, updated_at 7. Workers are NOT pre-spawned here -> spawned per-stage in Phase 4 **Success**: Team created, session file written, directories initialized. @@ -219,9 +215,9 @@ For callback/check/resume: load monitor logic and execute the appropriate handle **GC Round Tracking**: 1. Read critique file 2. Count severity: HIGH and CRITICAL -3. Read shared-memory.json for gc_round +3. Read .msg/meta.json for gc_round 4. If criticalCount > 0 AND gcRound < max_gc_rounds: - - Increment gc_round in shared-memory.json + - Increment gc_round in .msg/meta.json - Log team_msg with type "gc_loop_trigger" - Unblock IDEA-fix task 5. Else: Log team_msg with type "task_unblocked", unblock SYNTH diff --git a/.claude/skills/team-brainstorm/roles/coordinator/commands/dispatch.md b/.claude/skills/team-brainstorm/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..844d248f --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/coordinator/commands/dispatch.md @@ -0,0 +1,220 @@ +# Command: Dispatch + +Create the brainstorm task chain with correct dependencies and structured task descriptions based on selected pipeline mode. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| User topic | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline mode | From session.json pipeline | Yes | +| Angles | From session.json angles | Yes | + +1. Load topic, pipeline mode, and angles from session.json +2. Determine task chain from pipeline mode + +## Phase 3: Task Chain Creation + +### Task Description Template + +Every task description uses structured format: + +``` +TaskCreate({ + subject: "", + owner: "", + description: "PURPOSE: | Success: +TASK: + - + - + - +CONTEXT: + - Session: + - Topic: + - Angles: + - Upstream artifacts: +EXPECTED: + +CONSTRAINTS: +--- +InnerLoop: false", + blockedBy: [], + status: "pending" +}) +``` + +### Pipeline Router + +| Mode | Action | +|------|--------| +| quick | Create 3 tasks (IDEA -> CHALLENGE -> SYNTH) | +| deep | Create 6 tasks (IDEA -> CHALLENGE -> IDEA-fix -> CHALLENGE-2 -> SYNTH -> EVAL) | +| full | Create 7 tasks (3 parallel IDEAs -> CHALLENGE -> IDEA-fix -> SYNTH -> EVAL) | + +--- + +### Quick Pipeline + +**IDEA-001** (ideator): +``` +TaskCreate({ + subject: "IDEA-001", + owner: "ideator", + description: "PURPOSE: Generate multi-angle ideas for brainstorm topic | Success: >= 6 unique ideas across all angles +TASK: + - Read topic and angles from session context + - Generate 3+ ideas per angle with title, description, assumption, impact + - Self-review for coverage and uniqueness +CONTEXT: + - Session: + - Topic: + - Angles: +EXPECTED: /ideas/idea-001.md with >= 6 ideas +CONSTRAINTS: Divergent thinking only, no evaluation +--- +InnerLoop: false", + blockedBy: [], + status: "pending" +}) +``` + +**CHALLENGE-001** (challenger): +``` +TaskCreate({ + subject: "CHALLENGE-001", + owner: "challenger", + description: "PURPOSE: Challenge assumptions and assess feasibility of generated ideas | Success: Each idea rated by severity +TASK: + - Read all idea files from ideas/ directory + - Challenge each idea across 4 dimensions (assumption, feasibility, risk, competition) + - Assign severity (CRITICAL/HIGH/MEDIUM/LOW) per idea + - Determine GC signal (REVISION_NEEDED or CONVERGED) +CONTEXT: + - Session: + - Upstream artifacts: ideas/idea-001.md +EXPECTED: /critiques/critique-001.md with severity table and GC signal +CONSTRAINTS: Critical analysis only, do not generate alternative ideas +--- +InnerLoop: false", + blockedBy: ["IDEA-001"], + status: "pending" +}) +``` + +**SYNTH-001** (synthesizer): +``` +TaskCreate({ + subject: "SYNTH-001", + owner: "synthesizer", + description: "PURPOSE: Synthesize ideas and critiques into integrated proposals | Success: >= 1 consolidated proposal +TASK: + - Read all ideas and critiques + - Extract themes, resolve conflicts, group complementary ideas + - Generate 1-3 integrated proposals with feasibility and innovation scores +CONTEXT: + - Session: + - Upstream artifacts: ideas/*.md, critiques/*.md +EXPECTED: /synthesis/synthesis-001.md with proposals +CONSTRAINTS: Integration and synthesis only, no new ideas +--- +InnerLoop: false", + blockedBy: ["CHALLENGE-001"], + status: "pending" +}) +``` + +### Deep Pipeline + +Creates all 6 tasks. First 2 same as Quick, then: + +**IDEA-002** (ideator, GC revision): +``` +TaskCreate({ + subject: "IDEA-002", + owner: "ideator", + description: "PURPOSE: Revise ideas based on critique feedback (GC Round 1) | Success: HIGH/CRITICAL challenges addressed +TASK: + - Read critique feedback from critiques/ + - Revise challenged ideas, replace unsalvageable ones + - Retain unchallenged ideas intact +CONTEXT: + - Session: + - Upstream artifacts: critiques/critique-001.md +EXPECTED: /ideas/idea-002.md with revised ideas +CONSTRAINTS: Address critique only, focused revision +--- +InnerLoop: false", + blockedBy: ["CHALLENGE-001"], + status: "pending" +}) +``` + +**CHALLENGE-002** (challenger, round 2): +``` +TaskCreate({ + subject: "CHALLENGE-002", + owner: "challenger", + description: "PURPOSE: Validate revised ideas (GC Round 2) | Success: Severity assessment of revised ideas +TASK: + - Read revised idea files + - Re-evaluate previously challenged ideas + - Assess new replacement ideas +CONTEXT: + - Session: + - Upstream artifacts: ideas/idea-002.md +EXPECTED: /critiques/critique-002.md +CONSTRAINTS: Focus on revised/new ideas +--- +InnerLoop: false", + blockedBy: ["IDEA-002"], + status: "pending" +}) +``` + +**SYNTH-001** blocked by CHALLENGE-002. **EVAL-001** blocked by SYNTH-001: + +``` +TaskCreate({ + subject: "EVAL-001", + owner: "evaluator", + description: "PURPOSE: Score and rank synthesized proposals | Success: Ranked list with weighted scores +TASK: + - Read synthesis results + - Score each proposal across 4 dimensions (Feasibility 30%, Innovation 25%, Impact 25%, Cost 20%) + - Generate final ranking and recommendation +CONTEXT: + - Session: + - Upstream artifacts: synthesis/synthesis-001.md +EXPECTED: /evaluation/evaluation-001.md with scoring matrix +CONSTRAINTS: Evaluation only, no new proposals +--- +InnerLoop: false", + blockedBy: ["SYNTH-001"], + status: "pending" +}) +``` + +### Full Pipeline + +Creates 7 tasks. Parallel ideators: + +| Task | Owner | BlockedBy | +|------|-------|-----------| +| IDEA-001 | ideator-1 | (none) | +| IDEA-002 | ideator-2 | (none) | +| IDEA-003 | ideator-3 | (none) | +| CHALLENGE-001 | challenger | IDEA-001, IDEA-002, IDEA-003 | +| IDEA-004 | ideator | CHALLENGE-001 | +| SYNTH-001 | synthesizer | IDEA-004 | +| EVAL-001 | evaluator | SYNTH-001 | + +Each parallel IDEA task scoped to a specific angle from the angles list. + +## Phase 4: Validation + +1. Verify all tasks created with `TaskList()` +2. Check dependency chain integrity: + - No circular dependencies + - All blockedBy references exist + - First task(s) have empty blockedBy +3. Log task count and pipeline mode diff --git a/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md b/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..9f4f25f0 --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/coordinator/commands/monitor.md @@ -0,0 +1,165 @@ +# Command: Monitor + +Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion. + +## Constants + +| Key | Value | +|-----|-------| +| SPAWN_MODE | background | +| ONE_STEP_PER_INVOCATION | true | +| WORKER_AGENT | team-worker | +| MAX_GC_ROUNDS | 2 | + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session state | /session.json | Yes | +| Task list | TaskList() | Yes | +| Trigger event | From Entry Router detection | Yes | +| Meta state | /.msg/meta.json | Yes | + +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 + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +1. Parse message to identify role and task ID: + +| Message Pattern | Role Detection | +|----------------|---------------| +| `[ideator]` or task ID `IDEA-*` | ideator | +| `[challenger]` or task ID `CHALLENGE-*` | challenger | +| `[synthesizer]` or task ID `SYNTH-*` | synthesizer | +| `[evaluator]` or task ID `EVAL-*` | evaluator | + +2. Mark task as completed: + +``` +TaskUpdate({ taskId: "", 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 + - Read .msg/meta.json for gc_round + + | GC Signal | gc_round < max | Action | + |-----------|----------------|--------| + | REVISION_NEEDED | Yes | Increment gc_round, unblock IDEA-fix task | + | REVISION_NEEDED | No (>= max) | Force convergence, unblock SYNTH | + | CONVERGED | - | Unblock SYNTH (skip remaining GC tasks) | + + - Log team_msg with type "gc_loop_trigger" or "task_unblocked" + - If skipping GC tasks, mark them as completed (skip) + +5. 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. For each ready task, spawn team-worker: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker for ", + team_name: "brainstorm", + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: .claude/skills/team-brainstorm/role-specs/.md +session: +session_id: +team_name: brainstorm +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.` +}) +``` + +3. **Parallel spawn rules**: + +| Pipeline | Scenario | Spawn Behavior | +|----------|----------|---------------| +| Quick | Single sequential | One worker at a time | +| Deep | Sequential with GC | One worker at a time | +| 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. + +``` +Pipeline Status (): + [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: / +Session: +``` + +### 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 + +### handleConsensus + +Handle consensus_blocked signals. + +| Severity | Action | +|----------|--------| +| HIGH | Pause pipeline, notify user with findings summary | +| MEDIUM | Log finding, attempt to continue | +| LOW | Log finding, continue pipeline | + +### handleComplete + +Triggered when all pipeline tasks are completed. + +**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 (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 diff --git a/.claude/skills/team-brainstorm/roles/coordinator/role.md b/.claude/skills/team-brainstorm/roles/coordinator/role.md new file mode 100644 index 00000000..e9845357 --- /dev/null +++ b/.claude/skills/team-brainstorm/roles/coordinator/role.md @@ -0,0 +1,317 @@ +# Coordinator - Brainstorm Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: brainstorm + +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. + +## 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 +- Manage Generator-Critic loop count (max 2 rounds) +- 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/.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 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) | + +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 + +--- + +## 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 + +--- + +## Phase 1: Topic Clarification + Complexity Assessment + +1. Parse user task description from $ARGUMENTS +2. Parse optional `--team-name` flag (default: "brainstorm") + +3. Assess topic complexity: + +| Signal | Weight | Keywords | +|--------|--------|----------| +| Strategic/systemic | +3 | strategy, architecture, system, framework, paradigm | +| Multi-dimensional | +2 | multiple, compare, tradeoff, versus, alternative | +| Innovation-focused | +2 | innovative, creative, novel, breakthrough | +| Simple/basic | -2 | simple, quick, straightforward, basic | + +| Score | Complexity | Pipeline Recommendation | +|-------|------------|-------------------------| +| >= 4 | High | full | +| 2-3 | Medium | deep | +| 0-1 | Low | quick | + +4. Ask for missing parameters: + +``` +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 + +1. Generate session ID: `BRS--` +2. Create session folder structure: + +``` +Bash("mkdir -p .workflow/.team//ideas .workflow/.team//critiques .workflow/.team//synthesis .workflow/.team//evaluation .workflow/.team//wisdom .workflow/.team//.msg") +``` + +3. Write session.json: + +```json +{ + "status": "active", + "team_name": "brainstorm", + "topic": "", + "pipeline": "", + "angles": ["", ""], + "gc_round": 0, + "max_gc_rounds": 2, + "timestamp": "" +} +``` + +4. Initialize .msg/meta.json: + +```json +{ + "session_id": "", + "team_name": "brainstorm", + "topic": "", + "pipeline": "", + "angles": [], + "gc_round": 0, + "generated_ideas": [], + "critique_insights": [], + "synthesis_themes": [], + "evaluation_scores": [], + "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): + +``` +Task({ + 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_id: +team_name: brainstorm +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.` +}) +``` + +For **Full pipeline** with parallel ideators, spawn N team-worker agents: + +``` +// For each parallel IDEA task (IDEA-001, IDEA-002, IDEA-003) +Task({ + subagent_type: "team-worker", + description: "Spawn ideator worker for IDEA-", + 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_id: +team_name: brainstorm +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. + +All subsequent coordination handled by `commands/monitor.md` handlers. + +--- + +## Phase 5: Report + Completion Action + +1. Load session state -> count completed tasks, calculate duration +2. List deliverables: + +| Deliverable | Path | +|-------------|------| +| Ideas | /ideas/*.md | +| Critiques | /critiques/*.md | +| Synthesis | /synthesis/*.md | +| Evaluation | /evaluation/*.md (deep/full only) | + +3. Output pipeline summary: topic, pipeline mode, GC rounds, total ideas, key themes + +4. **Completion Action** (interactive): + +``` +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" } + ] + }] +}) +``` + +5. Handle user choice: + +| Choice | Steps | +|--------|-------| +| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("brainstorm") -> 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 | diff --git a/.claude/skills/team-brainstorm/roles/evaluator.md b/.claude/skills/team-brainstorm/roles/evaluator.md index a007a9f9..29ec9499 100644 --- a/.claude/skills/team-brainstorm/roles/evaluator.md +++ b/.claude/skills/team-brainstorm/roles/evaluator.md @@ -15,7 +15,7 @@ - 仅处理 `EVAL-*` 前缀的任务 - 所有输出必须带 `[evaluator]` 标识 - 仅通过 SendMessage 与 coordinator 通信 -- Phase 2 读取 shared-memory.json,Phase 5 写入 evaluation_scores +- Phase 2 读取 .msg/meta.json,Phase 5 写入 evaluation_scores - 使用标准化评分维度,确保评分可追溯 - 为每个方案提供评分理由和推荐 @@ -24,7 +24,7 @@ - 生成新创意、挑战假设或综合整合 - 直接与其他 worker 角色通信 - 为其他角色创建任务 -- 修改 shared-memory.json 中不属于自己的字段 +- 修改 .msg/meta.json 中不属于自己的字段 - 在输出中省略 `[evaluator]` 标识 --- @@ -38,7 +38,7 @@ | `TaskList` | Built-in | Phase 1 | Discover pending EVAL-* tasks | | `TaskGet` | Built-in | Phase 1 | Get task details | | `TaskUpdate` | Built-in | Phase 1/5 | Update task status | -| `Read` | Built-in | Phase 2 | Read shared-memory.json, synthesis files, ideas, critiques | +| `Read` | Built-in | Phase 2 | Read .msg/meta.json, synthesis files, ideas, critiques | | `Write` | Built-in | Phase 3/5 | Write evaluation files, update shared memory | | `Glob` | Built-in | Phase 2 | Find synthesis, idea, critique files | | `SendMessage` | Built-in | Phase 5 | Report to coordinator | @@ -60,19 +60,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: ****, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field. + session_id: , from: "evaluator", - to: "coordinator", type: "evaluation_ready", - summary: "[evaluator] Evaluation complete: Top pick \"\" (<score>/10)", - ref: <output-path> + data: {ref: <output-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from evaluator --to coordinator --type evaluation_ready --summary \"[evaluator] Evaluation complete\" --ref <output-path> --json") +Bash("ccw team log --session-id <session-id> --from evaluator --type evaluation_ready --json") ``` --- @@ -141,7 +139,7 @@ weightedScore = (Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + ( Standard report flow: team_msg log -> SendMessage with `[evaluator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. **Shared Memory Update**: -1. Set shared-memory.json.evaluation_scores +1. Set .msg/meta.json.evaluation_scores 2. Each entry: title, weighted_score, rank, recommendation --- diff --git a/.claude/skills/team-brainstorm/roles/ideator.md b/.claude/skills/team-brainstorm/roles/ideator.md index 52a29006..31fe819f 100644 --- a/.claude/skills/team-brainstorm/roles/ideator.md +++ b/.claude/skills/team-brainstorm/roles/ideator.md @@ -15,7 +15,7 @@ - 仅处理 `IDEA-*` 前缀的任务 - 所有输出(SendMessage、team_msg、日志)必须带 `[ideator]` 标识 - 仅通过 SendMessage 与 coordinator 通信 -- Phase 2 读取 shared-memory.json,Phase 5 写入 generated_ideas +- Phase 2 读取 .msg/meta.json,Phase 5 写入 generated_ideas - 针对每个指定角度产出至少3个创意 ### MUST NOT @@ -23,7 +23,7 @@ - 执行挑战/评估/综合等其他角色工作 - 直接与其他 worker 角色通信 - 为其他角色创建任务(TaskCreate 是 coordinator 专属) -- 修改 shared-memory.json 中不属于自己的字段 +- 修改 .msg/meta.json 中不属于自己的字段 - 在输出中省略 `[ideator]` 标识 --- @@ -37,7 +37,7 @@ | `TaskList` | Built-in | Phase 1 | Discover pending IDEA-* tasks | | `TaskGet` | Built-in | Phase 1 | Get task details | | `TaskUpdate` | Built-in | Phase 1/5 | Update task status | -| `Read` | Built-in | Phase 2 | Read shared-memory.json, critique files | +| `Read` | Built-in | Phase 2 | Read .msg/meta.json, critique files | | `Write` | Built-in | Phase 3/5 | Write idea files, update shared memory | | `Glob` | Built-in | Phase 2 | Find critique files | | `SendMessage` | Built-in | Phase 5 | Report to coordinator | @@ -60,19 +60,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "ideator", - to: "coordinator", type: <ideas_ready|ideas_revised>, - summary: "[ideator] <Generated|Revised> <count> ideas (round <num>)", - ref: <output-path> + data: {ref: <output-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from ideator --to coordinator --type <message-type> --summary \"[ideator] ideas complete\" --ref <output-path> --json") +Bash("ccw team log --session-id <session-id> --from ideator --type <message-type> --json") ``` --- @@ -92,20 +90,20 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. | Input | Source | Required | |-------|--------|----------| | Session folder | Task description (Session: line) | Yes | -| Topic | shared-memory.json | Yes | -| Angles | shared-memory.json | Yes | -| GC Round | shared-memory.json | Yes | +| Topic | .msg/meta.json | Yes | +| Angles | .msg/meta.json | Yes | +| GC Round | .msg/meta.json | Yes | | Previous critique | critiques/*.md | For revision tasks only | -| Previous ideas | shared-memory.json.generated_ideas | No | +| Previous ideas | .msg/meta.json.generated_ideas | No | **Loading steps**: 1. Extract session path from task description (match "Session: <path>") -2. Read shared-memory.json for topic, angles, gc_round +2. Read .msg/meta.json for topic, angles, gc_round 3. If task is revision (subject contains "revision" or "fix"): - Glob critique files - Read latest critique for revision context -4. Read previous ideas from shared-memory.generated_ideas +4. Read previous ideas from .msg/meta.json generated_ideas state ### Phase 3: Idea Generation @@ -143,7 +141,7 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. Standard report flow: team_msg log -> SendMessage with `[ideator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. **Shared Memory Update**: -1. Append new ideas to shared-memory.json.generated_ideas +1. Append new ideas to .msg/meta.json.generated_ideas 2. Each entry: id, title, round, revised flag --- diff --git a/.claude/skills/team-brainstorm/roles/synthesizer.md b/.claude/skills/team-brainstorm/roles/synthesizer.md index 4e8ccaef..2debbbe3 100644 --- a/.claude/skills/team-brainstorm/roles/synthesizer.md +++ b/.claude/skills/team-brainstorm/roles/synthesizer.md @@ -15,7 +15,7 @@ - 仅处理 `SYNTH-*` 前缀的任务 - 所有输出必须带 `[synthesizer]` 标识 - 仅通过 SendMessage 与 coordinator 通信 -- Phase 2 读取 shared-memory.json,Phase 5 写入 synthesis_themes +- Phase 2 读取 .msg/meta.json,Phase 5 写入 synthesis_themes - 从所有创意和挑战中提取共同主题 - 解决相互矛盾的想法,生成整合方案 @@ -24,7 +24,7 @@ - 生成新创意、挑战假设或评分排序 - 直接与其他 worker 角色通信 - 为其他角色创建任务 -- 修改 shared-memory.json 中不属于自己的字段 +- 修改 .msg/meta.json 中不属于自己的字段 - 在输出中省略 `[synthesizer]` 标识 --- @@ -38,7 +38,7 @@ | `TaskList` | Built-in | Phase 1 | Discover pending SYNTH-* tasks | | `TaskGet` | Built-in | Phase 1 | Get task details | | `TaskUpdate` | Built-in | Phase 1/5 | Update task status | -| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files, critique files | +| `Read` | Built-in | Phase 2 | Read .msg/meta.json, idea files, critique files | | `Write` | Built-in | Phase 3/5 | Write synthesis files, update shared memory | | `Glob` | Built-in | Phase 2 | Find idea and critique files | | `SendMessage` | Built-in | Phase 5 | Report to coordinator | @@ -60,19 +60,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "synthesizer", - to: "coordinator", type: "synthesis_ready", - summary: "[synthesizer] Synthesis complete: <themeCount> themes, <proposalCount> proposals", - ref: <output-path> + data: {ref: <output-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from synthesizer --to coordinator --type synthesis_ready --summary \"[synthesizer] Synthesis complete\" --ref <output-path> --json") +Bash("ccw team log --session-id <session-id> --from synthesizer --type synthesis_ready --json") ``` --- @@ -92,7 +90,7 @@ Standard task discovery flow: TaskList -> filter by prefix `SYNTH-*` + owner mat | Session folder | Task description (Session: line) | Yes | | All ideas | ideas/*.md files | Yes | | All critiques | critiques/*.md files | Yes | -| GC rounds completed | shared-memory.json.gc_round | Yes | +| GC rounds completed | .msg/meta.json.gc_round | Yes | **Loading steps**: @@ -100,7 +98,7 @@ Standard task discovery flow: TaskList -> filter by prefix `SYNTH-*` + owner mat 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 shared-memory.json for context +5. Read .msg/meta.json for context ### Phase 3: Synthesis Execution @@ -152,7 +150,7 @@ Standard task discovery flow: TaskList -> filter by prefix `SYNTH-*` + owner mat Standard report flow: team_msg log -> SendMessage with `[synthesizer]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. **Shared Memory Update**: -1. Set shared-memory.json.synthesis_themes +1. Set .msg/meta.json.synthesis_themes 2. Each entry: name, strength, supporting_ideas --- diff --git a/.claude/skills/team-coordinate-v2/SKILL.md b/.claude/skills/team-coordinate-v2/SKILL.md index eb16cf37..0db417e8 100644 --- a/.claude/skills/team-coordinate-v2/SKILL.md +++ b/.claude/skills/team-coordinate-v2/SKILL.md @@ -193,7 +193,9 @@ Beat Cycle (single beat) | +-- <role-2>.md +-- artifacts/ # All MD deliverables from workers | +-- <artifact>.md -+-- shared-memory.json # Cross-role state store ++-- .msg/ # Team message bus + state +| +-- messages.jsonl # Message log +| +-- meta.json # Session metadata + cross-role state +-- wisdom/ # Cross-task knowledge | +-- learnings.md | +-- decisions.md @@ -203,7 +205,6 @@ Beat Cycle (single beat) | +-- explore-<angle>.json +-- discussions/ # Inline discuss records | +-- <round>.md -+-- .msg/ # Team message bus logs ``` ### team-session.json Schema diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md index 139f0cc0..e1cf4690 100644 --- a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md @@ -35,7 +35,7 @@ CONTEXT: - Session: <session-folder> - Upstream artifacts: <artifact-1.md>, <artifact-2.md> - Key files: <file1>, <file2> - - Shared memory: <session>/shared-memory.json + - Shared state: team_msg(operation="get_state", session_id=<session-id>) EXPECTED: <deliverable path> + <quality criteria> CONSTRAINTS: <scope limits> --- @@ -63,7 +63,7 @@ CONTEXT: - Session: <session-folder> - Upstream artifacts: <comma-separated list from task-analysis.json#tasks[].upstream_artifacts[]> - Key files: <comma-separated list from task-analysis.json#tasks[].key_files[]> - - Shared memory: <session>/shared-memory.json + - Shared state: team_msg(operation="get_state", session_id=<session-id>) EXPECTED: <artifact path from task-analysis.json#capabilities[].artifacts[]> + <quality criteria based on capability type> CONSTRAINTS: <constraints from task-analysis.json#tasks[].constraints> --- diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md index 350dae4c..a83475ce 100644 --- a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md @@ -132,7 +132,7 @@ Ready tasks found? | +- YES -> SKIP spawn (existing worker will pick it up via inner loop) | +- NO -> normal spawn below +- TaskUpdate -> in_progress - +- team_msg log -> task_unblocked (team=<session-id>, NOT team name) + +- team_msg log -> task_unblocked (session_id=<session-id>) +- Spawn team-worker (see spawn tool call below) +- Add to session.active_workers Update session file -> output summary -> STOP diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/role.md b/.claude/skills/team-coordinate-v2/roles/coordinator/role.md index 0416bb1b..df230a43 100644 --- a/.claude/skills/team-coordinate-v2/roles/coordinator/role.md +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/role.md @@ -198,10 +198,12 @@ Regardless of complexity score or role count, coordinator MUST: 8. **Initialize shared infrastructure**: - `wisdom/learnings.md`, `wisdom/decisions.md`, `wisdom/issues.md` (empty with headers) - `explorations/cache-index.json` (`{ "entries": [] }`) - - `shared-memory.json` (`{}`) - `discussions/` (empty directory) -9. **Write team-session.json** with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], completion_action="interactive", created_at +9. **Initialize cross-role state** via team_msg: + - `team_msg(operation="log", session_id=<session-id>, from="coordinator", type="state_update", data={})` + +10. **Write team-session.json** with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], completion_action="interactive", created_at **Success**: Session created, role-spec files generated, shared infrastructure initialized. diff --git a/.claude/skills/team-coordinate-v2/specs/role-spec-template.md b/.claude/skills/team-coordinate-v2/specs/role-spec-template.md index 1245b57b..815a44c8 100644 --- a/.claude/skills/team-coordinate-v2/specs/role-spec-template.md +++ b/.claude/skills/team-coordinate-v2/specs/role-spec-template.md @@ -91,7 +91,7 @@ Phase 4 must produce a verification summary with these fields: - Phase 4 MUST verify Phase 3's **actual output** (not planned output) - Verification fails → retry Phase 3 (max 2 retries) - Still fails → report `partial_completion` with details, NOT `completed` -- Update `shared-memory.json` with key findings after verification passes +- Update shared state via `team_msg(operation="log", type="state_update", data={...})` after verification passes ### Error Protocol @@ -107,33 +107,33 @@ Coordinator MAY reference these patterns when composing Phase 2-4 content for a ### Research / Exploration -- Phase 2: Define exploration scope + load prior knowledge from shared-memory and wisdom +- Phase 2: Define exploration scope + load prior knowledge from shared state and wisdom - Phase 3: Explore via subagents, direct tool calls, or codebase search — approach chosen by agent -- Phase 4: Verify findings documented (Behavioral Traits) + update shared-memory +- Phase 4: Verify findings documented (Behavioral Traits) + update shared state ### Document / Content - Phase 2: Load upstream artifacts + read target files (if modifying existing docs) - Phase 3: Create new documents OR modify existing documents — determined by task, not template -- Phase 4: Verify documents exist with expected content (Behavioral Traits) + update shared-memory +- Phase 4: Verify documents exist with expected content (Behavioral Traits) + update shared state ### Code Implementation - Phase 2: Load design/spec artifacts from upstream - Phase 3: Implement code changes — subagent choice and approach determined by task complexity -- Phase 4: Syntax check + file verification (Behavioral Traits) + update shared-memory +- Phase 4: Syntax check + file verification (Behavioral Traits) + update shared state ### Analysis / Audit - Phase 2: Load analysis targets (artifacts or source files) - Phase 3: Multi-dimension analysis — perspectives and depth determined by task -- Phase 4: Verify report exists + severity classification (Behavioral Traits) + update shared-memory +- Phase 4: Verify report exists + severity classification (Behavioral Traits) + update shared state ### Validation / Testing - Phase 2: Detect test framework + identify changed files from upstream - Phase 3: Run test-fix cycle — iteration count and strategy determined by task -- Phase 4: Verify pass rate + coverage (Behavioral Traits) + update shared-memory +- Phase 4: Verify pass rate + coverage (Behavioral Traits) + update shared state --- @@ -146,7 +146,7 @@ How context flows between roles. Coordinator MUST reference this when composing | Channel | Scope | Mechanism | When to Use | |---------|-------|-----------|-------------| | **Artifacts** | Producer -> Consumer | Write to `<session>/artifacts/<name>.md`, consumer reads in Phase 2 | Structured deliverables (reports, plans, specs) | -| **shared-memory.json** | Cross-role | Read-merge-write `<session>/shared-memory.json` | Key findings, decisions, metadata (small, structured data) | +| **State Updates** | Cross-role | `team_msg(operation="log", type="state_update", data={...})` / `team_msg(operation="get_state", session_id=<session-id>)` | Key findings, decisions, metadata (small, structured data) | | **Wisdom** | Cross-task | Append to `<session>/wisdom/{learnings,decisions,conventions,issues}.md` | Patterns, conventions, risks discovered during execution | | **context_accumulator** | Intra-role (inner loop) | In-memory array, passed to each subsequent task in same-prefix loop | Prior task summaries within same role's inner loop | | **Exploration cache** | Cross-role | `<session>/explorations/cache-index.json` + per-angle JSON | Codebase discovery results, prevents duplicate exploration | @@ -158,22 +158,29 @@ Every generated role-spec Phase 2 MUST declare which upstream sources to load: ``` 1. Extract session path from task description 2. Read upstream artifacts: <list which artifacts from which upstream role> -3. Read shared-memory.json for cross-role decisions +3. Read cross-role state via `team_msg(operation="get_state", session_id=<session-id>)` 4. Load wisdom files for accumulated knowledge 5. For inner_loop roles: load context_accumulator from prior tasks 6. Check exploration cache before running new explorations ``` -### shared-memory.json Usage Convention +### State Update Convention -- **Read-merge-write**: Read current content -> merge new keys -> write back (NOT overwrite) -- **Namespaced keys**: Each role writes under its own namespace: `{ "<role_name>": { ... } }` +Cross-role state is managed via `team_msg` state updates instead of a separate file: + +- **Write state**: `team_msg(operation="log", session_id=<session-id>, from=<role>, type="state_update", data={ "<role_name>": { ... } })` +- **Read state**: `team_msg(operation="get_state", session_id=<session-id>)` +- **Namespaced keys**: Each role writes under its own namespace key in `data` - **Small data only**: Key findings, decision summaries, metadata. NOT full documents -- **Example**: - ```json - { - "researcher": { "key_findings": [...], "scope": "..." }, - "writer": { "documents_created": [...], "style_decisions": [...] }, - "developer": { "files_changed": [...], "patterns_used": [...] } - } +- **State stored in**: `.msg/meta.json` (auto-managed by team_msg) +- **Example write**: + ``` + team_msg(operation="log", session_id="TC-auth-2026-03-03", from="researcher", type="state_update", data={ + "researcher": { "key_findings": [...], "scope": "..." } + }) + ``` +- **Example read**: + ``` + team_msg(operation="get_state", session_id="TC-auth-2026-03-03") + // Returns merged state from all state_update messages ``` diff --git a/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md b/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md index 0eea3bf0..31f42cc3 100644 --- a/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md +++ b/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md @@ -126,7 +126,7 @@ Ready tasks found? | +- YES -> SKIP spawn (existing worker picks it up) | +- NO -> normal spawn below +- TaskUpdate -> in_progress - +- team_msg log -> task_unblocked (team=<session-id>) + +- team_msg log -> task_unblocked (session_id=<session-id>) +- Spawn team-worker (see spawn tool call below) +- Add to session.active_workers Update session file -> output summary -> STOP diff --git a/.claude/skills/team-executor-v2/specs/session-schema.md b/.claude/skills/team-executor-v2/specs/session-schema.md index 6b7c8180..91d75e53 100644 --- a/.claude/skills/team-executor-v2/specs/session-schema.md +++ b/.claude/skills/team-executor-v2/specs/session-schema.md @@ -13,7 +13,9 @@ Required session structure for team-executor v2. All components MUST exist for v | +-- <role-2>.md +-- artifacts/ # All MD deliverables from workers | +-- <artifact>.md -+-- shared-memory.json # Cross-role state store ++-- .msg/ # Team message bus + state +| +-- messages.jsonl # Message log +| +-- meta.json # Session metadata + cross-role state +-- wisdom/ # Cross-task knowledge | +-- learnings.md | +-- decisions.md @@ -23,7 +25,6 @@ Required session structure for team-executor v2. All components MUST exist for v | +-- explore-<angle>.json +-- discussions/ # Inline discuss records | +-- <round>.md -+-- .msg/ # Team message bus logs ``` ## Validation Checklist @@ -238,7 +239,7 @@ For each role-spec in role-specs/<role>.md: | +-- developer.md # YAML frontmatter + Phase 2-4 | +-- tester.md # YAML frontmatter + Phase 2-4 +-- artifacts/ # (may be empty) -+-- shared-memory.json # Valid JSON (may be {}) ++-- .msg/ # Team message bus + state (messages.jsonl + meta.json) +-- wisdom/ | +-- learnings.md | +-- decisions.md @@ -246,7 +247,6 @@ For each role-spec in role-specs/<role>.md: +-- explorations/ | +-- cache-index.json +-- discussions/ # (may be empty) -+-- .msg/ # (may be empty) ``` --- diff --git a/.claude/skills/team-frontend/SKILL.md b/.claude/skills/team-frontend/SKILL.md index 3ea82f3a..1d3adbff 100644 --- a/.claude/skills/team-frontend/SKILL.md +++ b/.claude/skills/team-frontend/SKILL.md @@ -1,97 +1,74 @@ --- name: team-frontend -description: Unified team skill for frontend development team. All roles invoke this skill with --role arg. Built-in ui-ux-pro-max design intelligence. Triggers on "team frontend". -allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), WebFetch(*), WebSearch(*) +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: Task, 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. All team members invoke with `--role=xxx` to route to role-specific execution. +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. ## Architecture ``` -┌──────────────────────────────────────────────────────┐ -│ Skill(skill="team-frontend") │ -│ args="<task-description>" or args="--role=xxx" │ -└──────────────────────────┬───────────────────────────┘ - │ Role Router - ┌──── --role present? ────┐ - │ NO │ YES - ↓ ↓ - Orchestration Mode Role Dispatch - (auto -> coordinator) (route to role.md) - │ - ┌────┴────┬───────────┬───────────┬───────────┐ - ↓ ↓ ↓ ↓ ↓ - ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ - │ coord │ │analyst │ │architect│ │developer│ │ qa │ - │ │ │ANALYZE-*│ │ARCH-* │ │DEV-* │ │QA-* │ - └────────┘ └────────┘ └────────┘ └────────┘ └────────┘ -``` ++---------------------------------------------------+ +| Skill(skill="team-frontend") | +| args="<task-description>" | ++-------------------+-------------------------------+ + | + Orchestration Mode (auto -> coordinator) + | + Coordinator (inline) + Phase 0-5 orchestration + | + +-------+-------+-------+-------+ + v v v v + [tw] [tw] [tw] [tw] +analyst archi- devel- qa + tect oper -## Command Architecture - -Each role is organized as a folder with a `role.md` orchestrator and optional `commands/` for delegation: - -``` -roles/ -├── coordinator/ -│ ├── role.md -│ └── commands/ -├── analyst/ -│ ├── role.md -│ └── commands/ -│ └── design-intelligence.md -├── architect/ -│ ├── role.md -│ └── commands/ -├── developer/ -│ ├── role.md -│ └── commands/ -└── qa/ - ├── role.md - └── commands/ - └── pre-delivery-checklist.md +(tw) = team-worker agent ``` ## 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` to extract `--role`. If absent -> Orchestration Mode (auto route to coordinator). +Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. ### Role Registry -| Role | File | Task Prefix | Type | Compact | -|------|------|-------------|------|---------| -| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | **compressed -> must re-read** | -| analyst | [roles/analyst/role.md](roles/analyst/role.md) | ANALYZE-* | pipeline | compressed -> must re-read | -| architect | [roles/architect/role.md](roles/architect/role.md) | ARCH-* | pipeline | compressed -> must re-read | -| developer | [roles/developer/role.md](roles/developer/role.md) | DEV-* | pipeline | compressed -> must re-read | -| qa | [roles/qa/role.md](roles/qa/role.md) | QA-* | pipeline | compressed -> must re-read | - -> **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. +| 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 -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 +Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. ### Orchestration Mode -When invoked without `--role`, coordinator auto-starts. User just provides task description. +User just provides task description. -**Invocation**: `Skill(skill="team-frontend", args="<task-description>")` +**Invocation**: +```bash +Skill(skill="team-frontend", args="<task-description>") +``` **Lifecycle**: ``` User provides task description - -> coordinator Phase 1-3: Requirement clarification + industry identification -> TeamCreate -> Create task chain + -> coordinator Phase 1-3: Parse requirements -> 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 + -> 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): @@ -103,272 +80,120 @@ User provides task description --- -## Shared Infrastructure +## Command Execution Protocol -The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic. +When coordinator needs to execute a command (dispatch, monitor): -### Worker Phase 1: Task Discovery (shared by all workers) +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 -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", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **CLI fallback**: When MCP unavailable -> `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` - - **Note**: `team` must be session ID (e.g., `FES-xxx-date`), NOT team name. Extract from `Session:` field in task description. -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**: +Example: ``` -<session-folder>/wisdom/ -├── learnings.md # Patterns and insights -├── decisions.md # Architecture and design decisions -├── conventions.md # Codebase conventions -└── issues.md # Known risks and issues +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 ``` -**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 code writing/modification | -| Create task chain (TaskCreate) | Calling implementation subagents | -| Dispatch tasks to workers | Direct analysis/testing/review | -| Monitor progress (message bus) | Bypassing workers | -| Report results to user | Modifying source code | - -#### Worker Isolation - -| 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 (TaskCreate) | -| Delegate to commands/ files | Modify resources outside own responsibility | - -### Message Bus (All Roles) - -Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log. - -**Message types by role**: - -| Role | Types | -|------|-------| -| coordinator | `task_unblocked`, `sync_checkpoint`, `fix_required`, `error`, `shutdown` | -| analyst | `analyze_ready`, `analyze_progress`, `error` | -| architect | `arch_ready`, `arch_revision`, `arch_progress`, `error` | -| developer | `dev_complete`, `dev_progress`, `error` | -| qa | `qa_passed`, `qa_result`, `fix_required`, `error` | - -### Shared Memory - -Cross-role accumulated knowledge stored in `shared-memory.json`: - -| Field | Owner | Content | -|-------|-------|---------| -| `design_intelligence` | analyst | ui-ux-pro-max output | -| `design_token_registry` | architect | colors, typography, spacing, shadows | -| `component_inventory` | architect | Component specs | -| `style_decisions` | architect | Design system decisions | -| `qa_history` | qa | QA audit results | -| `industry_context` | analyst | Industry-specific rules | - -Each role reads in Phase 2, writes own fields in Phase 5. - ---- - -## Pipeline Architecture - -### Three Pipeline Modes - -``` -page (single page - linear): - ANALYZE-001 -> ARCH-001 -> DEV-001 -> QA-001 - -feature (multi-component feature - with architecture review): - ANALYZE-001 -> ARCH-001(tokens+structure) -> QA-001(architecture-review) - -> DEV-001(components) -> QA-002(code-review) - -system (full frontend system - dual-track parallel): - ANALYZE-001 -> ARCH-001(tokens) -> QA-001(token-review) - -> [ARCH-002(components) || DEV-001(tokens)](parallel, blockedBy QA-001) - -> QA-002(component-review) -> DEV-002(components) -> QA-003(final) -``` - -### Generator-Critic Loop (developer <-> qa) - -Developer and qa iterate to ensure code quality and design compliance: - -``` -┌──────────┐ DEV artifact ┌──────────┐ -│ developer│ ─────────────────────> │ qa │ -│(Generator)│ │ (Critic) │ -│ │ <───────────────────── │ │ -└──────────┘ QA feedback └──────────┘ - (max 2 rounds) - -Convergence: qa.score >= 8 && qa.critical_count === 0 -``` - -### Consulting Pattern (developer -> analyst) - -Developer can request design decision consultation via coordinator: - -``` -developer -> coordinator: "Need design decision consultation" -coordinator -> analyst: Create ANALYZE-consult task -analyst -> coordinator: Design recommendation -coordinator -> developer: Forward recommendation -``` - -### 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**: - -``` -Page mode (4 beats, strictly serial) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 - │ │ │ │ - ANALYZE -> ARCH -> DEV -> QA - ▲ ▲ - pipeline pipeline - start done - -A=ANALYZE ARCH=architect D=DEV Q=QA - -Feature mode (5 beats, with architecture review gate) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 - │ │ │ │ │ - ANALYZE -> ARCH -> QA-1 -> DEV -> QA-2 - ▲ ▲ - arch review code review - -System mode (7 beats, dual-track parallel) -────────────────────────────────────────────────────────── -Beat 1 2 3 4 5 6 7 - │ │ │ ┌────┴────┐ │ │ │ - ANALYZE -> ARCH-1 -> QA-1 -> ARCH-2 || DEV-1 -> QA-2 -> DEV-2 -> QA-3 - ▲ ▲ - parallel window final check -``` - -**Checkpoints**: - -| Trigger | Location | Behavior | -|---------|----------|----------| -| Architecture review gate | QA-001 (arch review) complete | Pause if critical issues, wait for architect revision | -| GC loop limit | developer <-> qa max 2 rounds | Exceed rounds -> stop iteration, report current state | -| 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 | DEV/QA iteration > max_rounds | Terminate loop, output latest QA report | - -### Task Metadata Registry - -| Task ID | Role | Phase | Dependencies | Description | -|---------|------|-------|-------------|-------------| -| ANALYZE-001 | analyst | analysis | (none) | Requirement analysis + design intelligence via ui-ux-pro-max | -| ARCH-001 | architect | design | ANALYZE-001 | Design token system + component architecture | -| ARCH-002 | architect | design | QA-001 (system mode) | Component specs refinement | -| DEV-001 | developer | impl | ARCH-001 or QA-001 | Frontend component/page implementation | -| DEV-002 | developer | impl | QA-002 (system mode) | Component implementation from refined specs | -| QA-001 | qa | review | ARCH-001 or DEV-001 | Architecture review or code review | -| QA-002 | qa | review | DEV-001 | Code review (feature/system mode) | -| QA-003 | qa | review | DEV-002 (system mode) | Final quality check | - --- ## Coordinator Spawn Template -When coordinator spawns workers, use background mode (Spawn-and-Stop): +### v5 Worker Spawn (all roles) + +When coordinator spawns workers, use `team-worker` agent with role-spec path: ``` Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: "Spawn <role> worker", - team_name: <team-name>, + team_name: "frontend", name: "<role>", run_in_background: true, - prompt: `You are team "<team-name>" <ROLE>. + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-frontend/role-specs/<role>.md +session: <session-folder> +session_id: <session-id> +team_name: frontend +requirement: <task-description> +inner_loop: <true|false> -## Primary Directive -All your work must be executed through Skill to load role definition: -Skill(skill="team-frontend", args="--role=<role>") - -Current requirement: <task-description> -Session: <session-folder> - -## Role Guidelines -- Only process <PREFIX>-* tasks, do not execute other role work -- All output prefixed with [<role>] identifier -- Only communicate with coordinator -- Do not use TaskCreate for other roles -- Call mcp__ccw-tools__team_msg before every SendMessage - -## Workflow -1. Call Skill -> load role definition and execution logic -2. Follow role.md 5-Phase flow -3. team_msg + SendMessage results to coordinator -4. TaskUpdate completed -> check next task` +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** (developer): Set `inner_loop: true`. The team-worker agent handles the loop internally. + +**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 @@ -377,50 +202,100 @@ Analyst role invokes ui-ux-pro-max via Skill to obtain industry design intellige | Action | Invocation | |--------|------------| -| Full design system recommendation | `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` | -| Domain search (UX, typography, color) | `Skill(skill="ui-ux-pro-max", args="<query> --domain <domain>")` | +| 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>")` | -| Persist design system (cross-session) | `Skill(skill="ui-ux-pro-max", args="<query> --design-system --persist -p <projectName>")` | **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("frontend") -> 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` | + +--- + ## Session Directory ``` .workflow/.team/FE-<slug>-<YYYY-MM-DD>/ -├── team-session.json # Session state -├── shared-memory.json # Cross-role accumulated knowledge +├── .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 ├── analysis/ # Analyst output │ ├── design-intelligence.json │ └── requirements.md ├── architecture/ # Architect output │ ├── design-tokens.json │ ├── component-specs/ -│ │ └── <component-name>.md │ └── project-structure.md ├── qa/ # QA output │ └── audit-<NNN>.md └── build/ # Developer output - ├── token-files/ - └── component-files/ ``` ## 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) | -| QA score < 6 over 2 GC rounds | Coordinator reports to user | -| Dual-track sync failure | Fallback to single-track sequential execution | -| ui-ux-pro-max skill not installed | Degrade to LLM general design knowledge, show install command | -| DEV cannot find design files | Wait for sync point or escalate to coordinator | +| Unknown command | Error with available command list | +| 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/role-specs/analyst.md b/.claude/skills/team-frontend/role-specs/analyst.md new file mode 100644 index 00000000..e31e7cbe --- /dev/null +++ b/.claude/skills/team-frontend/role-specs/analyst.md @@ -0,0 +1,92 @@ +--- +prefix: ANALYZE +inner_loop: false +subagents: [] +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/role-specs/architect.md b/.claude/skills/team-frontend/role-specs/architect.md new file mode 100644 index 00000000..89583dbb --- /dev/null +++ b/.claude/skills/team-frontend/role-specs/architect.md @@ -0,0 +1,86 @@ +--- +prefix: ARCH +inner_loop: false +subagents: [] +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/role-specs/developer.md b/.claude/skills/team-frontend/role-specs/developer.md new file mode 100644 index 00000000..d2e9ddf9 --- /dev/null +++ b/.claude/skills/team-frontend/role-specs/developer.md @@ -0,0 +1,93 @@ +--- +prefix: DEV +inner_loop: true +subagents: [] +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/role-specs/qa.md b/.claude/skills/team-frontend/role-specs/qa.md new file mode 100644 index 00000000..e4b00a8e --- /dev/null +++ b/.claude/skills/team-frontend/role-specs/qa.md @@ -0,0 +1,79 @@ +--- +prefix: QA +inner_loop: false +subagents: [] +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/roles/analyst/commands/design-intelligence.md b/.claude/skills/team-frontend/roles/analyst/commands/design-intelligence.md deleted file mode 100644 index efb30ebb..00000000 --- a/.claude/skills/team-frontend/roles/analyst/commands/design-intelligence.md +++ /dev/null @@ -1,150 +0,0 @@ -# Command: design-intelligence - -> 通过 Skill 调用 ui-ux-pro-max 获取行业设计智能,生成 design-intelligence.json。 - -## When to Use - -- Phase 3 of analyst role: Core design intelligence retrieval -- ui-ux-pro-max skill 已安装 - -## Strategy - -### Delegation Mode - -**Mode**: Skill invocation -**Skill**: `ui-ux-pro-max` - -## Execution Steps - -### Step 1: 调用 ui-ux-pro-max 生成设计系统 - -analyst 在 subagent 中通过 Skill 调用 ui-ux-pro-max,获取完整设计系统推荐: - -```javascript -// 核心调用:生成完整设计系统 -// ui-ux-pro-max 的 Step 2 会自动执行 search.py --design-system -Task({ - subagent_type: "general-purpose", - run_in_background: false, - description: "Retrieve design intelligence via ui-ux-pro-max skill", - prompt: `调用 ui-ux-pro-max skill 获取设计系统推荐。 - -## 需求 -- 产品类型/行业: ${industry} -- 关键词: ${keywords} -- 技术栈: ${detectedStack} - -## 执行步骤 - -### 1. 生成设计系统(必须) -Skill(skill="ui-ux-pro-max", args="${industry} ${keywords} --design-system") - -### 2. 补充 UX 指南 -Skill(skill="ui-ux-pro-max", args="accessibility animation responsive --domain ux") - -### 3. 获取技术栈指南 -Skill(skill="ui-ux-pro-max", args="${keywords} --stack ${detectedStack}") - -## 输出 -将所有结果整合写入: ${sessionFolder}/analysis/design-intelligence-raw.md - -包含: -- 设计系统推荐(pattern, style, colors, typography, effects, anti-patterns) -- UX 最佳实践 -- 技术栈指南 -- 行业反模式列表 -` -}) -``` - -### Step 2: 解析 Skill 输出 - -```javascript -// 读取 ui-ux-pro-max 的原始输出 -let rawOutput = '' -try { - rawOutput = Read(`${sessionFolder}/analysis/design-intelligence-raw.md`) -} catch {} - -// 解析为结构化 design-intelligence.json -const designIntelligence = { - _source: "ui-ux-pro-max-skill", - _generated_at: new Date().toISOString(), - industry: industry, - detected_stack: detectedStack, - design_system: parseDesignSystem(rawOutput), - ux_guidelines: parseUxGuidelines(rawOutput), - stack_guidelines: parseStackGuidelines(rawOutput), - recommendations: { - style: null, - color_palette: null, - typography: null, - anti_patterns: parseAntiPatterns(rawOutput), - must_have: industryConfig?.mustHave || [] - } -} - -Write(`${sessionFolder}/analysis/design-intelligence.json`, JSON.stringify(designIntelligence, null, 2)) -``` - -### Step 3: Fallback - -```javascript -// 若 ui-ux-pro-max skill 不可用(未安装),降级为 LLM 通用设计知识 -// analyst 在 Phase 3 中直接基于 LLM 知识生成设计推荐 -if (!skillAvailable) { - return { - _source: "llm-general-knowledge", - _fallback: true, - note: "ui-ux-pro-max skill not installed. Install via: /plugin install ui-ux-pro-max@ui-ux-pro-max-skill" - } -} -``` - -## Skill 调用参考 - -ui-ux-pro-max 支持的调用方式: - -| 用途 | 调用 | -|------|------| -| 完整设计系统 | `Skill(skill="ui-ux-pro-max", args="<query> --design-system")` | -| 持久化设计系统 | `Skill(skill="ui-ux-pro-max", args="<query> --design-system --persist -p <name>")` | -| 领域搜索 | `Skill(skill="ui-ux-pro-max", args="<query> --domain <domain>")` | -| 技术栈指南 | `Skill(skill="ui-ux-pro-max", args="<query> --stack <stack>")` | - -可用领域: product, style, typography, color, landing, chart, ux, web -可用技术栈: html-tailwind, react, nextjs, vue, svelte, shadcn, swiftui, react-native, flutter - -## Output Format - -```json -{ - "_source": "ui-ux-pro-max-skill", - "design_system": { - "pattern": "...", - "style": "...", - "colors": { "primary": "...", "secondary": "...", "cta": "..." }, - "typography": { "heading": "...", "body": "..." }, - "effects": "...", - "anti_patterns": [] - }, - "ux_guidelines": [], - "stack_guidelines": {}, - "recommendations": { - "style": null, - "color_palette": null, - "typography": null, - "anti_patterns": [], - "must_have": [] - } -} -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| ui-ux-pro-max skill not installed | Fallback to LLM general knowledge, suggest install command | -| Skill execution error | Retry once, then fallback | -| Partial output | Use available data, fill gaps with defaults | -| Timeout | Use partial results, log warning | diff --git a/.claude/skills/team-frontend/roles/analyst/role.md b/.claude/skills/team-frontend/roles/analyst/role.md deleted file mode 100644 index 944f8634..00000000 --- a/.claude/skills/team-frontend/roles/analyst/role.md +++ /dev/null @@ -1,225 +0,0 @@ -# Analyst Role - -Requirements analyst. Invokes ui-ux-pro-max search engine to retrieve industry design intelligence, analyzes requirements, matches industry inference rules, generates design-intelligence.json for downstream consumption. - -## Identity - -- **Name**: `analyst` | **Tag**: `[analyst]` -- **Task Prefix**: `ANALYZE-*` -- **Responsibility**: Read-only analysis + design intelligence retrieval - -## Boundaries - -### MUST - -- Only process `ANALYZE-*` prefixed tasks -- All output (SendMessage, team_msg, logs) must carry `[analyst]` identifier -- Only communicate with coordinator via SendMessage -- Work strictly within requirement analysis and design intelligence scope - -### MUST NOT - -- Execute work outside this role's responsibility scope (architecture, implementation, QA) -- Communicate directly with other worker roles (must go through coordinator) -- Create tasks for other roles (TaskCreate is coordinator-exclusive) -- Modify source code files -- Omit `[analyst]` identifier in any output - ---- - -## Toolbox - -### Available Commands - -| Command | File | Phase | Description | -|---------|------|-------|-------------| -| `design-intelligence` | [commands/design-intelligence.md](commands/design-intelligence.md) | Phase 3 | ui-ux-pro-max integration for design system retrieval | - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `Read` | builtin | Phase 2 | Load session files, shared memory | -| `Glob` | builtin | Phase 2 | Detect existing token files, CSS files | -| `Grep` | builtin | Phase 2 | Search codebase patterns | -| `Bash` | builtin | Phase 3 | Call ui-ux-pro-max search.py | -| `WebSearch` | builtin | Phase 3 | Competitive reference, design trends | -| `Task(cli-explore-agent)` | subagent | Phase 3 | Deep codebase exploration | -| `Skill(ui-ux-pro-max)` | skill | Phase 3 | Design intelligence retrieval | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `analyze_ready` | analyst → coordinator | Analysis complete | Design intelligence ready for downstream consumption | -| `analyze_progress` | analyst → coordinator | Partial progress | Analysis progress update | -| `error` | analyst → coordinator | Analysis failure | Analysis failed or tool unavailable | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., FES-xxx-date), NOT team name. Extract from Session: field. - from: "analyst", - to: "coordinator", - type: <message-type>, - summary: "[analyst] ANALYZE complete: <task-subject>", - ref: <artifact-path> -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --team <session-id> --from analyst --to coordinator --type <message-type> --summary \"[analyst] ...\" --ref <artifact-path> --json") -``` - ---- - -## Execution (5-Phase) - -### Phase 1: Task Discovery - -> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery - -Standard task discovery flow: TaskList -> filter by prefix `ANALYZE-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress. - -### Phase 2: Context Loading - -**Input Sources**: - -| Input | Source | Required | -|-------|--------|----------| -| Session folder | Extract from task description `Session: <path>` | Yes | -| Industry context | Extract from task description `Industry: <type>` | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | No | -| Session info | `<session-folder>/team-session.json` | No | -| Existing tokens | Glob `**/*token*.*` | No | -| Existing CSS | Glob `**/*.css` | No | -| Package.json | For tech stack detection | No | - -**Loading Steps**: - -1. Extract session folder from task description -2. Extract industry context from task description -3. Load shared memory and session info -4. Detect existing design system in project -5. Detect tech stack from package.json - -**Tech Stack Detection**: - -| Detection | Stack | -|-----------|-------| -| `next` in dependencies | nextjs | -| `react` in dependencies | react | -| `vue` in dependencies | vue | -| `svelte` in dependencies | svelte | -| `@shadcn/ui` in dependencies | shadcn | -| No package.json | html-tailwind | - -### Phase 3: Core Analysis - Design Intelligence Retrieval - -Key integration point with ui-ux-pro-max. Retrieve design intelligence via Skill. - -**Execution Strategy**: - -| Condition | Strategy | -|-----------|----------| -| ui-ux-pro-max skill available | Full design system retrieval via Skill | -| ui-ux-pro-max not installed | Fallback to LLM general knowledge | - -**Step 1: Invoke ui-ux-pro-max via Skill** - -Delegate to `commands/design-intelligence.md` for detailed execution. - -**Skill Invocations**: - -| 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 - LLM General Knowledge** - -If ui-ux-pro-max skill not available (not installed or execution failed): -- Generate design recommendations from LLM general knowledge -- Quality is lower than data-driven recommendations from ui-ux-pro-max -- Suggest installation: `/plugin install ui-ux-pro-max@ui-ux-pro-max-skill` - -**Step 3: Analyze Existing Codebase** - -If existing token files or CSS files found: - -``` -Task({ - subagent_type: "cli-explore-agent", - run_in_background: false, - description: "Explore existing design system", - prompt: "Analyze existing design system: <token-files>, <css-files>. Find: color palette, typography scale, spacing system, component patterns. Output as JSON." -}) -``` - -**Step 4: Competitive Reference** (optional) - -If industry is not "Other": -- Quick web search for design inspiration -- `WebSearch({ query: "<industry> web design trends 2025 best practices" })` - -### Phase 4: Synthesis and Output - -**Compile Design Intelligence**: - -Generate `design-intelligence.json` with: - -| Field | Source | Description | -|-------|--------|-------------| -| `_source` | Execution | "ui-ux-pro-max-skill" or "llm-general-knowledge" | -| `industry` | Task | Industry context | -| `detected_stack` | Phase 2 | Tech stack detection result | -| `design_system` | Skill/fallback | Colors, typography, style | -| `ux_guidelines` | Skill | UX best practices | -| `stack_guidelines` | Skill | Tech-specific guidance | -| `existing_patterns` | Phase 3 | Codebase analysis results | -| `recommendations` | Synthesis | Style, colors, anti-patterns, must-have | - -**Output Files**: - -1. **design-intelligence.json**: Structured data for downstream consumption -2. **requirements.md**: Human-readable requirements summary - -**Update Shared Memory**: -- Write `design_intelligence` field -- Write `industry_context` field - -### Phase 5: Report to Coordinator - -> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report - -Standard report flow: team_msg log -> SendMessage with `[analyst]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. - -**Report Content**: -- Task subject and status -- Design intelligence source (ui-ux-pro-max or LLM fallback) -- Industry and detected stack -- Anti-patterns count -- Output file paths - ---- - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No ANALYZE-* tasks available | Idle, wait for coordinator assignment | -| ui-ux-pro-max not found | Fallback to LLM general knowledge, log warning | -| search.py execution error | Retry once, then fallback | -| Python not available | Fallback to LLM general knowledge | -| Session folder not found | Notify coordinator, request location | -| Web search fails | Skip competitive reference, continue | -| Critical issue beyond scope | SendMessage fix_required to coordinator | diff --git a/.claude/skills/team-frontend/roles/architect/role.md b/.claude/skills/team-frontend/roles/architect/role.md deleted file mode 100644 index 457ba2f2..00000000 --- a/.claude/skills/team-frontend/roles/architect/role.md +++ /dev/null @@ -1,219 +0,0 @@ -# Architect Role - -Frontend architect. Consumes design-intelligence.json, defines design token system, component architecture, project structure, and technology selection. Design token values should prioritize ui-ux-pro-max recommendations. - -## Identity - -- **Name**: `architect` | **Tag**: `[architect]` -- **Task Prefix**: `ARCH-*` -- **Responsibility**: Code generation (architecture artifacts) - -## Boundaries - -### MUST - -- Only process `ARCH-*` prefixed tasks -- All output (SendMessage, team_msg, logs) must carry `[architect]` identifier -- Only communicate with coordinator via SendMessage -- Work strictly within architecture design and token definition scope - -### MUST NOT - -- Execute work outside this role's responsibility scope (analysis, implementation, QA) -- Communicate directly with other worker roles (must go through coordinator) -- Create tasks for other roles (TaskCreate is coordinator-exclusive) -- Implement concrete component code (only define specifications) -- Omit `[architect]` identifier in any output - ---- - -## Toolbox - -### Available Commands - -> No command files -- all phases execute inline. - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `Read` | builtin | Phase 2-3 | Load design intelligence, shared memory | -| `Write` | builtin | Phase 3-4 | Write architecture artifacts | -| `Edit` | builtin | Phase 3-4 | Modify architecture files | -| `Glob` | builtin | Phase 2 | Detect project structure | -| `Grep` | builtin | Phase 2 | Search patterns | -| `Task(code-developer)` | subagent | Phase 3 | Complex architecture file generation | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `arch_ready` | architect → coordinator | Architecture complete | Architecture artifacts ready for downstream | -| `arch_revision` | architect → coordinator | Revision after QA feedback | Architecture revision complete | -| `arch_progress` | architect → coordinator | Partial progress | Architecture progress update | -| `error` | architect → coordinator | Architecture failure | Architecture design failed | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., FES-xxx-date), NOT team name. Extract from Session: field. - from: "architect", - to: "coordinator", - type: <message-type>, - summary: "[architect] ARCH complete: <task-subject>", - ref: <artifact-path> -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --team <session-id> --from architect --to coordinator --type <message-type> --summary \"[architect] ...\" --ref <artifact-path> --json") -``` - ---- - -## Execution (5-Phase) - -### Phase 1: Task Discovery - -> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery - -Standard task discovery flow: TaskList -> filter by prefix `ARCH-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress. - -### Phase 2: Context Loading - -**Input Sources**: - -| Input | Source | Required | -|-------|--------|----------| -| Session folder | Extract from task description `Session: <path>` | Yes | -| Scope | Extract from task description `Scope: <tokens|components|full>` | No (default: full) | -| Design intelligence | `<session-folder>/analysis/design-intelligence.json` | No | -| Shared memory | `<session-folder>/shared-memory.json` | No | -| Project files | Glob `src/**/*` | No | - -**Loading Steps**: - -1. Extract session folder from task description -2. Extract scope (tokens / components / full) -3. Load design intelligence from analyst output -4. Load shared memory -5. Load existing project structure via Glob - -**Fail-safe**: If design-intelligence.json not found -> SendMessage to coordinator requesting location. - -### Phase 3: Architecture Design - -**Scope Selection**: - -| Scope | Output | -|-------|--------| -| `tokens` | Design token system only | -| `components` | Component architecture only | -| `full` | Both tokens and components | - -#### Step 1: Design Token System (scope: tokens or full) - -Generate `design-tokens.json` with categories: - -| Category | Content | Source | -|----------|---------|--------| -| `color` | Primary, secondary, background, surface, text, CTA | ui-ux-pro-max recommendations | -| `typography` | Font families, font sizes | ui-ux-pro-max recommendations | -| `spacing` | Scale from xs to 2xl | Standard scale | -| `border-radius` | sm, md, lg, full | Standard scale | -| `shadow` | sm, md, lg | Standard elevation | -| `transition` | fast, normal, slow | Standard durations | - -**Token Structure**: -- Use `$type` and `$value` format (Design Tokens Community Group) -- Support light/dark mode via nested values -- Fallback to defaults if design intelligence unavailable - -#### Step 2: Component Architecture (scope: components or full) - -Generate component specifications in `architecture/component-specs/`: - -**Component Spec Template**: -1. Design Reference (style, stack) -2. Props table (name, type, default, description) -3. Variants table (name, description) -4. Accessibility requirements (role, keyboard, ARIA, contrast) -5. Implementation hints (CSS keywords) -6. Anti-patterns to avoid (from design intelligence) - -**Component List**: Derived from task description analysis. - -#### Step 3: Project Structure (scope: full or no existing project) - -Generate `project-structure.md`: - -**Stack-specific Structure**: - -| Stack | Directory Layout | -|-------|-----------------| -| react | src/components/, src/pages/, src/hooks/, src/styles/, src/utils/, src/types/ | -| nextjs | app/(routes)/, app/components/, app/lib/, app/styles/, app/types/ | -| vue | src/components/, src/views/, src/composables/, src/styles/, src/types/ | -| html-tailwind | src/components/, src/pages/, src/styles/, src/assets/ | - -**Conventions**: -- Naming: kebab-case for files, PascalCase for components -- Imports: absolute imports via @/ alias -- Styling: CSS Modules + design tokens (or Tailwind for html-tailwind) -- Testing: co-located test files (*.test.tsx) - -### Phase 4: Self-Validation - -**Validation Checks**: - -| Check | Method | Pass Criteria | -|-------|--------|---------------| -| JSON validity | Parse design-tokens.json | No errors | -| Required categories | Check for color, typography, spacing | All present | -| Anti-pattern compliance | Check token values against anti-patterns | No violations | -| File existence | Verify all planned files exist | All files present | - -**Validation Result**: - -| Status | Condition | -|--------|-----------| -| complete | No issues found | -| complete_with_warnings | Non-critical issues found | - -**Update Shared Memory**: -- Write `design_token_registry` field with generated tokens - -### Phase 5: Report to Coordinator - -> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report - -Standard report flow: team_msg log -> SendMessage with `[architect]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. - -**Report Content**: -- Task subject and status -- Scope completed -- Token counts (colors, typography, spacing) -- Design intelligence source -- Output file paths -- Validation warnings (if any) - ---- - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No ARCH-* tasks available | Idle, wait for coordinator assignment | -| design-intelligence.json not found | Use default token values, log warning | -| Session folder not found | Notify coordinator, request location | -| Token validation fails | Report issues, continue with warnings | -| Sub-agent failure | Retry once, fallback to direct execution | -| Critical issue beyond scope | SendMessage error to coordinator | diff --git a/.claude/skills/team-frontend/roles/coordinator/commands/dispatch.md b/.claude/skills/team-frontend/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..717f14e0 --- /dev/null +++ b/.claude/skills/team-frontend/roles/coordinator/commands/dispatch.md @@ -0,0 +1,202 @@ +# Command: Dispatch + +Create the frontend development task chain with correct dependencies and structured task descriptions. Supports page, feature, and system pipeline modes. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| User requirement | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline mode | From session.json `pipeline_mode` | Yes | +| Industry | From session.json `industry` | Yes | +| Constraints | From session.json `constraints` | No | + +1. Load user requirement and scope from session.json +2. Load pipeline mode (page / feature / system) from session.json +3. Load industry and constraints for task descriptions + +## Phase 3: Task Chain Creation + +### Task Description Template + +Every task description uses structured format: + +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + 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> + - Industry: <industry> + - Scope: <scope> + - Upstream artifacts: <artifact-1>, <artifact-2> + - Shared memory: <session>/.msg/meta.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### Mode Router + +| Mode | Task Chain | +|------|------------| +| `page` | ANALYZE-001 -> ARCH-001 -> DEV-001 -> QA-001 | +| `feature` | ANALYZE-001 -> ARCH-001 -> QA-001 -> DEV-001 -> QA-002 | +| `system` | ANALYZE-001 -> ARCH-001 -> QA-001 -> [ARCH-002 || DEV-001] -> QA-002 -> DEV-002 -> QA-003 | + +--- + +### Page Mode Task Chain (4 tasks) + +**ANALYZE-001** (analyst): +``` +TaskCreate({ + subject: "ANALYZE-001", + description: "PURPOSE: Analyze frontend requirements and retrieve design intelligence | Success: design-intelligence.json produced with industry-specific recommendations +TASK: + - Detect tech stack and existing design system + - Retrieve design intelligence via ui-ux-pro-max (or LLM fallback) + - Analyze existing codebase patterns + - Compile design-intelligence.json and requirements.md +CONTEXT: + - Session: <session-folder> + - Industry: <industry> + - Scope: <scope> + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/analysis/design-intelligence.json + requirements.md | Structured design data +CONSTRAINTS: Read-only analysis | No code modifications", + status: "pending" +}) +``` + +**ARCH-001** (architect): +``` +TaskCreate({ + subject: "ARCH-001", + description: "PURPOSE: Define design token system and component architecture | Success: design-tokens.json + component specs produced +TASK: + - Load design intelligence from analyst output + - Generate design token system (colors, typography, spacing, shadows) + - Define component architecture and specs + - Generate project structure +CONTEXT: + - Session: <session-folder> + - Industry: <industry> + - Scope: full + - Upstream artifacts: design-intelligence.json, requirements.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/architecture/design-tokens.json + component-specs/ + project-structure.md +CONSTRAINTS: Use ui-ux-pro-max recommendations for token values | Support light/dark mode", + blockedBy: ["ANALYZE-001"], + status: "pending" +}) +``` + +**DEV-001** (developer): +``` +TaskCreate({ + subject: "DEV-001", + description: "PURPOSE: Implement frontend page/components from architecture artifacts | Success: All planned files implemented with design token usage +TASK: + - Load design tokens, component specs, project structure + - Generate CSS custom properties from design tokens + - Implement components following specs and coding standards + - Self-validate: no hardcoded colors, cursor-pointer, focus styles, responsive +CONTEXT: + - Session: <session-folder> + - Industry: <industry> + - Scope: full + - Upstream artifacts: design-tokens.json, component-specs/, project-structure.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: src/styles/tokens.css + component files | Design-token compliant code +CONSTRAINTS: Use CSS variables from tokens | Mobile-first responsive | WCAG AA", + blockedBy: ["ARCH-001"], + status: "pending" +}) +``` + +**QA-001** (qa): +``` +TaskCreate({ + subject: "QA-001", + description: "PURPOSE: Execute 5-dimension quality audit on implementation | Success: Score >= 8 with 0 critical issues +TASK: + - Load design intelligence and tokens for compliance checks + - Execute 5-dimension audit (code quality, accessibility, design compliance, UX, pre-delivery) + - Calculate weighted score and determine verdict + - Write audit report +CONTEXT: + - Session: <session-folder> + - Industry: <industry> + - Review type: code-review + - Upstream artifacts: design-intelligence.json, design-tokens.json, src/** + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/qa/audit-001.md | Weighted score + verdict + categorized issues +CONSTRAINTS: Read-only review | No code modifications", + blockedBy: ["DEV-001"], + status: "pending" +}) +``` + +--- + +### Feature Mode Task Chain (5 tasks) + +Create ANALYZE-001 and ARCH-001 as page mode above, then: + +**QA-001** (qa, architecture review): +- blockedBy: ["ARCH-001"] +- Review type: architecture-review +- Reviews architecture artifacts before developer starts + +**DEV-001** (developer): +- blockedBy: ["QA-001"] (waits for arch review to pass) + +**QA-002** (qa, code review): +- blockedBy: ["DEV-001"] +- Review type: code-review + +--- + +### System Mode Task Chain (7 tasks) + +Create ANALYZE-001, ARCH-001, QA-001 as feature mode above, then: + +**ARCH-002** (architect, parallel with DEV-001): +- blockedBy: ["QA-001"] +- Scope: components (refined specs after QA feedback) + +**DEV-001** (developer, parallel with ARCH-002): +- blockedBy: ["QA-001"] +- Scope: tokens (CSS generation) + +**QA-002** (qa): +- blockedBy: ["ARCH-002"] +- Review type: component-review + +**DEV-002** (developer): +- blockedBy: ["QA-002"] +- Scope: components + +**QA-003** (qa, final review): +- blockedBy: ["DEV-002"] +- Review type: final + +## Phase 4: Validation + +| Check | Method | Expected | +|-------|--------|----------| +| Task count correct | TaskList count | page: 4, feature: 5, system: 7 | +| Dependencies correct | Trace dependency graph | Acyclic, correct blockedBy | +| Structured descriptions | Each has PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS | All present | +| Owner assignments correct | Role matches task prefix | ANALYZE->analyst, ARCH->architect, DEV->developer, QA->qa | + +If validation fails, fix the specific task and re-validate. diff --git a/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md b/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..854607de --- /dev/null +++ b/.claude/skills/team-frontend/roles/coordinator/commands/monitor.md @@ -0,0 +1,185 @@ +# Command: Monitor + +Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, GC loops, and completion. + +## Phase 2: Context Loading + +| 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 | + +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 + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +1. Parse message to identify role and task ID: + +| Message Pattern | Role Detection | +|----------------|---------------| +| `[analyst]` or task ID `ANALYZE-*` | analyst | +| `[architect]` or task ID `ARCH-*` | architect | +| `[developer]` or task ID `DEV-*` | developer | +| `[qa]` or task ID `QA-*` | qa | + +2. Mark task as completed: + +``` +TaskUpdate({ taskId: "<task-id>", status: "completed" }) +``` + +3. Record completion in session state + +4. Check if checkpoint applies: + +| Completed Task | Pipeline Mode | Checkpoint Action | +|---------------|---------------|-------------------| +| ANALYZE-001 | all | Log: analysis ready | +| ARCH-001 | feature/system | Log: architecture ready for review | +| QA-001 (arch review) | feature/system | Gate: pause if critical issues, wait for architect revision | +| QA-* (code review) | all | Check verdict for GC loop (see below) | + +5. **GC Loop Check** (when QA completes with fix_required): + +| Condition | Action | +|-----------|--------| +| QA verdict = PASSED or PASSED_WITH_WARNINGS | Proceed to handleSpawnNext | +| QA verdict = FIX_REQUIRED AND gc_round < 2 | Create DEV-fix + QA-recheck tasks, increment gc_round | +| QA verdict = FIX_REQUIRED AND gc_round >= 2 | Escalate to user: accept current state or manual intervention | + +**GC Fix Task Creation**: +``` +TaskCreate({ + subject: "DEV-fix-<round>", + description: "PURPOSE: Fix issues identified in QA audit | Success: All critical/high issues resolved +TASK: + - Load QA audit report with findings + - Address critical and high severity issues + - Re-validate fixes against coding standards +CONTEXT: + - Session: <session-folder> + - Upstream artifacts: <session>/qa/audit-<NNN>.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: Fixed source files | QA issues resolved +CONSTRAINTS: Targeted fixes only | Do not introduce regressions", + blockedBy: [], + status: "pending" +}) + +TaskCreate({ + subject: "QA-recheck-<round>", + description: "PURPOSE: Re-audit after developer fixes | Success: Score >= 8, critical == 0 +TASK: + - Execute 5-dimension audit on fixed code + - Focus on previously flagged issues + - Calculate new score +CONTEXT: + - Session: <session-folder> + - Review type: code-review + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/qa/audit-<NNN>.md | Improved score +CONSTRAINTS: Read-only review", + blockedBy: ["DEV-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. For each ready task, spawn team-worker: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <task-id>", + team_name: "frontend", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-frontend/role-specs/<role>.md +session: <session-folder> +session_id: <session-id> +team_name: frontend +requirement: <task-description> +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.` +}) +``` + +3. **Parallel spawn rules**: + +| Mode | Scenario | Spawn Behavior | +|------|----------|---------------| +| page | Each stage sequential | One worker at a time | +| feature | After QA-001 arch review | Spawn DEV-001 | +| system | After QA-001 arch review | Spawn ARCH-002 + DEV-001 in parallel | + +4. STOP after spawning -- wait for next callback + +### handleCheck + +Output current pipeline status. + +``` +Pipeline Status (<mode> mode): + [DONE] ANALYZE-001 (analyst) -> design-intelligence.json + [DONE] ARCH-001 (architect) -> design-tokens.json + [RUN] DEV-001 (developer) -> implementing... + [WAIT] QA-001 (qa) -> blocked by DEV-001 + +GC Rounds: 0/2 +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. + +**Completion check**: + +| Mode | Completion Condition | +|------|---------------------| +| page | All 4 tasks (+ any GC fix/recheck tasks) completed | +| feature | All 5 tasks (+ any GC fix/recheck tasks) completed | +| system | All 7 tasks (+ any GC fix/recheck tasks) completed | + +1. If any tasks not completed, return to handleSpawnNext +2. If all completed, transition to coordinator Phase 5 + +## Phase 4: State Persistence + +After every handler execution: + +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 diff --git a/.claude/skills/team-frontend/roles/coordinator/role.md b/.claude/skills/team-frontend/roles/coordinator/role.md index 4f949dc3..0797d8a9 100644 --- a/.claude/skills/team-frontend/roles/coordinator/role.md +++ b/.claude/skills/team-frontend/roles/coordinator/role.md @@ -1,257 +1,266 @@ -# Coordinator Role +# Coordinator - Frontend Development Team -Frontend team coordinator. Orchestrates pipeline: requirement clarification → industry identification → team creation → task chain → dispatch → monitoring → reporting. Manages Generator-Critic loops between developer and qa, consulting pattern between developer and analyst. +**Role**: coordinator +**Type**: Orchestrator +**Team**: frontend -## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Parse requirements → Create team → Dispatch tasks → Monitor progress → Report results +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. ## Boundaries ### MUST -- All output (SendMessage, team_msg, logs) must carry `[coordinator]` identifier -- Parse user requirements and clarify ambiguous inputs via AskUserQuestion -- Create team and spawn worker subagents in background -- Dispatch tasks with proper dependency chains (see SKILL.md Task Metadata Registry) -- Monitor progress via worker callbacks and route messages -- Maintain session state persistence +- 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 +- Handle GC loops (developer <-> qa) with max 2 iterations +- Execute completion action in Phase 5 ### MUST NOT -- Execute frontend development work directly (delegate to workers) -- Modify task outputs (workers own their deliverables) -- Call implementation subagents directly -- Skip dependency validation when creating task chains -- Omit `[coordinator]` identifier in any output +- 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 -> **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): + +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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline | -| New session | None of the above | -> Phase 0 (Session Resume Check) | +| 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) | + +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 --- -## Message Types +## Phase 0: Session Resume Check -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `task_unblocked` | coordinator → any | Dependency resolved | Notify worker of available task | -| `sync_checkpoint` | coordinator → all | QA passed at sync point | Design artifacts stable for consumption | -| `fix_required` | coordinator → developer | QA found issues | Create DEV-fix task | -| `error` | coordinator → all | Critical system error | Escalation to user | -| `shutdown` | coordinator → all | Team being dissolved | Clean shutdown signal | +Triggered when an active/paused session is detected on coordinator entry. -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: +1. Load session.json from detected session folder +2. Audit task list: ``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., FES-xxx-date), NOT team name. Extract from Session: field. - from: "coordinator", - to: <recipient>, - type: <message-type>, - summary: "[coordinator] <summary>", - ref: <artifact-path> +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 + +--- + +## Phase 1: Requirement Clarification + +1. Parse user task description from $ARGUMENTS + +2. Ask for missing parameters via AskUserQuestion: + + **Scope Selection**: + + | Option | Pipeline | + |--------|----------| + | Single page | page (4-beat linear) | + | Multi-component feature | feature (5-beat with arch review) | + | Full frontend system | system (7-beat dual-track) | + + **Industry Selection**: + + | Option | Strictness | + |--------|------------| + | SaaS/Tech | standard | + | E-commerce/Retail | standard | + | Healthcare/Finance | strict | + | Other | standard | + + **Design Constraints** (multi-select): Existing design system, WCAG AA, Responsive, Dark mode + +3. Record requirements: mode, scope, industry, constraints + +--- + +## Phase 2: Session & Team Setup + +1. Create session directory: + +``` +Bash("mkdir -p .workflow/.team/FE-<slug>-<YYYY-MM-DD>/{.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 .msg/meta.json: + +``` +Write("<session>/.msg/meta.json", { "session_id": "<session-id>", "requirement": "<requirement>", "pipeline_mode": "<mode>" }) +``` + +4. Create team: + +``` +TeamCreate({ team_name: "frontend" }) +``` + +--- + +## 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: + +``` +Task({ + 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.` }) ``` -**CLI fallback** (when MCP unavailable): +**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 + +--- + +## Phase 5: Report + Completion Action + +1. Load session state -> count completed tasks, calculate duration +2. List deliverables: + +| Deliverable | Path | +|-------------|------| +| Design Intelligence | <session>/analysis/design-intelligence.json | +| Requirements | <session>/analysis/requirements.md | +| Design Tokens | <session>/architecture/design-tokens.json | +| Component Specs | <session>/architecture/component-specs/ | +| Project Structure | <session>/architecture/project-structure.md | +| QA Audits | <session>/qa/audit-*.md | + +3. Output pipeline summary: task count, duration, QA scores + +4. **Completion Action** (interactive): ``` -Bash("ccw team log --team <session-id> --from coordinator --to <recipient> --type <message-type> --summary \"[coordinator] ...\" --ref <artifact-path> --json") +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: -## Execution (5-Phase) - -### 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 - ---- - -### Phase 1: Requirement Clarification - -**Objective**: Parse user input and gather execution parameters. - -**Workflow**: - -1. **Parse arguments** for explicit settings: mode, scope, focus areas - -2. **Ask for missing parameters** via AskUserQuestion: - - **Scope Selection**: - | Option | Description | Pipeline | - |--------|-------------|----------| - | Single page | Design and implement a standalone page/component | page | - | Multi-component feature | Multiple components + design tokens + interaction logic | feature | - | Full frontend system | Build complete frontend from scratch (tokens + component library + pages) | system | - - **Industry Selection**: - | Option | Description | Strictness | - |--------|-------------|------------| - | SaaS/Tech | SaaS, dev tools, AI products | standard | - | E-commerce/Retail | E-commerce, luxury, marketplace | standard | - | Healthcare/Finance | Healthcare, banking, insurance (high compliance) | strict | - | Other | Manual keyword input | standard | - - **Design Constraints** (multi-select): - - Existing design system (must be compatible with existing tokens/components) - - WCAG AA (must meet WCAG 2.1 AA accessibility standards) - - Responsive (must support mobile/tablet/desktop) - - Dark mode (must support light/dark theme switching) - -3. **Store requirements**: mode, scope, focus, constraints - -**Success**: All parameters captured, mode finalized. - ---- - -### Phase 2: Create Team + Initialize Session - -**Objective**: Initialize team, session file, and wisdom directory. - -**Workflow**: - -1. Generate session ID: `FE-<slug>-<YYYY-MM-DD>` -2. Create session folder structure -3. Call TeamCreate with team name -4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) -5. Write session file with: session_id, mode, scope, status="active" -6. Initialize shared-memory.json with empty structures -7. Do NOT pre-spawn workers (spawned per-stage in Phase 4) - -**Session Directory Structure**: -``` -.workflow/.team/FE-<slug>-<date>/ -├── team-session.json -├── shared-memory.json -├── wisdom/ -├── analysis/ -├── architecture/ -├── qa/ -└── build/ -``` - -**Success**: Team created, session file written, wisdom initialized. - ---- - -### Phase 3: Create Task Chain - -**Objective**: Dispatch tasks based on mode with proper dependencies. - -**Pipeline Definitions**: - -| Mode | Task Chain | Description | -|------|------------|-------------| -| page | ANALYZE-001 -> ARCH-001 -> DEV-001 -> QA-001 | Linear 4-beat | -| feature | ANALYZE-001 -> ARCH-001 -> QA-001 -> DEV-001 -> QA-002 | 5-beat with architecture review | -| system | ANALYZE-001 -> ARCH-001 -> QA-001 -> [ARCH-002 || DEV-001] -> QA-002 -> DEV-002 -> QA-003 | 7-beat dual-track | - -**Task Creation** (for each task): -- Include `Session: <session-folder>` in description -- Set owner based on role mapping -- Set blockedBy dependencies based on pipeline - -**Success**: All tasks created with correct dependencies. - ---- - -### Phase 4: Coordination Loop - -**Objective**: Spawn first batch of ready workers, then STOP. - -**Design**: Spawn-and-Stop + Callback pattern. -- Spawn workers with `Task(run_in_background: true)` -> immediately return -- Worker completes -> SendMessage callback -> auto-advance -- User can use "check" / "resume" to manually advance -- Coordinator does one operation per invocation, then STOPS - -**Pipeline advancement** driven by three wake sources: -- Worker callback (automatic) -> Entry Router -> handleCallback -- User "check" -> handleCheck (status only) -- User "resume" -> handleResume (advance) - -**Message Routing**: - -| Received Message | Action | -|-----------------|--------| -| analyst: `analyze_ready` | team_msg log -> TaskUpdate ANALYZE completed -> unblock ARCH | -| architect: `arch_ready` | team_msg log -> TaskUpdate ARCH completed -> unblock QA/DEV | -| developer: `dev_complete` | team_msg log -> TaskUpdate DEV completed -> unblock QA | -| qa: `qa_passed` | team_msg log -> TaskUpdate QA completed -> unblock next stage | -| qa: `fix_required` | Create DEV-fix task -> notify developer (GC loop) | -| developer: consult request | Create ANALYZE-consult task -> notify analyst | -| Worker: `error` | Assess severity -> retry or escalate to user | -| All tasks completed | -> Phase 5 | - -**GC Loop Control** (Generator-Critic: developer <-> qa): - -| Condition | Action | -|-----------|--------| -| QA sends fix_required && gcRound < MAX_GC_ROUNDS (2) | Create DEV-fix task + QA-recheck task, increment gcRound | -| QA sends fix_required && gcRound >= MAX_GC_ROUNDS | Escalate to user: accept current state or manual intervention | - ---- - -### Phase 5: Report + Next Steps - -**Objective**: Completion report and follow-up options. - -**Workflow**: -1. Load session state -> count completed tasks, duration -2. List deliverables with output paths -3. Update session status -> "completed" -4. Offer next steps to user via AskUserQuestion: - - New requirement -> back to Phase 1 - - Close team -> shutdown -> TeamDelete - ---- - -## Error Handling - -| Scenario | 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 | -| Teammate unresponsive | Send follow-up, 2x -> respawn | -| QA rejected 3+ times | Escalate to user | -| Dual-track sync failure | Fallback to single-track sequential | -| ui-ux-pro-max unavailable | Continue with LLM general knowledge | -| DEV can't find design files | Wait for sync point or escalate | +| Choice | Steps | +|--------|-------| +| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("frontend") -> 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 | diff --git a/.claude/skills/team-frontend/roles/developer/role.md b/.claude/skills/team-frontend/roles/developer/role.md deleted file mode 100644 index a4fa71dd..00000000 --- a/.claude/skills/team-frontend/roles/developer/role.md +++ /dev/null @@ -1,238 +0,0 @@ -# Developer Role - -Frontend developer. Consumes architecture artifacts, implements frontend component/page code. References design-intelligence.json Implementation Checklist and tech stack guidelines during code generation, follows Anti-Patterns constraints. - -## Identity - -- **Name**: `developer` | **Tag**: `[developer]` -- **Task Prefix**: `DEV-*` -- **Responsibility**: Code generation - -## Boundaries - -### MUST - -- Only process `DEV-*` prefixed tasks -- All output (SendMessage, team_msg, logs) must carry `[developer]` identifier -- Only communicate with coordinator via SendMessage -- Work strictly within frontend code implementation scope - -### MUST NOT - -- Execute work outside this role's responsibility scope (analysis, architecture, QA) -- Communicate directly with other worker roles (must go through coordinator) -- Create tasks for other roles (TaskCreate is coordinator-exclusive) -- Modify design token definitions (only consume them) -- Omit `[developer]` identifier in any output - ---- - -## Toolbox - -### Available Commands - -> No command files -- all phases execute inline. - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `Read` | builtin | Phase 2 | Load architecture artifacts | -| `Write` | builtin | Phase 3 | Write source code files | -| `Edit` | builtin | Phase 3 | Modify source code | -| `Bash` | builtin | Phase 3-4 | Run build commands, install deps, format | -| `Glob` | builtin | Phase 2-4 | Search project files | -| `Grep` | builtin | Phase 2-4 | Search code patterns | -| `Task(code-developer)` | subagent | Phase 3 | Complex component implementation | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `dev_complete` | developer → coordinator | Implementation complete | Code implementation finished | -| `dev_progress` | developer → coordinator | Partial progress | Implementation progress update | -| `error` | developer → coordinator | Implementation failure | Implementation failed | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., FES-xxx-date), NOT team name. Extract from Session: field. - from: "developer", - to: "coordinator", - type: <message-type>, - summary: "[developer] DEV complete: <task-subject>", - ref: <artifact-path> -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --team <session-id> --from developer --to coordinator --type <message-type> --summary \"[developer] ...\" --ref <artifact-path> --json") -``` - ---- - -## Execution (5-Phase) - -### Phase 1: Task Discovery - -> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery - -Standard task discovery flow: TaskList -> filter by prefix `DEV-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress. - -### Phase 2: Context Loading - -**Input Sources**: - -| Input | Source | Required | -|-------|--------|----------| -| Session folder | Extract from task description `Session: <path>` | Yes | -| Scope | Extract from task description `Scope: <tokens|components|full>` | No (default: full) | -| Design intelligence | `<session-folder>/analysis/design-intelligence.json` | No | -| Design tokens | `<session-folder>/architecture/design-tokens.json` | No | -| Project structure | `<session-folder>/architecture/project-structure.md` | No | -| Component specs | `<session-folder>/architecture/component-specs/*.md` | No | -| Shared memory | `<session-folder>/shared-memory.json` | No | - -**Loading Steps**: - -1. Extract session folder and scope from task description -2. Load design intelligence -3. Load design tokens -4. Load project structure -5. Load component specs (if available) -6. Load shared memory -7. Detect tech stack from design intelligence - -**Fail-safe**: If design-tokens.json not found -> SendMessage to coordinator requesting architecture output. - -### Phase 3: Code Implementation - -**Scope Selection**: - -| Scope | Output | -|-------|--------| -| `tokens` | Generate CSS custom properties from design tokens | -| `components` | Implement components from specs | -| `full` | Both tokens and components | - -#### Step 1: Generate Design Token CSS (scope: tokens or full) - -Convert `design-tokens.json` to CSS custom properties: - -**Token Category Mapping**: - -| JSON Category | CSS Variable Prefix | Example | -|---------------|---------------------|---------| -| color | `--color-` | `--color-primary` | -| typography.font-family | `--font-` | `--font-heading` | -| typography.font-size | `--text-` | `--text-lg` | -| spacing | `--space-` | `--space-md` | -| border-radius | `--radius-` | `--radius-lg` | -| shadow | `--shadow-` | `--shadow-md` | -| transition | `--duration-` | `--duration-normal` | - -**Output**: `src/styles/tokens.css` - -**Dark Mode Support**: Add `@media (prefers-color-scheme: dark)` override for colors. - -#### Step 2: Implement Components (scope: components or full) - -**Implementation Strategy**: - -| Condition | Strategy | -|-----------|----------| -| <= 2 tasks, low complexity | Direct: inline Edit/Write | -| 3-5 tasks, medium complexity | Single agent: one code-developer for all | -| > 5 tasks, high complexity | Batch agent: group by module, one agent per batch | - -**Subagent Delegation** (for complex implementation): - -``` -Task({ - subagent_type: "code-developer", - run_in_background: false, - description: "Implement frontend components: <task-description>", - prompt: "..." -}) -``` - -**Prompt Content for Subagent**: -- Goal: task description -- Tech stack: detected stack -- Design tokens: import path, CSS variable usage -- Component specs: from component-specs/*.md -- Stack-specific guidelines: from design intelligence -- Implementation checklist: from design intelligence -- Anti-patterns to avoid: from design intelligence -- Coding standards: design token usage, cursor styles, transitions, contrast, focus styles, reduced motion, responsive - -**Coding Standards**: -- Use design token CSS variables, never hardcode colors/spacing -- All interactive elements must have `cursor: pointer` -- Transitions: 150-300ms (use `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-Validation - -**Pre-delivery Self-checks**: - -| Check | Method | Pass Criteria | -|-------|--------|---------------| -| Hardcoded colors | Scan for hex codes outside tokens.css | None found | -| cursor-pointer | Check buttons/links for cursor style | 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 exist | All files present | -| Import resolution | Check no broken imports | All imports resolve | - -**Auto-fix** (if possible): -- Add missing cursor-pointer to buttons/links -- Add basic focus styles - -**Update Shared Memory**: -- Write `component_inventory` field with implemented files - -**Validation Result**: - -| Status | Condition | -|--------|-----------| -| complete | No issues found | -| complete_with_warnings | Non-critical issues found | - -### Phase 5: Report to Coordinator - -> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report - -Standard report flow: team_msg log -> SendMessage with `[developer]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. - -**Report Content**: -- Task subject and status -- Scope completed -- File count implemented -- Self-check results -- Output file paths - ---- - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No DEV-* tasks available | Idle, wait for coordinator assignment | -| design-tokens.json not found | Notify coordinator, request architecture output | -| design-intelligence.json not found | Use default implementation guidelines | -| Sub-agent failure | Retry once, fallback to direct implementation | -| Build/compile errors | Attempt auto-fix, report remaining issues | -| Critical issue beyond scope | SendMessage error to coordinator | diff --git a/.claude/skills/team-frontend/roles/qa/commands/pre-delivery-checklist.md b/.claude/skills/team-frontend/roles/qa/commands/pre-delivery-checklist.md deleted file mode 100644 index 4015dead..00000000 --- a/.claude/skills/team-frontend/roles/qa/commands/pre-delivery-checklist.md +++ /dev/null @@ -1,116 +0,0 @@ -# Command: pre-delivery-checklist - -> 最终交付前的 CSS 级别精准检查清单,融合 ui-ux-pro-max Pre-Delivery Checklist 和 ux-guidelines.csv 规则。 - -## When to Use - -- Phase 3 of qa role, Dimension 5: Pre-Delivery -- Final review type (`reviewType === 'final'` or `reviewType === 'code-review'`) - -## Strategy - -### Delegation Mode - -**Mode**: Direct (inline pattern matching) - -## Checklist Items - -### Accessibility - -| # | Check | Pattern | Severity | Do | Don't | -|---|-------|---------|----------|-----|-------| -| 1 | Images have alt text | `<img` without `alt=` | CRITICAL | Always provide descriptive alt text | Leave alt empty without role="presentation" | -| 2 | Form inputs have labels | `<input` without `<label`/`aria-label` | HIGH | Associate every input with a label | Use placeholder as sole label | -| 3 | Focus states visible | Interactive elements without `focus` styles | HIGH | Add focus-visible outline | Remove default focus ring without replacement | -| 4 | Color contrast 4.5:1 | Light text on light background | HIGH | Ensure 4.5:1 minimum ratio | Use low-contrast decorative text for content | -| 5 | prefers-reduced-motion | Animations without media query | MEDIUM | Wrap in @media (prefers-reduced-motion: no-preference) | Force animations on all users | -| 6 | Heading hierarchy | Skipped heading levels (h1→h3) | MEDIUM | Use sequential heading levels | Skip levels for visual sizing | - -### Interaction - -| # | Check | Pattern | Severity | Do | Don't | -|---|-------|---------|----------|-----|-------| -| 7 | cursor-pointer on clickable | Buttons/links without cursor-pointer | MEDIUM | Add cursor: pointer to all clickable elements | Leave default cursor | -| 8 | Transitions 150-300ms | Duration outside range | LOW | Use 150-300ms for micro-interactions | Use >500ms or <100ms transitions | -| 9 | Loading states | Async ops without loading indicator | MEDIUM | Show skeleton/spinner during fetch | Leave blank screen while loading | -| 10 | Error states | Async ops without error handling | HIGH | Show user-friendly error message | Silently fail or show raw error | - -### Design Compliance - -| # | Check | Pattern | Severity | Do | Don't | -|---|-------|---------|----------|-----|-------| -| 11 | No hardcoded colors | Hex values outside tokens.css | HIGH | Use var(--color-*) tokens | Hardcode #hex values | -| 12 | No hardcoded spacing | px values for margin/padding | MEDIUM | Use var(--space-*) tokens | Hardcode pixel values | -| 13 | No emoji as icons | Unicode emoji in UI | HIGH | Use proper SVG/icon library | Use emoji for functional icons | -| 14 | Dark mode support | No prefers-color-scheme | MEDIUM | Support light/dark themes | Design for light mode only | - -### Layout - -| # | Check | Pattern | Severity | Do | Don't | -|---|-------|---------|----------|-----|-------| -| 15 | Responsive breakpoints | No md:/lg:/@media | MEDIUM | Mobile-first responsive design | Desktop-only layout | -| 16 | No horizontal scroll | Fixed widths > viewport | HIGH | Use relative/fluid widths | Set fixed pixel widths on containers | - -## Execution - -```javascript -function runPreDeliveryChecklist(fileContents) { - const results = { passed: 0, failed: 0, items: [] } - - const checks = [ - { id: 1, check: "Images have alt text", test: (c) => /<img\s/.test(c) && !/<img\s[^>]*alt=/.test(c), severity: 'CRITICAL' }, - { id: 7, check: "cursor-pointer on clickable", test: (c) => /button|onClick/.test(c) && !/cursor-pointer/.test(c), severity: 'MEDIUM' }, - { id: 11, check: "No hardcoded colors", test: (c, f) => f !== 'src/styles/tokens.css' && /#[0-9a-fA-F]{6}/.test(c), severity: 'HIGH' }, - { id: 13, check: "No emoji as icons", test: (c) => /[\u{1F300}-\u{1F9FF}]/u.test(c), severity: 'HIGH' }, - { id: 14, check: "Dark mode support", test: (c) => !/prefers-color-scheme|dark:|\.dark/.test(c), severity: 'MEDIUM', global: true }, - { id: 15, check: "Responsive breakpoints", test: (c) => !/md:|lg:|@media.*min-width/.test(c), severity: 'MEDIUM', global: true } - ] - - // Per-file checks - for (const [file, content] of Object.entries(fileContents)) { - for (const check of checks.filter(c => !c.global)) { - if (check.test(content, file)) { - results.failed++ - results.items.push({ ...check, file, status: 'FAIL' }) - } else { - results.passed++ - results.items.push({ ...check, file, status: 'PASS' }) - } - } - } - - // Global checks (across all content) - const allContent = Object.values(fileContents).join('\n') - for (const check of checks.filter(c => c.global)) { - if (check.test(allContent)) { - results.failed++ - results.items.push({ ...check, file: 'global', status: 'FAIL' }) - } else { - results.passed++ - results.items.push({ ...check, file: 'global', status: 'PASS' }) - } - } - - return results -} -``` - -## Output Format - -``` -## Pre-Delivery Checklist Results -- Passed: X / Y -- Failed: Z - -### Failed Items -- [CRITICAL] #1 Images have alt text — src/components/Hero.tsx -- [HIGH] #11 No hardcoded colors — src/styles/custom.css -``` - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No files to check | Report empty checklist, score 10/10 | -| File read error | Skip file, note in report | -| Regex error | Skip check, note in report | diff --git a/.claude/skills/team-frontend/roles/qa/role.md b/.claude/skills/team-frontend/roles/qa/role.md deleted file mode 100644 index 475e92a7..00000000 --- a/.claude/skills/team-frontend/roles/qa/role.md +++ /dev/null @@ -1,257 +0,0 @@ -# QA Role - -Quality assurance engineer. Integrates ux-guidelines.csv Do/Don't rules, Pre-Delivery Checklist, and industry anti-pattern library to execute 5-dimension code review. Upgrades from conceptual review to CSS-level precise review. - -## Identity - -- **Name**: `qa` | **Tag**: `[qa]` -- **Task Prefix**: `QA-*` -- **Responsibility**: Read-only analysis (code review + quality audit) - -## Boundaries - -### MUST - -- Only process `QA-*` prefixed tasks -- All output (SendMessage, team_msg, logs) must carry `[qa]` identifier -- Only communicate with coordinator via SendMessage -- Work strictly within quality review scope - -### MUST NOT - -- Execute work outside this role's responsibility scope (analysis, architecture, implementation) -- Communicate directly with other worker roles (must go through coordinator) -- Create tasks for other roles (TaskCreate is coordinator-exclusive) -- Directly modify source code (only report issues) -- Omit `[qa]` identifier in any output - ---- - -## Toolbox - -### Available Commands - -| Command | File | Phase | Description | -|---------|------|-------|-------------| -| `pre-delivery-checklist` | [commands/pre-delivery-checklist.md](commands/pre-delivery-checklist.md) | Phase 3 | Final delivery checklist execution | - -### Tool Capabilities - -| Tool | Type | Used By | Purpose | -|------|------|---------|---------| -| `Read` | builtin | Phase 2-3 | Load artifacts, read code files | -| `Glob` | builtin | Phase 2 | Collect files to review | -| `Grep` | builtin | Phase 3 | Search code patterns | -| `Bash` | builtin | Phase 3 | Run read-only checks (lint, type-check) | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `qa_passed` | qa → coordinator | All checks passed | Review passed, proceed to next stage | -| `qa_result` | qa → coordinator | Review complete with findings | Review complete, has findings to address | -| `fix_required` | qa → coordinator | Critical issues found | Critical issues found, needs fix (triggers GC loop) | -| `error` | qa → coordinator | Review failure | Review process failed | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: - -``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., FES-xxx-date), NOT team name. Extract from Session: field. - from: "qa", - to: "coordinator", - type: <message-type>, - summary: "[qa] QA <verdict>: <task-subject> (<score>/10)", - ref: <audit-file> -}) -``` - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --team <session-id> --from qa --to coordinator --type <message-type> --summary \"[qa] ...\" --ref <audit-file> --json") -``` - ---- - -## 5-Dimension Audit Framework - -| Dimension | Weight | Source | Focus | -|-----------|--------|--------|-------| -| Code Quality | 0.20 | Standard code review | Code structure, naming, maintainability | -| Accessibility | 0.25 | ux-guidelines.csv accessibility rules | WCAG compliance, keyboard nav, screen reader | -| Design Compliance | 0.20 | design-intelligence.json anti-patterns | Industry anti-pattern check, design token usage | -| UX Best Practices | 0.20 | ux-guidelines.csv Do/Don't rules | Interaction patterns, responsive, animations | -| Pre-Delivery | 0.15 | ui-ux-pro-max Pre-Delivery Checklist | Final delivery checklist | - ---- - -## Execution (5-Phase) - -### Phase 1: Task Discovery - -> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery - -Standard task discovery flow: TaskList -> filter by prefix `QA-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress. - -### Phase 2: Context Loading - -**Input Sources**: - -| Input | Source | Required | -|-------|--------|----------| -| Session folder | Extract from task description `Session: <path>` | Yes | -| Review type | Extract from task description `Type: <type>` | No (default: code-review) | -| Design intelligence | `<session-folder>/analysis/design-intelligence.json` | No | -| Design tokens | `<session-folder>/architecture/design-tokens.json` | No | -| Shared memory | `<session-folder>/shared-memory.json` | No | - -**Review Types**: - -| Type | Files to Review | -|------|-----------------| -| architecture-review | `<session-folder>/architecture/**/*` | -| token-review | `<session-folder>/architecture/**/*` | -| component-review | `<session-folder>/architecture/component-specs/**/*` | -| code-review | `src/**/*.{tsx,jsx,vue,svelte,html,css}` | -| final | `src/**/*.{tsx,jsx,vue,svelte,html,css}` | - -**Loading Steps**: - -1. Extract session folder and review type -2. Load design intelligence (for anti-patterns, must-have) -3. Load design tokens (for compliance checks) -4. Load shared memory (for industry context, strictness) -5. Collect files to review based on review type - -### Phase 3: 5-Dimension Audit - -#### Dimension 1: Code Quality (weight: 0.20) - -| Check | Severity | Description | -|-------|----------|-------------| -| File length | MEDIUM | File exceeds 300 lines, consider splitting | -| console.log | LOW | console.log found in production code | -| Empty catch | HIGH | Empty catch block found | -| Unused imports | LOW | Unused imports detected | - -#### Dimension 2: Accessibility (weight: 0.25) - -| Check | Severity | Do | Don't | -|-------|----------|----|----| -| Image alt | CRITICAL | Always provide alt text | Leave alt empty without role="presentation" | -| Input labels | HIGH | Use <label> or aria-label | Rely on placeholder as label | -| Button text | HIGH | Add aria-label for icon-only buttons | Use title as sole accessible name | -| Heading hierarchy | MEDIUM | Maintain sequential heading levels | Skip heading levels | -| Focus styles | HIGH | Add focus-visible outline | Remove default outline without replacement | -| ARIA roles | MEDIUM | Include tabindex for non-native elements | Use role without keyboard support | - -**Strict Mode** (medical/financial): - -| Check | Severity | Do | Don't | -|-------|----------|----|----| -| Reduced motion | HIGH | Wrap animations in @media (prefers-reduced-motion) | Force animations on all users | - -#### Dimension 3: Design Compliance (weight: 0.20) - -| Check | Severity | Do | Don't | -|-------|----------|----|----| -| Hardcoded colors | HIGH | Use var(--color-primary) | Hardcode #1976d2 | -| Hardcoded spacing | MEDIUM | Use var(--space-md) | Hardcode 16px | -| Industry anti-patterns | CRITICAL/HIGH | Follow industry-specific guidelines | Violate anti-patterns (gradients, emojis as icons, etc.) | - -#### Dimension 4: UX Best Practices (weight: 0.20) - -| Check | Severity | Do | Don't | -|-------|----------|----|----| -| Cursor pointer | MEDIUM | Add cursor: pointer to all clickable elements | Leave default cursor on buttons/links | -| Transition duration | LOW | Use 150-300ms | Use durations outside 100-500ms | -| Responsive | MEDIUM | Use mobile-first responsive design | Design for desktop only | -| Loading states | MEDIUM | Show loading indicator during data fetching | Leave blank screen while loading | -| Error states | HIGH | Show user-friendly error message | Silently fail or show raw error | - -#### Dimension 5: Pre-Delivery (weight: 0.15) - -Only run on `final` or `code-review` types. - -| Check | Severity | -|-------|----------| -| No emojis as functional icons | HIGH | -| cursor-pointer on all clickable | MEDIUM | -| Transitions in valid range (150-300ms) | LOW | -| Focus states visible | HIGH | -| prefers-reduced-motion support | MEDIUM | -| Responsive breakpoints | MEDIUM | -| No hardcoded colors | HIGH | -| Dark mode support | MEDIUM | - -### Phase 4: Score Calculation and Report - -**Calculate Weighted Score**: - -``` -score = sum(dimension_score * dimension_weight) for all dimensions -``` - -**Collect Issues**: - -- Aggregate all issues from all dimensions -- Count critical issues - -**Determine Verdict**: - -| Condition | Verdict | -|-----------|---------| -| score >= 8 AND critical_count === 0 | PASSED | -| score >= 6 AND critical_count === 0 | PASSED_WITH_WARNINGS | -| score < 6 OR critical_count > 0 | FIX_REQUIRED | - -**Write Audit Report** to `<session-folder>/qa/audit-<NNN>.md`: - -Report structure: -1. Summary (verdict, score, critical count, total issues) -2. Dimension scores table -3. Issues (by severity, with Do/Don't guidance) -4. Passed dimensions - -**Update Shared Memory**: -- Append to `qa_history` array - -### Phase 5: Report to Coordinator - -> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report - -Standard report flow: team_msg log -> SendMessage with `[qa]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task. - -**Message Type Selection**: - -| Verdict | Message Type | -|---------|-------------| -| PASSED | `qa_passed` | -| PASSED_WITH_WARNINGS | `qa_result` | -| FIX_REQUIRED | `fix_required` | - -**Report Content**: -- Task subject -- Verdict and score -- Dimension summary -- Critical issues (if any) -- High priority issues (if any) -- Audit report path - ---- - -## Error Handling - -| Scenario | Resolution | -|----------|------------| -| No QA-* tasks available | Idle, wait for coordinator assignment | -| design-intelligence.json not found | Skip design compliance dimension, adjust weights | -| No files to review | Report empty review, notify coordinator | -| Session folder not found | Notify coordinator, request location | -| Critical issue beyond scope | SendMessage error to coordinator | diff --git a/.claude/skills/team-issue/SKILL.md b/.claude/skills/team-issue/SKILL.md index 2d0a3bcb..176ea1c8 100644 --- a/.claude/skills/team-issue/SKILL.md +++ b/.claude/skills/team-issue/SKILL.md @@ -116,10 +116,10 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` - - **Note**: `team` must be session ID (e.g., `ISS-xxx-date`), NOT team name. Extract from `Session:` field in task description. -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) + - 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 @@ -158,11 +158,12 @@ All outputs must carry `[role_name]` prefix in both SendMessage content/summary Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: -**Parameters**: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> +**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} -**CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` +`to` and `summary` auto-defaulted -- do NOT specify explicitly. + +**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json` -**Note**: `team` must be session ID (e.g., `ISS-xxx-date`), NOT team name. Extract from `Session:` field in task description. **Message types by role**: @@ -399,8 +400,9 @@ Skill(skill="team-issue", args="--role=<role> --agent-name=<role>-<N>") ``` .workflow/.team-plan/issue/ -├── team-session.json # Session state -├── shared-memory.json # Cross-role state +├── .msg/ +│ ├── messages.jsonl # Message bus log +│ └── meta.json # Session state + cross-role state ├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md diff --git a/.claude/skills/team-issue/role-specs/explorer.md b/.claude/skills/team-issue/role-specs/explorer.md new file mode 100644 index 00000000..753975b5 --- /dev/null +++ b/.claude/skills/team-issue/role-specs/explorer.md @@ -0,0 +1,105 @@ +--- +prefix: EXPLORE +inner_loop: false +subagents: [cli-explore-agent] +message_types: + success: context_ready + error: 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 | +| .msg/meta.json | <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-explore-agent | +| 2-3 | Medium | Hybrid: ACE search + selective agent | +| 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 | Spawn cli-explore-agent: `Task({ subagent_type: "cli-explore-agent", run_in_background: false })` | + +**cli-explore-agent prompt template**: + +``` +## Issue Context +ID: <issueId> +Title: <issue.title> +Description: <issue.context> +Priority: <issue.priority> + +## MANDATORY FIRST STEPS +1. Run: ccw tool exec get_modules_by_depth '{}' +2. Execute ACE searches based on issue keywords +3. Run: ccw spec load --category exploration + +## Exploration Focus +- Identify files directly related to this issue +- Map dependencies and integration points +- Assess impact scope (how many modules/files affected) +- Find existing patterns relevant to the fix +- Check for previous related changes (git log) + +## Output +Write findings 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/role-specs/implementer.md b/.claude/skills/team-issue/role-specs/implementer.md new file mode 100644 index 00000000..79bef5d1 --- /dev/null +++ b/.claude/skills/team-issue/role-specs/implementer.md @@ -0,0 +1,89 @@ +--- +prefix: BUILD +inner_loop: false +message_types: + success: impl_complete + failed: impl_failed + error: 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 | +|---------|-----------|--------| +| agent | task_count <= 3 or explicit | `Task({ subagent_type: "code-developer", run_in_background: false })` | +| codex | task_count > 3 or explicit | `ccw cli --tool codex --mode write --id issue-<issueId>` | +| gemini | explicit | `ccw cli --tool gemini --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: Agent|Codex|Gemini|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 -> agent, 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: +- **agent**: `Task({ subagent_type: "code-developer", run_in_background: false, prompt: <prompt> })` +- **codex**: `Bash("ccw cli -p \"<prompt>\" --tool codex --mode write --id issue-<issueId>")` +- **gemini**: `Bash("ccw cli -p \"<prompt>\" --tool gemini --mode write --id issue-<issueId>")` + +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/role-specs/integrator.md b/.claude/skills/team-issue/role-specs/integrator.md new file mode 100644 index 00000000..8df37f30 --- /dev/null +++ b/.claude/skills/team-issue/role-specs/integrator.md @@ -0,0 +1,94 @@ +--- +prefix: MARSHAL +inner_loop: false +subagents: [issue-queue-agent] +message_types: + success: queue_ready + conflict: conflict_found + error: error +--- + +# Issue Integrator + +Queue orchestration, conflict detection, and execution order optimization. Internally invokes issue-queue-agent 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 | +| .msg/meta.json | <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 issue-queue-agent + +**Agent invocation**: + +``` +Task({ + subagent_type: "issue-queue-agent", + run_in_background: false, + description: "Form queue for <count> issues", + prompt: " +## Issues to Queue +Issue IDs: <issueIds> + +## Bound Solutions +<solution list with issue_id, solution_id, task_count> + +## Instructions +1. Load all bound solutions from .workflow/issues/solutions/ +2. Analyze file conflicts between solutions using Gemini CLI +3. Determine optimal execution order (DAG-based) +4. Produce ordered execution queue + +## Expected Output +Write queue to: .workflow/issues/queue/execution-queue.json +" +}) +``` + +**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/role-specs/planner.md b/.claude/skills/team-issue/role-specs/planner.md new file mode 100644 index 00000000..b3588a70 --- /dev/null +++ b/.claude/skills/team-issue/role-specs/planner.md @@ -0,0 +1,85 @@ +--- +prefix: SOLVE +inner_loop: false +additional_prefixes: [SOLVE-fix] +subagents: [issue-plan-agent] +message_types: + success: solution_ready + multi: multi_solution + error: error +--- + +# Issue Planner + +Design solutions and decompose into implementation tasks. Internally invokes issue-plan-agent 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 | +| .msg/meta.json | <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 issue-plan-agent + +**Agent invocation**: + +``` +Task({ + subagent_type: "issue-plan-agent", + run_in_background: false, + description: "Plan solution for <issueId>", + prompt: " +issue_ids: [\"<issueId>\"] +project_root: \"<projectRoot>\" + +## Explorer Context (pre-gathered) +Relevant files: <explorerContext.relevant_files> +Key findings: <explorerContext.key_findings> +Complexity: <explorerContext.complexity_assessment> + +## Revision Required (if SOLVE-fix) +Previous solution was rejected by reviewer. Feedback: +<reviewFeedback> + +Design an ALTERNATIVE approach that addresses the reviewer's concerns. +" +}) +``` + +**Expected agent result**: + +| Field | Description | +|-------|-------------| +| `bound` | Array of auto-bound solutions: `[{issue_id, solution_id, task_count}]` | +| `pending_selection` | Array of multi-solution issues: `[{issue_id, solutions: [...]}]` | + +## 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/role-specs/reviewer.md b/.claude/skills/team-issue/role-specs/reviewer.md new file mode 100644 index 00000000..aadbfdf8 --- /dev/null +++ b/.claude/skills/team-issue/role-specs/reviewer.md @@ -0,0 +1,89 @@ +--- +prefix: AUDIT +inner_loop: false +message_types: + success: approved + concerns: concerns + rejected: rejected + error: 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 | +| .msg/meta.json | <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/roles/coordinator.md b/.claude/skills/team-issue/roles/coordinator.md index fe87c99a..aa4d440b 100644 --- a/.claude/skills/team-issue/roles/coordinator.md +++ b/.claude/skills/team-issue/roles/coordinator.md @@ -74,20 +74,16 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "coordinator", - to: "<recipient>", type: <message-type>, - summary: "[coordinator] <summary>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` -**CLI fallback** (when MCP unavailable): +`to` and `summary` auto-defaulted -- do NOT specify explicitly. -``` -Bash("ccw team log --team <session-id> --from coordinator --to <recipient> --type <message-type> --summary \"[coordinator] ...\" --json") -``` +**CLI fallback**: `ccw team log --session-id <session-id> --from coordinator --type <type> --json` --- diff --git a/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md b/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..6672d7ec --- /dev/null +++ b/.claude/skills/team-issue/roles/coordinator/commands/dispatch.md @@ -0,0 +1,375 @@ +# Command: Dispatch + +Create the issue resolution task chain with correct dependencies and structured task descriptions based on selected pipeline mode. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Requirement | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline mode | From session.json mode | Yes | +| Issue IDs | From session.json issue_ids | Yes | +| Execution method | From session.json execution_method | Yes | +| Code review | From session.json code_review | No | + +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 + +Every task description uses structured format: + +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + description: "PURPOSE: <what this task achieves> | Success: <completion criteria> +TASK: + - <step 1> + - <step 2> + - <step 3> +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> + - Upstream artifacts: <artifact-list> +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits> +--- +InnerLoop: false +execution_method: <method> +code_review: <setting>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### 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 Pipeline + +**EXPLORE-001** (explorer): +``` +TaskCreate({ + subject: "EXPLORE-001", + owner: "explorer", + description: "PURPOSE: Analyze issue context and map codebase impact | Success: Context report with relevant files and dependencies +TASK: + - Load issue details via ccw issue status + - Explore codebase for relevant files and patterns + - Assess complexity and impact scope +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> +EXPECTED: <session>/explorations/context-<issueId>.json with relevant files, dependencies, and impact assessment +CONSTRAINTS: Exploration and analysis only, no solution design +--- +InnerLoop: false", + blockedBy: [], + status: "pending" +}) +``` + +**SOLVE-001** (planner): +``` +TaskCreate({ + subject: "SOLVE-001", + owner: "planner", + 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 + - Bind solution to issue +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> + - Upstream artifacts: explorations/context-<issueId>.json +EXPECTED: <session>/solutions/solution-<issueId>.json with solution plan and task list +CONSTRAINTS: Solution design only, no code implementation +--- +InnerLoop: false", + blockedBy: ["EXPLORE-001"], + status: "pending" +}) +``` + +**MARSHAL-001** (integrator): +``` +TaskCreate({ + subject: "MARSHAL-001", + owner: "integrator", + description: "PURPOSE: Form execution queue with conflict detection and ordering | Success: Execution queue file with resolved conflicts +TASK: + - Verify all issues have bound solutions + - Detect file conflicts between solutions + - Produce ordered execution queue with DAG-based parallel groups +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> + - Upstream artifacts: solutions/solution-<issueId>.json +EXPECTED: .workflow/issues/queue/execution-queue.json with queue, conflicts, parallel groups +CONSTRAINTS: Queue formation only, no implementation +--- +InnerLoop: false", + blockedBy: ["SOLVE-001"], + status: "pending" +}) +``` + +**BUILD-001** (implementer): +``` +TaskCreate({ + subject: "BUILD-001", + owner: "implementer", + 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) + - Run tests and verify implementation + - Commit changes +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> + - Upstream artifacts: explorations/context-<issueId>.json, solutions/solution-<issueId>.json, queue/execution-queue.json +EXPECTED: <session>/builds/ with implementation results, tests passing +CONSTRAINTS: Follow solution plan, no scope creep +--- +InnerLoop: false +execution_method: <execution_method> +code_review: <code_review>", + blockedBy: ["MARSHAL-001"], + status: "pending" +}) +``` + +### 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. + +**AUDIT-001** (reviewer): +``` +TaskCreate({ + subject: "AUDIT-001", + owner: "reviewer", + description: "PURPOSE: Review solution for technical feasibility, risk, and completeness | Success: Clear verdict (approved/rejected/concerns) with scores +TASK: + - Load explorer context and bound solution + - Score across 3 dimensions: technical feasibility (40%), risk (30%), completeness (30%) + - Produce verdict: approved (>=80), concerns (60-79), rejected (<60) +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issue-id-list> + - Upstream artifacts: explorations/context-<issueId>.json, solutions/solution-<issueId>.json +EXPECTED: <session>/audits/audit-report.json with per-issue scores and overall verdict +CONSTRAINTS: Review only, do not modify solutions +--- +InnerLoop: false", + blockedBy: ["SOLVE-001"], + status: "pending" +}) +``` + +**MARSHAL-001** (integrator): Same as Quick, but `blockedBy: ["AUDIT-001"]`. + +**BUILD-001** (implementer): Same as Quick, `blockedBy: ["MARSHAL-001"]`. + +### Batch Pipeline + +Creates tasks in parallel batches. Issue count = N, BUILD tasks = M (from queue parallel groups). + +**EXPLORE-001..N** (explorer, parallel): + +For each issue in issue_ids, create an EXPLORE task. When N > 1, assign distinct owners for parallel spawn: + +| Issue Count | Owner Assignment | +|-------------|-----------------| +| N = 1 | owner: "explorer" | +| N > 1 | owner: "explorer-1", "explorer-2", ..., "explorer-N" (max 5) | + +``` +TaskCreate({ + subject: "EXPLORE-<NNN>", + owner: "explorer-<N>", + description: "PURPOSE: Analyze issue <issueId> context and map codebase impact | Success: Context report for <issueId> +TASK: + - Load issue details for <issueId> + - Explore codebase for relevant files + - Assess complexity and impact scope +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issueId> +EXPECTED: <session>/explorations/context-<issueId>.json +CONSTRAINTS: Single issue scope, exploration only +--- +InnerLoop: false", + blockedBy: [], + status: "pending" +}) +``` + +**SOLVE-001..N** (planner, sequential after all EXPLORE): + +For each issue, create a SOLVE task blocked by all EXPLORE tasks: + +``` +TaskCreate({ + subject: "SOLVE-<NNN>", + owner: "planner", + description: "PURPOSE: Design solution for <issueId> | Success: Bound solution with tasks +TASK: + - Load explorer context for <issueId> + - Generate solution plan + - Bind solution +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issueId> + - Upstream artifacts: explorations/context-<issueId>.json +EXPECTED: <session>/solutions/solution-<issueId>.json +CONSTRAINTS: Solution design only +--- +InnerLoop: false", + blockedBy: ["EXPLORE-001", ..., "EXPLORE-<N>"], + status: "pending" +}) +``` + +**AUDIT-001** (reviewer, batch review): +``` +TaskCreate({ + subject: "AUDIT-001", + owner: "reviewer", + description: "PURPOSE: Batch review all solutions | Success: Verdict for each solution +TASK: + - Load all explorer contexts and bound solutions + - Score each solution across 3 dimensions + - Produce per-issue verdicts and overall verdict +CONTEXT: + - Session: <session-folder> + - Issue IDs: <all-issue-ids> + - Upstream artifacts: explorations/*.json, solutions/*.json +EXPECTED: <session>/audits/audit-report.json with batch results +CONSTRAINTS: Review only +--- +InnerLoop: false", + blockedBy: ["SOLVE-001", ..., "SOLVE-<N>"], + status: "pending" +}) +``` + +**MARSHAL-001** (integrator): `blockedBy: ["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: + +| Build Count | Owner Assignment | +|-------------|-----------------| +| M <= 2 | owner: "implementer" | +| M > 2 | owner: "implementer-1", ..., "implementer-M" (max 3) | + +``` +TaskCreate({ + subject: "BUILD-<NNN>", + owner: "implementer-<M>", + description: "PURPOSE: Implement solution for <issueId> | Success: Code committed, tests pass +TASK: + - Load bound solution and explorer context + - Execute implementation via <execution_method> + - Run tests, commit +CONTEXT: + - Session: <session-folder> + - Issue IDs: <issueId> + - Upstream artifacts: explorations/context-<issueId>.json, solutions/solution-<issueId>.json, queue/execution-queue.json +EXPECTED: <session>/builds/ with results +CONSTRAINTS: Follow solution plan +--- +InnerLoop: false +execution_method: <execution_method> +code_review: <code_review>", + blockedBy: ["MARSHAL-001"], + status: "pending" +}) +``` + +> **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): + +**SOLVE-fix-001** (planner, revision): +``` +TaskCreate({ + subject: "SOLVE-fix-001", + owner: "planner", + description: "PURPOSE: Revise solution addressing reviewer feedback (fix cycle <round>) | Success: Revised solution addressing rejection reasons +TASK: + - Read reviewer feedback from audit report + - Design alternative approach addressing concerns + - Re-bind revised solution +CONTEXT: + - Session: <session-folder> + - Issue IDs: <rejected-issue-ids> + - Upstream artifacts: audits/audit-report.json + - Reviewer feedback: <rejection-reasons> +EXPECTED: <session>/solutions/solution-<issueId>.json (revised) +CONSTRAINTS: Address reviewer concerns specifically +--- +InnerLoop: false", + blockedBy: ["AUDIT-001"], + status: "pending" +}) +``` + +**AUDIT-002** (reviewer, re-review): +``` +TaskCreate({ + subject: "AUDIT-002", + owner: "reviewer", + description: "PURPOSE: Re-review revised solution (fix cycle <round>) | Success: Verdict on revised solution +TASK: + - Load revised solution + - Re-evaluate previously rejected dimensions + - Produce updated verdict +CONTEXT: + - Session: <session-folder> + - Issue IDs: <rejected-issue-ids> + - Upstream artifacts: solutions/solution-<issueId>.json (revised), audits/audit-report.json +EXPECTED: <session>/audits/audit-report.json (updated) +CONSTRAINTS: Focus on previously rejected dimensions +--- +InnerLoop: false", + blockedBy: ["SOLVE-fix-001"], + status: "pending" +}) +``` + +These fix tasks are created dynamically by handleCallback in monitor.md when reviewer reports rejection, NOT during initial dispatch. + +## Phase 4: Validation + +1. Verify all tasks created with `TaskList()` +2. Check dependency chain integrity: + - No circular dependencies + - All blockedBy references exist + - First task(s) have empty blockedBy (EXPLORE tasks) +3. Log task count and pipeline mode +4. Verify mode-specific constraints: + +| Mode | Constraint | +|------|-----------| +| quick | Exactly 4 tasks, no AUDIT | +| full | Exactly 5 tasks, includes AUDIT | +| batch | N EXPLORE + N SOLVE + 1 AUDIT + 1 MARSHAL + M BUILD | diff --git a/.claude/skills/team-issue/roles/coordinator/commands/monitor.md b/.claude/skills/team-issue/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..ff3d1ff5 --- /dev/null +++ b/.claude/skills/team-issue/roles/coordinator/commands/monitor.md @@ -0,0 +1,202 @@ +# Command: Monitor + +Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, review-fix cycle control, and completion. + +## Constants + +| Key | Value | +|-----|-------| +| SPAWN_MODE | background | +| ONE_STEP_PER_INVOCATION | true | +| WORKER_AGENT | team-worker | +| MAX_FIX_CYCLES | 2 | + +## Phase 2: Context Loading + +| 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 | + +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 + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +1. Parse message to identify role and task ID: + +| Message Pattern | Role Detection | +|----------------|---------------| +| `[explorer]` or task ID `EXPLORE-*` | explorer | +| `[planner]` or task ID `SOLVE-*` | planner | +| `[reviewer]` or task ID `AUDIT-*` | reviewer | +| `[integrator]` or task ID `MARSHAL-*` | integrator | +| `[implementer]` or task ID `BUILD-*` | implementer | + +2. Mark task as completed: + +``` +TaskUpdate({ taskId: "<task-id>", status: "completed" }) +``` + +3. Record completion in session state + +4. **Review gate check** (when reviewer completes): + - If completed task is AUDIT-* AND pipeline is full or batch: + - Read audit report from `<session>/audits/audit-report.json` + - Read .msg/meta.json for fix_cycles + + | 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 | + | concerns | - | Log concerns, proceed to MARSHAL (non-blocking) | + | approved | - | Proceed to MARSHAL via handleSpawnNext | + + - Log team_msg with type "review_result" or "fix_required" + - If force proceeding past rejection, mark skipped fix tasks as completed (skip) + +5. **Deferred BUILD task creation** (when integrator completes): + - If completed task is MARSHAL-* AND pipeline is batch: + - Read execution queue from `.workflow/issues/queue/execution-queue.json` + - Parse parallel_groups to determine BUILD task count M + - Create BUILD-001..M tasks dynamically (see dispatch.md Batch Pipeline BUILD section) + - Proceed to handleSpawnNext + +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. For each ready task, spawn team-worker: + +``` +Task({ + 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.` +}) +``` + +3. **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 | Other stages | One worker at a time | + +4. **Parallel spawn** (Batch mode with multiple ready tasks for same role): + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn <role>-<N> worker for <task-id>", + team_name: "issue", + name: "<role>-<N>", + 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 + +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.` +}) +``` + +5. STOP after spawning -- wait for next callback + +### handleCheck + +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**: + +| 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 | + +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) + +**Stall detection** (no ready tasks and no running tasks but pipeline not complete): + +| 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 | + +## Phase 4: State Persistence + +After every handler execution: + +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 diff --git a/.claude/skills/team-issue/roles/coordinator/role.md b/.claude/skills/team-issue/roles/coordinator/role.md new file mode 100644 index 00000000..da3c31df --- /dev/null +++ b/.claude/skills/team-issue/roles/coordinator/role.md @@ -0,0 +1,277 @@ +# Coordinator - Issue Resolution Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: issue + +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. + +## 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 +- 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 +- 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 implementation subagents directly (issue-plan-agent, issue-queue-agent, code-developer) + +--- + +## 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 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) | + +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 + +--- + +## 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 + +--- + +## Phase 1: Requirement Clarification + +1. Parse user task description from $ARGUMENTS +2. **Parse arguments** for issue IDs and mode: + +| 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 | + +3. **Load pending issues** if `--all-pending`: + +``` +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`): + +| 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` | + +6. **Execution method selection** (for BUILD phase): + +| 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) | + +7. Record requirement with scope, mode, execution_method, code_review settings + +--- + +## Phase 2: Session & Team Setup + +1. Create session directory: + +``` +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") +``` + +2. Write session state to `.msg/meta.json`: + +```json +{ + "session_id": "<session-id>", + "status": "active", + "team_name": "issue", + "mode": "<quick|full|batch>", + "issue_ids": [], + "requirement": "<requirement>", + "execution_method": "<method>", + "code_review": "<setting>", + "timestamp": "<ISO-8601>", + "fix_cycles": {} +} +``` + +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: + +``` +Task({ + 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 + +--- + +## Phase 5: Report + Completion Action + +1. Load session state -> count completed tasks, calculate duration +2. List deliverables: + +| Deliverable | Path | +|-------------|------| +| Context Reports | <session>/explorations/context-*.json | +| Solution Plans | <session>/solutions/solution-*.json | +| Audit Reports | <session>/audits/audit-report.json | +| Execution Queue | .workflow/issues/queue/execution-queue.json | +| Build Results | <session>/builds/ | + +3. Output pipeline summary: task count, duration, 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: + +| Choice | Steps | +|--------|-------| +| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("issue") -> output final summary | +| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-issue', args='resume')" | +| New Batch | Return to Phase 1 | diff --git a/.claude/skills/team-issue/roles/explorer.md b/.claude/skills/team-issue/roles/explorer.md index 2853bc41..7845801e 100644 --- a/.claude/skills/team-issue/roles/explorer.md +++ b/.claude/skills/team-issue/roles/explorer.md @@ -63,19 +63,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "explorer", - to: "coordinator", type: <message-type>, - summary: "[explorer] <task-prefix> complete: <task-subject>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from explorer --to coordinator --type <message-type> --summary \"[explorer] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from explorer --type <message-type> --json") ``` --- diff --git a/.claude/skills/team-issue/roles/implementer.md b/.claude/skills/team-issue/roles/implementer.md index 5e7e6e5a..4cb940c1 100644 --- a/.claude/skills/team-issue/roles/implementer.md +++ b/.claude/skills/team-issue/roles/implementer.md @@ -72,19 +72,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "implementer", - to: "coordinator", type: <message-type>, - summary: "[implementer] <task-prefix> complete: <task-subject>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from implementer --to coordinator --type <message-type> --summary \"[implementer] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from implementer --type <message-type> --json") ``` --- @@ -264,15 +262,13 @@ Bash("<testCmd> 2>&1 || echo \"TEST_FAILED\"") ``` mcp__ccw-tools__team_msg({ - operation: "log", team: **<session-id>**, from: "implementer", to: "coordinator", // MUST be session ID, NOT team name + operation: "log", session_id: <session-id>, from: "implementer", type: "impl_failed", - summary: "[implementer] Tests failing for <issueId> after implementation (via <executor>)" }) SendMessage({ type: "message", recipient: "coordinator", content: "## [implementer] Implementation Failed\n\n**Issue**: <issueId>\n**Executor**: <executor>\n**Status**: Tests failing\n**Test Output** (truncated):\n<truncated output>\n\n**Action**: May need solution revision or manual intervention.", - summary: "[implementer] impl_failed: <issueId> (<executor>)" }) ``` diff --git a/.claude/skills/team-issue/roles/integrator.md b/.claude/skills/team-issue/roles/integrator.md index 625e0e4b..2efdf70e 100644 --- a/.claude/skills/team-issue/roles/integrator.md +++ b/.claude/skills/team-issue/roles/integrator.md @@ -62,19 +62,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "integrator", - to: "coordinator", type: <message-type>, - summary: "[integrator] <task-prefix> complete: <task-subject>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from integrator --to coordinator --type <message-type> --summary \"[integrator] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from integrator --type <message-type> --json") ``` --- @@ -116,15 +114,13 @@ Bash("ccw issue solutions <issueId> --json") ``` mcp__ccw-tools__team_msg({ - operation: "log", team: **<session-id>**, from: "integrator", to: "coordinator", // MUST be session ID, NOT team name + operation: "log", session_id: <session-id>, from: "integrator", type: "error", - summary: "[integrator] Unbound issues: <issueIds> - cannot form queue" }) SendMessage({ type: "message", recipient: "coordinator", content: "## [integrator] Error: Unbound Issues\n\nThe following issues have no bound solution:\n<unbound list>\n\nPlanner must create solutions before queue formation.", - summary: "[integrator] error: <count> unbound issues" }) ``` @@ -192,15 +188,13 @@ Read(".workflow/issues/queue/execution-queue.json") ``` mcp__ccw-tools__team_msg({ - operation: "log", team: **<session-id>**, from: "integrator", to: "coordinator", // MUST be session ID, NOT team name + operation: "log", session_id: <session-id>, from: "integrator", type: "conflict_found", - summary: "[integrator] <count> unresolved conflicts in queue" }) SendMessage({ type: "message", recipient: "coordinator", content: "## [integrator] Conflicts Found\n\n**Unresolved Conflicts**: <count>\n\n<conflict details>\n\n**Action Required**: Coordinator should present conflicts to user for resolution, then re-trigger MARSHAL.", - summary: "[integrator] conflict_found: <count> conflicts" }) ``` diff --git a/.claude/skills/team-issue/roles/planner.md b/.claude/skills/team-issue/roles/planner.md index 23df2e35..aaf726db 100644 --- a/.claude/skills/team-issue/roles/planner.md +++ b/.claude/skills/team-issue/roles/planner.md @@ -62,19 +62,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "planner", - to: "coordinator", type: <message-type>, - summary: "[planner] <task-prefix> complete: <task-subject>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from planner --to coordinator --type <message-type> --summary \"[planner] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from planner --type <message-type> --json") ``` --- @@ -159,15 +157,13 @@ Design an ALTERNATIVE approach that addresses the reviewer's concerns. ``` mcp__ccw-tools__team_msg({ - operation: "log", team: **<session-id>**, from: "planner", to: "coordinator", // MUST be session ID, NOT team name + operation: "log", session_id: <session-id>, from: "planner", type: "solution_ready", - summary: "[planner] Solution <solution_id> bound to <issue_id> (<task_count> tasks)" }) SendMessage({ type: "message", recipient: "coordinator", content: "## [planner] Solution Ready\n\n**Issue**: <issue_id>\n**Solution**: <solution_id>\n**Tasks**: <task_count>\n**Status**: Auto-bound (single solution)", - summary: "[planner] SOLVE complete: <issue_id>" }) ``` @@ -175,15 +171,13 @@ SendMessage({ ``` mcp__ccw-tools__team_msg({ - operation: "log", team: **<session-id>**, from: "planner", to: "coordinator", // MUST be session ID, NOT team name + operation: "log", session_id: <session-id>, from: "planner", type: "multi_solution", - summary: "[planner] <count> solutions for <issue_id>, user selection needed" }) SendMessage({ type: "message", recipient: "coordinator", content: "## [planner] Multiple Solutions\n\n**Issue**: <issue_id>\n**Solutions**: <count> options\n\n### Options\n<solution details>\n\n**Action Required**: Coordinator should present options to user for selection.", - summary: "[planner] multi_solution: <issue_id>" }) ``` diff --git a/.claude/skills/team-issue/roles/reviewer.md b/.claude/skills/team-issue/roles/reviewer.md index 232223ac..748af09e 100644 --- a/.claude/skills/team-issue/roles/reviewer.md +++ b/.claude/skills/team-issue/roles/reviewer.md @@ -65,19 +65,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: **<session-id>**, // MUST be session ID (e.g., ISS-xxx-date), NOT team name. Extract from Session: field. + session_id: <session-id>, from: "reviewer", - to: "coordinator", type: <message-type>, - summary: "[reviewer] <task-prefix> complete: <task-subject>", - ref: <artifact-path> + data: {ref: <artifact-path>} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from reviewer --to coordinator --type <message-type> --summary \"[reviewer] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from reviewer --type <message-type> --json") ``` --- diff --git a/.claude/skills/team-iterdev/SKILL.md b/.claude/skills/team-iterdev/SKILL.md index c734acf6..c85c6e1a 100644 --- a/.claude/skills/team-iterdev/SKILL.md +++ b/.claude/skills/team-iterdev/SKILL.md @@ -98,10 +98,10 @@ Each worker executes the same task discovery flow on startup: Standard report flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. - - **CLI fallback**: When MCP unavailable -> `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` -2. **SendMessage**: Send result to coordinator (content and summary both with `[<role>]` prefix) + - 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 @@ -110,18 +110,17 @@ Standard report flow after task completion: | Allowed | Prohibited | |---------|------------| | Process tasks with own prefix | Process other roles' prefix tasks | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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 calling implementation-type subagents, no directly executing analysis/testing/review. ### Message Bus -Call `mcp__ccw-tools__team_msg` with: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<type>, summary="[<role>] <summary>", ref="<file_path>" +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. -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. - -**CLI Fallback**: `ccw team log --team "<session-id>" --from "<role>" --to "coordinator" --type "<type>" --summary "<summary>" --json` +**CLI Fallback**: `ccw team log --session-id "<session-id>" --from "<role>" --type "<type>" --json` | Role | Message Types | |------|---------------| @@ -137,7 +136,7 @@ Call `mcp__ccw-tools__team_msg` with: operation="log", team=<session-id>, from=< |---------|-------| | Team name | iterdev | | Session directory | `.workflow/.team/IDS-{slug}-{date}/` | -| Shared memory file | shared-memory.json | +| State sharing | team_msg(type='state_update') + .msg/meta.json | | Task ledger file | task-ledger.json | --- @@ -154,7 +153,7 @@ Concurrency control for shared resources. Prevents multiple workers from modifyi | Action | Trigger Condition | Coordinator Behavior | |--------|-------------------|----------------------| -| Acquire lock | Worker requests exclusive access to a resource | Check `resource_locks` in shared-memory.json. If unlocked, record lock with task ID, timestamp, and holder role. Log `resource_locked` message. Return success. | +| 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. | @@ -196,7 +195,7 @@ 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` in shared-memory.json with timestamp and state data pointer. Retain last 5 checkpoints per task. Log `context_checkpoint_saved`. | +| 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. | @@ -206,7 +205,7 @@ 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` in shared-memory.json (max 50 items). Log `user_feedback_received`. | +| 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. | @@ -216,7 +215,7 @@ 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` in shared-memory.json. Log `tech_debt_identified`. | +| 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. | @@ -444,8 +443,9 @@ Session: <session-folder> ``` .workflow/.team/IDS-{slug}-{YYYY-MM-DD}/ -+-- team-session.json -+-- shared-memory.json # Cross-sprint learning ++-- .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 @@ -467,7 +467,7 @@ Session: <session-folder> Coordinator supports `--resume` / `--continue` for interrupted sessions: -1. Scan `.workflow/.team/IDS-*/team-session.json` for active/paused 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) diff --git a/.claude/skills/team-iterdev/role-specs/architect.md b/.claude/skills/team-iterdev/role-specs/architect.md new file mode 100644 index 00000000..652a64b1 --- /dev/null +++ b/.claude/skills/team-iterdev/role-specs/architect.md @@ -0,0 +1,64 @@ +--- +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/role-specs/developer.md b/.claude/skills/team-iterdev/role-specs/developer.md new file mode 100644 index 00000000..8cbd2a1b --- /dev/null +++ b/.claude/skills/team-iterdev/role-specs/developer.md @@ -0,0 +1,73 @@ +--- +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/role-specs/reviewer.md b/.claude/skills/team-iterdev/role-specs/reviewer.md new file mode 100644 index 00000000..026b1988 --- /dev/null +++ b/.claude/skills/team-iterdev/role-specs/reviewer.md @@ -0,0 +1,65 @@ +--- +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/role-specs/tester.md b/.claude/skills/team-iterdev/role-specs/tester.md new file mode 100644 index 00000000..21eb7a76 --- /dev/null +++ b/.claude/skills/team-iterdev/role-specs/tester.md @@ -0,0 +1,74 @@ +--- +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 | Delegate fix to code-developer subagent | +| 6 | Increment iteration counter | +| 7 | iteration >= MAX (5) -> exit loop (report failures) | +| 8 | Go to Step 1 | + +**Fix delegation**: Spawn code-developer subagent with test output and changed file list. Run synchronously (run_in_background: false). + +## 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/roles/architect.md b/.claude/skills/team-iterdev/roles/architect.md index 89b30a8b..b065535f 100644 --- a/.claude/skills/team-iterdev/roles/architect.md +++ b/.claude/skills/team-iterdev/roles/architect.md @@ -14,7 +14,7 @@ Technical architect. Responsible for technical design, task decomposition, and a - Only process `DESIGN-*` prefixed tasks - All output must carry `[architect]` identifier -- Phase 2: Read shared-memory.json, Phase 5: Write architecture_decisions +- Phase 2: Read .msg/meta.json, Phase 5: Write architecture_decisions - Work strictly within technical design responsibility scope ### MUST NOT @@ -53,24 +53,21 @@ Technical architect. Responsible for technical design, task decomposition, and a Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TID-project-2026-02-27", NOT "iterdev" + session_id: <session-id>, from: "architect", - to: "coordinator", type: <message-type>, - summary: "[architect] DESIGN complete: <task-subject>", - ref: <design-path> + data: { ref: <design-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from architect --to coordinator --type <message-type> --summary \"[architect] DESIGN complete\" --ref <design-path> --json") +Bash("ccw team log --session-id <session-id> --from architect --type <message-type> --json") ``` --- @@ -90,17 +87,17 @@ Standard task discovery flow: TaskList -> filter by prefix `DESIGN-*` + owner ma | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Codebase | Project files | Yes | | Wisdom | <session-folder>/wisdom/ | No | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json for context +2. Read .msg/meta.json for context ``` -Read(<session-folder>/shared-memory.json) +Read(<session-folder>/.msg/meta.json) ``` 3. Multi-angle codebase exploration via cli-explore-agent: @@ -217,17 +214,16 @@ sharedMemory.architecture_decisions.push({ components: <component-names>, task_count: <count> }) -Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2)) +Write(<session-folder>/.msg/meta.json, JSON.stringify(sharedMemory, null, 2)) ``` 2. **Log and send message**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id>, from: "architect", to: "coordinator", // team = session ID, e.g., "TID-project-2026-02-27" + operation: "log", session_id: <session-id>, from: "architect", type: "design_ready", - summary: "[architect] Design complete: <count> components, <task-count> tasks", - ref: <design-path> + data: { ref: <design-path> } }) SendMessage({ @@ -238,7 +234,6 @@ SendMessage({ **Tasks**: <task-count> **Design**: <design-path> **Breakdown**: <breakdown-path>`, - summary: "[architect] Design: <task-count> tasks" }) ``` diff --git a/.claude/skills/team-iterdev/roles/coordinator.md b/.claude/skills/team-iterdev/roles/coordinator.md index 37273043..1623369f 100644 --- a/.claude/skills/team-iterdev/roles/coordinator.md +++ b/.claude/skills/team-iterdev/roles/coordinator.md @@ -14,7 +14,7 @@ Orchestrate the IterDev workflow: Sprint planning, backlog management, task ledg - All output must carry `[coordinator]` identifier - Maintain task-ledger.json for real-time progress - Manage developer<->reviewer GC loop (max 3 rounds) -- Record learning to shared-memory.json at Sprint end +- Record learning to .msg/meta.json at Sprint end - Detect and coordinate task conflicts - Manage shared resource locks (resource_locks) - Record rollback points and support emergency rollback @@ -55,7 +55,7 @@ For callback/check/resume: load monitor logic and execute the appropriate handle **Workflow**: -1. Scan `.workflow/.team/IDS-*/team-session.json` for sessions with status "active" or "paused" +1. Scan `.workflow/.team/IDS-*/.msg/meta.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 @@ -142,7 +142,7 @@ AskUserQuestion({ } ``` -7. Initialize shared-memory.json: +7. Initialize .msg/meta.json: ``` { @@ -227,7 +227,7 @@ Subsequent sprints created dynamically after Sprint N completes. When receiving `review_revision` or `review_critical`: -1. Read shared-memory.json -> get gc_round +1. Read .msg/meta.json -> get gc_round 2. If gc_round < max_gc_rounds (3): - Increment gc_round - Create DEV-fix task with review feedback @@ -247,7 +247,7 @@ When receiving `review_revision` or `review_critical`: **Workflow**: 1. Load session state -> count completed tasks, duration -2. Record sprint learning to shared-memory.json +2. Record sprint learning to .msg/meta.json 3. List deliverables with output paths 4. Update session status -> "completed" 5. Offer next steps via AskUserQuestion @@ -262,7 +262,7 @@ Concurrency control for shared resources. Prevents multiple workers from modifyi | Action | Trigger Condition | Behavior | |--------|-------------------|----------| -| Acquire lock | Worker requests exclusive access | Check resource_locks in shared-memory.json. If unlocked, record lock with task ID, timestamp, holder. Log resource_locked. Return success. | +| Acquire lock | Worker requests exclusive access | Check resource_locks via team_msg(type='state_update'). If unlocked, record lock with task ID, timestamp, holder. Log resource_locked. Return success. | | Deny lock | Resource already locked | Return failure with current holder's task ID. Log resource_contention. Worker must wait. | | Release lock | Worker completes task | Remove lock entry. Log resource_unlocked. | | Force release | Lock held beyond timeout (5 min) | Force-remove lock entry. Notify holder. Log warning. | @@ -381,24 +381,21 @@ Identifies, tracks, and prioritizes technical debt. Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TID-project-2026-02-27", NOT "iterdev" + session_id: <session-id>, from: "coordinator", - to: "all", type: <message-type>, - summary: "[coordinator] <summary>", - ref: <artifact-path> + data: { ref: <artifact-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from coordinator --to all --type <message-type> --summary \"[coordinator] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from coordinator --type <message-type> --json") ``` --- diff --git a/.claude/skills/team-iterdev/roles/coordinator/commands/dispatch.md b/.claude/skills/team-iterdev/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..0e969d8f --- /dev/null +++ b/.claude/skills/team-iterdev/roles/coordinator/commands/dispatch.md @@ -0,0 +1,248 @@ +# Command: Dispatch + +Create the iterative development task chain with correct dependencies and structured task descriptions. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| User requirement | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline definition | From SKILL.md Pipeline Definitions | Yes | +| Pipeline mode | From session.json `pipeline` | Yes | + +1. Load user requirement and scope from session.json +2. Load pipeline stage definitions from SKILL.md Task Metadata Registry +3. Read `pipeline` mode from session.json (patch / sprint / multi-sprint) + +## Phase 3: Task Chain Creation + +### Task Description Template + +Every task description uses structured format for clarity: + +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + 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: <task-scope> + - Upstream artifacts: <artifact-1>, <artifact-2> + - Shared memory: <session>/.msg/meta.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas> +--- +InnerLoop: <true|false>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### Mode Router + +| Mode | Action | +|------|--------| +| `patch` | Create DEV-001 + VERIFY-001 | +| `sprint` | Create DESIGN-001 + DEV-001 + VERIFY-001 + REVIEW-001 | +| `multi-sprint` | Create Sprint 1 chain, subsequent sprints created dynamically | + +--- + +### Patch Pipeline + +**DEV-001** (developer): +``` +TaskCreate({ + subject: "DEV-001", + owner: "developer", + description: "PURPOSE: Implement fix | Success: Fix applied, syntax clean +TASK: + - Load target files and understand context + - Apply fix changes + - Validate syntax +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Shared memory: <session>/.msg/meta.json +EXPECTED: Modified source files + <session>/code/dev-log.md | Syntax clean +CONSTRAINTS: Minimal changes | Preserve existing behavior +--- +InnerLoop: true", + status: "pending" +}) +``` + +**VERIFY-001** (tester): +``` +TaskCreate({ + subject: "VERIFY-001", + owner: "tester", + description: "PURPOSE: Verify fix correctness | Success: Tests pass, no regressions +TASK: + - Detect test framework + - Run targeted tests for changed files + - Run regression test suite +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Upstream artifacts: code/dev-log.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/verify/verify-001.json | Pass rate >= 95% +CONSTRAINTS: Focus on changed files | Report any regressions +--- +InnerLoop: false", + blockedBy: ["DEV-001"], + status: "pending" +}) +``` + +--- + +### Sprint Pipeline + +**DESIGN-001** (architect): +``` +TaskCreate({ + subject: "DESIGN-001", + owner: "architect", + description: "PURPOSE: Technical design and task breakdown | Success: Design document + task breakdown ready +TASK: + - Explore codebase for patterns and dependencies + - Create component design with integration points + - Break down into implementable tasks with acceptance criteria +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/design/design-001.md + <session>/design/task-breakdown.json | Components defined, tasks actionable +CONSTRAINTS: Focus on <task-scope> | Risk assessment required +--- +InnerLoop: false", + status: "pending" +}) +``` + +**DEV-001** (developer): +``` +TaskCreate({ + subject: "DEV-001", + owner: "developer", + description: "PURPOSE: Implement design | Success: All design tasks implemented, syntax clean +TASK: + - Load design and task breakdown + - Implement tasks in execution order + - Validate syntax after changes +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Upstream artifacts: design/design-001.md, design/task-breakdown.json + - Shared memory: <session>/.msg/meta.json +EXPECTED: Modified source files + <session>/code/dev-log.md | Syntax clean, all tasks done +CONSTRAINTS: Follow design | Preserve existing behavior | Follow code conventions +--- +InnerLoop: true", + blockedBy: ["DESIGN-001"], + status: "pending" +}) +``` + +**VERIFY-001** (tester, parallel with REVIEW-001): +``` +TaskCreate({ + subject: "VERIFY-001", + owner: "tester", + description: "PURPOSE: Verify implementation | Success: Tests pass, no regressions +TASK: + - Detect test framework + - Run tests for changed files + - Run regression test suite +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Upstream artifacts: code/dev-log.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/verify/verify-001.json | Pass rate >= 95% +CONSTRAINTS: Focus on changed files | Report regressions +--- +InnerLoop: false", + blockedBy: ["DEV-001"], + status: "pending" +}) +``` + +**REVIEW-001** (reviewer, parallel with VERIFY-001): +``` +TaskCreate({ + subject: "REVIEW-001", + owner: "reviewer", + description: "PURPOSE: Code review for correctness and quality | Success: All dimensions reviewed, verdict issued +TASK: + - Load changed files and design document + - Review across 4 dimensions: correctness, completeness, maintainability, security + - Score quality (1-10) and issue verdict +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Upstream artifacts: design/design-001.md, code/dev-log.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: <session>/review/review-001.md | Per-dimension findings with severity +CONSTRAINTS: Focus on implementation changes | Provide file:line references +--- +InnerLoop: false", + blockedBy: ["DEV-001"], + status: "pending" +}) +``` + +--- + +### Multi-Sprint Pipeline + +Sprint 1: DESIGN-001 -> DEV-001 -> DEV-002(incremental) -> VERIFY-001 -> DEV-fix -> REVIEW-001 + +Create Sprint 1 tasks using sprint templates above, plus: + +**DEV-002** (developer, incremental): +``` +TaskCreate({ + subject: "DEV-002", + owner: "developer", + description: "PURPOSE: Incremental implementation | Success: Remaining tasks implemented +TASK: + - Load remaining tasks from breakdown + - Implement incrementally + - Validate syntax +CONTEXT: + - Session: <session-folder> + - Scope: <task-scope> + - Upstream artifacts: design/task-breakdown.json, code/dev-log.md + - Shared memory: <session>/.msg/meta.json +EXPECTED: Modified source files + updated dev-log.md +CONSTRAINTS: Incremental delivery | Follow existing patterns +--- +InnerLoop: true", + blockedBy: ["DEV-001"], + status: "pending" +}) +``` + +Subsequent sprints created dynamically after Sprint N completes. + +## Phase 4: Validation + +Verify task chain integrity: + +| Check | Method | Expected | +|-------|--------|----------| +| Task count correct | TaskList count | patch: 2, sprint: 4, multi: 5+ | +| Dependencies correct | Trace blockedBy graph | Acyclic, correct ordering | +| No circular dependencies | Trace full graph | Acyclic | +| Structured descriptions | Each has PURPOSE/TASK/CONTEXT/EXPECTED | All present | + +If validation fails, fix the specific task and re-validate. diff --git a/.claude/skills/team-iterdev/roles/coordinator/role.md b/.claude/skills/team-iterdev/roles/coordinator/role.md new file mode 100644 index 00000000..728a68d9 --- /dev/null +++ b/.claude/skills/team-iterdev/roles/coordinator/role.md @@ -0,0 +1,269 @@ +# Coordinator - Iterative Development Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: iterdev + +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. + +## 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 +- Handle developer<->reviewer GC loop (max 3 rounds) +- Maintain task-ledger.json for real-time progress +- 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 +``` + +--- + +## 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) | + +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 + +--- + +## 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 + +--- + +## Phase 1: Requirement Clarification + +1. Parse user task description from $ARGUMENTS +2. Assess complexity for pipeline selection: + +| Signal | Weight | +|--------|--------| +| 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 | + +3. Ask for missing parameters via AskUserQuestion (mode selection) +4. Record requirement with scope, pipeline mode + +--- + +## Phase 2: Session & Team Setup + +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") +``` + +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 .msg/meta.json: + +```json +{ + "session_id": "<session-id>", + "requirement": "<requirement>", + "pipeline": "<pipeline>", + "architecture_decisions": [], + "implementation_context": [], + "review_feedback_trends": [], + "gc_round": 0, + "max_gc_rounds": 3, + "sprint_history": [] +} +``` + +--- + +## 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: + +``` +Task({ + 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 + +--- + +## Phase 5: Report + Completion Action + +1. Load session state -> count completed tasks, calculate duration +2. Record sprint learning to .msg/meta.json sprint_history +3. List deliverables: + +| Deliverable | Path | +|-------------|------| +| Design Document | <session>/design/design-001.md | +| Task Breakdown | <session>/design/task-breakdown.json | +| Dev Log | <session>/code/dev-log.md | +| Verification Results | <session>/verify/verify-001.json | +| Review Report | <session>/review/review-001.md | + +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 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("iterdev") -> 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 | diff --git a/.claude/skills/team-iterdev/roles/developer.md b/.claude/skills/team-iterdev/roles/developer.md index 578565d3..b5d2ba0b 100644 --- a/.claude/skills/team-iterdev/roles/developer.md +++ b/.claude/skills/team-iterdev/roles/developer.md @@ -14,7 +14,7 @@ Code implementer. Responsible for implementing code according to design, increme - Only process `DEV-*` prefixed tasks - All output must carry `[developer]` identifier -- Phase 2: Read shared-memory.json + design, Phase 5: Write implementation_context +- Phase 2: Read .msg/meta.json + design, Phase 5: Write implementation_context - For fix tasks (DEV-fix-*): Reference review feedback - Work strictly within code implementation responsibility scope @@ -56,24 +56,21 @@ Code implementer. Responsible for implementing code according to design, increme Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TID-project-2026-02-27", NOT "iterdev" + session_id: <session-id>, from: "developer", - to: "coordinator", type: <message-type>, - summary: "[developer] DEV complete: <task-subject>", - ref: <dev-log-path> + data: { ref: <dev-log-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from developer --to coordinator --type <message-type> --summary \"[developer] DEV complete\" --ref <dev-log-path> --json") +Bash("ccw team log --session-id <session-id> --from developer --type <message-type> --json") ``` --- @@ -93,7 +90,7 @@ Standard task discovery flow: TaskList -> filter by prefix `DEV-*` + owner match | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Design document | <session-folder>/design/design-001.md | For non-fix tasks | | Task breakdown | <session-folder>/design/task-breakdown.json | For non-fix tasks | | Review feedback | <session-folder>/review/*.md | For fix tasks | @@ -102,10 +99,10 @@ Standard task discovery flow: TaskList -> filter by prefix `DEV-*` + owner match **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json +2. Read .msg/meta.json ``` -Read(<session-folder>/shared-memory.json) +Read(<session-folder>/.msg/meta.json) ``` 3. Check if this is a fix task (GC loop): @@ -227,17 +224,16 @@ sharedMemory.implementation_context.push({ is_fix: <is-fix-task>, syntax_clean: <has-syntax-errors> }) -Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2)) +Write(<session-folder>/.msg/meta.json, JSON.stringify(sharedMemory, null, 2)) ``` 2. **Log and send message**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id>, from: "developer", to: "coordinator", // team = session ID, e.g., "TID-project-2026-02-27" + operation: "log", session_id: <session-id>, from: "developer", type: "dev_complete", - summary: "[developer] <Fix|Implementation> complete: <file-count> files changed", - ref: <dev-log-path> + data: { ref: <dev-log-path> } }) SendMessage({ @@ -252,7 +248,6 @@ SendMessage({ ### Files - <file-1> - <file-2>`, - summary: "[developer] <file-count> files <fixed|implemented>" }) ``` diff --git a/.claude/skills/team-iterdev/roles/reviewer.md b/.claude/skills/team-iterdev/roles/reviewer.md index 210cc959..33ba9fa0 100644 --- a/.claude/skills/team-iterdev/roles/reviewer.md +++ b/.claude/skills/team-iterdev/roles/reviewer.md @@ -14,7 +14,7 @@ Code reviewer. Responsible for multi-dimensional review, quality scoring, and im - Only process `REVIEW-*` prefixed tasks - All output must carry `[reviewer]` identifier -- Phase 2: Read shared-memory.json + design, Phase 5: Write review_feedback_trends +- Phase 2: Read .msg/meta.json + design, Phase 5: Write review_feedback_trends - Mark each issue with severity (CRITICAL/HIGH/MEDIUM/LOW) - Provide quality score (1-10) - Work strictly within code review responsibility scope @@ -55,24 +55,21 @@ Code reviewer. Responsible for multi-dimensional review, quality scoring, and im Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TID-project-2026-02-27", NOT "iterdev" + session_id: <session-id>, from: "reviewer", - to: "coordinator", type: <message-type>, - summary: "[reviewer] REVIEW complete: <task-subject>", - ref: <review-path> + data: { ref: <review-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from reviewer --to coordinator --type <message-type> --summary \"[reviewer] REVIEW complete\" --ref <review-path> --json") +Bash("ccw team log --session-id <session-id> --from reviewer --type <message-type> --json") ``` --- @@ -92,7 +89,7 @@ Standard task discovery flow: TaskList -> filter by prefix `REVIEW-*` + owner ma | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Design document | <session-folder>/design/design-001.md | For requirements alignment | | Changed files | Git diff | Yes | | Wisdom | <session-folder>/wisdom/ | No | @@ -100,10 +97,10 @@ Standard task discovery flow: TaskList -> filter by prefix `REVIEW-*` + owner ma **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json +2. Read .msg/meta.json ``` -Read(<session-folder>/shared-memory.json) +Read(<session-folder>/.msg/meta.json) ``` 3. Read design document for requirements alignment: @@ -245,7 +242,7 @@ sharedMemory.review_feedback_trends.push({ dimensions: <dimension-list>, gc_round: sharedMemory.gc_round || 0 }) -Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2)) +Write(<session-folder>/.msg/meta.json, JSON.stringify(sharedMemory, null, 2)) ``` 2. **Determine message type**: @@ -260,10 +257,9 @@ Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2) ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id>, from: "reviewer", to: "coordinator", // team = session ID, e.g., "TID-project-2026-02-27" + operation: "log", session_id: <session-id>, from: "reviewer", type: <message-type>, - summary: "[reviewer] Review <message-type>: score=<score>/10, <critical-count>C/<high-count>H", - ref: <review-path> + data: { ref: <review-path> } }) SendMessage({ @@ -279,7 +275,6 @@ SendMessage({ ### Top Issues - **[CRITICAL/HIGH]** <title> (<file>:<line>) ...`, - summary: "[reviewer] <message-type>: <score>/10" }) ``` diff --git a/.claude/skills/team-iterdev/roles/tester.md b/.claude/skills/team-iterdev/roles/tester.md index b44a57dc..690bbd38 100644 --- a/.claude/skills/team-iterdev/roles/tester.md +++ b/.claude/skills/team-iterdev/roles/tester.md @@ -14,7 +14,7 @@ Test validator. Responsible for test execution, fix cycles, and regression detec - Only process `VERIFY-*` prefixed tasks - All output must carry `[tester]` identifier -- Phase 2: Read shared-memory.json, Phase 5: Write test_patterns +- Phase 2: Read .msg/meta.json, Phase 5: Write test_patterns - Work strictly within test validation responsibility scope ### MUST NOT @@ -54,24 +54,21 @@ Test validator. Responsible for test execution, fix cycles, and regression detec Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TID-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TID-project-2026-02-27", NOT "iterdev" + session_id: <session-id>, from: "tester", - to: "coordinator", type: <message-type>, - summary: "[tester] VERIFY complete: <task-subject>", - ref: <verify-path> + data: { ref: <verify-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from tester --to coordinator --type <message-type> --summary \"[tester] VERIFY complete\" --ref <verify-path> --json") +Bash("ccw team log --session-id <session-id> --from tester --type <message-type> --json") ``` --- @@ -91,17 +88,17 @@ Standard task discovery flow: TaskList -> filter by prefix `VERIFY-*` + owner ma | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Changed files | Git diff | Yes | | Wisdom | <session-folder>/wisdom/ | No | **Detection steps**: 1. Extract session path from task description -2. Read shared-memory.json +2. Read .msg/meta.json ``` -Read(<session-folder>/shared-memory.json) +Read(<session-folder>/.msg/meta.json) ``` 3. Get changed files: @@ -197,7 +194,7 @@ sharedMemory.test_patterns = sharedMemory.test_patterns || [] if (passRate >= 0.95) { sharedMemory.test_patterns.push(`verify-<num>: passed in <iterations> iterations`) } -Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2)) +Write(<session-folder>/.msg/meta.json, JSON.stringify(sharedMemory, null, 2)) ``` 2. **Determine message type**: @@ -212,10 +209,9 @@ Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2) ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id>, from: "tester", to: "coordinator", // team = session ID, e.g., "TID-project-2026-02-27" + operation: "log", session_id: <session-id>, from: "tester", type: <message-type>, - summary: "[tester] <message-type>: pass_rate=<rate>%, iterations=<count>", - ref: <verify-path> + data: { ref: <verify-path> } }) SendMessage({ @@ -226,7 +222,6 @@ SendMessage({ **Iterations**: <count>/<MAX> **Regression**: <passed/failed> **Status**: <PASSED/NEEDS FIX>`, - summary: "[tester] <PASSED/FAILED>: <rate>%" }) ``` diff --git a/.claude/skills/team-perf-opt/SKILL.md b/.claude/skills/team-perf-opt/SKILL.md index 30d14bc6..9acfe03c 100644 --- a/.claude/skills/team-perf-opt/SKILL.md +++ b/.claude/skills/team-perf-opt/SKILL.md @@ -384,7 +384,8 @@ AskUserQuestion({ | +-- <hash>.md # Cached exploration results +-- wisdom/ | +-- patterns.md # Discovered patterns and conventions -| +-- shared-memory.json # Cross-role structured data +| +-- .msg/messages.jsonl # Team message bus +| +-- .msg/meta.json # Session metadata +-- discussions/ | +-- DISCUSS-OPT.md # Strategy discussion record | +-- DISCUSS-REVIEW.md # Review discussion record diff --git a/.claude/skills/team-perf-opt/role-specs/benchmarker.md b/.claude/skills/team-perf-opt/role-specs/benchmarker.md index 59cd2fb4..172333ac 100644 --- a/.claude/skills/team-perf-opt/role-specs/benchmarker.md +++ b/.claude/skills/team-perf-opt/role-specs/benchmarker.md @@ -17,7 +17,7 @@ Run benchmarks comparing before/after optimization metrics. Validate that improv |-------|--------|----------| | Baseline metrics | <session>/artifacts/baseline-metrics.json (shared) | Yes | | Optimization plan / detail | Varies by mode (see below) | Yes | -| shared-memory.json | <session>/wisdom/shared-memory.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | 1. Extract session path from task description 2. **Detect branch/pipeline context** from task description: @@ -37,7 +37,7 @@ Run benchmarks comparing before/after optimization metrics. Validate that improv - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/optimization-detail.md` -- only this branch's criteria - Independent: Read `<session>/artifacts/pipelines/{P}/optimization-plan.md` -5. Load shared-memory.json for project type and optimization scope +5. Load .msg/meta.json for project type and optimization scope 6. Detect available benchmark tools from project: | Signal | Benchmark Tool | Method | @@ -101,7 +101,7 @@ Compare against baseline and plan criteria: - Independent: `<session>/artifacts/pipelines/{P}/benchmark-results.json` - Content: Per-metric: name, baseline value, current value, improvement %, verdict; Overall verdict: PASS / WARN / FAIL; Regression details (if any) -2. Update `<session>/wisdom/shared-memory.json` under scoped namespace: +2. Update `<session>/.msg/meta.json` under scoped namespace: - Single: merge `{ "benchmarker": { verdict, improvements, regressions } }` - Fan-out: merge `{ "benchmarker.B{NN}": { verdict, improvements, regressions } }` - Independent: merge `{ "benchmarker.{P}": { verdict, improvements, regressions } }` diff --git a/.claude/skills/team-perf-opt/role-specs/optimizer.md b/.claude/skills/team-perf-opt/role-specs/optimizer.md index 1b1db039..fa279f14 100644 --- a/.claude/skills/team-perf-opt/role-specs/optimizer.md +++ b/.claude/skills/team-perf-opt/role-specs/optimizer.md @@ -28,7 +28,7 @@ Implement optimization changes following the strategy plan. For FIX tasks, apply | 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) | -| shared-memory.json | <session>/wisdom/shared-memory.json | Yes | +| .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) | diff --git a/.claude/skills/team-perf-opt/role-specs/profiler.md b/.claude/skills/team-perf-opt/role-specs/profiler.md index 07037533..af7c775f 100644 --- a/.claude/skills/team-perf-opt/role-specs/profiler.md +++ b/.claude/skills/team-perf-opt/role-specs/profiler.md @@ -17,7 +17,7 @@ Profile application performance to identify CPU, memory, I/O, network, and rende |-------|--------|----------| | Task description | From task subject/description | Yes | | Session path | Extracted from task description | Yes | -| shared-memory.json | <session>/wisdom/shared-memory.json | No | +| .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: @@ -69,5 +69,5 @@ Execute profiling based on detected project type: - Evidence summary per bottleneck - Detected project type and profiling methods used -3. Update `<session>/wisdom/shared-memory.json` under `profiler` namespace: +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/role-specs/reviewer.md b/.claude/skills/team-perf-opt/role-specs/reviewer.md index 787aa283..21f7337e 100644 --- a/.claude/skills/team-perf-opt/role-specs/reviewer.md +++ b/.claude/skills/team-perf-opt/role-specs/reviewer.md @@ -21,7 +21,7 @@ Review optimization code changes for correctness, side effects, regression risks | 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 | -| shared-memory.json | <session>/wisdom/shared-memory.json | Yes | +| .msg/meta.json | <session>/.msg/meta.json | Yes | 1. Extract session path from task description 2. **Detect branch/pipeline context** from task description: @@ -37,7 +37,7 @@ Review optimization code changes for correctness, side effects, regression risks - Fan-out branch: Read `<session>/artifacts/branches/B{NN}/optimization-detail.md` - Independent: Read `<session>/artifacts/pipelines/{P}/optimization-plan.md` -4. Load shared-memory.json for scoped optimizer namespace: +4. Load .msg/meta.json for scoped optimizer namespace: - Single: `optimizer` namespace - Fan-out: `optimizer.B{NN}` namespace - Independent: `optimizer.{P}` namespace @@ -83,7 +83,7 @@ Classify overall verdict based on findings: - 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/shared-memory.json` under scoped namespace: +2. Update `<session>/.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 } }` diff --git a/.claude/skills/team-perf-opt/role-specs/strategist.md b/.claude/skills/team-perf-opt/role-specs/strategist.md index 98ee5172..263586a8 100644 --- a/.claude/skills/team-perf-opt/role-specs/strategist.md +++ b/.claude/skills/team-perf-opt/role-specs/strategist.md @@ -18,13 +18,13 @@ Analyze bottleneck reports and baseline metrics to design a prioritized optimiza |-------|--------|----------| | Bottleneck report | <session>/artifacts/bottleneck-report.md | Yes | | Baseline metrics | <session>/artifacts/baseline-metrics.json | Yes | -| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.json for profiler findings (project_type, scope) +4. Load .msg/meta.json for profiler findings (project_type, scope) 5. Assess overall optimization complexity: | Bottleneck Count | Severity Mix | Complexity | @@ -88,7 +88,7 @@ Define measurable success criteria per optimization (target metric value or impr - Each optimization must be **non-overlapping** in target files (no two OPT-IDs modify the same file unless explicitly noted with conflict resolution) - Implementation guidance must be self-contained -- a branch optimizer should be able to work from a single OPT block without reading others -2. Update `<session>/wisdom/shared-memory.json` under `strategist` namespace: +2. Update `<session>/.msg/meta.json` under `strategist` namespace: - Read existing -> merge -> write back: ```json { diff --git a/.claude/skills/team-perf-opt/roles/coordinator/commands/dispatch.md b/.claude/skills/team-perf-opt/roles/coordinator/commands/dispatch.md index b270b653..68598f9d 100644 --- a/.claude/skills/team-perf-opt/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-perf-opt/roles/coordinator/commands/dispatch.md @@ -38,7 +38,7 @@ CONTEXT: - Scope: <optimization-scope> - Branch: <branch-id or 'none'> - Upstream artifacts: <artifact-1>, <artifact-2> - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: <deliverable path> + <quality criteria> CONSTRAINTS: <scope limits, focus areas> --- @@ -77,7 +77,7 @@ CONTEXT: - Session: <session-folder> - Scope: <optimization-scope> - Branch: none - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: <session>/artifacts/baseline-metrics.json + <session>/artifacts/bottleneck-report.md | Quantified metrics with evidence CONSTRAINTS: Focus on <optimization-scope> | Profile before any changes --- @@ -101,7 +101,7 @@ CONTEXT: - Scope: <optimization-scope> - Branch: none - Upstream artifacts: baseline-metrics.json, bottleneck-report.md - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: <session>/artifacts/optimization-plan.md | Priority-ordered with improvement targets, discrete OPT-IDs CONSTRAINTS: Focus on highest-impact optimizations | Risk assessment required | Non-overlapping file targets per OPT-ID --- @@ -125,7 +125,7 @@ CONTEXT: - Scope: <optimization-scope> - Branch: none - Upstream artifacts: optimization-plan.md - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: Modified source files + validation passing | Optimizations applied without regressions CONSTRAINTS: Preserve existing behavior | Minimal changes per optimization | Follow code conventions --- @@ -149,7 +149,7 @@ CONTEXT: - Scope: <optimization-scope> - Branch: none - Upstream artifacts: baseline-metrics.json, optimization-plan.md - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: <session>/artifacts/benchmark-results.json | Per-metric comparison with verdicts CONSTRAINTS: Must compare against baseline | Flag any regressions --- @@ -173,7 +173,7 @@ CONTEXT: - Scope: <optimization-scope> - Branch: none - Upstream artifacts: optimization-plan.md, benchmark-results.json (if available) - - Shared memory: <session>/wisdom/shared-memory.json + - Shared memory: <session>/.msg/meta.json EXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity CONSTRAINTS: Focus on optimization changes only | Provide specific file:line references --- @@ -233,7 +233,7 @@ CONTEXT: - Session: <session-folder> - Scope: optimize rendering - Pipeline: A - - Shared memory: <session>/wisdom/shared-memory.json (namespace: profiler.A) + - Shared memory: <session>/.msg/meta.json (namespace: profiler.A) EXPECTED: <session>/artifacts/pipelines/A/baseline-metrics.json + bottleneck-report.md CONSTRAINTS: Focus on rendering scope --- @@ -252,7 +252,7 @@ PipelineId: A", **Procedure**: 1. Read `<session>/artifacts/optimization-plan.md` to count OPT-IDs -2. Read `shared-memory.json` -> `strategist.optimization_count` +2. Read `.msg/meta.json` -> `strategist.optimization_count` 3. **Auto mode decision**: | Optimization Count | Decision | @@ -289,7 +289,7 @@ CONTEXT: - Session: <session-folder> - Branch: B{NN} - Upstream artifacts: branches/B{NN}/optimization-detail.md - - Shared memory: <session>/wisdom/shared-memory.json (namespace: optimizer.B{NN}) + - Shared memory: <session>/.msg/meta.json (namespace: optimizer.B{NN}) EXPECTED: Modified source files for OPT-{NNN} only CONSTRAINTS: Only implement this branch's optimization | Do not touch files outside OPT-{NNN} scope --- @@ -310,7 +310,7 @@ CONTEXT: - Session: <session-folder> - Branch: B{NN} - Upstream artifacts: baseline-metrics.json, branches/B{NN}/optimization-detail.md - - Shared memory: <session>/wisdom/shared-memory.json (namespace: benchmarker.B{NN}) + - Shared memory: <session>/.msg/meta.json (namespace: benchmarker.B{NN}) EXPECTED: <session>/artifacts/branches/B{NN}/benchmark-results.json CONSTRAINTS: Only benchmark this branch's metrics --- @@ -331,7 +331,7 @@ CONTEXT: - Session: <session-folder> - Branch: B{NN} - Upstream artifacts: branches/B{NN}/optimization-detail.md - - Shared memory: <session>/wisdom/shared-memory.json (namespace: reviewer.B{NN}) + - Shared memory: <session>/.msg/meta.json (namespace: reviewer.B{NN}) EXPECTED: <session>/artifacts/branches/B{NN}/review-report.md CONSTRAINTS: Only review this branch's changes --- diff --git a/.claude/skills/team-perf-opt/roles/coordinator/commands/monitor.md b/.claude/skills/team-perf-opt/roles/coordinator/commands/monitor.md index 1b1edac9..691f76cf 100644 --- a/.claude/skills/team-perf-opt/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-perf-opt/roles/coordinator/commands/monitor.md @@ -166,7 +166,7 @@ CONTEXT: - Session: <session-folder> - Branch: B{NN} - Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/benchmark-results.json - - Shared memory: <session>/wisdom/shared-memory.json (namespace: optimizer.B{NN}) + - Shared memory: <session>/.msg/meta.json (namespace: optimizer.B{NN}) EXPECTED: Fixed source files for B{NN} only CONSTRAINTS: Targeted fixes only | Do not touch other branches --- diff --git a/.claude/skills/team-perf-opt/roles/coordinator/role.md b/.claude/skills/team-perf-opt/roles/coordinator/role.md index 386db7f7..b5259f14 100644 --- a/.claude/skills/team-perf-opt/roles/coordinator/role.md +++ b/.claude/skills/team-perf-opt/roles/coordinator/role.md @@ -69,7 +69,7 @@ For callback/check/resume/complete: load `commands/monitor.md` and execute match ### Router Implementation 1. **Load session context** (if exists): - - Scan `.workflow/.team/PERF-OPT-*/team-session.json` for active/paused sessions + - 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: @@ -186,10 +186,10 @@ Bash("mkdir -p .workflow/<session-id>/artifacts/pipelines/A .workflow/<session-i - `independent_targets`: populated for independent mode (e.g., ["optimize rendering", "optimize API"]) - `fix_cycles`: populated per-branch/pipeline as fix cycles occur -3. Initialize shared-memory.json: +3. Initialize .msg/meta.json: ``` -Write("<session>/wisdom/shared-memory.json", { "session_id": "<session-id>", "requirement": "<requirement>", "parallel_mode": "<mode>" }) +Write("<session>/.msg/meta.json", { "session_id": "<session-id>", "requirement": "<requirement>", "parallel_mode": "<mode>" }) ``` 4. Create team: diff --git a/.claude/skills/team-planex/SKILL.md b/.claude/skills/team-planex/SKILL.md index d5bc526a..e13eb9d7 100644 --- a/.claude/skills/team-planex/SKILL.md +++ b/.claude/skills/team-planex/SKILL.md @@ -260,7 +260,7 @@ if (autoYes) { ``` .workflow/.team/PEX-{slug}-{date}/ -├── team-session.json # Session state +├── .msg/meta.json # Session state ├── artifacts/ │ └── solutions/ # Planner solution output per issue │ ├── {issueId-1}.json @@ -270,7 +270,8 @@ if (autoYes) { │ ├── decisions.md │ ├── conventions.md │ └── issues.md -└── shared-memory.json # Cross-role state +├── .msg/messages.jsonl # Team message bus +└── .msg/meta.json # Session metadata ``` --- @@ -279,8 +280,9 @@ if (autoYes) { 每次 SendMessage 前,先调用 `mcp__ccw-tools__team_msg` 记录: -- 参数: operation="log", team=`<session-id>`, from=`<role>`, to=`<target-role>`, type=`<type>`, summary="[`<role>`] `<summary>`" -- **注意**: `team` 必须是 **session ID** (如 `PEX-project-2026-02-27`), 不是 team name. +- 参数: 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**: diff --git a/.claude/skills/team-planex/role-specs/executor.md b/.claude/skills/team-planex/role-specs/executor.md index fa0e8fb3..14fd3f76 100644 --- a/.claude/skills/team-planex/role-specs/executor.md +++ b/.claude/skills/team-planex/role-specs/executor.md @@ -88,8 +88,7 @@ ccw issue update <issueId> --status completed ### Report -Send `impl_complete` message to coordinator via team_msg + SendMessage: -- summary: `[executor] Implemented <issueId>: <title>` +Send `impl_complete` message to coordinator via team_msg + SendMessage. ## Boundaries diff --git a/.claude/skills/team-planex/role-specs/planner.md b/.claude/skills/team-planex/role-specs/planner.md index 5fe96568..e2bca7e0 100644 --- a/.claude/skills/team-planex/role-specs/planner.md +++ b/.claude/skills/team-planex/role-specs/planner.md @@ -88,7 +88,6 @@ InnerLoop: true`, Send message via team_msg + SendMessage to coordinator: - type: `issue_ready` -- summary: `[planner] Solution ready for <issueId>` ### 3f. Continue Loop diff --git a/.claude/skills/team-planex/roles/coordinator/commands/monitor.md b/.claude/skills/team-planex/roles/coordinator/commands/monitor.md index 1c95f29f..dd337b54 100644 --- a/.claude/skills/team-planex/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-planex/roles/coordinator/commands/monitor.md @@ -16,7 +16,7 @@ Event-driven pipeline coordination with Spawn-and-Stop pattern. Three wake-up so | Input | Source | Required | |-------|--------|----------| -| Session file | `<session-folder>/team-session.json` | Yes | +| Session file | `<session-folder>/.msg/meta.json` | Yes | | Task list | `TaskList()` | Yes | | Active workers | session.active_workers[] | Yes | diff --git a/.claude/skills/team-planex/roles/coordinator/role.md b/.claude/skills/team-planex/roles/coordinator/role.md index c1995caa..03601ee6 100644 --- a/.claude/skills/team-planex/roles/coordinator/role.md +++ b/.claude/skills/team-planex/roles/coordinator/role.md @@ -14,7 +14,7 @@ Orchestrate the team-planex pipeline: parse input, create team, dispatch tasks, - Create team and initialize session directory - Dispatch tasks via `commands/dispatch.md` - Monitor progress via `commands/monitor.md` with Spawn-and-Stop pattern -- Maintain session state (team-session.json) +- Maintain session state (.msg/meta.json) ### MUST NOT - Execute planning or implementation work directly (delegate to workers) @@ -62,7 +62,7 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat ## Phase 0: Session Resume Check -1. Scan `.workflow/.team/PEX-*/team-session.json` for sessions with status "active" or "paused" +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) 4. Multiple sessions -> AskUserQuestion for selection @@ -95,7 +95,7 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat 3. Create subdirectories: `artifacts/solutions/`, `wisdom/` 4. Call `TeamCreate` with team name (default: "planex") 5. Initialize wisdom files (learnings.md, decisions.md, conventions.md, issues.md) -6. Write team-session.json: +6. Write .msg/meta.json: ``` { diff --git a/.claude/skills/team-quality-assurance/SKILL.md b/.claude/skills/team-quality-assurance/SKILL.md index 3dd256ce..37cfed5f 100644 --- a/.claude/skills/team-quality-assurance/SKILL.md +++ b/.claude/skills/team-quality-assurance/SKILL.md @@ -135,10 +135,10 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **NOTE**: `team` must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. - - **CLI fallback**: When MCP unavailable -> `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) + - 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 @@ -178,7 +178,7 @@ All outputs must carry `[role_name]` prefix. | Allowed | Forbidden | |---------|-----------| | Process tasks with own prefix | Process tasks with other role prefixes | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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 | @@ -193,7 +193,7 @@ All outputs must carry `[role_name]` prefix. ### Shared Memory -Cross-role accumulated knowledge stored in `shared-memory.json`: +Cross-role accumulated knowledge stored via team_msg(type='state_update'): | Field | Owner | Content | |-------|-------|---------| @@ -431,8 +431,9 @@ Skill(skill="team-quality-assurance", args="--role=<role> --agent-name=<role>-<N ``` .workflow/.team/QA-<slug>-<YYYY-MM-DD>/ -├── team-session.json # Session state -├── shared-memory.json # Discovered issues / test strategy / defect patterns / coverage history +├── .msg/meta.json # Session state +├── .msg/messages.jsonl # Team message bus +├── .msg/meta.json # Session metadata ├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md diff --git a/.claude/skills/team-quality-assurance/role-specs/analyst.md b/.claude/skills/team-quality-assurance/role-specs/analyst.md new file mode 100644 index 00000000..f77437fc --- /dev/null +++ b/.claude/skills/team-quality-assurance/role-specs/analyst.md @@ -0,0 +1,80 @@ +--- +prefix: QAANA +inner_loop: false +subagents: [] +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/role-specs/executor.md b/.claude/skills/team-quality-assurance/role-specs/executor.md new file mode 100644 index 00000000..c26a8a35 --- /dev/null +++ b/.claude/skills/team-quality-assurance/role-specs/executor.md @@ -0,0 +1,65 @@ +--- +prefix: QARUN +inner_loop: true +additional_prefixes: [QARUN-gc] +subagents: [] +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 to code-developer subagent 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/role-specs/generator.md b/.claude/skills/team-quality-assurance/role-specs/generator.md new file mode 100644 index 00000000..114992f3 --- /dev/null +++ b/.claude/skills/team-quality-assurance/role-specs/generator.md @@ -0,0 +1,68 @@ +--- +prefix: QAGEN +inner_loop: false +additional_prefixes: [QAGEN-fix] +subagents: [] +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 to code-developer subagent | + +**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/role-specs/scout.md b/.claude/skills/team-quality-assurance/role-specs/scout.md new file mode 100644 index 00000000..9bd77f4e --- /dev/null +++ b/.claude/skills/team-quality-assurance/role-specs/scout.md @@ -0,0 +1,67 @@ +--- +prefix: SCOUT +inner_loop: false +subagents: [] +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/role-specs/strategist.md b/.claude/skills/team-quality-assurance/role-specs/strategist.md new file mode 100644 index 00000000..f617983f --- /dev/null +++ b/.claude/skills/team-quality-assurance/role-specs/strategist.md @@ -0,0 +1,71 @@ +--- +prefix: QASTRAT +inner_loop: false +subagents: [] +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/roles/analyst/commands/quality-report.md b/.claude/skills/team-quality-assurance/roles/analyst/commands/quality-report.md index 143db2b7..aa711596 100644 --- a/.claude/skills/team-quality-assurance/roles/analyst/commands/quality-report.md +++ b/.claude/skills/team-quality-assurance/roles/analyst/commands/quality-report.md @@ -82,7 +82,7 @@ if (mode === 'direct') { Bash(`ccw cli -p "PURPOSE: Perform deep quality analysis on QA results to identify defect patterns, coverage trends, and improvement opportunities TASK: • Classify defects by root cause pattern (logic errors, integration issues, missing validation, etc.) • Identify files with highest defect density • Analyze coverage gaps vs risk levels • Compare actual coverage to targets • Generate actionable improvement recommendations MODE: analysis -CONTEXT: @${sessionFolder}/shared-memory.json @${sessionFolder}/results/**/* +CONTEXT: @${sessionFolder}/.msg/meta.json @${sessionFolder}/results/**/* EXPECTED: Structured analysis with: defect pattern taxonomy, risk-coverage matrix, quality score rationale, top 5 improvement recommendations with expected impact CONSTRAINTS: Be data-driven, avoid speculation without evidence" --tool gemini --mode analysis --rule analysis-analyze-code-patterns`, { run_in_background: true @@ -277,7 +277,7 @@ sharedMemory.coverage_history.push({ quality_score: analysis.quality_score, issues: analysis.defect_patterns.total }) -Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) function generateReportMarkdown(analysis) { return `# Quality Assurance Report diff --git a/.claude/skills/team-quality-assurance/roles/analyst/role.md b/.claude/skills/team-quality-assurance/roles/analyst/role.md index 9d73a233..84e7fe91 100644 --- a/.claude/skills/team-quality-assurance/roles/analyst/role.md +++ b/.claude/skills/team-quality-assurance/roles/analyst/role.md @@ -56,24 +56,21 @@ Quality analyst. Analyze defect patterns, coverage gaps, test effectiveness, and Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TQA-project-2026-02-27", NOT "quality-assurance" + session_id: <session-id>, from: "analyst", - to: "coordinator", type: <message-type>, - summary: "[analyst] quality score: <score>/100, defect patterns: <count>, coverage: <coverage>%", - ref: <report-path> + data: { ref: <report-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from analyst --to coordinator --type <message-type> --summary \"[analyst] analysis complete\" --ref <report-path> --json") +Bash("ccw team log --session-id <session-id> --from analyst --type <message-type> --json") ``` --- @@ -95,7 +92,7 @@ Standard task discovery flow: TaskList -> filter by prefix `QAANA-*` + owner mat | Input | Source | Required | |-------|--------|----------| -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Discovered issues | sharedMemory.discovered_issues | No | | Test strategy | sharedMemory.test_strategy | No | | Generated tests | sharedMemory.generated_tests | No | 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 e79e1f55..e01001eb 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/commands/dispatch.md @@ -2,7 +2,6 @@ > 任务链创建与依赖管理。根据 QA 模式创建 pipeline 任务链并分配给 worker 角色。 -**NOTE**: `teamName` variable must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ## When to Use @@ -114,9 +113,8 @@ const chainValid = chainTasks.length === pipeline.length if (!chainValid) { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: teamName, from: "coordinator", to: "user", type: "error", - summary: `[coordinator] 任务链创建不完整: ${chainTasks.length}/${pipeline.length}` }) } ``` 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 2f01b23b..d940a52d 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/commands/monitor.md @@ -2,7 +2,6 @@ > 阶段驱动的协调循环。按 pipeline 阶段顺序等待 worker 完成,路由消息,触发 GC 循环,执行质量门控。 -**NOTE**: `teamName` variable must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ## When to Use @@ -77,7 +76,7 @@ const autoYes = /\b(-y|--yes)\b/.test(args) ```javascript // 从 shared memory 获取覆盖率目标 -const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const strategy = sharedMemory.test_strategy || {} const coverageTargets = {} for (const layer of (strategy.layers || [])) { @@ -108,9 +107,7 @@ for (const stageTask of pipelineTasks) { if (!workerConfig) { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] 未知阶段前缀: ${stagePrefix},跳过` + operation: "log", session_id: teamName, from: "coordinator", }) continue } @@ -119,36 +116,31 @@ for (const stageTask of pipelineTasks) { TaskUpdate({ taskId: stageTask.id, status: 'in_progress' }) mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: teamName, from: "coordinator", to: workerConfig.role, type: "task_unblocked", - summary: `[coordinator] 启动阶段: ${stageTask.subject} → ${workerConfig.role}` }) // 3. 同步 spawn worker — 阻塞直到 worker 返回(Stop-Wait 核心) const workerResult = Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn ${workerConfig.role} worker for ${stageTask.subject}`, team_name: teamName, name: workerConfig.role, - prompt: `你是 team "${teamName}" 的 ${workerConfig.role.toUpperCase()}。 + prompt: `## Role Assignment +role: ${workerConfig.role} +role_spec: .claude/skills/team-quality-assurance/role-specs/${workerConfig.role}.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: ${teamName} +requirement: ${stageTask.description || taskDescription} +inner_loop: false -## ⚠️ 首要指令(MUST) -Skill(skill="team-quality-assurance", args="${workerConfig.skillArgs}") +## Current Task +- Task ID: ${stageTask.id} +- Task: ${stageTask.subject} -## 当前任务 -- 任务 ID: ${stageTask.id} -- 任务: ${stageTask.subject} -- 描述: ${stageTask.description || taskDescription} -- Session: ${sessionFolder} - -## 角色准则(强制) -- 所有输出必须带 [${workerConfig.role}] 标识前缀 -- 仅与 coordinator 通信 - -## 工作流程 -1. Skill(skill="team-quality-assurance", args="${workerConfig.skillArgs}") 获取角色定义 -2. 执行任务 → 汇报结果 -3. TaskUpdate({ taskId: "${stageTask.id}", status: "completed" })`, +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 }) @@ -159,9 +151,8 @@ Skill(skill="team-quality-assurance", args="${workerConfig.skillArgs}") // Worker 返回但未标记 completed → 异常处理 if (autoYes) { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] [auto] 阶段 ${stageTask.subject} 未完成,自动跳过` + operation: "log", session_id: teamName, from: "coordinator", + type: "error", }) TaskUpdate({ taskId: stageTask.id, status: 'deleted' }) continue @@ -186,24 +177,21 @@ Skill(skill="team-quality-assurance", args="${workerConfig.skillArgs}") continue } else if (answer === "终止") { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: teamName, from: "coordinator", to: "user", type: "shutdown", - summary: `[coordinator] 用户终止流水线,当前阶段: ${stageTask.subject}` }) break } // 重试: continue to next iteration will re-process if logic wraps } else { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "user", type: "quality_gate", - summary: `[coordinator] 阶段完成: ${stageTask.subject}` + operation: "log", session_id: teamName, from: "coordinator", }) } // 5. 阶段间检查(QARUN 阶段检查覆盖率,决定 GC 循环) if (stagePrefix === 'QARUN') { - const latestMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const latestMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const coverage = latestMemory.execution_results?.coverage || 0 const targetLayer = stageTask.metadata?.layer || 'L1' const target = coverageTargets[targetLayer] || 80 @@ -211,9 +199,8 @@ Skill(skill="team-quality-assurance", args="${workerConfig.skillArgs}") if (coverage < target && gcIteration < MAX_GC_ITERATIONS) { gcIteration++ mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: teamName, from: "coordinator", to: "generator", type: "gc_loop_trigger", - summary: `[coordinator] GC循环 #${gcIteration}: 覆盖率 ${coverage}% < ${target}%,请修复` }) // 创建 GC 修复任务追加到 pipeline } @@ -247,16 +234,15 @@ function processMessage(msg, handler) { case 'quality_gate': { // 重新读取最新 shared memory - const latestMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const latestMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const qualityScore = latestMemory.quality_score || 0 let status = 'PASS' if (qualityScore < 60) status = 'FAIL' else if (qualityScore < 80) status = 'CONDITIONAL' mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: teamName, from: "coordinator", to: "user", type: "quality_gate", - summary: `[coordinator] 质量门控: ${status} (score: ${qualityScore})` }) break } @@ -266,7 +252,6 @@ function processMessage(msg, handler) { if (severity === 'critical') { SendMessage({ content: `## [coordinator] Critical Error from ${msg.from}\n\n${msg.summary}`, - summary: `[coordinator] Critical error: ${msg.summary}` }) } break @@ -278,17 +263,13 @@ function handleGCDecision(coverage, targetLayer) { if (gcIteration < MAX_GC_ITERATIONS) { gcIteration++ mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "generator", type: "gc_loop_trigger", - summary: `[coordinator] GC循环 #${gcIteration}: 覆盖率 ${coverage}% 未达标,请修复`, + operation: "log", session_id: teamName, from: "coordinator", data: { iteration: gcIteration, layer: targetLayer, coverage } }) // 创建 GC 修复任务(参见 dispatch.md createGCLoopTasks) } else { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "user", type: "quality_gate", - summary: `[coordinator] GC循环已达上限(${MAX_GC_ITERATIONS}),接受当前覆盖率 ${coverage}%` + operation: "log", session_id: teamName, from: "coordinator", }) } } @@ -298,7 +279,7 @@ function handleGCDecision(coverage, targetLayer) { ```javascript // 汇总所有结果 -const finalSharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const finalSharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const allFinalTasks = TaskList() const workerTasks = allFinalTasks.filter(t => t.owner && t.owner !== 'coordinator') const summary = { diff --git a/.claude/skills/team-quality-assurance/roles/coordinator/role.md b/.claude/skills/team-quality-assurance/roles/coordinator/role.md index cc910fb2..b42a7c1a 100644 --- a/.claude/skills/team-quality-assurance/roles/coordinator/role.md +++ b/.claude/skills/team-quality-assurance/roles/coordinator/role.md @@ -26,18 +26,56 @@ Orchestrate the Quality Assurance workflow: requirement clarification, mode sele --- +## 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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline | -| New session | None of the above | -> Phase 0 (Session Resume Check) | +| 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) | +| New session | None of above | -> Phase 1 | -For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP. +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 --- @@ -101,7 +139,7 @@ For callback/check/resume: load `commands/monitor.md` and execute the appropriat 1. Generate session ID 2. Create session folder 3. Call TeamCreate with team name -4. Initialize shared-memory.json with empty fields +4. Initialize .msg/meta.json with empty fields 5. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) 6. Write session file with: session_id, mode, scope, status="active" diff --git a/.claude/skills/team-quality-assurance/roles/executor/commands/run-fix-cycle.md b/.claude/skills/team-quality-assurance/roles/executor/commands/run-fix-cycle.md index afc7b4e5..d1184b40 100644 --- a/.claude/skills/team-quality-assurance/roles/executor/commands/run-fix-cycle.md +++ b/.claude/skills/team-quality-assurance/roles/executor/commands/run-fix-cycle.md @@ -183,7 +183,7 @@ sharedMemory.execution_results = sharedMemory.execution_results || {} sharedMemory.execution_results[targetLayer] = resultData sharedMemory.execution_results.pass_rate = passRate sharedMemory.execution_results.coverage = coverage -Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) ``` ## Output Format diff --git a/.claude/skills/team-quality-assurance/roles/executor/role.md b/.claude/skills/team-quality-assurance/roles/executor/role.md index aa06cfb7..c749e00b 100644 --- a/.claude/skills/team-quality-assurance/roles/executor/role.md +++ b/.claude/skills/team-quality-assurance/roles/executor/role.md @@ -57,25 +57,21 @@ Test executor. Run test suites, collect coverage data, and perform automatic fix Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TQA-project-2026-02-27", NOT "quality-assurance" + session_id: <session-id>, from: "executor", - to: "coordinator", type: <message-type>, - summary: "[executor] <layer>: <status-message>", - ref: <results-file>, - data: { pass_rate, coverage, iterations } + data: { ref: <results-file>, pass_rate, coverage, iterations } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from executor --to coordinator --type <message-type> --summary \"[executor] test execution complete\" --ref <results-file> --json") +Bash("ccw team log --session-id <session-id> --from executor --type <message-type> --json") ``` --- @@ -99,7 +95,7 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. | Input | Source | Required | |-------|--------|----------| -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Test strategy | sharedMemory.test_strategy | Yes | | Generated tests | sharedMemory.generated_tests | Yes | | Target layer | task description | Yes | diff --git a/.claude/skills/team-quality-assurance/roles/generator/commands/generate-tests.md b/.claude/skills/team-quality-assurance/roles/generator/commands/generate-tests.md index ea52601e..2a154b08 100644 --- a/.claude/skills/team-quality-assurance/roles/generator/commands/generate-tests.md +++ b/.claude/skills/team-quality-assurance/roles/generator/commands/generate-tests.md @@ -228,7 +228,7 @@ const testInfo = { sharedMemory.generated_tests = sharedMemory.generated_tests || {} sharedMemory.generated_tests[targetLayer] = testInfo -Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) ``` ## Output Format diff --git a/.claude/skills/team-quality-assurance/roles/generator/role.md b/.claude/skills/team-quality-assurance/roles/generator/role.md index c0abd2c4..c15754fd 100644 --- a/.claude/skills/team-quality-assurance/roles/generator/role.md +++ b/.claude/skills/team-quality-assurance/roles/generator/role.md @@ -57,24 +57,21 @@ Test case generator. Generate test code according to strategist's strategy and l Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TQA-project-2026-02-27", NOT "quality-assurance" + session_id: <session-id>, from: "generator", - to: "coordinator", type: <message-type>, - summary: "[generator] <layer> test generation complete: <file-count> files", - ref: <first-test-file> + data: { ref: <first-test-file> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from generator --to coordinator --type <message-type> --summary \"[generator] test generation complete\" --ref <test-file> --json") +Bash("ccw team log --session-id <session-id> --from generator --type <message-type> --json") ``` --- @@ -98,7 +95,7 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. | Input | Source | Required | |-------|--------|----------| -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Test strategy | sharedMemory.test_strategy | Yes | | Target layer | task description or strategy.layers[0] | Yes | diff --git a/.claude/skills/team-quality-assurance/roles/scout/role.md b/.claude/skills/team-quality-assurance/roles/scout/role.md index 3cffed40..32316eb2 100644 --- a/.claude/skills/team-quality-assurance/roles/scout/role.md +++ b/.claude/skills/team-quality-assurance/roles/scout/role.md @@ -86,7 +86,7 @@ const changedFiles = Bash(`git diff --name-only HEAD~5 2>/dev/null || echo ""`) // 读取 shared memory 获取历史缺陷模式 const sessionFolder = task.description.match(/session:\s*(.+)/)?.[1] || '.' let sharedMemory = {} -try { sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) } catch {} +try { sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) } catch {} const knownPatterns = sharedMemory.defect_patterns || [] // 确定扫描视角 @@ -164,7 +164,7 @@ const discoveredIssues = allFindings.critical // 更新 shared memory sharedMemory.discovered_issues = discoveredIssues -Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) // 保存扫描结果 Write(`${sessionFolder}/scan/scan-results.json`, JSON.stringify({ @@ -189,12 +189,10 @@ const resultSummary = `发现 ${discoveredIssues.length} 个问题(Critical: $ mcp__ccw-tools__team_msg({ operation: "log", - team: teamName, + session_id: teamName, from: "scout", - to: "coordinator", type: discoveredIssues.length > 0 ? "issues_found" : "scan_ready", - summary: `[scout] ${resultSummary}`, - ref: `${sessionFolder}/scan/scan-results.json` + data: { ref: `${sessionFolder}/scan/scan-results.json` } }) SendMessage({ diff --git a/.claude/skills/team-quality-assurance/roles/strategist/role.md b/.claude/skills/team-quality-assurance/roles/strategist/role.md index e4542f08..d78e720c 100644 --- a/.claude/skills/team-quality-assurance/roles/strategist/role.md +++ b/.claude/skills/team-quality-assurance/roles/strategist/role.md @@ -55,24 +55,21 @@ Test strategist. Analyze change scope, determine test layers (L1-L3), define cov Before every SendMessage, log via `mcp__ccw-tools__team_msg`: -**NOTE**: `team` must be **session ID** (e.g., `TQA-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description. ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // e.g., "TQA-project-2026-02-27", NOT "quality-assurance" + session_id: <session-id>, from: "strategist", - to: "coordinator", type: <message-type>, - summary: "[strategist] QASTRAT complete: <layers-summary>", - ref: <artifact-path> + data: { ref: <artifact-path> } }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from strategist --to coordinator --type <message-type> --summary \"[strategist] QASTRAT complete\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from strategist --type <message-type> --json") ``` --- @@ -94,7 +91,7 @@ Standard task discovery flow: TaskList -> filter by prefix `QASTRAT-*` + owner m | Input | Source | Required | |-------|--------|----------| -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Shared memory | <session-folder>/.msg/meta.json | Yes | | Discovered issues | sharedMemory.discovered_issues | No | | Defect patterns | sharedMemory.defect_patterns | No | diff --git a/.claude/skills/team-review/SKILL.md b/.claude/skills/team-review/SKILL.md index af75b422..ccc7dbd0 100644 --- a/.claude/skills/team-review/SKILL.md +++ b/.claude/skills/team-review/SKILL.md @@ -170,9 +170,10 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team="review", from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **CLI fallback**: When MCP unavailable → `ccw team log --team review --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) + - 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 @@ -206,7 +207,7 @@ Coordinator additional restrictions: Do not write/modify code directly, do not c | Component | Location | |-----------|----------| | Session directory | `.workflow/.team-review/<workflow_id>/` | -| Shared memory | `shared-memory.json` in session dir | +| Shared memory | `.msg/meta.json` in session dir | | Team config | `specs/team-config.json` | | Finding schema | `specs/finding-schema.json` | | Dimensions | `specs/dimensions.md` | diff --git a/.claude/skills/team-review/role-specs/fixer.md b/.claude/skills/team-review/role-specs/fixer.md new file mode 100644 index 00000000..a7c850ba --- /dev/null +++ b/.claude/skills/team-review/role-specs/fixer.md @@ -0,0 +1,75 @@ +--- +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/role-specs/reviewer.md b/.claude/skills/team-review/role-specs/reviewer.md new file mode 100644 index 00000000..a175ef4f --- /dev/null +++ b/.claude/skills/team-review/role-specs/reviewer.md @@ -0,0 +1,66 @@ +--- +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/role-specs/scanner.md b/.claude/skills/team-review/role-specs/scanner.md new file mode 100644 index 00000000..dcbd889d --- /dev/null +++ b/.claude/skills/team-review/role-specs/scanner.md @@ -0,0 +1,70 @@ +--- +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/roles/coordinator/commands/dispatch.md b/.claude/skills/team-review/roles/coordinator/commands/dispatch.md index e29cfdb0..1d48df65 100644 --- a/.claude/skills/team-review/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-review/roles/coordinator/commands/dispatch.md @@ -51,10 +51,10 @@ function buildPipeline(pipelineMode) { ```javascript // Session directory already created in Phase 2 // Write pipeline config to shared memory -const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +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}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) ``` ### Step 2: Create Task Chain @@ -110,16 +110,14 @@ const chainValid = chainTasks.length === pipeline.length if (!chainValid) { mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] Task chain incomplete: ${chainTasks.length}/${pipeline.length}` + operation: "log", session_id: sessionId, from: "coordinator", + type: "error", }) } mcp__ccw-tools__team_msg({ - operation: "log", team: teamName, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: "all", type: "dispatch_ready", - summary: `[coordinator] Task chain created: ${pipeline.map(s => `${s.prefix}-${s.suffix}`).join(' -> ')} (mode: ${pipelineMode})` }) ``` diff --git a/.claude/skills/team-review/roles/coordinator/commands/monitor.md b/.claude/skills/team-review/roles/coordinator/commands/monitor.md index 69448021..83783297 100644 --- a/.claude/skills/team-review/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-review/roles/coordinator/commands/monitor.md @@ -30,7 +30,7 @@ const STAGE_WORKER_MAP = { ### Step 1: Context Preparation ```javascript -const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) // Get pipeline tasks in creation order (= dependency order) const allTasks = TaskList() @@ -55,9 +55,8 @@ for (const stageTask of pipelineTasks) { if (!workerConfig) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] Unknown stage prefix: ${stagePrefix}, skipping` + operation: "log", session_id: sessionId, from: "coordinator", + type: "error", }) continue } @@ -66,9 +65,8 @@ for (const stageTask of pipelineTasks) { TaskUpdate({ taskId: stageTask.id, status: 'in_progress' }) mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: workerConfig.role, type: "stage_transition", - summary: `[coordinator] Starting stage: ${stageTask.subject} -> ${workerConfig.role}` }) // 3. Build worker arguments @@ -86,19 +84,17 @@ for (const stageTask of pipelineTasks) { if (action === 'skip') continue } else { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "stage_transition", - summary: `[coordinator] Stage complete: ${stageTask.subject}` + operation: "log", session_id: sessionId, from: "coordinator", + type: "stage_transition", }) } // 6. Post-stage: After SCAN check findings if (stagePrefix === 'SCAN') { - const mem = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const mem = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) if ((mem.findings_count || 0) === 0) { - mcp__ccw-tools__team_msg({ operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "pipeline_complete", - summary: `[coordinator] 0 findings. Code is clean. Skipping review/fix.` }) + mcp__ccw-tools__team_msg({ operation: "log", session_id: sessionId, from: "coordinator", + type: "pipeline_complete", for (const r of pipelineTasks.slice(pipelineTasks.indexOf(stageTask) + 1)) TaskUpdate({ taskId: r.id, status: 'deleted' }) break @@ -107,7 +103,7 @@ for (const stageTask of pipelineTasks) { // 7. Post-stage: After REV confirm fix scope if (stagePrefix === 'REV' && pipelineMode === 'full') { - const mem = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const mem = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) if (!autoYes) { const conf = AskUserQuestion({ questions: [{ @@ -126,7 +122,7 @@ for (const stageTask of pipelineTasks) { break } mem.fix_scope = conf["Fix Confirmation"] === "Fix critical/high only" ? 'critical,high' : 'all' - Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(mem, null, 2)) + Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(mem, null, 2)) } Write(`${sessionFolder}/fix/fix-manifest.json`, JSON.stringify({ @@ -163,9 +159,8 @@ function buildWorkerArgs(stageTask, workerConfig) { ```javascript function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { if (autoYes) { - mcp__ccw-tools__team_msg({ operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] [auto] ${stageTask.subject} incomplete, skipping` }) + mcp__ccw-tools__team_msg({ operation: "log", session_id: sessionId, from: "coordinator", + type: "error", TaskUpdate({ taskId: stageTask.id, status: 'deleted' }) return 'skip' } @@ -191,9 +186,8 @@ function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { TaskUpdate({ taskId: stageTask.id, status: 'deleted' }) return 'skip' } else { - mcp__ccw-tools__team_msg({ operation: "log", team: sessionId // MUST be session ID (e.g., RC-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] User aborted at: ${stageTask.subject}` }) + mcp__ccw-tools__team_msg({ operation: "log", session_id: sessionId, from: "coordinator", + type: "error", return 'abort' } } @@ -202,10 +196,10 @@ function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { ### Step 3: Finalize ```javascript -const finalMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const finalMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) finalMemory.pipeline_status = 'complete' finalMemory.completed_at = new Date().toISOString() -Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(finalMemory, null, 2)) +Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(finalMemory, null, 2)) ``` ## Error Handling diff --git a/.claude/skills/team-review/roles/coordinator/role.md b/.claude/skills/team-review/roles/coordinator/role.md index 1c29b0ec..244c8e55 100644 --- a/.claude/skills/team-review/roles/coordinator/role.md +++ b/.claude/skills/team-review/roles/coordinator/role.md @@ -32,18 +32,56 @@ Code review team coordinator. Orchestrates the scan-review-fix pipeline (CP-1 Li --- +## 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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[scanner]`, `[reviewer]`, or `[fixer]` tag | -> handleCallback: auto-advance pipeline | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline | -| New session | None of the above | -> Phase 1 (Parse Arguments) | +| 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) | -For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP. +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-review/RC-*/.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 + - For Phase 1: Execute Parse Arguments below --- @@ -86,18 +124,16 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RC-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "coordinator", - to: "user", - type: "dispatch_ready", - summary: "[coordinator] Task chain created, pipeline ready" + type: "dispatch_ready" }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from coordinator --to user --type dispatch_ready --summary \"[coordinator] Task chain created\" --json") +Bash("ccw team log --session-id <session-id> --from coordinator --type dispatch_ready --json") ``` --- @@ -156,10 +192,12 @@ Bash("ccw team log --team <session-id> --from coordinator --to user --type dispa │ ├── decisions.md │ ├── conventions.md │ └── issues.md -└── shared-memory.json +├── .msg/ +│ ├── messages.jsonl +│ └── meta.json ``` -3. Initialize shared-memory.json with: workflow_id, mode, target, dimensions, auto flag +3. Initialize .msg/meta.json with: workflow_id, mode, target, dimensions, auto flag **Success**: Session folder created, shared memory initialized. diff --git a/.claude/skills/team-review/roles/fixer/commands/execute-fixes.md b/.claude/skills/team-review/roles/fixer/commands/execute-fixes.md index 06dddd2c..a9a2eb1d 100644 --- a/.claude/skills/team-review/roles/fixer/commands/execute-fixes.md +++ b/.claude/skills/team-review/roles/fixer/commands/execute-fixes.md @@ -139,9 +139,8 @@ if (isQuickPath) { results_so_far:{fixed:results.fixed.length, failed:results.failed.length} }, null, 2)) - mcp__ccw-tools__team_msg({ operation:"log", team:"team-review", from:"fixer", + mcp__ccw-tools__team_msg({ operation:"log", session_id: sessionId, from:"fixer", to:"coordinator", type:"fix_progress", - summary:`[fixer] Group ${gid}: ${results.fixed.length} fixed, ${results.failed.length} failed` }) } } ``` diff --git a/.claude/skills/team-review/roles/fixer/commands/plan-fixes.md b/.claude/skills/team-review/roles/fixer/commands/plan-fixes.md index 75142b85..7839bc40 100644 --- a/.claude/skills/team-review/roles/fixer/commands/plan-fixes.md +++ b/.claude/skills/team-review/roles/fixer/commands/plan-fixes.md @@ -172,9 +172,8 @@ const fixPlan = { Bash(`mkdir -p "${sessionFolder}/fix"`) Write(`${sessionFolder}/fix/fix-plan.json`, JSON.stringify(fixPlan, null, 2)) -mcp__ccw-tools__team_msg({ operation:"log", team:"team-review", from:"fixer", +mcp__ccw-tools__team_msg({ operation:"log", session_id: sessionId, from:"fixer", to:"coordinator", type:"fix_progress", - summary:`[fixer] Fix plan: ${totalGroups} groups, ${totalFindings} findings, path=${isQuickPath ? 'quick' : 'standard'}` }) ``` ## Error Handling diff --git a/.claude/skills/team-review/roles/fixer/role.md b/.claude/skills/team-review/roles/fixer/role.md index 6b73fff4..6d4c7103 100644 --- a/.claude/skills/team-review/roles/fixer/role.md +++ b/.claude/skills/team-review/roles/fixer/role.md @@ -67,11 +67,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RC-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "fixer", - to: "coordinator", type: "fix_complete", - summary: "[fixer] Fix: <fixed>/<total> (<rate>%)", ref: "<session-folder>/fix/fix-summary.json" }) ``` @@ -79,7 +77,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from fixer --to coordinator --type fix_complete --summary \"[fixer] Fix complete\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from fixer --type fix_complete --ref <path> --json") ``` --- @@ -214,7 +212,7 @@ Delegate to `commands/execute-fixes.md`. 1. Generate fix-summary.json with: fix_id, fix_date, scope, total, fixed, failed, skipped, fix_rate, verification results 2. Generate fix-summary.md (human-readable) -3. Update shared-memory.json with fix results +3. Update .msg/meta.json with fix results 4. Log via team_msg with `[fixer]` prefix 5. SendMessage to coordinator 6. TaskUpdate completed diff --git a/.claude/skills/team-review/roles/reviewer/role.md b/.claude/skills/team-review/roles/reviewer/role.md index 2bfe1cdb..027cc8c2 100644 --- a/.claude/skills/team-review/roles/reviewer/role.md +++ b/.claude/skills/team-review/roles/reviewer/role.md @@ -66,11 +66,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RC-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "reviewer", - to: "coordinator", type: "review_complete", - summary: "[reviewer] Review complete: <count> findings (<severity-summary>)", ref: "<session-folder>/review/review-report.json" }) ``` @@ -78,7 +76,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from reviewer --to coordinator --type review_complete --summary \"[reviewer] Review complete\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from reviewer --type review_complete --ref <path> --json") ``` --- @@ -200,7 +198,7 @@ Delegate to `commands/generate-report.md`. **Workflow**: -1. Update shared-memory.json with review results summary +1. Update .msg/meta.json with review results summary 2. Build top findings summary (critical/high, max 8) 3. Log via team_msg with `[reviewer]` prefix 4. SendMessage to coordinator diff --git a/.claude/skills/team-review/roles/scanner/role.md b/.claude/skills/team-review/roles/scanner/role.md index f0e684fe..6c52d0d6 100644 --- a/.claude/skills/team-review/roles/scanner/role.md +++ b/.claude/skills/team-review/roles/scanner/role.md @@ -67,11 +67,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RC-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "scanner", - to: "coordinator", type: "scan_complete", - summary: "[scanner] Scan complete: <count> findings (<dimension-summary>)", ref: "<session-folder>/scan/scan-results.json" }) ``` @@ -79,7 +77,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from scanner --to coordinator --type scan_complete --summary \"[scanner] Scan complete\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from scanner --type scan_complete --ref <path> --json") ``` --- @@ -222,7 +220,7 @@ If no source files found -> report empty, complete task cleanly. **Workflow**: -1. Update shared-memory.json with scan results summary +1. Update .msg/meta.json with scan results summary 2. Build top findings summary (critical/high, max 10) 3. Log via team_msg with `[scanner]` prefix 4. SendMessage to coordinator diff --git a/.claude/skills/team-roadmap-dev/SKILL.md b/.claude/skills/team-roadmap-dev/SKILL.md index 0953559f..e405d277 100644 --- a/.claude/skills/team-roadmap-dev/SKILL.md +++ b/.claude/skills/team-roadmap-dev/SKILL.md @@ -159,9 +159,10 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team="roadmap-dev", from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **CLI fallback**: When MCP unavailable → `ccw team log --team roadmap-dev --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` -2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) + - 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 @@ -362,7 +363,9 @@ Session: <session-folder> │ └── verification.md ├── phase-2/ │ └── ... -└── shared-memory.json # Cross-role state +├── .msg/ +│ ├── messages.jsonl # Team message bus log +│ └── meta.json # Session metadata + shared state ``` ## Session Resume diff --git a/.claude/skills/team-roadmap-dev/role-specs/executor.md b/.claude/skills/team-roadmap-dev/role-specs/executor.md new file mode 100644 index 00000000..0abca649 --- /dev/null +++ b/.claude/skills/team-roadmap-dev/role-specs/executor.md @@ -0,0 +1,60 @@ +--- +prefix: EXEC +inner_loop: true +subagents: + - code-developer +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 code-developer subagent. 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 code-developer for all | +| > 5 | Batch: one code-developer 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 code-developer subagent (`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/role-specs/planner.md b/.claude/skills/team-roadmap-dev/role-specs/planner.md new file mode 100644 index 00000000..7ae1353b --- /dev/null +++ b/.claude/skills/team-roadmap-dev/role-specs/planner.md @@ -0,0 +1,60 @@ +--- +prefix: PLAN +inner_loop: true +subagents: + - cli-explore-agent + - action-planning-agent +message_types: + success: plan_ready + progress: plan_progress + error: error +--- + +# Planner + +Research and plan creation per roadmap phase. Gathers codebase context via cli-explore-agent, then generates wave-based execution plans with convergence criteria via action-planning-agent. + +## 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-explore-agent with phase requirements as exploration query: + - 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 action-planning-agent with: + - Phase context + roadmap section + prior summaries + - Task ID format: `IMPL-{phase}{seq}` (e.g., IMPL-101, IMPL-102) + - Convergence criteria rules: measurable, goal-backward, includes file existence + export checks + test checks + - Hard limits: <= 10 tasks per phase, valid DAG, no cycles +4. Agent 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/role-specs/verifier.md b/.claude/skills/team-roadmap-dev/role-specs/verifier.md new file mode 100644 index 00000000..192291d9 --- /dev/null +++ b/.claude/skills/team-roadmap-dev/role-specs/verifier.md @@ -0,0 +1,72 @@ +--- +prefix: VERIFY +inner_loop: true +subagents: [] +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/roles/coordinator/commands/dispatch.md b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/dispatch.md index 98f62100..bf28dc98 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/dispatch.md @@ -147,10 +147,9 @@ Edit(`${sessionFolder}/state.md`, { ```javascript mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, // MUST be session ID (e.g., RD-xxx-date), NOT team name + operation: "log", session_id: sessionId, from: "coordinator", to: "all", type: "phase_started", - summary: `[coordinator] Phase ${phaseNumber} dispatched: PLAN-${phaseNumber}01 → EXEC-${phaseNumber}01 → VERIFY-${phaseNumber}01`, ref: `${sessionFolder}/roadmap.md` }) ``` 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 d3ce0b41..97f21979 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/monitor.md @@ -171,26 +171,25 @@ function spawnPlanner(phase, gapIteration, sessionFolder) { // Synchronous call - blocks until planner returns Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn planner worker for phase ${phase}`, team_name: "roadmap-dev", name: "planner", - prompt: `You are the PLANNER for team "roadmap-dev". + prompt: `## Role Assignment +role: planner +role_spec: .claude/skills/team-roadmap-dev/role-specs/planner.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: roadmap-dev +requirement: Phase ${phase} planning${gapContext} +inner_loop: false -## Primary Directive -Skill(skill="team-roadmap-dev", args="--role=planner") - -## Assignment -- Session: ${sessionFolder} +## Current Task +- Task: PLAN-${phase}${suffix} - Phase: ${phase} -- Task: PLAN-${phase}${suffix}${gapContext} -## Workflow -1. Skill(skill="team-roadmap-dev", args="--role=planner") -2. TaskList → find PLAN-${phase}${suffix} → execute -3. TaskUpdate completed when done - -All outputs carry [planner] tag.`, +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 // CRITICAL: Stop-Wait, blocks until done }) } @@ -203,26 +202,25 @@ function spawnExecutor(phase, gapIteration, sessionFolder) { const suffix = gapIteration === 0 ? "01" : `0${gapIteration + 1}` Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn executor worker for phase ${phase}`, team_name: "roadmap-dev", name: "executor", - prompt: `You are the EXECUTOR for team "roadmap-dev". + prompt: `## Role Assignment +role: executor +role_spec: .claude/skills/team-roadmap-dev/role-specs/executor.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: roadmap-dev +requirement: Phase ${phase} execution +inner_loop: false -## Primary Directive -Skill(skill="team-roadmap-dev", args="--role=executor") - -## Assignment -- Session: ${sessionFolder} -- Phase: ${phase} +## Current Task - Task: EXEC-${phase}${suffix} +- Phase: ${phase} -## Workflow -1. Skill(skill="team-roadmap-dev", args="--role=executor") -2. TaskList → find EXEC-${phase}${suffix} → execute plans -3. TaskUpdate completed when done - -All outputs carry [executor] tag.`, +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 // CRITICAL: Stop-Wait }) } @@ -235,26 +233,25 @@ function spawnVerifier(phase, gapIteration, sessionFolder) { const suffix = gapIteration === 0 ? "01" : `0${gapIteration + 1}` Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn verifier worker for phase ${phase}`, team_name: "roadmap-dev", name: "verifier", - prompt: `You are the VERIFIER for team "roadmap-dev". + prompt: `## Role Assignment +role: verifier +role_spec: .claude/skills/team-roadmap-dev/role-specs/verifier.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: roadmap-dev +requirement: Phase ${phase} verification +inner_loop: false -## Primary Directive -Skill(skill="team-roadmap-dev", args="--role=verifier") - -## Assignment -- Session: ${sessionFolder} -- Phase: ${phase} +## Current Task - Task: VERIFY-${phase}${suffix} +- Phase: ${phase} -## Workflow -1. Skill(skill="team-roadmap-dev", args="--role=verifier") -2. TaskList → find VERIFY-${phase}${suffix} → verify against success criteria -3. TaskUpdate completed when done - -All outputs carry [verifier] tag.`, +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 // CRITICAL: Stop-Wait }) } @@ -271,7 +268,6 @@ function triggerGapClosure(phase, iteration, gaps, sessionFolder) { operation: "log", team: sessionId // MUST be session ID (e.g., RD-xxx-date), NOT team name, from: "coordinator", to: "planner", type: "gap_closure", - summary: `[coordinator] Gap closure iteration ${iteration} for phase ${phase}: ${gaps.length} gaps`, ref: `${sessionFolder}/phase-${phase}/verification.md` }) @@ -337,7 +333,6 @@ mcp__ccw-tools__team_msg({ operation: "log", team: sessionId // MUST be session ID (e.g., RD-xxx-date), NOT team name, from: "coordinator", to: "all", type: "project_complete", - summary: `[coordinator] All ${totalPhases} phases complete.`, ref: `${sessionFolder}/roadmap.md` }) ``` diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/pause.md b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/pause.md index 9ea542d0..217a8067 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/pause.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/pause.md @@ -55,10 +55,9 @@ Edit(`${sessionFolder}/state.md`, { ```javascript mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", + operation: "log", session_id: sessionId, from: "coordinator", to: "all", type: "phase_paused", - summary: `[coordinator] Session paused at phase ${currentPhase}, step: ${currentStep}`, ref: `${sessionFolder}/state.md` }) ``` diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/resume.md b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/resume.md index 8a271999..2b43cac7 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/commands/resume.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/commands/resume.md @@ -67,10 +67,9 @@ Edit(`${sessionFolder}/state.md`, { ```javascript mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", + operation: "log", session_id: sessionId, from: "coordinator", to: "all", type: "phase_started", - summary: `[coordinator] Session resumed at phase ${pausedPhase}, step: ${pausedStep}`, ref: `${sessionFolder}/state.md` }) ``` diff --git a/.claude/skills/team-roadmap-dev/roles/coordinator/role.md b/.claude/skills/team-roadmap-dev/roles/coordinator/role.md index 0739d878..648eb97b 100644 --- a/.claude/skills/team-roadmap-dev/roles/coordinator/role.md +++ b/.claude/skills/team-roadmap-dev/roles/coordinator/role.md @@ -37,16 +37,58 @@ Orchestrate the roadmap-driven development workflow: init prerequisites -> roadm --- +## Command Execution Protocol + +When coordinator needs to execute a command (dispatch, monitor, pause, resume): + +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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| +| Worker callback | Message contains role tag [planner], [executor], [verifier] | -> handleCallback | | Resume mode | Arguments contain `--resume` | -> commands/resume.md: load session, re-enter monitor | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual continue | Arguments contain "resume" or "continue" | -> handleContinue: check worker states, advance pipeline | -| New session | None of the above | -> Phase 1 (Init Prerequisites) | +| 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 (Init Prerequisites) | + +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/RD-*/.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", "--resume" keywords + +3. **Route to handler**: + - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP + - For --resume: Read `commands/resume.md`, execute resume flow + - For Phase 0: Execute Session Resume Check + - For Phase 1: Execute Init Prerequisites below --- @@ -92,11 +134,10 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "coordinator", to: <target-role>, type: <message-type>, - summary: "[coordinator] <summary>", ref: <artifact-path> }) ``` @@ -104,7 +145,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from coordinator --to <target> --type <type> --summary \"[coordinator] <summary>\" --json") +Bash("ccw team log --session-id <session-id> --from coordinator --type <type> --json") ``` --- diff --git a/.claude/skills/team-roadmap-dev/roles/executor/commands/implement.md b/.claude/skills/team-roadmap-dev/roles/executor/commands/implement.md index 45177523..e1d0a22f 100644 --- a/.claude/skills/team-roadmap-dev/roles/executor/commands/implement.md +++ b/.claude/skills/team-roadmap-dev/roles/executor/commands/implement.md @@ -203,10 +203,9 @@ ${(task.convergence?.criteria || []).map(c => `- [ ] ${c}`).join('\n')} // 2e. Report wave progress mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "executor", to: "coordinator", + operation: "log", session_id: sessionId, + from: "executor", type: "exec_progress", - summary: `[executor] Wave ${waveNum}/${totalWaves} complete (${completedTasks}/${totalTasks} tasks done)`, ref: `${sessionFolder}/phase-${phaseNumber}/` }) } @@ -216,10 +215,9 @@ ${(task.convergence?.criteria || []).map(c => `- [ ] ${c}`).join('\n')} ```javascript mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "executor", to: "coordinator", + operation: "log", session_id: sessionId, + from: "executor", type: "exec_complete", - summary: `[executor] All ${totalTasks} tasks executed across ${totalWaves} waves for phase ${phaseNumber}`, ref: `${sessionFolder}/phase-${phaseNumber}/` }) ``` diff --git a/.claude/skills/team-roadmap-dev/roles/executor/role.md b/.claude/skills/team-roadmap-dev/roles/executor/role.md index 1add3059..5d79168b 100644 --- a/.claude/skills/team-roadmap-dev/roles/executor/role.md +++ b/.claude/skills/team-roadmap-dev/roles/executor/role.md @@ -69,11 +69,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "executor", - to: "coordinator", type: <message-type>, - summary: "[executor] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -81,7 +79,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from executor --to coordinator --type <type> --summary \"[executor] <summary>\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from executor --type <type> --ref <artifact-path> --json") ``` --- @@ -192,7 +190,6 @@ Standard report flow: team_msg log -> SendMessage with `[executor]` prefix -> Ta **Report message**: ``` SendMessage({ - to: "coordinator", message: "[executor] Phase <N> execution complete. - Tasks executed: <count> - Waves: <wave-count> diff --git a/.claude/skills/team-roadmap-dev/roles/planner/commands/create-plans.md b/.claude/skills/team-roadmap-dev/roles/planner/commands/create-plans.md index 53b40c58..22e6fb34 100644 --- a/.claude/skills/team-roadmap-dev/roles/planner/commands/create-plans.md +++ b/.claude/skills/team-roadmap-dev/roles/planner/commands/create-plans.md @@ -168,10 +168,9 @@ Each task: cli_execution.id = "RD-${sessionFolder.split('/').pop()}-{task_id}" const taskFiles = Glob(`${taskDir}/IMPL-*.json`) if (!taskFiles || taskFiles.length === 0) { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "error", - summary: `[planner] action-planning-agent produced no task JSONs for phase ${phaseNumber}` }) return } @@ -185,10 +184,9 @@ for (const taskFile of taskFiles) { for (const field of requiredFields) { if (!taskJson[field]) { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: `[planner] Warning: ${taskFile} missing field: ${field}` }) } } @@ -196,20 +194,18 @@ for (const taskFile of taskFiles) { // Convergence criteria check if (!taskJson.convergence?.criteria || taskJson.convergence.criteria.length === 0) { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: `[planner] Warning: ${taskFile} has no convergence criteria` }) } // Dependency cycle check (simple: task cannot depend on itself) if (taskJson.depends_on?.includes(taskJson.id)) { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "error", - summary: `[planner] Self-dependency detected in ${taskJson.id}` }) } } @@ -223,10 +219,9 @@ for (const task of allTasks) { for (const dep of (task.depends_on || [])) { if (!taskIds.has(dep)) { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: `[planner] Warning: ${task.id} depends on unknown task ${dep}` }) } } @@ -236,10 +231,9 @@ for (const task of allTasks) { const implPlanExists = Bash(`test -f "${implPlanPath}" && echo "EXISTS" || echo "NOT_FOUND"`).trim() if (implPlanExists === "NOT_FOUND") { mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: `[planner] Warning: IMPL_PLAN.md not generated, creating minimal version` }) // Create minimal IMPL_PLAN.md from task JSONs generateMinimalImplPlan(allTasks, implPlanPath, phaseGoal, phaseNumber) @@ -284,10 +278,9 @@ const { waves, totalWaves } = computeWaves(allTasks) const taskCount = allTasks.length mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: `[planner] Created ${taskCount} tasks across ${totalWaves} waves for phase ${phaseNumber}`, ref: `${sessionFolder}/phase-${phaseNumber}/` }) diff --git a/.claude/skills/team-roadmap-dev/roles/planner/role.md b/.claude/skills/team-roadmap-dev/roles/planner/role.md index def9093f..9cabd2ba 100644 --- a/.claude/skills/team-roadmap-dev/roles/planner/role.md +++ b/.claude/skills/team-roadmap-dev/roles/planner/role.md @@ -71,11 +71,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "planner", - to: "coordinator", type: <message-type>, - summary: "[planner] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -83,7 +81,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from planner --to coordinator --type <type> --summary \"[planner] <summary>\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from planner --type <type> --ref <artifact-path> --json") ``` --- @@ -129,10 +127,9 @@ Delegate to `commands/research.md`: **Report progress via team_msg**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: "roadmap-dev", - from: "planner", to: "coordinator", + operation: "log", session_id: sessionId, + from: "planner", type: "plan_progress", - summary: "[planner] Research complete for phase <N>. Context written.", ref: "<session>/phase-<N>/context.md" }) ``` @@ -211,7 +208,6 @@ Standard report flow: team_msg log -> SendMessage with `[planner]` prefix -> Tas **Report message**: ``` SendMessage({ - to: "coordinator", message: "[planner] Phase <N> planning complete. - Tasks: <count> - Waves: <wave-count> diff --git a/.claude/skills/team-roadmap-dev/roles/verifier/role.md b/.claude/skills/team-roadmap-dev/roles/verifier/role.md index 81336eb0..3a3e88a1 100644 --- a/.claude/skills/team-roadmap-dev/roles/verifier/role.md +++ b/.claude/skills/team-roadmap-dev/roles/verifier/role.md @@ -70,11 +70,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., RD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "verifier", - to: "coordinator", type: <message-type>, - summary: "[verifier] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -82,7 +80,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from verifier --to coordinator --type <type> --summary \"[verifier] <summary>\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from verifier --type <type> --ref <artifact-path> --json") ``` --- @@ -218,7 +216,6 @@ Standard report flow: team_msg log -> SendMessage with `[verifier]` prefix -> Ta **Report message**: ``` SendMessage({ - to: "coordinator", message: "[verifier] Phase <N> verification complete. - Status: <status> - Tasks: <passed>/<total> passed diff --git a/.claude/skills/team-tech-debt/SKILL.md b/.claude/skills/team-tech-debt/SKILL.md index b9ef6ab7..e8704f08 100644 --- a/.claude/skills/team-tech-debt/SKILL.md +++ b/.claude/skills/team-tech-debt/SKILL.md @@ -61,7 +61,7 @@ roles/ ### Input Parsing -Parse `$ARGUMENTS` to extract `--role` and optional `--agent-name`, `--team` (default: "tech-debt"), `--mode` (scan/remediate/targeted). +Parse `$ARGUMENTS` to extract `--role` and optional `--agent-name`, `--mode` (scan/remediate/targeted). If no `--role` -> Orchestration Mode (auto route to coordinator). @@ -134,7 +134,7 @@ If no `--role` -> Orchestration Mode (auto route to coordinator). |-----|-------| | name | tech-debt | | sessionDir | `.workflow/.team/TD-{slug}-{date}/` | -| sharedMemory | shared-memory.json | +| 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) | @@ -166,7 +166,7 @@ If no `--role` -> Orchestration Mode (auto route to coordinator). | 允许 | 禁止 | |------|------| | 处理自己前缀的任务 | 处理其他角色前缀的任务 | -| 读写 shared-memory.json (自己的字段) | 为其他角色创建任务 | +| Share state via team_msg(type='state_update') | 为其他角色创建任务 | | SendMessage 给 coordinator | 直接与其他 worker 通信 | ### Worker Phase 1: Task Discovery (所有 worker 共享) @@ -188,9 +188,10 @@ If no `--role` -> Orchestration Mode (auto route to coordinator). 任务完成后的标准报告流程: 1. **Message Bus**: 调用 `mcp__ccw-tools__team_msg` 记录消息 - - 参数: operation="log", team=`<team-name>`, from=`<role>`, to="coordinator", type=`<消息类型>`, summary="[`<role>`] `<摘要>`", ref=`<产物路径>` - - **CLI fallback**: 当 MCP 不可用时 -> `ccw team log --team <team> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` -2. **SendMessage**: 发送结果给 coordinator (content 和 summary 都带 `[<role>]` 前缀) + - 参数: 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 检查下一个任务 @@ -429,8 +430,9 @@ Beat 1 ⏸ 2 3 ``` .workflow/.team/TD-{slug}-{YYYY-MM-DD}/ -├── team-session.json -├── shared-memory.json # 债务清单 / 评估矩阵 / 治理方案 / 修复结果 / 验证结果 / worktree 信息 +├── .msg/ +│ ├── messages.jsonl # Team message bus log +│ └── meta.json # Session metadata + shared state ├── scan/ # Scanner output │ └── debt-inventory.json ├── assessment/ # Assessor output @@ -447,7 +449,7 @@ Beat 1 ⏸ 2 3 ├── conventions.md └── issues.md -# shared-memory.json worktree 字段(TDFIX 前由 coordinator 写入): +# .msg/meta.json worktree 字段(TDFIX 前由 coordinator 写入): # { # ... # "worktree": { diff --git a/.claude/skills/team-tech-debt/role-specs/assessor.md b/.claude/skills/team-tech-debt/role-specs/assessor.md new file mode 100644 index 00000000..975cfced --- /dev/null +++ b/.claude/skills/team-tech-debt/role-specs/assessor.md @@ -0,0 +1,70 @@ +--- +prefix: TDEVAL +inner_loop: false +message_types: + success: assessment_complete + error: error +--- + +# 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/role-specs/executor.md b/.claude/skills/team-tech-debt/role-specs/executor.md new file mode 100644 index 00000000..b413c351 --- /dev/null +++ b/.claude/skills/team-tech-debt/role-specs/executor.md @@ -0,0 +1,68 @@ +--- +prefix: TDFIX +inner_loop: true +message_types: + success: fix_complete + progress: fix_progress + error: error +--- + +# Tech Debt Executor + +Debt cleanup executor. Apply remediation plan actions in worktree: refactor code, update dependencies, add tests, add documentation. Batch-delegate to code-developer subagent, 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, delegate to `code-developer` subagent (synchronous, `run_in_background: false`): + +**Worktree constraint**: ALL file operations and commands must execute within worktree path. Use `cd "<worktree-path>" && ...` prefix for all Bash commands. + +**Per-batch delegation**: +- Provide batch type prompt (refactor/update-deps/add-tests/add-docs/restructure) +- List all items with file paths, descriptions, and fix steps +- Enforce: read files before modifying, minimal changes, backward compatibility, no new features, no suppressions + +**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/role-specs/planner.md b/.claude/skills/team-tech-debt/role-specs/planner.md new file mode 100644 index 00000000..5a859811 --- /dev/null +++ b/.claude/skills/team-tech-debt/role-specs/planner.md @@ -0,0 +1,71 @@ +--- +prefix: TDPLAN +inner_loop: false +message_types: + success: plan_ready + revision: plan_revision + error: error +--- + +# 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/role-specs/scanner.md b/.claude/skills/team-tech-debt/role-specs/scanner.md new file mode 100644 index 00000000..d2b6aebd --- /dev/null +++ b/.claude/skills/team-tech-debt/role-specs/scanner.md @@ -0,0 +1,84 @@ +--- +prefix: TDSCAN +inner_loop: false +subagents: [] +message_types: + success: scan_complete + error: error + info: debt_items_found +--- + +# 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: subagent explore + CLI 5 dimensions + multi-perspective Gemini | +| 2-3 | Medium | Dual Fan-out: subagent 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: Subagent exploration (structure, patterns, dependencies angles) via `cli-explore-agent` +- 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/role-specs/validator.md b/.claude/skills/team-tech-debt/role-specs/validator.md new file mode 100644 index 00000000..38b6468c --- /dev/null +++ b/.claude/skills/team-tech-debt/role-specs/validator.md @@ -0,0 +1,70 @@ +--- +prefix: TDVAL +inner_loop: false +message_types: + success: validation_complete + error: error + fix: regression_found +--- + +# 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): +- Spawn code-developer subagent to fix regressions in worktree +- Constraints: fix only regressions, preserve debt cleanup changes, no suppressions +- Re-run 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/roles/assessor/role.md b/.claude/skills/team-tech-debt/roles/assessor/role.md index d3d80bdf..6aba8737 100644 --- a/.claude/skills/team-tech-debt/roles/assessor/role.md +++ b/.claude/skills/team-tech-debt/roles/assessor/role.md @@ -58,11 +58,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "assessor", - to: "coordinator", type: <message-type>, - summary: "[assessor] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -70,7 +68,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from assessor --to coordinator --type <message-type> --summary \"[assessor] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from assessor --type <message-type> --ref <artifact-path> --json") ``` --- @@ -88,13 +86,13 @@ Standard task discovery flow: TaskList -> filter by prefix `TDEVAL-*` + owner ma | Input | Source | Required | |-------|--------|----------| | Session folder | task.description (regex: `session:\s*(.+)`) | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | Yes | -| Debt inventory | shared-memory.debt_inventory OR `<session-folder>/scan/debt-inventory.json` | Yes | +| Shared memory | `<session-folder>/.msg/meta.json` | Yes | +| Debt inventory | meta.json:debt_inventory OR `<session-folder>/scan/debt-inventory.json` | Yes | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json +2. Read .msg/meta.json 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 @@ -156,7 +154,7 @@ Delegate to `commands/evaluate.md` if available, otherwise execute inline. **Save outputs**: 1. Write `<session-folder>/assessment/priority-matrix.json` -2. Update shared-memory.json with `priority_matrix` summary and evaluated `debt_inventory` +2. Update .msg/meta.json with `priority_matrix` summary and evaluated `debt_inventory` ### Phase 5: Report to Coordinator diff --git a/.claude/skills/team-tech-debt/roles/coordinator/commands/dispatch.md b/.claude/skills/team-tech-debt/roles/coordinator/commands/dispatch.md index 74359a6a..be8a34ff 100644 --- a/.claude/skills/team-tech-debt/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-tech-debt/roles/coordinator/commands/dispatch.md @@ -102,9 +102,8 @@ const chainValid = chainTasks.length === pipeline.length if (!chainValid) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", // team must be session ID (e.g., TD-xxx-date), NOT team name - to: "user", type: "error", - summary: `[coordinator] 任务链创建不完整: ${chainTasks.length}/${pipeline.length}` + operation: "log", session_id: sessionId, from: "coordinator", // team must be session ID (e.g., TD-xxx-date), NOT team name + type: "error", }) } ``` 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 d4c8bdfc..d77890e5 100644 --- a/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-tech-debt/roles/coordinator/commands/monitor.md @@ -47,7 +47,7 @@ const STAGE_WORKER_MAP = { ### Step 1: Context Preparation ```javascript -const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) let fixVerifyIteration = 0 const MAX_FIX_VERIFY_ITERATIONS = 3 @@ -76,9 +76,8 @@ for (const stageTask of pipelineTasks) { if (!workerConfig) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] 未知阶段前缀: ${stagePrefix},跳过` + operation: "log", session_id: sessionId, from: "coordinator", + type: "error", }) continue } @@ -87,15 +86,14 @@ for (const stageTask of pipelineTasks) { TaskUpdate({ taskId: stageTask.id, status: 'in_progress' }) mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: workerConfig.role, type: "task_unblocked", - summary: `[coordinator] 启动阶段: ${stageTask.subject} → ${workerConfig.role}` }) // 3. 同步 spawn worker — 阻塞直到 worker 返回(Stop-Wait 核心) // Task() 本身就是等待机制,无需 sleep/poll const workerResult = Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn ${workerConfig.role} worker for ${stageTask.subject}`, team_name: teamName, name: workerConfig.role, @@ -111,9 +109,8 @@ for (const stageTask of pipelineTasks) { handleStageFailure(stageTask, taskState, workerConfig, autoYes) } else { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "quality_gate", - summary: `[coordinator] 阶段完成: ${stageTask.subject}` + operation: "log", session_id: sessionId, from: "coordinator", + type: "quality_gate", }) } @@ -127,9 +124,8 @@ for (const stageTask of pipelineTasks) { } mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "plan_approval", - summary: `[coordinator] 治理方案已生成,等待审批` + operation: "log", session_id: sessionId, from: "coordinator", + type: "plan_approval", }) if (!autoYes) { @@ -166,9 +162,8 @@ for (const stageTask of pipelineTasks) { continue // 跳到下一阶段(即刚插入的修订任务) } else if (planDecision === "终止") { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "shutdown", - summary: `[coordinator] 用户终止流水线(方案审批阶段)` + operation: "log", session_id: sessionId, from: "coordinator", + type: "shutdown", }) break // 退出 pipeline 循环 } @@ -189,14 +184,13 @@ for (const stageTask of pipelineTasks) { // 存入 shared memory sharedMemory.worktree = { path: worktreePath, branch: branchName } - Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2)) + Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2)) worktreeCreated = true mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "worktree_created", - summary: `[coordinator] Worktree 已创建: ${worktreePath} (branch: ${branchName})` + operation: "log", session_id: sessionId, from: "coordinator", + type: "worktree_created", }) } @@ -231,32 +225,22 @@ function buildWorkerPrompt(stageTask, workerConfig, sessionFolder, taskDescripti - 禁止在主工作树中修改任何文件` } - return `你是 team "${teamName}" 的 ${workerConfig.role.toUpperCase()}。 + return `## Role Assignment +role: ${workerConfig.role} +role_spec: .claude/skills/team-tech-debt/role-specs/${workerConfig.role}.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: ${teamName} +requirement: ${stageTask.description || taskDescription} +inner_loop: false -## ⚠️ 首要指令(MUST) -你的所有工作必须通过调用 Skill 获取角色定义后执行,禁止自行发挥: -Skill(skill="team-tech-debt", args="${workerConfig.skillArgs}") -此调用会加载你的角色定义(role.md)、可用命令(commands/*.md)和完整执行逻辑。 - -## 当前任务 -- 任务 ID: ${stageTask.id} -- 任务: ${stageTask.subject} -- 描述: ${stageTask.description || taskDescription} -- Session: ${sessionFolder} +## Current Task +- Task ID: ${stageTask.id} +- Task: ${stageTask.subject} +- Task Prefix: ${stagePrefix} ${worktreeSection} -## 角色准则(强制) -- 你只能处理 ${stagePrefix}-* 前缀的任务 -- 所有输出必须带 [${workerConfig.role}] 标识前缀 -- 仅与 coordinator 通信,不得直接联系其他 worker - -## 消息总线(必须) -每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。 - -## 工作流程(严格按顺序) -1. 调用 Skill(skill="team-tech-debt", args="${workerConfig.skillArgs}") 获取角色定义和执行逻辑 -2. 按 role.md 中的 5-Phase 流程执行 -3. team_msg log + SendMessage 结果给 coordinator -4. TaskUpdate({ taskId: "${stageTask.id}", status: "completed" })` +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.` } ``` @@ -266,9 +250,8 @@ ${worktreeSection} function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { if (autoYes) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] [auto] 阶段 ${stageTask.subject} 未完成 (status=${taskState.status}),自动跳过` + operation: "log", session_id: sessionId, from: "coordinator", + type: "error", }) TaskUpdate({ taskId: stageTask.id, status: 'deleted' }) return 'skip' @@ -292,7 +275,7 @@ function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { // 重新 spawn worker(递归单次) TaskUpdate({ taskId: stageTask.id, status: 'in_progress' }) const retryResult = Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Retry ${workerConfig.role} worker for ${stageTask.subject}`, team_name: teamName, name: workerConfig.role, @@ -309,9 +292,8 @@ function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { return 'skip' } else { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "shutdown", - summary: `[coordinator] 用户终止流水线,当前阶段: ${stageTask.subject}` + operation: "log", session_id: sessionId, from: "coordinator", + type: "shutdown", }) return 'abort' } @@ -322,7 +304,7 @@ function handleStageFailure(stageTask, taskState, workerConfig, autoYes) { ```javascript function evaluateValidationResult(sessionFolder) { - const latestMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const latestMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const debtBefore = latestMemory.debt_score_before || 0 const debtAfter = latestMemory.debt_score_after || 0 const regressions = latestMemory.validation_results?.regressions || 0 @@ -333,9 +315,8 @@ function evaluateValidationResult(sessionFolder) { else if (!improved) status = 'CONDITIONAL' mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "quality_gate", - summary: `[coordinator] 质量门控: ${status} (债务分 ${debtBefore} → ${debtAfter}, 回归 ${regressions})` + operation: "log", session_id: sessionId, from: "coordinator", + type: "quality_gate", }) return regressions > 0 @@ -346,7 +327,7 @@ function evaluateValidationResult(sessionFolder) { ```javascript // 汇总所有结果 -const finalSharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const finalSharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`)) const allFinalTasks = TaskList() const workerTasks = allFinalTasks.filter(t => t.owner && t.owner !== 'coordinator') @@ -387,18 +368,16 @@ EOF )"`) mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "pr_created", - summary: `[coordinator] PR 已创建: branch ${branch}` + operation: "log", session_id: sessionId, from: "coordinator", + type: "pr_created", }) // Cleanup worktree Bash(`git worktree remove "${wtPath}" 2>/dev/null || true`) } else if (finalSharedMemory.worktree && !finalSharedMemory.validation_results?.passed) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId // MUST be session ID (e.g., TD-xxx-date), NOT team name, from: "coordinator", - to: "user", type: "quality_gate", - summary: `[coordinator] 验证未通过,worktree 保留于 ${finalSharedMemory.worktree.path},请手动检查` + operation: "log", session_id: sessionId, from: "coordinator", + type: "quality_gate", }) } diff --git a/.claude/skills/team-tech-debt/roles/coordinator/role.md b/.claude/skills/team-tech-debt/roles/coordinator/role.md index b6fa1f7f..8a9e8656 100644 --- a/.claude/skills/team-tech-debt/roles/coordinator/role.md +++ b/.claude/skills/team-tech-debt/roles/coordinator/role.md @@ -29,18 +29,56 @@ --- +## 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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline | -| New session | None of the above | -> Phase 0 (Session Resume Check) | +| 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) | +| New session | None of above | -> Phase 1 | -For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP. +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 --- @@ -86,11 +124,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "coordinator", - to: "user", type: <message-type>, - summary: "[coordinator] <summary>", ref: <artifact-path> }) ``` @@ -98,7 +134,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from coordinator --to user --type <message-type> --summary \"[coordinator] ...\" --json") +Bash("ccw team log --session-id <session-id> --from coordinator --type <message-type> --json") ``` --- @@ -188,7 +224,7 @@ Bash("ccw team log --team <session-id> --from coordinator --to user --type <mess └── issues.md ``` -3. Initialize shared-memory.json: +3. Initialize .msg/meta.json: | Field | Initial Value | |-------|---------------| @@ -308,7 +344,7 @@ Session: <session-folder> **Worktree Creation** (before TDFIX): 1. Create worktree: `git worktree add <path> -b <branch>` -2. Update shared-memory.json with worktree info +2. Update .msg/meta.json with worktree info 3. Notify user via team_msg **Fix-Verify Loop** (when TDVAL finds regressions): diff --git a/.claude/skills/team-tech-debt/roles/executor/role.md b/.claude/skills/team-tech-debt/roles/executor/role.md index d12f3961..1b1f1982 100644 --- a/.claude/skills/team-tech-debt/roles/executor/role.md +++ b/.claude/skills/team-tech-debt/roles/executor/role.md @@ -61,11 +61,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "executor", - to: "coordinator", type: <message-type>, - summary: "[executor] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -73,7 +71,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from executor --to coordinator --type <message-type> --summary \"[executor] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from executor --type <message-type> --ref <artifact-path> --json") ``` --- @@ -91,13 +89,13 @@ Standard task discovery flow: TaskList -> filter by prefix `TDFIX-*` + owner mat | Input | Source | Required | |-------|--------|----------| | Session folder | task.description (regex: `session:\s*(.+)`) | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | Yes | +| Shared memory | `<session-folder>/.msg/meta.json` | Yes | | Remediation plan | `<session-folder>/plan/remediation-plan.json` | Yes | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json for worktree info: +2. Read .msg/meta.json for worktree info: | Field | Description | |-------|-------------| @@ -194,7 +192,7 @@ Execute tech debt cleanup for <batch-type> items. 2. Run lint check -> record PASS/FAIL 3. Update fix_results.self_validation 4. Write `<session-folder>/fixes/fix-log.json` -5. Update shared-memory.json with fix_results +5. Update .msg/meta.json with fix_results ### Phase 5: Report to Coordinator diff --git a/.claude/skills/team-tech-debt/roles/planner/role.md b/.claude/skills/team-tech-debt/roles/planner/role.md index 2c0ba993..f6a16707 100644 --- a/.claude/skills/team-tech-debt/roles/planner/role.md +++ b/.claude/skills/team-tech-debt/roles/planner/role.md @@ -58,11 +58,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "planner", - to: "coordinator", type: <message-type>, - summary: "[planner] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -70,7 +68,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from planner --to coordinator --type <message-type> --summary \"[planner] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from planner --type <message-type> --ref <artifact-path> --json") ``` --- @@ -88,13 +86,13 @@ Standard task discovery flow: TaskList -> filter by prefix `TDPLAN-*` + owner ma | Input | Source | Required | |-------|--------|----------| | Session folder | task.description (regex: `session:\s*(.+)`) | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | Yes | +| Shared memory | `<session-folder>/.msg/meta.json` | Yes | | Priority matrix | `<session-folder>/assessment/priority-matrix.json` | Yes | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json for debt_inventory +2. Read .msg/meta.json for debt_inventory 3. Read priority-matrix.json for quadrant groupings 4. Group items by priority quadrant: @@ -157,7 +155,7 @@ Delegate to `commands/create-plan.md` if available, otherwise execute inline. 1. Write `<session-folder>/plan/remediation-plan.md` (markdown format) 2. Write `<session-folder>/plan/remediation-plan.json` (machine-readable) -3. Update shared-memory.json with `remediation_plan` summary +3. Update .msg/meta.json with `remediation_plan` summary ### Phase 5: Report to Coordinator diff --git a/.claude/skills/team-tech-debt/roles/scanner/role.md b/.claude/skills/team-tech-debt/roles/scanner/role.md index c0224c3e..71436608 100644 --- a/.claude/skills/team-tech-debt/roles/scanner/role.md +++ b/.claude/skills/team-tech-debt/roles/scanner/role.md @@ -58,11 +58,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "scanner", - to: "coordinator", type: <message-type>, - summary: "[scanner] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -70,7 +68,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from scanner --to coordinator --type <message-type> --summary \"[scanner] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from scanner --type <message-type> --ref <artifact-path> --json") ``` --- @@ -89,12 +87,12 @@ Standard task discovery flow: TaskList -> filter by prefix `TDSCAN-*` + owner ma |-------|--------|----------| | Scan scope | task.description (regex: `scope:\s*(.+)`) | No (default: `**/*`) | | Session folder | task.description (regex: `session:\s*(.+)`) | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | Yes | +| Shared memory | `<session-folder>/.msg/meta.json` | Yes | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json for team context +2. Read .msg/meta.json for team context 3. Detect project type and framework: | Detection | Method | @@ -182,7 +180,7 @@ For each finding, create entry: **Save outputs**: -1. Update shared-memory.json with `debt_inventory` and `debt_score_before` +1. Update .msg/meta.json with `debt_inventory` and `debt_score_before` 2. Write `<session-folder>/scan/debt-inventory.json`: | Field | Description | diff --git a/.claude/skills/team-tech-debt/roles/validator/role.md b/.claude/skills/team-tech-debt/roles/validator/role.md index 03e79bf2..8faea1ff 100644 --- a/.claude/skills/team-tech-debt/roles/validator/role.md +++ b/.claude/skills/team-tech-debt/roles/validator/role.md @@ -59,11 +59,9 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TD-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "validator", - to: "coordinator", type: <message-type>, - summary: "[validator] <task-prefix> complete: <task-subject>", ref: <artifact-path> }) ``` @@ -71,7 +69,7 @@ mcp__ccw-tools__team_msg({ **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from validator --to coordinator --type <message-type> --summary \"[validator] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from validator --type <message-type> --ref <artifact-path> --json") ``` --- @@ -89,13 +87,13 @@ Standard task discovery flow: TaskList -> filter by prefix `TDVAL-*` + owner mat | Input | Source | Required | |-------|--------|----------| | Session folder | task.description (regex: `session:\s*(.+)`) | Yes | -| Shared memory | `<session-folder>/shared-memory.json` | Yes | +| Shared memory | `<session-folder>/.msg/meta.json` | Yes | | Fix log | `<session-folder>/fixes/fix-log.json` | No | **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json for: +2. Read .msg/meta.json for: | Field | Description | |-------|-------------| @@ -198,7 +196,7 @@ Delegate to `commands/verify.md` if available, otherwise execute inline. **Save outputs**: 1. Write `<session-folder>/validation/validation-report.json` -2. Update shared-memory.json with `validation_results` and `debt_score_after` +2. Update .msg/meta.json with `validation_results` and `debt_score_after` ### Phase 5: Report to Coordinator diff --git a/.claude/skills/team-tech-debt/specs/team-config.json b/.claude/skills/team-tech-debt/specs/team-config.json index abffe69d..0de6ce83 100644 --- a/.claude/skills/team-tech-debt/specs/team-config.json +++ b/.claude/skills/team-tech-debt/specs/team-config.json @@ -96,7 +96,7 @@ }, "shared_memory": { - "file": "shared-memory.json", + "file": ".msg/meta.json", "fields": { "debt_inventory": { "owner": "scanner", "type": "array" }, "assessment_matrix": { "owner": "assessor", "type": "object" }, diff --git a/.claude/skills/team-testing/SKILL.md b/.claude/skills/team-testing/SKILL.md index 54d56f9b..0ebe0f82 100644 --- a/.claude/skills/team-testing/SKILL.md +++ b/.claude/skills/team-testing/SKILL.md @@ -11,23 +11,23 @@ Unified team skill: progressive test coverage through Generator-Critic loops (ge ## Architecture ``` -┌───────────────────────────────────────────────────┐ -│ Skill(skill="team-testing") │ -│ args="<task>" or args="--role=xxx" │ -└───────────────────┬───────────────────────────────┘ - │ Role Router - ┌──── --role present? ────┐ - │ NO │ YES - ↓ ↓ - Orchestration Mode Role Dispatch - (auto → coordinator) (route to role.md) - │ - ┌────┴────┬───────────┬───────────┬───────────┐ - ↓ ↓ ↓ ↓ ↓ -┌──────────┐┌──────────┐┌──────────┐┌──────────┐┌─────────┐ -│coordinator││strategist││generator ││ executor ││ analyst │ -│ ││STRATEGY-*││TESTGEN-* ││TESTRUN-* ││TESTANA-*│ -└──────────┘└──────────┘└──────────┘└──────────┘└─────────┘ ++---------------------------------------------------+ +| Skill(skill="team-testing") | +| args="<task-description>" | ++-------------------+-------------------------------+ + | + Orchestration Mode (auto -> coordinator) + | + 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 ``` ## Role Router @@ -38,13 +38,13 @@ Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto r ### Role Registry -| Role | File | Task Prefix | Type | Compact | -|------|------|-------------|------|---------| -| coordinator | [roles/coordinator.md](roles/coordinator.md) | (none) | orchestrator | **⚠️ 压缩后必须重读** | -| strategist | [roles/strategist.md](roles/strategist.md) | STRATEGY-* | pipeline | 压缩后必须重读 | -| generator | [roles/generator.md](roles/generator.md) | TESTGEN-* | pipeline | 压缩后必须重读 | -| executor | [roles/executor.md](roles/executor.md) | TESTRUN-* | pipeline | 压缩后必须重读 | -| analyst | [roles/analyst.md](roles/analyst.md) | TESTANA-* | pipeline | 压缩后必须重读 | +| 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 | > **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 @@ -101,8 +101,9 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team="testing", from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` // team must be session ID + - 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 @@ -129,7 +130,7 @@ Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at se |---------|-----------| | Process tasks with own prefix | Process tasks with other role prefixes | | SendMessage to coordinator | Communicate directly with other workers | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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. @@ -142,11 +143,11 @@ All outputs must carry `[role_name]` prefix in both SendMessage content/summary Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: -**Parameters**: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> +**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} -> **CRITICAL**: `team` must be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. +> `to` and `summary` are auto-defaulted by the tool. -**CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` +**CLI fallback**: When MCP unavailable → `ccw team log --session-id <session-id> --from <role> --type <type> --json` **Message types by role**: @@ -158,9 +159,9 @@ Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: | executor | `tests_passed`, `tests_failed`, `coverage_report`, `error` | | analyst | `analysis_ready`, `error` | -### Shared Memory +### Shared State -All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: +All roles share state via `team_msg(type='state_update')` + `meta.json`: | Role | Field | |------|-------| @@ -175,7 +176,6 @@ All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: |---------|-------| | Team name | testing | | Session directory | `.workflow/.team/TST-<slug>-<date>/` | -| Shared memory | `shared-memory.json` in session dir | | Test layers | L1: Unit (80%), L2: Integration (60%), L3: E2E (40%) | --- @@ -330,8 +330,8 @@ Session: <session-folder> ``` .workflow/.team/TST-<slug>-<YYYY-MM-DD>/ -├── team-session.json # Session state -├── shared-memory.json # Defect patterns / effective test patterns / coverage history +├── .msg/messages.jsonl # Message bus log +├── .msg/meta.json # Session metadata ├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md diff --git a/.claude/skills/team-testing/role-specs/analyst.md b/.claude/skills/team-testing/role-specs/analyst.md new file mode 100644 index 00000000..1a553c63 --- /dev/null +++ b/.claude/skills/team-testing/role-specs/analyst.md @@ -0,0 +1,94 @@ +--- +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/role-specs/executor.md b/.claude/skills/team-testing/role-specs/executor.md new file mode 100644 index 00000000..a5daae5a --- /dev/null +++ b/.claude/skills/team-testing/role-specs/executor.md @@ -0,0 +1,92 @@ +--- +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 code-developer subagent | +| 6 | Increment iteration; >= 3 -> exit with failures | + +``` +Bash("<test-command> 2>&1 || true") +``` + +**Auto-fix delegation** (on failure): + +``` +Task({ + subagent_type: "code-developer", + run_in_background: false, + description: "Fix test failures (iteration <N>)", + prompt: "Fix these test failures:\n<test-output>\nOnly fix test files, not source code." +}) +``` + +**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/role-specs/generator.md b/.claude/skills/team-testing/role-specs/generator.md new file mode 100644 index 00000000..2349a8b1 --- /dev/null +++ b/.claude/skills/team-testing/role-specs/generator.md @@ -0,0 +1,92 @@ +--- +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 + +**Agent delegation** (medium/high complexity): + +``` +Task({ + subagent_type: "code-developer", + run_in_background: false, + description: "Generate <layer> tests", + prompt: "Generate <layer> tests using <framework>... + <file-list-with-content> + <if-revision: previous failures + effective patterns> + Write test files to: <session>/tests/<layer>/" +}) +``` + +**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/role-specs/strategist.md b/.claude/skills/team-testing/role-specs/strategist.md new file mode 100644 index 00000000..b51a8ee1 --- /dev/null +++ b/.claude/skills/team-testing/role-specs/strategist.md @@ -0,0 +1,82 @@ +--- +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/roles/analyst.md b/.claude/skills/team-testing/roles/analyst.md index ae5fd6ce..6a9ac535 100644 --- a/.claude/skills/team-testing/roles/analyst.md +++ b/.claude/skills/team-testing/roles/analyst.md @@ -16,8 +16,8 @@ Test quality analyst. Responsible for defect pattern analysis, coverage gap iden - All output (SendMessage, team_msg, logs) must carry `[analyst]` identifier - Only communicate with coordinator via SendMessage - Work strictly within read-only analysis responsibility scope -- Phase 2: Read shared-memory.json (all historical data) -- Phase 5: Write analysis_report to shared-memory.json +- Phase 2: Read role states via team_msg(operation='get_state') +- Phase 5: Share analysis_report via team_msg(type='state_update') ### MUST NOT @@ -35,7 +35,7 @@ Test quality analyst. Responsible for defect pattern analysis, coverage gap iden | Tool | Type | Used By | Purpose | |------|------|---------|---------| -| Read | Read | Phase 2 | Load shared-memory.json, strategy, results | +| Read | Read | Phase 2 | Load role states, strategy, results | | Glob | Read | Phase 2 | Find result files, test files | | Write | Write | Phase 3 | Create quality-report.md | | TaskUpdate | Write | Phase 5 | Mark task completed | @@ -57,19 +57,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "analyst", - to: "coordinator", type: <message-type>, - summary: "[analyst] TESTANA complete: <summary>", - ref: <artifact-path> + data: {ref: "<artifact-path>"} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from analyst --to coordinator --type <message-type> --summary \"[analyst] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from analyst --type <message-type> --json") ``` --- @@ -89,7 +87,7 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTANA-*` + owner m | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Role state | team_msg(operation="get_state", session_id=<session-id>) | Yes | | Execution results | <session-folder>/results/run-*.json | Yes | | Test strategy | <session-folder>/strategy/test-strategy.md | Yes | | Test files | <session-folder>/tests/**/* | Yes | @@ -98,10 +96,10 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTANA-*` + owner m 1. Extract session path from task description (look for `Session: <path>`) -2. Read shared memory: +2. Read role states: ``` -Read("<session-folder>/shared-memory.json") +mcp__ccw-tools__team_msg({ operation: "get_state", session_id: <session-id> }) ``` 3. Read all execution results: @@ -186,7 +184,7 @@ Write("<session-folder>/analysis/quality-report.md", <report-content>) **Historical comparison**: ``` -Glob({ pattern: ".workflow/.team/TST-*/shared-memory.json" }) +Glob({ pattern: ".workflow/.team/TST-*/.msg/meta.json" }) ``` If multiple sessions exist: @@ -198,27 +196,31 @@ If multiple sessions exist: > See SKILL.md Shared Infrastructure -> Worker Phase 5: Report -1. **Update shared memory**: +1. **Share analysis report via team_msg(type='state_update')**: ``` -sharedMemory.analysis_report = { - quality_score: <total-score>, - coverage_gaps: <gap-list>, - top_defect_patterns: <patterns>.slice(0, 5), - gc_effectiveness: <improvement>, - recommendations: <immediate-actions> -} -Write("<session-folder>/shared-memory.json", <updated-json>) +mcp__ccw-tools__team_msg({ + operation: "log", session_id: <session-id>, from: "analyst", + type: "state_update", + data: { + analysis_report: { + quality_score: <total-score>, + coverage_gaps: <gap-list>, + top_defect_patterns: <patterns>.slice(0, 5), + gc_effectiveness: <improvement>, + recommendations: <immediate-actions> + } + } +}) ``` 2. **Log via team_msg**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id> // MUST be session ID, NOT team name, from: "analyst", to: "coordinator", + operation: "log", session_id: <session-id>, from: "analyst", type: "analysis_ready", - summary: "[analyst] Quality report: score <score>/10, <pattern-count> defect patterns, <gap-count> coverage gaps", - ref: "<session-folder>/analysis/quality-report.md" + data: {ref: "<session-folder>/analysis/quality-report.md"} }) ``` diff --git a/.claude/skills/team-testing/roles/coordinator.md b/.claude/skills/team-testing/roles/coordinator.md index c30ef0da..3e1050b7 100644 --- a/.claude/skills/team-testing/roles/coordinator.md +++ b/.claude/skills/team-testing/roles/coordinator.md @@ -134,27 +134,44 @@ Extract changed files and modules for pipeline selection. 3. Call TeamCreate with team name 4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md) -5. Initialize shared memory: +5. Initialize shared state via `team_msg(type='state_update')` and write `meta.json`: ``` -Write("<session-folder>/shared-memory.json", { - task: <description>, - pipeline: <selected-pipeline>, - changed_files: [...], - changed_modules: [...], - coverage_targets: {...}, - gc_round: 0, - max_gc_rounds: 3, - test_strategy: null, - generated_tests: [], - execution_results: [], - defect_patterns: [], - effective_test_patterns: [], - coverage_history: [] +Write("<session-folder>/.msg/meta.json", { + session_id: <session-id>, + mode: <selected-mode>, + scope: <scope>, + status: "active" }) ``` -6. Write session file with: session_id, mode, scope, status="active" +6. Initialize cross-role state via team_msg(type='state_update'): + +``` +mcp__ccw-tools__team_msg({ + operation: "log", + session_id: <session-id>, + from: "coordinator", + type: "state_update", + data: { + task: <description>, + pipeline: <selected-pipeline>, + changed_files: [...], + changed_modules: [...], + coverage_targets: {...}, + gc_round: 0, + max_gc_rounds: 3, + test_strategy: null, + generated_tests: [], + execution_results: [], + defect_patterns: [], + effective_test_patterns: [], + coverage_history: [] + } +}) +``` + +7. Write session state with: session_id, mode, scope, status="active" **Success**: Team created, session file written, wisdom initialized. @@ -238,10 +255,10 @@ When receiving `tests_failed` or `coverage_report`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. - from: "coordinator", to: "generator", + session_id: <session-id>, + from: "coordinator", type: "gc_loop_trigger", - summary: "[coordinator] GC round <N>: coverage <X>% < target <Y>%, revise tests" + data: {ref: "<session-folder>"} }) ``` diff --git a/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md b/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..90e7cd4d --- /dev/null +++ b/.claude/skills/team-testing/roles/coordinator/commands/dispatch.md @@ -0,0 +1,156 @@ +# Command: Dispatch + +Create the testing task chain with correct dependencies and structured task descriptions. Supports targeted, standard, and comprehensive pipelines. + +## Phase 2: Context Loading + +| 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. 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: + +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + description: "PURPOSE: <what this task achieves> | Success: <measurable criteria> +TASK: + - <step 1: specific action> + - <step 2: specific action> +CONTEXT: + - Session: <session-folder> + - Scope: <scope> + - Layer: <L1-unit|L2-integration|L3-e2e> + - Upstream artifacts: <artifact-1>, <artifact-2> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas> +--- +InnerLoop: <true|false>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### 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 | + +--- + +### 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", + blockedBy: [], + status: "pending" +}) +``` + +**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", + blockedBy: ["STRATEGY-001"], + status: "pending" +}) +``` + +**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", + blockedBy: ["TESTGEN-001"], + status: "pending" +}) +``` + +### 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"] + +### Comprehensive Pipeline + +**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"] + +## Phase 4: Validation + +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: + +``` +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-testing/roles/coordinator/commands/monitor.md b/.claude/skills/team-testing/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..902987f1 --- /dev/null +++ b/.claude/skills/team-testing/roles/coordinator/commands/monitor.md @@ -0,0 +1,188 @@ +# Command: Monitor + +Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion. + +## Phase 2: Context Loading + +| 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 | + +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 + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +1. Parse message to identify role, task ID: + +| Message Pattern | Role Detection | +|----------------|---------------| +| `[strategist]` or task ID `STRATEGY-*` | strategist | +| `[generator]` or task ID `TESTGEN-*` | generator | +| `[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**: + +``` +TaskCreate({ + subject: "TESTGEN-<layer>-fix-<round>", + owner: "generator", + description: "PURPOSE: Revise tests to fix failures and improve coverage +TASK: + - Read previous test results and failure details + - Revise tests to address failures + - Improve coverage for uncovered areas +CONTEXT: + - Session: <session-folder> + - Layer: <layer> + - Previous results: <session>/results/run-<N>.json +EXPECTED: Revised test files in <session>/tests/<layer>/ +--- +InnerLoop: true", + blockedBy: [], + status: "pending" +}) +``` + +Create TESTRUN-fix blocked on TESTGEN-fix. + +### 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. For each ready task, determine role from task subject prefix: + +| Prefix | Role | Inner Loop | +|--------|------|------------| +| STRATEGY-* | strategist | false | +| TESTGEN-* | generator | true | +| TESTRUN-* | executor | true | +| TESTANA-* | analyst | false | + +3. Spawn team-worker: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn <role> worker for <task-id>", + team_name: "testing", + name: "<role>", + run_in_background: true, + prompt: `## Role Assignment +role: <role> +role_spec: .claude/skills/team-testing/role-specs/<role>.md +session: <session-folder> +session_id: <session-id> +team_name: testing +requirement: <task-description> +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.` +}) +``` + +4. **Parallel spawn** (comprehensive pipeline): + +| Scenario | Spawn Behavior | +|----------|---------------| +| TESTGEN-001 + TESTGEN-002 both unblocked | Spawn both in parallel | +| TESTRUN-001 + TESTRUN-002 both unblocked | Spawn both in parallel | + +5. STOP after spawning -- wait for next callback + +### handleCheck + +Output current pipeline status. + +``` +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 + ... + +GC Rounds: L1: 0/3, L2: 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 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 + +## Phase 4: State Persistence + +After every handler execution: + +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 diff --git a/.claude/skills/team-testing/roles/coordinator/role.md b/.claude/skills/team-testing/roles/coordinator/role.md new file mode 100644 index 00000000..b70c5000 --- /dev/null +++ b/.claude/skills/team-testing/roles/coordinator/role.md @@ -0,0 +1,276 @@ +# Coordinator - Testing Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: testing + +Orchestrates the testing pipeline: manages task chains, spawns team-worker agents, handles Generator-Critic loops, quality gates, and drives the pipeline to completion. + +## 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 +- Handle Generator-Critic cycles with max 3 iterations per layer +- 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 +``` + +--- + +## 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) | + +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 + +--- + +## 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: "testing" }) +``` + +5. Spawn workers for ready tasks -> Phase 4 coordination loop + +--- + +## Phase 1: Change Scope Analysis + +1. Parse user 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. + +3. Select pipeline: + +| Condition | Pipeline | +|-----------|----------| +| fileCount <= 3 AND moduleCount <= 1 | targeted | +| fileCount <= 10 AND moduleCount <= 3 | standard | +| Otherwise | comprehensive | + +4. Ask for missing parameters via AskUserQuestion if scope is unclear + +5. Record requirements: mode, scope, focus, constraints + +--- + +## Phase 2: Session & Team Setup + +1. Create session directory: + +``` +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") +``` + +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: + +``` +Write("<session>/wisdom/.msg/meta.json", { "session_id": "<session-id>", "requirement": "<requirement>", "pipeline": "<mode>" }) +``` + +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: + +``` +Task({ + 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 + +--- + +## 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("testing") -> 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 | + +--- + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Teammate no response | Send tracking message, 2 times -> respawn worker | +| 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.md b/.claude/skills/team-testing/roles/executor.md index 6ed8ee53..672b0d00 100644 --- a/.claude/skills/team-testing/roles/executor.md +++ b/.claude/skills/team-testing/roles/executor.md @@ -16,8 +16,8 @@ Test executor. Executes tests, collects coverage, attempts auto-fix for failures - All output (SendMessage, team_msg, logs) must carry `[executor]` identifier - Only communicate with coordinator via SendMessage - Work strictly within validation responsibility scope -- Phase 2: Read shared-memory.json -- Phase 5: Write execution_results + defect_patterns to shared-memory.json +- Phase 2: Read role states via team_msg(operation='get_state') +- Phase 5: Share execution_results + defect_patterns via team_msg(type='state_update') - Report coverage and pass rate for coordinator's GC decision ### MUST NOT @@ -36,7 +36,7 @@ Test executor. Executes tests, collects coverage, attempts auto-fix for failures | Tool | Type | Used By | Purpose | |------|------|---------|---------| -| Read | Read | Phase 2 | Load shared-memory.json | +| Read | Read | Phase 2 | Load role states | | Glob | Read | Phase 2 | Find test files to execute | | Bash | Execute | Phase 3 | Run test commands | | Write | Write | Phase 3 | Save test results | @@ -62,19 +62,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "executor", - to: "coordinator", type: <message-type>, - summary: "[executor] TESTRUN complete: <summary>", - ref: <artifact-path> + data: {ref: "<artifact-path>"} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from executor --to coordinator --type <message-type> --summary \"[executor] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from executor --type <message-type> --json") ``` --- @@ -94,7 +92,7 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTRUN-*` + owner m | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Role state | team_msg(operation="get_state", session_id=<session-id>) | Yes | | Test directory | Task description (Input: <path>) | Yes | | Coverage target | Task description | Yes | @@ -105,7 +103,7 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTRUN-*` + owner m 3. Extract coverage target from task description (default: 80%) ``` -Read("<session-folder>/shared-memory.json") +mcp__ccw-tools__team_msg({ operation: "get_state", session_id: <session-id> }) ``` 4. Determine test framework from shared memory: @@ -219,39 +217,39 @@ Write("<session-folder>/results/run-<N>.json", <result-json>) > See SKILL.md Shared Infrastructure -> Worker Phase 5: Report -1. **Update shared memory**: +1. **Share execution results via team_msg(type='state_update')**: ``` -sharedMemory.execution_results.push(<result-data>) -if (<result-data>.defect_patterns) { - sharedMemory.defect_patterns = [ - ...sharedMemory.defect_patterns, - ...<result-data>.defect_patterns - ] -} -if (<result-data>.effective_patterns) { - sharedMemory.effective_test_patterns = [ - ...new Set([...sharedMemory.effective_test_patterns, ...<result-data>.effective_patterns]) - ] -} -sharedMemory.coverage_history.push({ - layer: <test-dir>, - coverage: <coverage>, - target: <target>, - pass_rate: <pass_rate>, - timestamp: <ISO-date> +mcp__ccw-tools__team_msg({ + operation: "log", session_id: <session-id>, from: "executor", + type: "state_update", + data: { + execution_results: [...sharedMemory.execution_results, <result-data>], + defect_patterns: [ + ...sharedMemory.defect_patterns, + ...(<result-data>.defect_patterns || []) + ], + effective_test_patterns: [ + ...new Set([...sharedMemory.effective_test_patterns, ...(<result-data>.effective_patterns || [])]) + ], + coverage_history: [...sharedMemory.coverage_history, { + layer: <test-dir>, + coverage: <coverage>, + target: <target>, + pass_rate: <pass_rate>, + timestamp: <ISO-date> + }] + } }) -Write("<session-folder>/shared-memory.json", <updated-json>) ``` 2. **Log via team_msg**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id> // MUST be session ID, NOT team name, from: "executor", to: "coordinator", + operation: "log", session_id: <session-id>, from: "executor", type: <passed ? "tests_passed" : "tests_failed">, - summary: "[executor] <passed|failed>: pass=<pass_rate>%, coverage=<coverage>% (target: <target>%), iterations=<N>", - ref: "<session-folder>/results/run-<N>.json" + data: {ref: "<session-folder>/results/run-<N>.json"} }) ``` diff --git a/.claude/skills/team-testing/roles/generator.md b/.claude/skills/team-testing/roles/generator.md index 7f4263d2..99e7e778 100644 --- a/.claude/skills/team-testing/roles/generator.md +++ b/.claude/skills/team-testing/roles/generator.md @@ -16,8 +16,8 @@ Test case generator. Generates test code by layer (L1 unit / L2 integration / L3 - All output (SendMessage, team_msg, logs) must carry `[generator]` identifier - Only communicate with coordinator via SendMessage - Work strictly within code generation responsibility scope -- Phase 2: Read shared-memory.json + test strategy -- Phase 5: Write generated_tests to shared-memory.json +- Phase 2: Read role states via team_msg(operation='get_state') + test strategy +- Phase 5: Share generated_tests via team_msg(type='state_update') - Generate executable test code ### MUST NOT @@ -36,7 +36,7 @@ Test case generator. Generates test code by layer (L1 unit / L2 integration / L3 | Tool | Type | Used By | Purpose | |------|------|---------|---------| -| Read | Read | Phase 2 | Load shared-memory.json, strategy, source files | +| Read | Read | Phase 2 | Load role states, strategy, source files | | Glob | Read | Phase 2 | Find test files, source files | | Write | Write | Phase 3 | Create test files | | Edit | Write | Phase 3 | Modify existing test files | @@ -62,19 +62,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "generator", - to: "coordinator", type: <message-type>, - summary: "[generator] TESTGEN complete: <summary>", - ref: <artifact-path> + data: {ref: "<artifact-path>"} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from generator --to coordinator --type <message-type> --summary \"[generator] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from generator --type <message-type> --json") ``` --- @@ -94,7 +92,7 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTGEN-*` + owner m | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Role state | team_msg(operation="get_state", session_id=<session-id>) | Yes | | Test strategy | <session-folder>/strategy/test-strategy.md | Yes | | Source files | From test_strategy.priority_files | Yes | | Wisdom | <session-folder>/wisdom/ | No | @@ -104,10 +102,10 @@ Standard task discovery flow: TaskList -> filter by prefix `TESTGEN-*` + owner m 1. Extract session path from task description (look for `Session: <path>`) 2. Extract layer from task description (look for `Layer: <L1-unit|L2-integration|L3-e2e>`) -3. Read shared memory: +3. Read role states: ``` -Read("<session-folder>/shared-memory.json") +mcp__ccw-tools__team_msg({ operation: "get_state", session_id: <session-id> }) ``` 4. Read test strategy: @@ -213,29 +211,33 @@ If syntax errors found, attempt auto-fix for common issues (imports, types). > See SKILL.md Shared Infrastructure -> Worker Phase 5: Report -1. **Update shared memory**: +1. **Share generated tests via team_msg(type='state_update')**: ``` -sharedMemory.generated_tests = [ - ...sharedMemory.generated_tests, - ...<new-test-files>.map(f => ({ - file: f, - layer: <layer>, - round: <is-revision ? gc_round : 0>, - revised: <is-revision> - })) -] -Write("<session-folder>/shared-memory.json", <updated-json>) +mcp__ccw-tools__team_msg({ + operation: "log", session_id: <session-id>, from: "generator", + type: "state_update", + data: { + generated_tests: [ + ...sharedMemory.generated_tests, + ...<new-test-files>.map(f => ({ + file: f, + layer: <layer>, + round: <is-revision ? gc_round : 0>, + revised: <is-revision> + })) + ] + } +}) ``` 2. **Log via team_msg**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: <session-id> // MUST be session ID, NOT team name, from: "generator", to: "coordinator", + operation: "log", session_id: <session-id>, from: "generator", type: <is-revision ? "tests_revised" : "tests_generated">, - summary: "[generator] <Generated|Revised> <file-count> <layer> test files", - ref: "<session-folder>/tests/<layer>/" + data: {ref: "<session-folder>/tests/<layer>/"} }) ``` diff --git a/.claude/skills/team-testing/roles/strategist.md b/.claude/skills/team-testing/roles/strategist.md index 1453e919..7891d0c0 100644 --- a/.claude/skills/team-testing/roles/strategist.md +++ b/.claude/skills/team-testing/roles/strategist.md @@ -16,8 +16,8 @@ Test strategy designer. Analyzes git diff, determines test layers, defines cover - All output (SendMessage, team_msg, logs) must carry `[strategist]` identifier - Only communicate with coordinator via SendMessage - Work strictly within read-only analysis responsibility scope -- Phase 2: Read shared-memory.json -- Phase 5: Write test_strategy to shared-memory.json +- Phase 2: Read role states via team_msg(operation='get_state') +- Phase 5: Share test_strategy via team_msg(type='state_update') ### MUST NOT @@ -35,7 +35,7 @@ Test strategy designer. Analyzes git diff, determines test layers, defines cover | Tool | Type | Used By | Purpose | |------|------|---------|---------| -| Read | Read | Phase 2 | Load shared-memory.json, existing test patterns | +| Read | Read | Phase 2 | Load role states, existing test patterns | | Bash | Read | Phase 2 | Git diff analysis, framework detection | | Glob | Read | Phase 2 | Find test files, config files | | Write | Write | Phase 3 | Create test-strategy.md | @@ -58,19 +58,17 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, // MUST be session ID (e.g., TST-xxx-date), NOT team name. Extract from Session: field in task description. + session_id: <session-id>, from: "strategist", - to: "coordinator", type: <message-type>, - summary: "[strategist] STRATEGY complete: <summary>", - ref: <artifact-path> + data: {ref: "<artifact-path>"} }) ``` **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from strategist --to coordinator --type <message-type> --summary \"[strategist] ...\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from strategist --type <message-type> --json") ``` --- @@ -90,17 +88,17 @@ Standard task discovery flow: TaskList -> filter by prefix `STRATEGY-*` + owner | Input | Source | Required | |-------|--------|----------| | Session path | Task description (Session: <path>) | Yes | -| Shared memory | <session-folder>/shared-memory.json | Yes | +| Role state | team_msg(operation="get_state", session_id=<session-id>) | Yes | | Git diff | `git diff HEAD~1` or `git diff --cached` | Yes | | Changed files | From git diff --name-only | Yes | **Loading steps**: 1. Extract session path from task description (look for `Session: <path>`) -2. Read shared-memory.json for changed files and modules +2. Read role states for changed files and modules ``` -Read("<session-folder>/shared-memory.json") +mcp__ccw-tools__team_msg({ operation: "get_state", session_id: <session-id> }) ``` 3. Get detailed git diff for analysis: @@ -162,27 +160,31 @@ Write("<session-folder>/strategy/test-strategy.md", <strategy-content>) > See SKILL.md Shared Infrastructure -> Worker Phase 5: Report -1. **Update shared memory**: +1. **Share test strategy via team_msg(type='state_update')**: ``` -sharedMemory.test_strategy = { - framework: <detected-framework>, - layers: { L1: [...], L2: [...], L3: [...] }, - coverage_targets: { L1: <n>, L2: <n>, L3: <n> }, - priority_files: [...], - risks: [...] -} -Write("<session-folder>/shared-memory.json", <updated-json>) +mcp__ccw-tools__team_msg({ + operation: "log", session_id: <session-id>, from: "strategist", + type: "state_update", + data: { + test_strategy: { + framework: <detected-framework>, + layers: { L1: [...], L2: [...], L3: [...] }, + coverage_targets: { L1: <n>, L2: <n>, L3: <n> }, + priority_files: [...], + risks: [...] + } + } +}) ``` 2. **Log via team_msg**: ``` mcp__ccw-tools__team_msg({ - operation: "log", team: "testing", from: "strategist", to: "coordinator", + operation: "log", session_id: <session-id>, from: "strategist", type: "strategy_ready", - summary: "[strategist] Strategy complete: <file-count> files, L1-L3 layers defined", - ref: "<session-folder>/strategy/test-strategy.md" + data: {ref: "<session-folder>/strategy/test-strategy.md"} }) ``` diff --git a/.claude/skills/team-uidesign/SKILL.md b/.claude/skills/team-uidesign/SKILL.md index e54b3f76..298c493d 100644 --- a/.claude/skills/team-uidesign/SKILL.md +++ b/.claude/skills/team-uidesign/SKILL.md @@ -101,9 +101,9 @@ Every worker executes the same task discovery flow on startup: Standard reporting flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. - - **CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` + - 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 @@ -130,7 +130,7 @@ Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at se |---------|-----------| | Process tasks with own prefix | Process tasks with other role prefixes | | SendMessage to coordinator | Communicate directly with other workers | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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 call implementation subagents, do not execute analysis/audits, do not bypass workers. @@ -143,11 +143,11 @@ All outputs must carry `[role_name]` prefix in both SendMessage content/summary Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: -**Parameters**: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> +**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"} -> **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. -**CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` +**CLI fallback**: When MCP unavailable → `ccw team log --session-id <session-id> --from <role> --type <type> --json` **Message types by role**: @@ -159,9 +159,9 @@ Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: | reviewer | `audit_result`, `audit_passed`, `fix_required`, `error` | | implementer | `build_complete`, `build_progress`, `error` | -### Shared Memory +### Shared State -All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: +All roles share state via `team_msg(type='state_update')` + `meta.json`: | Role | Field | |------|-------| @@ -200,7 +200,6 @@ design-intelligence.json |---------|-------| | Team name | uidesign | | Session directory | `.workflow/.team/UDS-<slug>-<date>/` | -| Shared memory | `shared-memory.json` in session dir | --- @@ -378,8 +377,8 @@ Session: <session-folder> ``` .workflow/.team/UDS-<slug>-<YYYY-MM-DD>/ -├── team-session.json # Session state -├── shared-memory.json # Cross-role accumulated knowledge +├── .msg/messages.jsonl # Message bus log +├── .msg/meta.json # Session metadata ├── wisdom/ # Cross-task knowledge │ ├── learnings.md │ ├── decisions.md diff --git a/.claude/skills/team-uidesign/role-specs/designer.md b/.claude/skills/team-uidesign/role-specs/designer.md new file mode 100644 index 00000000..ba94bff0 --- /dev/null +++ b/.claude/skills/team-uidesign/role-specs/designer.md @@ -0,0 +1,72 @@ +--- +prefix: DESIGN +inner_loop: false +message_types: + success: design_ready + revision: design_revision + progress: design_progress + error: error +--- + +# 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/role-specs/implementer.md b/.claude/skills/team-uidesign/role-specs/implementer.md new file mode 100644 index 00000000..ff4dac02 --- /dev/null +++ b/.claude/skills/team-uidesign/role-specs/implementer.md @@ -0,0 +1,74 @@ +--- +prefix: BUILD +inner_loop: false +message_types: + success: build_complete + progress: build_progress + error: error +--- + +# 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/role-specs/researcher.md b/.claude/skills/team-uidesign/role-specs/researcher.md new file mode 100644 index 00000000..14073429 --- /dev/null +++ b/.claude/skills/team-uidesign/role-specs/researcher.md @@ -0,0 +1,85 @@ +--- +prefix: RESEARCH +inner_loop: false +subagents: [explore] +message_types: + success: research_ready + progress: research_progress + error: error +--- + +# 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 `explore` subagent 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/role-specs/reviewer.md b/.claude/skills/team-uidesign/role-specs/reviewer.md new file mode 100644 index 00000000..297c5689 --- /dev/null +++ b/.claude/skills/team-uidesign/role-specs/reviewer.md @@ -0,0 +1,70 @@ +--- +prefix: AUDIT +inner_loop: false +message_types: + success: audit_passed + result: audit_result + fix: fix_required + error: error +--- + +# 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/roles/coordinator.md b/.claude/skills/team-uidesign/roles/coordinator.md index 6e2ae4a3..a3fcd778 100644 --- a/.claude/skills/team-uidesign/roles/coordinator.md +++ b/.claude/skills/team-uidesign/roles/coordinator.md @@ -127,8 +127,8 @@ For callback/check/resume: load coordination logic and execute the appropriate h ``` UDS-<slug>-<date>/ -├── team-session.json -├── shared-memory.json +├── .msg/messages.jsonl +├── .msg/meta.json ├── wisdom/ │ ├── learnings.md │ ├── decisions.md @@ -144,17 +144,28 @@ UDS-<slug>-<date>/ └── component-files/ ``` -5. Initialize shared-memory.json with: - - design_intelligence: {} - - design_token_registry: { colors, typography, spacing, shadows, borders } - - style_decisions: [] - - component_inventory: [] - - accessibility_patterns: [] - - audit_history: [] - - industry_context: { industry, config } - - _metadata: { created_at, pipeline } +5. Initialize cross-role state via team_msg(type='state_update'): -6. Write team-session.json with: +``` +mcp__ccw-tools__team_msg({ + operation: "log", + session_id: <session-id>, + from: "coordinator", + type: "state_update", + data: { + design_intelligence: {}, + design_token_registry: { colors: {}, typography: {}, spacing: {}, shadows: {}, borders: {} }, + style_decisions: [], + component_inventory: [], + accessibility_patterns: [], + audit_history: [], + industry_context: { industry: <industry>, config: <config> }, + _metadata: { created_at: <timestamp>, pipeline: <pipeline> } + } +}) +``` + +6. Write meta.json with: - session_id, team_name, topic, pipeline, status - current_phase, completed_tasks, sync_points - gc_state: { round, max_rounds: 2, converged } diff --git a/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md b/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..dc3fa09c --- /dev/null +++ b/.claude/skills/team-uidesign/roles/coordinator/commands/dispatch.md @@ -0,0 +1,190 @@ +# Command: Dispatch + +Create the UI design task chain with correct dependencies and structured task descriptions. Supports component, system, and full-system pipeline modes. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| User requirement | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline mode | From session.json `pipeline` | Yes | +| 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 +3. Read `pipeline` and `industry` from session.json + +## Phase 3: Task Chain Creation (Mode-Branched) + +### Task Description Template + +Every task description uses structured format: + +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + 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: <design-scope> + - Industry: <industry> + - Upstream artifacts: <artifact-1>, <artifact-2> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### Mode Router + +| Mode | Action | +|------|--------| +| `component` | Create 4 tasks: RESEARCH -> DESIGN -> AUDIT -> BUILD | +| `system` | Create 7 tasks: dual-track with 2 sync points | +| `full-system` | Create 8 tasks: dual-track with 3 sync points (final audit) | + +--- + +### Component Pipeline Task Chain + +**RESEARCH-001** (researcher): +``` +TaskCreate({ + subject: "RESEARCH-001", + description: "PURPOSE: Analyze existing design system, build component inventory, assess accessibility baseline | Success: 4 research artifacts produced with valid data +TASK: + - Analyze existing design tokens and styling patterns + - Build component inventory with props and states + - Assess accessibility baseline (WCAG level, ARIA coverage) + - Retrieve design intelligence via ui-ux-pro-max +CONTEXT: + - Session: <session-folder> + - Scope: <design-scope> + - Industry: <industry> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/research/*.json | All 4 research files with valid JSON +CONSTRAINTS: Read-only analysis | Focus on <design-scope>", + status: "pending" +}) +``` + +**DESIGN-001** (designer): +``` +TaskCreate({ + subject: "DESIGN-001", + description: "PURPOSE: Define component design with tokens and specifications | Success: Design tokens + component spec with all states defined +TASK: + - Define design tokens consuming research findings + - Create component specification with all 5 interactive states + - Ensure accessibility spec (role, ARIA, keyboard, focus) + - Reference design intelligence recommendations +CONTEXT: + - Session: <session-folder> + - Scope: <design-scope> + - Industry: <industry> + - Upstream artifacts: research/*.json + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/design/design-tokens.json + component-specs/*.md | Complete token system + spec +CONSTRAINTS: Follow W3C Design Tokens Format | All color tokens need light/dark", + blockedBy: ["RESEARCH-001"], + status: "pending" +}) +``` + +**AUDIT-001** (reviewer): +``` +TaskCreate({ + subject: "AUDIT-001", + description: "PURPOSE: Audit design for consistency, accessibility, and quality | Success: Audit score >= 8 with 0 critical issues +TASK: + - Score 5 dimensions: consistency, accessibility, completeness, quality, industry compliance + - Check token naming, theme completeness, contrast ratios + - Verify component states and ARIA spec + - Check against design intelligence anti-patterns +CONTEXT: + - Session: <session-folder> + - Scope: <design-scope> + - Industry: <industry> + - Upstream artifacts: design/design-tokens.json, design/component-specs/*.md + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/audit/audit-001.md | 5-dimension scored report +CONSTRAINTS: Read-only analysis | GC convergence: score >= 8 and 0 critical", + blockedBy: ["DESIGN-001"], + status: "pending" +}) +``` + +**BUILD-001** (implementer): +``` +TaskCreate({ + subject: "BUILD-001", + description: "PURPOSE: Implement component code from design specs | Success: Production code with token consumption and accessibility +TASK: + - Generate CSS custom properties from design tokens + - Implement component with all 5 states + - Add ARIA attributes and keyboard navigation + - Validate no hardcoded values +CONTEXT: + - Session: <session-folder> + - Scope: <design-scope> + - Industry: <industry> + - Upstream artifacts: design/design-tokens.json, design/component-specs/*.md, audit/audit-001.md + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/build/**/* | Component + tokens CSS/TS + tests +CONSTRAINTS: Use var(--token-name) only | Follow project patterns", + blockedBy: ["AUDIT-001"], + status: "pending" +}) +``` + +--- + +### System Pipeline Task Chain (Dual-Track) + +Create tasks in dependency order: + +| Task | Role | blockedBy | Description | +|------|------|-----------|-------------| +| RESEARCH-001 | researcher | (none) | Design system analysis | +| DESIGN-001 | designer | RESEARCH-001 | Token system design | +| AUDIT-001 | reviewer | DESIGN-001 | Token audit [Sync Point 1] | +| DESIGN-002 | designer | AUDIT-001 | Component specification | +| BUILD-001 | implementer | AUDIT-001 | Token code implementation | +| AUDIT-002 | reviewer | DESIGN-002 | Component audit [Sync Point 2] | +| BUILD-002 | implementer | AUDIT-002, BUILD-001 | Component code implementation | + +Task descriptions follow same template as component pipeline, with subject-specific content for tokens vs components and appropriate upstream artifacts. + +--- + +### Full-System Pipeline Task Chain + +Same as System Pipeline, plus: + +| Task | Role | blockedBy | Description | +|------|------|-----------|-------------| +| AUDIT-003 | reviewer | BUILD-002 | Final integrated audit (cross-cutting) | + +--- + +## Phase 4: Validation + +Verify task chain integrity: + +| Check | Method | Expected | +|-------|--------|----------| +| Task count correct | TaskList count | component: 4, system: 7, full-system: 8 | +| Dependencies correct | Trace dependency graph | Acyclic, correct blockedBy | +| No circular dependencies | Trace dependency graph | Acyclic | +| Task IDs use correct prefixes | Pattern check | RESEARCH/DESIGN/AUDIT/BUILD | +| Structured descriptions complete | Each has PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS | All present | + +If validation fails, fix the specific task and re-validate. diff --git a/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md b/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..a0e31cba --- /dev/null +++ b/.claude/skills/team-uidesign/roles/coordinator/commands/monitor.md @@ -0,0 +1,203 @@ +# Command: Monitor + +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. + +## Phase 2: Context Loading + +| 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 | + +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 + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +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" }) +``` + +3. Record completion in session state + +4. Check if checkpoint feedback is configured for this stage: + +| 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 | +| 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) + +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. For each ready task, spawn team-worker: + +``` +Task({ + subagent_type: "team-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 +session: <session-folder> +session_id: <session-id> +team_name: uidesign +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.` +}) +``` + +3. **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 | + +4. STOP after spawning -- wait for next callback + +### Generator-Critic Loop Control + +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", + blockedBy: [], + status: "pending" +}) +``` + +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. + +**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" | + +If any tasks not completed, return to handleSpawnNext. +If all completed, transition to coordinator Phase 5. + +## Phase 4: State Persistence + +After every handler execution: + +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 diff --git a/.claude/skills/team-uidesign/roles/coordinator/role.md b/.claude/skills/team-uidesign/roles/coordinator/role.md new file mode 100644 index 00000000..6c0638d3 --- /dev/null +++ b/.claude/skills/team-uidesign/roles/coordinator/role.md @@ -0,0 +1,278 @@ +# Coordinator - UI Design Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: uidesign + +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. + +## 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 +- Handle Generator-Critic loops with max 2 iterations +- Execute completion action in Phase 5 + +### 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 + +--- + +## 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 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) | + +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 + +--- + +## 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 + +--- + +## Phase 1: Requirement Clarification + +1. Parse user task description from $ARGUMENTS +2. Identify design scope: + +| Signal | Target | +|--------|--------| +| Single component mentioned | Component pipeline | +| Multiple components or "design system" | System pipeline | +| Full redesign or "complete design system" | Full-system pipeline | + +3. If scope is unclear, ask for clarification: + +``` +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. Map scope to pipeline: component / system / full-system +5. Record requirement with scope, industry, and pipeline mode + +--- + +## Phase 2: Session & Team Setup + +1. Create session directory: + +``` +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") +``` + +2. Write session.json: + +```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: + +``` +Write("<session>/wisdom/.msg/meta.json", { "session_id": "<session-id>", "requirement": "<requirement>", "pipeline": "<pipeline>" }) +``` + +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: + +``` +Task({ + 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 + +--- + +## Phase 5: Report + Completion Action + +1. Load session state -> count completed tasks, calculate duration +2. List deliverables: + +| Deliverable | Path | +|-------------|------| +| Design System Analysis | <session>/research/design-system-analysis.json | +| Component Inventory | <session>/research/component-inventory.json | +| Accessibility Audit | <session>/research/accessibility-audit.json | +| Design Intelligence | <session>/research/design-intelligence.json | +| Design Tokens | <session>/design/design-tokens.json | +| Component Specs | <session>/design/component-specs/*.md | +| Audit Reports | <session>/audit/audit-*.md | +| 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 + +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 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("uidesign") -> 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 | diff --git a/.claude/skills/team-uidesign/roles/designer.md b/.claude/skills/team-uidesign/roles/designer.md index c4289725..b2bad844 100644 --- a/.claude/skills/team-uidesign/roles/designer.md +++ b/.claude/skills/team-uidesign/roles/designer.md @@ -59,21 +59,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "designer", - to: "coordinator", type: <message-type>, - summary: "[designer] DESIGN complete: <task-subject>", ref: <artifact-path> }) ``` -> **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from designer --to coordinator --type <message-type> --summary \"[designer] DESIGN complete\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from designer --type <message-type> --json") ``` --- @@ -99,7 +97,7 @@ Standard task discovery flow: TaskList -> filter by prefix `DESIGN-*` + owner ma **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json +2. Read role states via team_msg(operation="get_state") 3. Read research findings: | File | Content | diff --git a/.claude/skills/team-uidesign/roles/implementer.md b/.claude/skills/team-uidesign/roles/implementer.md index 48d17dea..c5cf7cc1 100644 --- a/.claude/skills/team-uidesign/roles/implementer.md +++ b/.claude/skills/team-uidesign/roles/implementer.md @@ -61,21 +61,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "implementer", - to: "coordinator", type: <message-type>, - summary: "[implementer] BUILD complete: <task-subject>", ref: <artifact-path> }) ``` -> **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from implementer --to coordinator --type <message-type> --summary \"[implementer] BUILD complete\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from implementer --type <message-type> --json") ``` --- @@ -100,7 +98,7 @@ Standard task discovery flow: TaskList -> filter by prefix `BUILD-*` + owner mat **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json: +2. Read role states via team_msg(operation="get_state"): | Field | Usage | |-------|-------| diff --git a/.claude/skills/team-uidesign/roles/researcher.md b/.claude/skills/team-uidesign/roles/researcher.md index 2153718d..752d9f5e 100644 --- a/.claude/skills/team-uidesign/roles/researcher.md +++ b/.claude/skills/team-uidesign/roles/researcher.md @@ -59,21 +59,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "researcher", - to: "coordinator", type: <message-type>, - summary: "[researcher] RESEARCH complete: <task-subject>", ref: <artifact-path> }) ``` -> **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from researcher --to coordinator --type <message-type> --summary \"[researcher] RESEARCH complete\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from researcher --type <message-type> --json") ``` --- @@ -91,7 +89,7 @@ Standard task discovery flow: TaskList -> filter by prefix `RESEARCH-*` + owner **Loading steps**: 1. Extract session path from task description (pattern: `Session: <path>`) -2. Read shared-memory.json from session folder +2. Read role states via team_msg(operation="get_state") from session 3. Load existing component_inventory and accessibility_patterns if available **Input Sources**: @@ -99,7 +97,7 @@ Standard task discovery flow: TaskList -> filter by prefix `RESEARCH-*` + owner | Input | Source | Required | |-------|--------|----------| | Session folder | Task description | Yes | -| shared-memory.json | Session folder | Yes | +| Role state | team_msg(operation="get_state", session_id=<session-id>) | Yes | | Wisdom files | Session/wisdom/ | No | ### Phase 3: Research Execution diff --git a/.claude/skills/team-uidesign/roles/reviewer.md b/.claude/skills/team-uidesign/roles/reviewer.md index ddfc3742..75e46497 100644 --- a/.claude/skills/team-uidesign/roles/reviewer.md +++ b/.claude/skills/team-uidesign/roles/reviewer.md @@ -58,21 +58,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "reviewer", - to: "coordinator", type: <message-type>, - summary: "[reviewer] AUDIT complete: <task-subject>", ref: <artifact-path> }) ``` -> **Note**: `team` must be session ID (e.g., `UDS-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from reviewer --to coordinator --type <message-type> --summary \"[reviewer] AUDIT complete\" --ref <artifact-path> --json") +Bash("ccw team log --session-id <session-id> --from reviewer --type <message-type> --json") ``` --- @@ -99,7 +97,7 @@ Standard task discovery flow: TaskList -> filter by prefix `AUDIT-*` + owner mat **Loading steps**: 1. Extract session path from task description -2. Read shared-memory.json: +2. Read role states via team_msg(operation="get_state"): | Field | Usage | |-------|-------| diff --git a/.claude/skills/team-ultra-analyze/SKILL.md b/.claude/skills/team-ultra-analyze/SKILL.md index e1c59360..602d27cf 100644 --- a/.claude/skills/team-ultra-analyze/SKILL.md +++ b/.claude/skills/team-ultra-analyze/SKILL.md @@ -130,9 +130,9 @@ Each worker executes the same task discovery flow on startup: Standard report flow after task completion: 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message - - Parameters: operation="log", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - - **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. - - **CLI fallback**: When MCP unavailable -> `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` + - 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 @@ -159,16 +159,16 @@ Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory durin |---------|-----------| | Process tasks matching own prefix | Process tasks with other role prefixes | | SendMessage to coordinator | Communicate directly with other workers | -| Read/write shared-memory.json (own fields) | Create tasks for other roles | +| 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. -### Shared Memory +### Cross-Role State -Core shared artifact stored at `<session-folder>/shared-memory.json`. Each role reads the full memory but writes only to its own designated field: +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 | Write Field | +| Role | State Field | |------|-------------| | explorer | `explorations` | | analyst | `analyses` | @@ -176,13 +176,13 @@ Core shared artifact stored at `<session-folder>/shared-memory.json`. Each role | synthesizer | `synthesis` | | coordinator | `decision_trail` + `current_understanding` | -On startup, read the file. After completing work, update own field and write back. If file does not exist, initialize with empty object. +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", team=<session-id>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<file-path>. +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. + -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. | Role | Types | |------|-------| @@ -192,9 +192,8 @@ All roles log messages before sending via SendMessage. Call `mcp__ccw-tools__tea | discussant | `discussion_processed`, `error` | | synthesizer | `synthesis_ready`, `error` | -**CLI fallback**: When MCP unavailable -> `ccw team log --team "<session-id>" --from "<role>" --to "coordinator" --type "<type>" --summary "<summary>" --json` +**CLI fallback**: When MCP unavailable -> `ccw team log --session-id <session-id> --from <role> --type <type> --json` -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. --- @@ -393,7 +392,7 @@ Session: <session-folder> |---------|-------| | Team name | ultra-analyze | | Session directory | .workflow/.team/UAN-{slug}-{date}/ | -| Shared memory file | shared-memory.json | + | Analysis dimensions | architecture, implementation, performance, security, concept, comparison, decision | | Max discussion rounds | 5 | @@ -401,7 +400,8 @@ Session: <session-folder> ``` .workflow/.team/UAN-{slug}-{YYYY-MM-DD}/ -+-- shared-memory.json # Exploration/analysis/discussion/synthesis shared memory ++-- .msg/messages.jsonl # Message bus log ++-- .msg/meta.json # Session metadata +-- discussion.md # Understanding evolution and discussion timeline +-- explorations/ # Explorer output | +-- exploration-001.json diff --git a/.claude/skills/team-ultra-analyze/role-specs/analyst.md b/.claude/skills/team-ultra-analyze/role-specs/analyst.md new file mode 100644 index 00000000..44b74c1f --- /dev/null +++ b/.claude/skills/team-ultra-analyze/role-specs/analyst.md @@ -0,0 +1,90 @@ +--- +prefix: ANALYZE +inner_loop: false +additional_prefixes: [ANALYZE-fix] +subagents: [] +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/role-specs/discussant.md b/.claude/skills/team-ultra-analyze/role-specs/discussant.md new file mode 100644 index 00000000..0e8d49fc --- /dev/null +++ b/.claude/skills/team-ultra-analyze/role-specs/discussant.md @@ -0,0 +1,90 @@ +--- +prefix: DISCUSS +inner_loop: false +subagents: [cli-explore-agent] +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 | subagent | Spawn cli-explore-agent to investigate open questions deeper | +| direction-adjusted | cli | Re-analyze via `ccw cli` from adjusted perspective | +| specific-questions | subagent | 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**: Spawn cli-explore-agent focused on open questions and uncertain insights: +``` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + prompt: "Focus on open questions: <questions>. Find evidence for uncertain insights. Write to: <session>/discussions/deepen-<num>.json" +}) +``` + +**direction-adjusted**: CLI re-analysis from adjusted focus: +``` +ccw cli -p "Re-analyze '<topic>' with adjusted focus on '<userFeedback>'" --tool gemini --mode analysis +``` + +**specific-questions**: Spawn cli-explore-agent targeting user's questions: +``` +Task({ subagent_type: "cli-explore-agent", prompt: "Answer: <userFeedback>. Write to: <session>/discussions/questions-<num>.json" }) +``` + +## 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/role-specs/explorer.md b/.claude/skills/team-ultra-analyze/role-specs/explorer.md new file mode 100644 index 00000000..c9491867 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/role-specs/explorer.md @@ -0,0 +1,90 @@ +--- +prefix: EXPLORE +inner_loop: false +subagents: [cli-explore-agent] +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 + +Spawn `cli-explore-agent` subagent for actual exploration: + +``` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: "Explore codebase: <topic> (<perspective>)", + prompt: ` +## Analysis Context +Topic: <topic> +Perspective: <perspective> -- <strategy.focus> +Dimensions: <dimensions> +Session: <session-folder> + +## MANDATORY FIRST STEPS +1. Run: ccw tool exec get_modules_by_depth '{}' +2. Execute searches based on topic + perspective keywords +3. Run: ccw spec load --category exploration + +## Exploration Focus (<perspective> angle) +<dimension-specific exploration instructions> + +## Output +Write findings to: <session>/explorations/exploration-<num>.json +Schema: { perspective, relevant_files: [{path, relevance, summary}], patterns: [string], + key_findings: [string], module_map: {module: [files]}, questions_for_analysis: [string], + _metadata: {agent, perspective, search_queries, timestamp} } +` +}) +``` + +**ACE fallback** (when cli-explore-agent produces no output): +``` +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/role-specs/synthesizer.md b/.claude/skills/team-ultra-analyze/role-specs/synthesizer.md new file mode 100644 index 00000000..5a114430 --- /dev/null +++ b/.claude/skills/team-ultra-analyze/role-specs/synthesizer.md @@ -0,0 +1,78 @@ +--- +prefix: SYNTH +inner_loop: false +subagents: [] +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/roles/analyst/role.md b/.claude/skills/team-ultra-analyze/roles/analyst/role.md index be2d8464..abdc7224 100644 --- a/.claude/skills/team-ultra-analyze/roles/analyst/role.md +++ b/.claude/skills/team-ultra-analyze/roles/analyst/role.md @@ -17,7 +17,7 @@ - Only communicate with coordinator via SendMessage - Work strictly within deep analysis responsibility scope - Base analysis on explorer exploration results -- Write analysis results to shared-memory.json `analyses` field +- Share analysis results via team_msg(type='state_update') ### MUST NOT @@ -72,21 +72,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "analyst", - to: "coordinator", type: "analysis_ready", - summary: "[analyst] ANALYZE complete: <summary>", ref: "<output-path>" }) ``` -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from analyst --to coordinator --type analysis_ready --summary \"[analyst] ...\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from analyst --type analysis_ready --ref <path> --json") ``` --- @@ -108,7 +106,7 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. 1. Extract session path from task description 2. Extract topic, perspective, dimensions from task metadata 3. Check for direction-fix type (补充分析) -4. Read shared-memory.json for existing context +4. Read role states via team_msg(operation="get_state") for existing context 5. Read corresponding exploration results **Context extraction**: diff --git a/.claude/skills/team-ultra-analyze/roles/coordinator/commands/dispatch.md b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/dispatch.md index 78429fbb..7e290edd 100644 --- a/.claude/skills/team-ultra-analyze/roles/coordinator/commands/dispatch.md +++ b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/dispatch.md @@ -1,237 +1,294 @@ -# Command: dispatch +# Command: Dispatch -> 任务链创建与依赖管理。根据管道模式创建 pipeline 任务链并分配给 worker 角色。 +Create the analysis task chain with correct dependencies and structured task descriptions. Supports Quick, Standard, and Deep pipeline modes. -## When to Use +## Phase 2: Context Loading -- Phase 3 of Coordinator -- 管道模式已确定,需要创建任务链 -- 团队已创建,worker 已 spawn +| Input | Source | Required | +|-------|--------|----------| +| User topic | From coordinator Phase 1 | Yes | +| Session folder | From coordinator Phase 2 | Yes | +| Pipeline mode | From coordinator Phase 1 | Yes | +| Perspectives | From coordinator Phase 1 (dimension detection) | Yes | -**Trigger conditions**: -- Coordinator Phase 2 完成后 -- 讨论循环中需要创建补充分析任务 -- 方向调整需要创建新探索/分析任务 +1. Load topic, pipeline mode, and selected perspectives from coordinator state +2. Load pipeline stage definitions from SKILL.md Task Metadata Registry +3. Determine depth = number of selected perspectives (Quick: always 1) -## Strategy +## Phase 3: Task Chain Creation -### Delegation Mode +### Task Description Template -**Mode**: Direct(coordinator 直接操作 TaskCreate/TaskUpdate) +Every task description uses structured format: -### Decision Logic - -```javascript -// 根据 pipelineMode 和 perspectives 选择 pipeline -function buildPipeline(pipelineMode, perspectives, sessionFolder, taskDescription, dimensions) { - const pipelines = { - 'quick': [ - { prefix: 'EXPLORE', suffix: '001', owner: 'explorer', desc: '代码库探索', meta: `perspective: general\ndimensions: ${dimensions.join(', ')}`, blockedBy: [] }, - { prefix: 'ANALYZE', suffix: '001', owner: 'analyst', desc: '综合分析', meta: `perspective: technical\ndimensions: ${dimensions.join(', ')}`, blockedBy: ['EXPLORE-001'] }, - { prefix: 'SYNTH', suffix: '001', owner: 'synthesizer', desc: '结论综合', blockedBy: ['ANALYZE-001'] } - ], - 'standard': buildStandardPipeline(perspectives, dimensions), - 'deep': buildDeepPipeline(perspectives, dimensions) - } - return pipelines[pipelineMode] || pipelines['standard'] -} - -function buildStandardPipeline(perspectives, dimensions) { - const stages = [] - const perspectiveList = perspectives.length > 0 ? perspectives : ['technical'] - const isParallel = perspectiveList.length > 1 - - // Parallel explorations — each gets a distinct agent name for true parallelism - perspectiveList.forEach((p, i) => { - const num = String(i + 1).padStart(3, '0') - const explorerName = isParallel ? `explorer-${i + 1}` : 'explorer' - stages.push({ - prefix: 'EXPLORE', suffix: num, owner: explorerName, - desc: `代码库探索 (${p})`, - meta: `perspective: ${p}\ndimensions: ${dimensions.join(', ')}`, - blockedBy: [] - }) - }) - - // Parallel analyses — each gets a distinct agent name for true parallelism - perspectiveList.forEach((p, i) => { - const num = String(i + 1).padStart(3, '0') - const analystName = isParallel ? `analyst-${i + 1}` : 'analyst' - stages.push({ - prefix: 'ANALYZE', suffix: num, owner: analystName, - desc: `深度分析 (${p})`, - meta: `perspective: ${p}\ndimensions: ${dimensions.join(', ')}`, - blockedBy: [`EXPLORE-${num}`] - }) - }) - - // Discussion (blocked by all analyses) - const analyzeIds = perspectiveList.map((_, i) => `ANALYZE-${String(i + 1).padStart(3, '0')}`) - stages.push({ - prefix: 'DISCUSS', suffix: '001', owner: 'discussant', - desc: '讨论处理 (Round 1)', - meta: `round: 1\ntype: initial`, - blockedBy: analyzeIds - }) - - // Synthesis (blocked by discussion) - stages.push({ - prefix: 'SYNTH', suffix: '001', owner: 'synthesizer', - desc: '结论综合', - blockedBy: ['DISCUSS-001'] - }) - - return stages -} - -function buildDeepPipeline(perspectives, dimensions) { - // Same as standard but SYNTH is not created initially - // It will be created after discussion loop completes - const stages = buildStandardPipeline(perspectives, dimensions) - // Remove SYNTH — will be created dynamically after discussion loop - return stages.filter(s => s.prefix !== 'SYNTH') -} +``` +TaskCreate({ + subject: "<TASK-ID>", + owner: "<role>", + 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> + - Topic: <analysis-topic> + - Perspective: <perspective or 'all'> + - Upstream artifacts: <artifact-1>, <artifact-2> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas> +--- +InnerLoop: false", + blockedBy: [<dependency-list>], + status: "pending" +}) ``` -## Execution Steps +### Mode Router -### Step 1: Context Preparation +| Mode | Action | +|------|--------| +| `quick` | Create 3 tasks: EXPLORE-001 -> ANALYZE-001 -> SYNTH-001 | +| `standard` | Create N explorers + N analysts + DISCUSS-001 + SYNTH-001 | +| `deep` | Same as standard but omit SYNTH-001 (created after discussion loop) | -```javascript -const pipeline = buildPipeline(pipelineMode, selectedPerspectives, sessionFolder, taskDescription, dimensions) +--- + +### Quick Mode Task Chain + +**EXPLORE-001** (explorer): +``` +TaskCreate({ + subject: "EXPLORE-001", + description: "PURPOSE: Explore codebase structure for analysis topic | Success: Key files, patterns, and findings collected +TASK: + - Detect project structure and relevant modules + - Search for code related to analysis topic + - Collect file references, patterns, and key findings +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Perspective: general + - Dimensions: <dimensions> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/explorations/exploration-001.json | Structured exploration with files and findings +CONSTRAINTS: Focus on <topic> scope +--- +InnerLoop: false", + status: "pending" +}) ``` -### Step 2: Execute Strategy - -```javascript -const taskIds = {} - -for (const stage of pipeline) { - const taskSubject = `${stage.prefix}-${stage.suffix}: ${stage.desc}` - - // 构建任务描述(包含 session 和上下文信息) - const fullDesc = [ - stage.desc, - `\nsession: ${sessionFolder}`, - `\ntopic: ${taskDescription}`, - stage.meta ? `\n${stage.meta}` : '', - `\n\n目标: ${taskDescription}` - ].join('') - - // 创建任务 - TaskCreate({ - subject: taskSubject, - description: fullDesc, - activeForm: `${stage.desc}进行中` - }) - - // 记录任务 ID - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith(`${stage.prefix}-${stage.suffix}`)) - taskIds[`${stage.prefix}-${stage.suffix}`] = newTask.id - - // 设置 owner 和依赖 - const blockedByIds = stage.blockedBy - .map(dep => taskIds[dep]) - .filter(Boolean) - - TaskUpdate({ - taskId: newTask.id, - owner: stage.owner, - addBlockedBy: blockedByIds - }) -} +**ANALYZE-001** (analyst): +``` +TaskCreate({ + subject: "ANALYZE-001", + description: "PURPOSE: Deep analysis of topic from technical perspective | Success: Actionable insights with confidence levels +TASK: + - Load exploration results and build analysis context + - Analyze from technical perspective across selected dimensions + - Generate insights, findings, discussion points, recommendations +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Perspective: technical + - Dimensions: <dimensions> + - Upstream artifacts: explorations/exploration-001.json + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/analyses/analysis-001.json | Structured analysis with evidence +CONSTRAINTS: Focus on technical perspective | <dimensions> +--- +InnerLoop: false", + blockedBy: ["EXPLORE-001"], + status: "pending" +}) ``` -### Step 3: Result Processing - -```javascript -// 验证任务链 -const allTasks = TaskList() -const chainTasks = pipeline.map(s => taskIds[`${s.prefix}-${s.suffix}`]).filter(Boolean) -const chainValid = chainTasks.length === pipeline.length - -if (!chainValid) { - mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", - to: "user", type: "error", - summary: `[coordinator] 任务链创建不完整: ${chainTasks.length}/${pipeline.length}` - }) -} +**SYNTH-001** (synthesizer): ``` +TaskCreate({ + subject: "SYNTH-001", + description: "PURPOSE: Integrate analysis into final conclusions | Success: Executive summary with recommendations +TASK: + - Load all exploration, analysis, and discussion artifacts + - Extract themes, consolidate evidence, prioritize recommendations + - Write conclusions and update discussion.md +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Upstream artifacts: explorations/*.json, analyses/*.json + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/conclusions.json + discussion.md update | Final conclusions with confidence levels +CONSTRAINTS: Pure integration, no new exploration +--- +InnerLoop: false", + blockedBy: ["ANALYZE-001"], + status: "pending" +}) +``` + +--- + +### Standard Mode Task Chain + +Create tasks in dependency order with parallel exploration and analysis windows: + +**EXPLORE-001..N** (explorer, parallel): One per perspective. Each receives unique agent name (explorer-1, explorer-2, ...) for task discovery matching. + +``` +// For each perspective[i]: +TaskCreate({ + subject: "EXPLORE-<NNN>", + owner: "explorer-<i+1>", + description: "PURPOSE: Explore codebase from <perspective> angle | Success: Perspective-specific files and patterns collected +TASK: + - Search codebase from <perspective> perspective + - Collect files, patterns, findings relevant to this angle + - Generate questions for downstream analysis +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Perspective: <perspective> + - Dimensions: <dimensions> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/explorations/exploration-<NNN>.json +CONSTRAINTS: Focus on <perspective> angle +--- +InnerLoop: false", + status: "pending" +}) +``` + +**ANALYZE-001..N** (analyst, parallel): One per perspective. Each blocked by its corresponding EXPLORE-N. + +``` +TaskCreate({ + subject: "ANALYZE-<NNN>", + owner: "analyst-<i+1>", + description: "PURPOSE: Deep analysis from <perspective> perspective | Success: Insights with confidence and evidence +TASK: + - Load exploration-<NNN> results + - Analyze from <perspective> perspective + - Generate insights, discussion points, open questions +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Perspective: <perspective> + - Dimensions: <dimensions> + - Upstream artifacts: explorations/exploration-<NNN>.json + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/analyses/analysis-<NNN>.json +CONSTRAINTS: <perspective> perspective | <dimensions> +--- +InnerLoop: false", + blockedBy: ["EXPLORE-<NNN>"], + status: "pending" +}) +``` + +**DISCUSS-001** (discussant): Blocked by all ANALYZE tasks. + +``` +TaskCreate({ + subject: "DISCUSS-001", + description: "PURPOSE: Process analysis results into discussion summary | Success: Convergent themes and discussion points identified +TASK: + - Aggregate all analysis results across perspectives + - Identify convergent themes and conflicting views + - Generate top discussion points and open questions +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Round: 1 + - Type: initial + - Upstream artifacts: analyses/*.json + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/discussions/discussion-round-001.json + discussion.md update +CONSTRAINTS: Aggregate only, no new exploration +--- +InnerLoop: false", + blockedBy: ["ANALYZE-001", ..., "ANALYZE-<N>"], + status: "pending" +}) +``` + +**SYNTH-001** (synthesizer): Blocked by DISCUSS-001. + +``` +TaskCreate({ + subject: "SYNTH-001", + description: "PURPOSE: Cross-perspective integration into final conclusions | Success: Executive summary with prioritized recommendations +...same as Quick mode SYNTH-001 but blocked by DISCUSS-001..." + blockedBy: ["DISCUSS-001"], + status: "pending" +}) +``` + +--- + +### Deep Mode Task Chain + +Same as Standard mode, but **omit SYNTH-001**. It will be created dynamically after the discussion loop completes, blocked by the last DISCUSS-N task. + +--- ## Discussion Loop Task Creation -讨论循环中动态创建任务: +Dynamic tasks created during discussion loop: -```javascript -// 创建新一轮讨论任务 -function createDiscussionTask(round, type, userFeedback, sessionFolder) { - const suffix = String(round).padStart(3, '0') - TaskCreate({ - subject: `DISCUSS-${suffix}: 讨论处理 (Round ${round})`, - description: `讨论处理\nsession: ${sessionFolder}\nround: ${round}\ntype: ${type}\nuser_feedback: ${userFeedback}`, - activeForm: `讨论 Round ${round} 进行中` - }) - - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith(`DISCUSS-${suffix}`)) - TaskUpdate({ taskId: newTask.id, owner: 'discussant' }) - return newTask.id -} - -// 创建补充分析任务(方向调整时) -function createAnalysisFix(round, adjustedFocus, sessionFolder) { - const suffix = `fix-${round}` - TaskCreate({ - subject: `ANALYZE-${suffix}: 补充分析 (方向调整 Round ${round})`, - description: `补充分析\nsession: ${sessionFolder}\nadjusted_focus: ${adjustedFocus}\ntype: direction-fix`, - activeForm: `补充分析 Round ${round} 进行中` - }) - - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith(`ANALYZE-${suffix}`)) - TaskUpdate({ taskId: newTask.id, owner: 'analyst' }) - return newTask.id -} - -// 创建最终综合任务 -function createSynthesisTask(sessionFolder, blockedByIds) { - TaskCreate({ - subject: `SYNTH-001: 结论综合`, - description: `跨视角整合\nsession: ${sessionFolder}\ntype: final`, - activeForm: `结论综合进行中` - }) - - const allTasks = TaskList() - const newTask = allTasks.find(t => t.subject.startsWith('SYNTH-001')) - TaskUpdate({ - taskId: newTask.id, - owner: 'synthesizer', - addBlockedBy: blockedByIds - }) - return newTask.id -} +**DISCUSS-N** (subsequent rounds): +``` +TaskCreate({ + subject: "DISCUSS-<NNN>", + description: "PURPOSE: Process discussion round <N> | Success: Updated understanding with user feedback integrated +TASK: + - Process user feedback: <feedback> + - Execute <type> discussion strategy + - Update discussion timeline +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Round: <N> + - Type: <deepen|direction-adjusted|specific-questions> + - User feedback: <feedback> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/discussions/discussion-round-<NNN>.json +--- +InnerLoop: false", + status: "pending" +}) ``` -## Output Format - +**ANALYZE-fix-N** (direction adjustment): ``` -## Task Chain Created - -### Mode: [quick|standard|deep] -### Pipeline Stages: [count] -- [prefix]-[suffix]: [description] (owner: [role], blocked by: [deps]) - -### Verification: PASS/FAIL +TaskCreate({ + subject: "ANALYZE-fix-<N>", + description: "PURPOSE: Supplementary analysis with adjusted focus | Success: New insights from adjusted direction +TASK: + - Re-analyze from adjusted perspective: <adjusted_focus> + - Build on previous exploration findings + - Generate updated discussion points +CONTEXT: + - Session: <session-folder> + - Topic: <topic> + - Type: direction-fix + - Adjusted focus: <adjusted_focus> + - Shared memory: <session>/wisdom/.msg/meta.json +EXPECTED: <session>/analyses/analysis-fix-<N>.json +--- +InnerLoop: false", + status: "pending" +}) ``` -## Error Handling +## Phase 4: Validation -| Scenario | Resolution | -|----------|------------| -| Task creation fails | Retry once, then report to user | -| Dependency cycle detected | Flatten dependencies, warn coordinator | -| Invalid pipelineMode | Default to 'standard' mode | -| Too many perspectives (>4) | Truncate to first 4, warn user | -| Timeout (>5 min) | Report partial results, notify coordinator | +Verify task chain integrity: + +| Check | Method | Expected | +|-------|--------|----------| +| Task count correct | TaskList count | quick: 3, standard: 2N+2, deep: 2N+1 | +| Dependencies correct | Trace blockedBy | Acyclic, correct ordering | +| All descriptions have PURPOSE/TASK/CONTEXT/EXPECTED | Pattern check | All present | +| Session path in every task | Check CONTEXT | Session: <folder> present | diff --git a/.claude/skills/team-ultra-analyze/roles/coordinator/commands/monitor.md b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/monitor.md index a81674f9..a19182fc 100644 --- a/.claude/skills/team-ultra-analyze/roles/coordinator/commands/monitor.md +++ b/.claude/skills/team-ultra-analyze/roles/coordinator/commands/monitor.md @@ -67,8 +67,8 @@ const autoYes = /\b(-y|--yes)\b/.test(args) ### Step 1: Context Preparation ```javascript -// 从 shared memory 获取当前状态 -const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +// 从 role state 获取当前状态 +const sharedMemory = mcp__ccw-tools__team_msg({ operation: "get_state", session_id: sessionId }) let discussionRound = 0 const MAX_DISCUSSION_ROUNDS = pipelineMode === 'deep' ? 5 : (pipelineMode === 'standard' ? 1 : 0) @@ -102,36 +102,32 @@ for (const stageTask of preDiscussionTasks) { TaskUpdate({ taskId: stageTask.id, status: 'in_progress' }) mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: workerConfig.role, type: "task_unblocked", summary: `[coordinator] 启动阶段: ${stageTask.subject} → ${workerConfig.role}` }) // 3. 同步 spawn worker — 阻塞直到 worker 返回(Stop-Wait 核心) const workerResult = Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn ${workerConfig.role} worker for ${stageTask.subject}`, team_name: teamName, name: workerConfig.role, - prompt: `你是 team "${teamName}" 的 ${workerConfig.role.toUpperCase()}。 + prompt: `## Role Assignment +role: ${workerConfig.role} +role_spec: .claude/skills/team-ultra-analyze/role-specs/${workerConfig.role}.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: ${teamName} +requirement: ${stageTask.description || taskDescription} +inner_loop: false -## ⚠️ 首要指令(MUST) -Skill(skill="team-ultra-analyze", args="${workerConfig.skillArgs}") +## Current Task +- Task ID: ${stageTask.id} +- Task: ${stageTask.subject} -## 当前任务 -- 任务 ID: ${stageTask.id} -- 任务: ${stageTask.subject} -- 描述: ${stageTask.description || taskDescription} -- Session: ${sessionFolder} - -## 角色准则(强制) -- 所有输出必须带 [${workerConfig.role}] 标识前缀 -- 仅与 coordinator 通信 - -## 工作流程 -1. Skill(skill="team-ultra-analyze", args="${workerConfig.skillArgs}") 获取角色定义 -2. 执行任务 → 汇报结果 -3. TaskUpdate({ taskId: "${stageTask.id}", status: "completed" })`, +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 }) @@ -142,7 +138,7 @@ Skill(skill="team-ultra-analyze", args="${workerConfig.skillArgs}") handleStageTimeout(stageTask, 0, autoYes) } else { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: "user", type: "quality_gate", summary: `[coordinator] 阶段完成: ${stageTask.subject}` }) @@ -206,26 +202,25 @@ if (MAX_DISCUSSION_ROUNDS === 0) { if (discussTask) { TaskUpdate({ taskId: discussTask.id, status: 'in_progress' }) const discussResult = Task({ - subagent_type: "general-purpose", + subagent_type: "team-worker", description: `Spawn discussant worker for ${discussTask.subject}`, team_name: teamName, name: "discussant", - prompt: `你是 team "${teamName}" 的 DISCUSSANT。 + prompt: `## Role Assignment +role: discussant +role_spec: .claude/skills/team-ultra-analyze/role-specs/discussant.md +session: ${sessionFolder} +session_id: ${sessionId} +team_name: ${teamName} +requirement: Discussion round ${discussionRound + 1} +inner_loop: false -## Primary Directive -Skill(skill="team-ultra-analyze", args="--role=discussant") - -## Assignment +## Current Task - Task ID: ${discussTask.id} - Task: ${discussTask.subject} -- Session: ${sessionFolder} -## Workflow -1. Skill(skill="team-ultra-analyze", args="--role=discussant") to load role definition -2. Execute task per role.md -3. TaskUpdate({ taskId: "${discussTask.id}", status: "completed" }) - -All outputs carry [discussant] tag.`, +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 }) } @@ -248,14 +243,19 @@ All outputs carry [discussant] tag.`, const feedback = feedbackResult["Discussion Feedback"] // 📌 记录用户反馈到 decision_trail - const latestMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) + const latestMemory = mcp__ccw-tools__team_msg({ operation: "get_state", session_id: sessionId }) + latestMemory.decision_trail = latestMemory.decision_trail || [] latestMemory.decision_trail.push({ round: discussionRound + 1, decision: feedback, context: `User feedback at discussion round ${discussionRound + 1}`, timestamp: new Date().toISOString() }) - Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(latestMemory, null, 2)) + mcp__ccw-tools__team_msg({ + operation: "log", session_id: sessionId, from: "coordinator", + type: "state_update", + data: { decision_trail: latestMemory.decision_trail } + }) if (feedback === "分析完成") { // 📌 Record completion decision @@ -356,7 +356,7 @@ ${data.updated_understanding || '(Updated by discussant)'} function handleStageTimeout(stageTask, _unused, autoYes) { if (autoYes) { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: "user", type: "error", summary: `[coordinator] [auto] 阶段 ${stageTask.subject} worker 返回但未完成,自动跳过` }) @@ -382,7 +382,7 @@ function handleStageTimeout(stageTask, _unused, autoYes) { TaskUpdate({ taskId: stageTask.id, status: 'deleted' }) } else if (answer === "终止流水线") { mcp__ccw-tools__team_msg({ - operation: "log", team: sessionId, from: "coordinator", + operation: "log", session_id: sessionId, from: "coordinator", to: "user", type: "shutdown", summary: `[coordinator] 用户终止流水线,当前阶段: ${stageTask.subject}` }) @@ -423,7 +423,7 @@ All outputs carry [synthesizer] tag.`, } // 汇总所有结果 -const finalMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`)) +const finalMemory = mcp__ccw-tools__team_msg({ operation: "get_state", session_id: sessionId }) const allFinalTasks = TaskList() const workerTasks = allFinalTasks.filter(t => t.owner && t.owner !== 'coordinator') const summary = { diff --git a/.claude/skills/team-ultra-analyze/roles/coordinator/role.md b/.claude/skills/team-ultra-analyze/roles/coordinator/role.md index 01cc2cf9..e3d37e62 100644 --- a/.claude/skills/team-ultra-analyze/roles/coordinator/role.md +++ b/.claude/skills/team-ultra-analyze/roles/coordinator/role.md @@ -1,340 +1,254 @@ -# Coordinator Role +# Coordinator - Ultra Analyze Team -分析团队协调者。编排 pipeline:话题澄清 → 管道选择 → 团队创建 → 任务分发 → 讨论循环 → 结果汇报。 +**Role**: coordinator +**Type**: Orchestrator +**Team**: ultra-analyze -## Identity - -- **Name**: `coordinator` | **Tag**: `[coordinator]` -- **Responsibility**: Orchestration (Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results) +Orchestrates the analysis pipeline: topic clarification, pipeline mode selection, task dispatch, discussion loop management, and final synthesis. Spawns team-worker agents for all worker roles. ## Boundaries ### MUST -- 所有输出(SendMessage、team_msg、日志)必须带 `[coordinator]` 标识 -- 仅负责话题澄清、管道选择、任务创建/分发、讨论循环驱动、结果汇报 -- 通过 TaskCreate 创建任务并分配给 worker 角色 -- 通过消息总线监控 worker 进度并路由消息 -- 讨论循环中通过 AskUserQuestion 收集用户反馈 -- 维护会话状态持久化 +- 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 +- Handle discussion loop with max 5 rounds (Deep mode) +- Execute completion action in Phase 5 ### MUST NOT -- 直接执行任何业务任务(代码探索、CLI 分析、综合整合等) -- 直接调用 cli-explore-agent、code-developer 等实现类 subagent -- 直接调用 CLI 分析工具(ccw cli) -- 绕过 worker 角色自行完成应委派的工作 -- 在输出中省略 `[coordinator]` 标识 - -> **核心原则**: coordinator 是指挥者,不是执行者。所有实际工作必须通过 TaskCreate 委派给 worker 角色。 +- Implement domain logic (exploring, analyzing, discussing, synthesizing) -- workers handle this +- Spawn workers without creating tasks first +- Skip checkpoints when configured +- Force-advance pipeline past failed stages +- Directly call cli-explore-agent, CLI analysis tools, or execute codebase exploration --- -## Toolbox +## Command Execution Protocol -### Available Commands +When coordinator needs to execute a command (dispatch, monitor): -| 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 | -|------|------|---------|---------| -| `TaskCreate` | Task | coordinator | 创建任务并分配给 worker | -| `TaskList` | Task | coordinator | 监控任务状态 | -| `TeamCreate` | Team | coordinator | 创建分析团队 | -| `AskUserQuestion` | Interaction | coordinator | 收集用户反馈 | -| `SendMessage` | Communication | coordinator | 与 worker 通信 | -| `Read/Write` | File | coordinator | 会话状态管理 | - ---- - -## Message Types - -| Type | Direction | Trigger | Description | -|------|-----------|---------|-------------| -| `pipeline_selected` | coordinator → all | 管道模式确定 | Quick/Standard/Deep | -| `discussion_round` | coordinator → discussant | 用户反馈收集后 | 触发讨论处理 | -| `direction_adjusted` | coordinator → analyst | 方向调整 | 触发补充分析 | -| `task_unblocked` | coordinator → worker | 依赖解除 | 任务可执行 | -| `error` | coordinator → user | 协调错误 | 阻塞性问题 | -| `shutdown` | coordinator → all | 团队关闭 | 清理资源 | - -## Message Bus - -Before every SendMessage, log via `mcp__ccw-tools__team_msg`: +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: ``` -mcp__ccw-tools__team_msg({ - operation: "log", - team: <session-id>, - from: "coordinator", - to: "<recipient>", - type: "<message-type>", - summary: "[coordinator] <summary>", - ref: "<artifact-path>" -}) -``` - -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. - -**CLI fallback** (when MCP unavailable): - -``` -Bash("ccw team log --team <session-id> --from coordinator --to <recipient> --type <type> --summary \"[coordinator] ...\" --ref <path> --json") +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, first detect the invocation type: +When coordinator is invoked, detect invocation type: | Detection | Condition | Handler | |-----------|-----------|---------| -| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline | -| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement | -| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline | -| New session | None of the above | -> Phase 0 (Session Resume Check) | +| 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) | -For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP. +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/UAN-*/.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 Topic Understanding below --- ## Phase 0: Session Resume Check -**Objective**: Detect and resume interrupted sessions before creating new ones. +Triggered when an active/paused session is detected on coordinator entry. -**Workflow**: +1. Load session.json from detected session folder +2. Audit task list: -1. Scan `.workflow/.team/UAN-*/` 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 +``` +TaskList() +``` -**Session Reconciliation**: +3. Reconcile session state vs task status: -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 +| 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: "ultra-analyze" }) +``` + +5. Spawn workers for ready tasks -> Phase 4 coordination loop --- ## Phase 1: Topic Understanding & Requirement Clarification -**Objective**: Parse user input and gather execution parameters. - -**Workflow**: - -1. **Parse arguments** for explicit settings: mode, scope, focus areas - -2. **Extract topic description**: Remove `--role`, `--team`, `--mode` flags from arguments +1. Parse user task description from $ARGUMENTS +2. Extract explicit settings: `--mode`, scope, focus areas 3. **Pipeline mode selection**: -| Condition | Mode | -|-----------|------| -| `--mode=quick` explicit or topic contains "quick/overview/fast" | Quick | -| `--mode=deep` explicit or topic contains "deep/thorough/detailed/comprehensive" | Deep | -| Default (no match) | Standard | +| 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, 选择 | +| 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 only): - -| Question | Purpose | -|----------|---------| -| Analysis Focus | Multi-select focus directions | -| Analysis Perspectives | Select technical/architectural/business/domain views | -| Analysis Depth | Confirm Quick/Standard/Deep | - -**Success**: All parameters captured, mode finalized. +5. **Interactive clarification** (non-auto mode): AskUserQuestion for focus, perspectives, depth. --- ## Phase 2: Create Team + Initialize Session -**Objective**: Initialize team, session file, and wisdom directory. - -**Workflow**: - -1. **Generate session ID**: `UAN-{slug}-{YYYY-MM-DD}` -2. **Create session folder structure**: +1. Generate session ID: `UAN-{slug}-{YYYY-MM-DD}` +2. Create session folder structure: ``` .workflow/.team/UAN-{slug}-{date}/ -+-- shared-memory.json ++-- .msg/messages.jsonl ++-- .msg/meta.json +-- discussion.md +-- explorations/ +-- analyses/ +-- discussions/ +-- wisdom/ - +-- learnings.md - +-- decisions.md - +-- conventions.md - +-- issues.md + +-- learnings.md, decisions.md, conventions.md, issues.md ``` -3. **Initialize shared-memory.json**: - -```json -{ - "explorations": [], - "analyses": [], - "discussions": [], - "synthesis": null, - "decision_trail": [], - "current_understanding": { - "established": [], - "clarified": [], - "key_insights": [] - } -} -``` - -4. **Initialize discussion.md** with session metadata -5. **Call TeamCreate** with team name "ultra-analyze" -6. **Spawn worker roles** (see SKILL.md Coordinator Spawn Template) - -**Success**: Team created, session file written, wisdom initialized, workers ready. +3. Write session.json with mode, requirement, timestamp +4. Initialize .msg/meta.json +5. Call `TeamCreate({ team_name: "ultra-analyze" })` --- ## Phase 3: Create Task Chain -**Objective**: Dispatch tasks based on mode with proper dependencies. +Execute `commands/dispatch.md` inline (Command Execution Protocol): -Delegate to `commands/dispatch.md` which creates the full task chain: - -**Quick Mode** (3 beats, serial): - -``` -EXPLORE-001 → ANALYZE-001 → SYNTH-001 -``` - -**Standard Mode** (4 beats, parallel windows): - -``` -[EXPLORE-001..N](parallel) → [ANALYZE-001..N](parallel) → DISCUSS-001 → SYNTH-001 -``` - -**Deep Mode** (4+ beats, with discussion loop): - -``` -[EXPLORE-001..N] → [ANALYZE-001..N] → DISCUSS-001 → [ANALYZE-fix] → DISCUSS-002 → ... → SYNTH-001 -``` - -**Task chain rules**: - -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 +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 --- -## Phase 4: Discussion Loop + Coordination +## Phase 4: Spawn & Coordination Loop -**Objective**: Spawn workers in background, monitor callbacks, drive discussion loop. +### Initial Spawn -**Design**: Spawn-and-Stop + Callback pattern. +Find first unblocked tasks and spawn their workers: -- Spawn workers with `Task(run_in_background: true)` -> immediately return -- Worker completes -> SendMessage callback -> auto-advance -- User can use "check" / "resume" to manually advance -- Coordinator does one operation per invocation, then STOPS +``` +Task({ + 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 -**Workflow** (see `commands/monitor.md` for details): +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.` +}) +``` -1. Load `commands/monitor.md` -2. Find tasks with: status=pending, blockedBy all resolved, owner assigned -3. For each ready task -> spawn worker (see SKILL.md Spawn Template) -4. Output status summary -5. STOP +**STOP** after spawning. Wait for worker callback. -**Callback handlers**: +### Coordination (via monitor.md handlers) -| Received Message | Action | -|-----------------|--------| -| `exploration_ready` | Mark EXPLORE complete -> unblock ANALYZE | -| `analysis_ready` | Mark ANALYZE complete -> unblock DISCUSS or SYNTH | -| `discussion_processed` | Mark DISCUSS complete -> AskUser -> decide next | -| `synthesis_ready` | Mark SYNTH complete -> Phase 5 | -| Worker: `error` | Assess severity -> retry or report to user | +All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: -**Discussion loop logic** (Standard/Deep mode): - -| Round | Action | -|-------|--------| -| After DISCUSS-N completes | AskUserQuestion: continue / adjust direction / complete / specific questions | -| User: "继续深入" | Create DISCUSS-(N+1) | -| User: "调整方向" | Create ANALYZE-fix + DISCUSS-(N+1) | -| User: "分析完成" | Exit loop, create SYNTH-001 | -| Round > MAX_ROUNDS (5) | Force synthesis, offer continuation | - -**Pipeline advancement** driven by three wake sources: - -- Worker callback (automatic) -> Entry Router -> handleCallback -- User "check" -> handleCheck (status only) -- User "resume" -> handleResume (advance) +- handleCallback -> mark task done -> check pipeline -> handleSpawnNext +- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP +- handleComplete -> all done -> Phase 5 --- -## Phase 5: Report + Persist +## Phase 5: Report + Completion Action -**Objective**: Completion report and follow-up options. +1. Load session state -> count completed tasks, calculate duration +2. List deliverables: -**Workflow**: +| Deliverable | Path | +|-------------|------| +| Explorations | <session>/explorations/*.json | +| Analyses | <session>/analyses/*.json | +| Discussion | <session>/discussion.md | +| Conclusions | <session>/conclusions.json | -1. Load session state -> count completed tasks, duration -2. List deliverables with output paths -3. Update session status -> "completed" -4. Output final report -5. Offer next steps to user +3. Include discussion summaries and decision trail +4. Output pipeline summary: task count, duration, mode -**Report structure**: +5. **Completion Action** (interactive): ``` -## [coordinator] Analysis Complete - -**Mode**: <mode> -**Topic**: <topic> -**Explorations**: <count> -**Analyses**: <count> -**Discussion Rounds**: <count> -**Decisions Made**: <count> - -📄 Discussion: <session-folder>/discussion.md -📊 Conclusions: <session-folder>/conclusions.json +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" } + ] + }] +}) ``` -**Next step options**: +6. Handle user choice: -| Option | Description | -|--------|-------------| -| 创建Issue | 基于结论创建 Issue | -| 生成任务 | 启动 workflow-lite-planex 规划实施 | -| 导出报告 | 生成独立分析报告 | -| 关闭团队 | 关闭所有 teammate 并清理 | +| Choice | Steps | +|--------|-------| +| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("ultra-analyze") -> output final summary | +| Keep Active | Update session status="paused" -> output resume instructions | +| Export Results | AskUserQuestion for target directory -> copy artifacts -> Archive & Clean | --- @@ -345,10 +259,6 @@ EXPLORE-001 → ANALYZE-001 → SYNTH-001 | Teammate unresponsive | Send follow-up, 2x -> respawn | | Explorer finds nothing | Continue with limited context, note limitation | | Discussion loop stuck >5 rounds | Force synthesis, offer continuation | -| CLI unavailable | Fallback chain: gemini -> codex -> manual | +| CLI unavailable | Fallback chain: gemini -> codex -> claude | | User timeout in discussion | Save state, show resume command | -| Max rounds reached | Force synthesis, offer continuation option | | Session folder conflict | Append timestamp suffix | -| 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-ultra-analyze/roles/discussant/role.md b/.claude/skills/team-ultra-analyze/roles/discussant/role.md index 0c9d5d47..35e0f096 100644 --- a/.claude/skills/team-ultra-analyze/roles/discussant/role.md +++ b/.claude/skills/team-ultra-analyze/roles/discussant/role.md @@ -17,7 +17,7 @@ - Only communicate with coordinator via SendMessage - Work strictly within discussion processing responsibility scope - Execute deep exploration based on user feedback and existing analysis -- Write discussion results to shared-memory.json `discussions` field +- Share discussion results via team_msg(type='state_update') - Update discussion.md discussion timeline ### MUST NOT @@ -71,21 +71,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "discussant", - to: "coordinator", type: "discussion_processed", - summary: "[discussant] DISCUSS complete: <summary>", ref: "<output-path>" }) ``` -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from discussant --to coordinator --type discussion_processed --summary \"[discussant] ...\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from discussant --type discussion_processed --ref <path> --json") ``` --- @@ -106,7 +104,7 @@ Falls back to `discussant` for single-instance role. 1. Extract session path from task description 2. Extract topic, round number, discussion type, user feedback -3. Read shared-memory.json for existing context +3. Read role states via team_msg(operation="get_state") for existing context 4. Read all analysis results 5. Read all exploration results 6. Aggregate current findings, insights, questions diff --git a/.claude/skills/team-ultra-analyze/roles/explorer/role.md b/.claude/skills/team-ultra-analyze/roles/explorer/role.md index bb29c9d6..82e210a9 100644 --- a/.claude/skills/team-ultra-analyze/roles/explorer/role.md +++ b/.claude/skills/team-ultra-analyze/roles/explorer/role.md @@ -16,7 +16,7 @@ - All output (SendMessage, team_msg, logs) must carry `[explorer]` identifier - Only communicate with coordinator via SendMessage - Work strictly within codebase exploration responsibility scope -- Write exploration results to shared-memory.json `explorations` field +- Share exploration results via team_msg(type='state_update') ### MUST NOT @@ -64,21 +64,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "explorer", - to: "coordinator", type: "exploration_ready", - summary: "[explorer] EXPLORE complete: <summary>", ref: "<output-path>" }) ``` -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from explorer --to coordinator --type exploration_ready --summary \"[explorer] ...\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from explorer --type exploration_ready --ref <path> --json") ``` --- @@ -99,7 +97,7 @@ For parallel instances, parse `--agent-name` from arguments for owner matching. 1. Extract session path from task description 2. Extract topic, perspective, dimensions from task metadata -3. Read shared-memory.json for existing context +3. Read role states via team_msg(operation="get_state") for existing context 4. Determine exploration number from task subject (EXPLORE-N) **Context extraction**: diff --git a/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md b/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md index a98cac23..65dc3494 100644 --- a/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md +++ b/.claude/skills/team-ultra-analyze/roles/synthesizer/role.md @@ -17,7 +17,7 @@ - Only communicate with coordinator via SendMessage - Work strictly within synthesis responsibility scope - Integrate all role outputs to generate final conclusions -- Write synthesis results to shared-memory.json `synthesis` field +- Share synthesis results via team_msg(type='state_update') - Update discussion.md conclusions section ### MUST NOT @@ -65,21 +65,19 @@ Before every SendMessage, log via `mcp__ccw-tools__team_msg`: ``` mcp__ccw-tools__team_msg({ operation: "log", - team: <session-id>, + session_id: <session-id>, from: "synthesizer", - to: "coordinator", type: "synthesis_ready", - summary: "[synthesizer] SYNTH complete: <summary>", ref: "<output-path>" }) ``` -> **Note**: `team` must be session ID (e.g., `UAN-xxx-date`), NOT team name. Extract from `Session:` field in task description. +> `to` and `summary` are auto-defaulted by the tool. **CLI fallback** (when MCP unavailable): ``` -Bash("ccw team log --team <session-id> --from synthesizer --to coordinator --type synthesis_ready --summary \"[synthesizer] ...\" --ref <path> --json") +Bash("ccw team log --session-id <session-id> --from synthesizer --type synthesis_ready --ref <path> --json") ``` --- @@ -100,7 +98,7 @@ Falls back to `synthesizer` for single-instance role. 1. Extract session path from task description 2. Extract topic -3. Read shared-memory.json +3. Read role states via team_msg(operation="get_state") 4. Read all exploration files 5. Read all analysis files 6. Read all discussion round files diff --git a/ccw/src/cli.ts b/ccw/src/cli.ts index f04dde6f..6b5479b1 100644 --- a/ccw/src/cli.ts +++ b/ccw/src/cli.ts @@ -358,7 +358,7 @@ export function run(argv: string[]): void { program .command('team [subcommand] [args...]') .description('Team message bus for Agent Team communication') - .option('--team <name>', 'Session ID (e.g., TLS-my-project-2026-02-27)') + .option('--session-id <id>', 'Session ID (e.g., TLS-my-project-2026-02-27)') .option('--from <role>', 'Sender role name') .option('--to <role>', 'Recipient role name (default: coordinator)') .option('--type <type>', 'Message type') diff --git a/ccw/src/commands/team.ts b/ccw/src/commands/team.ts index 9b41500b..a2a832af 100644 --- a/ccw/src/commands/team.ts +++ b/ccw/src/commands/team.ts @@ -3,21 +3,21 @@ * Delegates to team-msg.ts handler for JSONL-based persistent messaging * * Commands: - * ccw team log --team <session-id> --from <role> [--to <role>] [--type <type>] [--summary "..."] - * ccw team broadcast --team <session-id> --from <role> [--type <type>] [--summary "..."] - * ccw team get_state --team <session-id> [--role <role>] - * ccw team read --team <session-id> --id <MSG-NNN> - * ccw team list --team <session-id> [--from <role>] [--to <role>] [--type <type>] [--last <n>] - * ccw team status --team <session-id> - * ccw team delete --team <session-id> --id <MSG-NNN> - * ccw team clear --team <session-id> + * ccw team log --session-id <id> --from <role> [--to <role>] [--type <type>] [--summary "..."] + * ccw team broadcast --session-id <id> --from <role> [--type <type>] [--summary "..."] + * ccw team get_state --session-id <id> [--role <role>] + * ccw team read --session-id <id> --id <MSG-NNN> + * ccw team list --session-id <id> [--from <role>] [--to <role>] [--type <type>] [--last <n>] + * ccw team status --session-id <id> + * ccw team delete --session-id <id> --id <MSG-NNN> + * ccw team clear --session-id <id> */ import chalk from 'chalk'; import { handler } from '../tools/team-msg.js'; interface TeamOptions { - team?: string; + sessionId?: string; from?: string; to?: string; type?: string; @@ -40,15 +40,15 @@ export async function teamCommand( return; } - if (!options.team) { - console.error(chalk.red('Error: --team is required')); + if (!options.sessionId) { + console.error(chalk.red('Error: --session-id is required')); process.exit(1); } // Build params for handler const params: Record<string, unknown> = { operation: subcommand, - team: options.team, + session_id: options.sessionId, }; if (options.from) params.from = options.from; @@ -165,7 +165,7 @@ function printHelp(): void { console.log(chalk.gray(' clear Clear all messages for a team')); console.log(); console.log(' Required:'); - console.log(chalk.gray(' --team <session-id> Session ID (e.g., TLS-my-project-2026-02-27), NOT team name')); + console.log(chalk.gray(' --session-id <id> Session ID (e.g., TLS-my-project-2026-02-27), NOT team name')); console.log(); console.log(' Log/Broadcast Options:'); console.log(chalk.gray(' --from <role> Sender role name (required)')); @@ -190,11 +190,11 @@ function printHelp(): void { console.log(chalk.gray(' --json Output as JSON')); console.log(); console.log(' Examples:'); - console.log(chalk.gray(' ccw team log --team TLS-xxx --from executor --type state_update --data \'{"status":"done"}\'')); - console.log(chalk.gray(' ccw team broadcast --team TLS-xxx --from coordinator --type shutdown')); - console.log(chalk.gray(' ccw team get_state --team TLS-xxx --role executor')); - console.log(chalk.gray(' ccw team list --team TLS-xxx --last 5')); - console.log(chalk.gray(' ccw team read --team TLS-xxx --id MSG-003')); - console.log(chalk.gray(' ccw team status --team TLS-xxx')); + console.log(chalk.gray(' ccw team log --session-id TLS-xxx --from executor --type state_update --data \'{"status":"done"}\'')); + console.log(chalk.gray(' ccw team broadcast --session-id TLS-xxx --from coordinator --type shutdown')); + console.log(chalk.gray(' ccw team get_state --session-id TLS-xxx --role executor')); + console.log(chalk.gray(' ccw team list --session-id TLS-xxx --last 5')); + console.log(chalk.gray(' ccw team read --session-id TLS-xxx --id MSG-003')); + console.log(chalk.gray(' ccw team status --session-id TLS-xxx')); console.log(); } diff --git a/ccw/src/tools/team-msg.ts b/ccw/src/tools/team-msg.ts index 498a824b..c5bb4435 100644 --- a/ccw/src/tools/team-msg.ts +++ b/ccw/src/tools/team-msg.ts @@ -186,9 +186,12 @@ export interface StatusEntry { const ParamsSchema = z.object({ operation: z.enum(['log', 'read', 'list', 'status', 'delete', 'clear', 'broadcast', 'get_state']).describe('Operation to perform'), - // Accept both 'team' (legacy) and 'team_session_id' (preferred) - team: z.string().optional().describe('[deprecated] Use team_session_id instead'), - team_session_id: z.string().optional().describe('Session ID that determines message storage path (e.g., TLS-my-project-2026-02-27)'), + // Session identifier (primary) + session_id: z.string().optional().describe('Session ID that determines message storage path (e.g., TLS-my-project-2026-02-27)'), + + // Legacy params (backward compat) + team_session_id: z.string().optional().describe('[deprecated] Use session_id'), + team: z.string().optional().describe('[deprecated] Use session_id'), // log/broadcast params from: z.string().optional().describe('[log/broadcast/list] Sender role name'), @@ -206,16 +209,15 @@ const ParamsSchema = z.object({ // get_state params role: z.string().optional().describe('[get_state] Role name to query. Omit to get all role states'), - // Legacy backward compat (accepted but ignored — team_session_id replaces this) + // Legacy backward compat (accepted but ignored — session_id replaces this) ref: z.string().optional().describe('[deprecated] Use data.ref instead'), - session_id: z.string().optional().describe('[deprecated] Use team_session_id instead'), }); type Params = z.infer<typeof ParamsSchema>; -/** Resolve team session ID from params, supporting legacy 'team' and new 'team_session_id' */ +/** Resolve team session ID from params, supporting legacy 'team_session_id' and 'team' */ function resolveTeamId(params: Params): string | null { - return params.team_session_id || params.team || params.session_id || null; + return params.session_id || params.team_session_id || params.team || null; } // --- Tool Schema --- @@ -231,15 +233,15 @@ Directory Structure (LEGACY): .workflow/.team-msg/{team-name}/messages.jsonl Operations: - team_msg(operation="log", team_session_id="TLS-xxx", from="planner", type="plan_ready", data={ref: "plan.json"}) - team_msg(operation="log", team_session_id="TLS-xxx", from="coordinator", type="state_update", data={pipeline_mode: "full"}) - team_msg(operation="broadcast", team_session_id="TLS-xxx", from="coordinator", type="shutdown") - team_msg(operation="get_state", team_session_id="TLS-xxx", role="researcher") - team_msg(operation="read", team_session_id="TLS-xxx", id="MSG-003") - team_msg(operation="list", team_session_id="TLS-xxx", from="tester", last=5) - team_msg(operation="status", team_session_id="TLS-xxx") - team_msg(operation="delete", team_session_id="TLS-xxx", id="MSG-003") - team_msg(operation="clear", team_session_id="TLS-xxx") + team_msg(operation="log", session_id="TLS-xxx", from="planner", type="plan_ready", data={ref: "plan.json"}) + team_msg(operation="log", session_id="TLS-xxx", from="coordinator", type="state_update", data={pipeline_mode: "full"}) + team_msg(operation="broadcast", session_id="TLS-xxx", from="coordinator", type="shutdown") + team_msg(operation="get_state", session_id="TLS-xxx", role="researcher") + team_msg(operation="read", session_id="TLS-xxx", id="MSG-003") + team_msg(operation="list", session_id="TLS-xxx", from="tester", last=5) + team_msg(operation="status", session_id="TLS-xxx") + team_msg(operation="delete", session_id="TLS-xxx", id="MSG-003") + team_msg(operation="clear", session_id="TLS-xxx") Defaults: to="coordinator", summary=auto-generated if omitted, type="message" Message types: plan_ready, plan_approved, plan_revision, task_unblocked, impl_complete, impl_progress, test_result, review_result, fix_required, error, shutdown, state_update`, @@ -251,7 +253,7 @@ Message types: plan_ready, plan_approved, plan_revision, task_unblocked, impl_co enum: ['log', 'read', 'list', 'status', 'delete', 'clear', 'broadcast', 'get_state'], description: 'Operation: log | read | list | status | delete | clear | broadcast | get_state', }, - team_session_id: { + session_id: { type: 'string', description: 'Session ID (e.g., TLS-my-project-2026-02-27). Maps to .workflow/.team/{session-id}/.msg/', }, @@ -264,9 +266,9 @@ Message types: plan_ready, plan_approved, plan_revision, task_unblocked, impl_co last: { type: 'number', description: '[list] Last N messages (default 20)', minimum: 1, maximum: 100 }, role: { type: 'string', description: '[get_state] Role name to query. Omit for all roles' }, // Legacy params (backward compat) - team: { type: 'string', description: '[deprecated] Use team_session_id' }, + team_session_id: { type: 'string', description: '[deprecated] Use session_id' }, + team: { type: 'string', description: '[deprecated] Use session_id' }, ref: { type: 'string', description: '[deprecated] Use data.ref instead' }, - session_id: { type: 'string', description: '[deprecated] Use team_session_id' }, }, required: ['operation'], }, @@ -541,10 +543,10 @@ export async function handler(params: Record<string, unknown>): Promise<ToolResu const p = parsed.data; - // Resolve team ID from team_session_id / team / session_id (backward compat) + // Resolve team ID from session_id / team_session_id / team (backward compat) const teamId = resolveTeamId(p); if (!teamId) { - return { success: false, error: 'Missing required parameter: team_session_id (or legacy "team")' }; + return { success: false, error: 'Missing required parameter: session_id (or legacy "team_session_id" / "team")' }; } switch (p.operation) {