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.
This commit is contained in:
catlog22
2026-03-03 23:35:41 +08:00
parent a7ed0365f7
commit 26bda9c634
188 changed files with 9332 additions and 3512 deletions

View File

@@ -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>,
session_id=<session_id>,
from=<role>,
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>,
session_id=<session_id>,
from=<role>,
type="fast_advance",
summary="[<role>] fast-advanced <completed-task-id> → spawned <successor-role> for <successor-task-id>"
@@ -393,7 +393,7 @@ Always use `mcp__ccw-tools__team_msg` for team communication.
| Param | Value |
|-------|-------|
| operation | "log" |
| team_session_id | `<session_id>` (NOT team_name) |
| session_id | `<session_id>` (NOT team_name) |
| from | `<role>` |
| 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>,
session_id=<session_id>,
role=<upstream_role> // omit to get ALL role states
)
```
@@ -418,7 +418,7 @@ Returns `role_state[<role>]` from meta.json.
```
mcp__ccw-tools__team_msg(
operation="broadcast",
team_session_id=<session_id>,
session_id=<session_id>,
from=<role>,
type=<type>
)
@@ -428,7 +428,7 @@ Equivalent to `log` with `to="all"`. Summary auto-generated.
**CLI fallback** (if MCP tool unavailable):
```
ccw team log --team <session_id> --from <role> --type <type> --json
ccw team log --session-id <session_id> --from <role> --type <type> --json
```
---

View File

@@ -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 <path>]",
"category": "general",
"subcategory": null,
"usage_scenario": "implementation",

View File

@@ -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"
}
]
]

View File

@@ -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"
]
}
}
}

View File

@@ -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"
}
]
}
}

View File

@@ -384,7 +384,9 @@ AskUserQuestion({
| +-- <hash>.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 |

View File

@@ -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 | <session>/wisdom/shared-memory.json | No |
| .msg/meta.json | <session>/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 `<session>/wisdom/shared-memory.json` under `analyzer` namespace:
3. Update `<session>/wisdom/.msg/meta.json` under `analyzer` namespace:
- Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back

View File

@@ -18,13 +18,13 @@ Analyze architecture reports and baseline metrics to design a prioritized refact
|-------|--------|----------|
| Architecture report | <session>/artifacts/architecture-report.md | Yes |
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
| shared-memory.json | <session>/wisdom/shared-memory.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
1. Extract session path from task description
2. Read architecture report -- extract ranked issue list with severities and categories
3. Read architecture baseline -- extract current structural metrics
4. Load 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 `<session>/wisdom/shared-memory.json` under `designer` namespace:
2. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace:
- Read existing -> merge -> write back:
```json
{

View File

@@ -28,7 +28,7 @@ Implement architecture refactoring changes following the design plan. For FIX ta
| Branch refactoring detail | <session>/artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) |
| Pipeline refactoring plan | <session>/artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) |
| Review/validation feedback | From task description | Yes (FIX) |
| shared-memory.json | <session>/wisdom/shared-memory.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) |
@@ -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

View File

@@ -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 | <session>/wisdom/shared-memory.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. **Detect branch/pipeline context** from task description:
@@ -37,7 +37,7 @@ Review refactoring code changes for correctness, pattern consistency, completene
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md`
- Independent: Read `<session>/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: `<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>/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 } }`

View File

@@ -17,7 +17,7 @@ Validate refactoring changes by running build checks, test suites, dependency me
|-------|--------|----------|
| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes |
| Refactoring plan / detail | Varies by mode (see below) | Yes |
| shared-memory.json | <session>/wisdom/shared-memory.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. **Detect branch/pipeline context** from task description:
@@ -37,7 +37,7 @@ Validate refactoring changes by running build checks, test suites, dependency me
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
5. Load 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: `<session>/artifacts/pipelines/{P}/validation-results.json`
- Content: Per-dimension: name, baseline value, current value, improvement/regression, verdict; Overall verdict: PASS / WARN / FAIL; Failure details (if any)
2. Update `<session>/wisdom/shared-memory.json` under scoped namespace:
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
- Single: merge `{ "validator": { verdict, improvements, regressions, build_pass, test_pass } }`
- Fan-out: merge `{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } }`
- Independent: merge `{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }`

View File

@@ -38,7 +38,7 @@ CONTEXT:
- Scope: <refactoring-scope>
- Branch: <branch-id or 'none'>
- Upstream artifacts: <artifact-1>, <artifact-2>
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits, focus areas>
---
@@ -77,7 +77,7 @@ CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/architecture-baseline.json + <session>/artifacts/architecture-report.md | Quantified metrics with evidence
CONSTRAINTS: Focus on <refactoring-scope> | Analyze before any changes
---
@@ -101,7 +101,7 @@ CONTEXT:
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, architecture-report.md
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/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: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/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: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, refactoring-plan.md
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/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: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md, validation-results.json (if available)
- Shared memory: <session>/wisdom/shared-memory.json
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/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-<P>01", ... }) // blockedBy: ["REFACTOR-<P>
Task descriptions follow same template as single mode, with additions:
- `Pipeline: <P>` in CONTEXT
- Artifact paths use `<session>/artifacts/pipelines/<P>/` instead of `<session>/artifacts/`
- Shared-memory namespace uses `<role>.<P>` (e.g., `analyzer.A`, `refactorer.B`)
- Meta.json namespace uses `<role>.<P>` (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: <session-folder>
- Scope: refactor auth module
- Pipeline: A
- Shared memory: <session>/wisdom/shared-memory.json (namespace: analyzer.A)
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: analyzer.A)
EXPECTED: <session>/artifacts/pipelines/A/architecture-baseline.json + architecture-report.md
CONSTRAINTS: Focus on auth module scope
---
@@ -255,7 +255,7 @@ PipelineId: A",
**Procedure**:
1. Read `<session>/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: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/shared-memory.json (namespace: refactorer.B{NN})
- Shared memory: <session>/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: <session-folder>
- Branch: B{NN}
- Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/shared-memory.json (namespace: validator.B{NN})
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: validator.B{NN})
EXPECTED: <session>/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: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/shared-memory.json (namespace: reviewer.B{NN})
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: reviewer.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/review-report.md
CONSTRAINTS: Only review this branch's changes
---

View File

@@ -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: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/validation-results.json
- Shared memory: <session>/wisdom/shared-memory.json (namespace: refactorer.B{NN})
- Shared memory: <session>/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
---

View File

@@ -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/<session-id>/artifacts/pipelines/A .workflow/<session-i
- `independent_targets`: populated for independent mode (e.g., ["refactor auth", "refactor 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>/wisdom/.msg/meta.json", { "session_id": "<session-id>", "requirement": "<requirement>", "parallel_mode": "<mode>" })
```
4. Create team:

View File

@@ -11,23 +11,23 @@ Unified team skill: multi-angle brainstorming via Generator-Critic loops, shared
## Architecture
```
┌───────────────────────────────────────────────────┐
Skill(skill="team-brainstorm")
args="<topic>" 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="<topic-description>" |
+-------------------+-------------------------------+
|
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=**<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., `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 `[<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
@@ -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=**<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., `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-<slug>-<date>/` |
| 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 <role> worker",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `You are team "brainstorm" <ROLE>.
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: <true|false>
## Primary Directive
All your work must be executed through Skill to load role definition:
Skill(skill="team-brainstorm", args="--role=<role>")
Current topic: <topic-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).`
})
```
**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-<N> worker",
team_name: "brainstorm",
name: "ideator-<N>",
run_in_background: true,
prompt: `You are team "brainstorm" IDEATOR (ideator-<N>).
Your agent name is "ideator-<N>", 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-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
agent_name: ideator-<N>
inner_loop: false
## Primary Directive
Skill(skill="team-brainstorm", args="--role=ideator --agent-name=ideator-<N>")
Current topic: <topic-description>
Session: <session-folder>
## Role Guidelines
- Only process tasks where owner === "ideator-<N>" with IDEA-* prefix
- All output prefixed with [ideator] identifier
## Workflow
1. TaskList -> find tasks where owner === "ideator-<N>" 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-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
@@ -371,12 +354,40 @@ Session: <session-folder>
---
## 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-<slug>-<YYYY-MM-DD>/
├── 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

View File

@@ -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 | <session>/ideas/*.md files | Yes |
| Previous critiques | <session>/.msg/meta.json critique_insights | No |
1. Extract session path from task description (match "Session: <path>")
2. Glob idea files from <session>/ideas/
3. Read all idea files for analysis
4. Read .msg/meta.json critique_insights to avoid repeating past challenges
## Phase 3: Critical Analysis
**Challenge Dimensions** (apply to each idea):
| Dimension | Focus |
|-----------|-------|
| Assumption Validity | Does the core assumption hold? Counter-examples? |
| Feasibility | Technical/resource/time feasibility? |
| Risk Assessment | Worst case scenario? Hidden risks? |
| Competitive Analysis | Better alternatives already exist? |
**Severity Classification**:
| Severity | Criteria |
|----------|----------|
| CRITICAL | Fundamental issue, idea may need replacement |
| HIGH | Significant flaw, requires revision |
| MEDIUM | Notable weakness, needs consideration |
| LOW | Minor concern, does not invalidate the idea |
**Generator-Critic Signal**:
| Condition | Signal |
|-----------|--------|
| Any CRITICAL or HIGH severity | REVISION_NEEDED |
| All MEDIUM or lower | CONVERGED |
**Output**: Write to `<session>/critiques/critique-<num>.md`
- Sections: Ideas Reviewed, Per-idea challenges with severity, Summary table with counts, GC Signal
## Phase 4: Severity Summary
1. Count challenges by severity level
2. Determine signal: REVISION_NEEDED if critical+high > 0, else CONVERGED
3. Update shared state:
- Append challenges to .msg/meta.json critique_insights
- Each entry: idea, severity, key_challenge, round

View File

@@ -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 | <session>/synthesis/*.md files | Yes |
| All ideas | <session>/ideas/*.md files | No (for context) |
| All critiques | <session>/critiques/*.md files | No (for context) |
1. Extract session path from task description (match "Session: <path>")
2. Glob synthesis files from <session>/synthesis/
3. Read all synthesis files for evaluation
4. Optionally read ideas and critiques for full context
## Phase 3: Evaluation and Scoring
**Scoring Dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Feasibility | 30% | Technical feasibility, resource needs, timeline |
| Innovation | 25% | Novelty, differentiation, breakthrough potential |
| Impact | 25% | Scope of impact, value creation, problem resolution |
| Cost Efficiency | 20% | Implementation cost, risk cost, opportunity cost |
**Weighted Score**: `(Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + (Cost * 0.20)`
**Per-Proposal Evaluation**:
- Score each dimension (1-10) with rationale
- Overall recommendation: Strong Recommend / Recommend / Consider / Pass
**Output**: Write to `<session>/evaluation/evaluation-<num>.md`
- Sections: Input summary, Scoring Matrix (ranked table), Detailed Evaluation per proposal, Final Recommendation, Action Items, Risk Summary
## Phase 4: Consistency Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Score spread | max - min >= 0.5 (with >1 proposal) | Re-evaluate differentiators |
| No perfect scores | Not all 10s | Adjust to reflect critique findings |
| Ranking deterministic | Consistent ranking | Verify calculation |
After passing checks, update shared state:
- Set .msg/meta.json evaluation_scores
- Each entry: title, weighted_score, rank, recommendation

View File

@@ -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 | <session>/.msg/meta.json | Yes |
| Angles | <session>/.msg/meta.json | Yes |
| GC Round | <session>/.msg/meta.json | Yes |
| Previous critique | <session>/critiques/*.md | For revision tasks only |
| Previous ideas | <session>/.msg/meta.json generated_ideas | No |
1. Extract session path from task description (match "Session: <path>")
2. Read .msg/meta.json for topic, angles, gc_round
3. Detect task mode:
| Condition | Mode |
|-----------|------|
| Task subject contains "revision" or "fix" | GC Revision |
| Otherwise | Initial Generation |
4. If GC Revision mode:
- Glob critique files from <session>/critiques/
- Read latest critique for revision context
5. Read previous ideas from .msg/meta.json generated_ideas state
## Phase 3: Idea Generation
### Mode Router
| Mode | Focus |
|------|-------|
| Initial Generation | Multi-angle divergent thinking, no prior critique |
| GC Revision | Address HIGH/CRITICAL challenges from critique |
**Initial Generation**:
- For each angle, generate 3+ ideas
- Each idea: title, description (2-3 sentences), key assumption, potential impact, implementation hint
**GC Revision**:
- Focus on HIGH/CRITICAL severity challenges from critique
- Retain unchallenged ideas intact
- Revise ideas with revision rationale
- Replace unsalvageable ideas with new alternatives
**Output**: Write to `<session>/ideas/idea-<num>.md`
- Sections: Topic, Angles, Mode, [Revision Context if applicable], Ideas list, Summary
## Phase 4: Self-Review
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Minimum count | >= 6 (initial) or >= 3 (revision) | Generate additional ideas |
| No duplicates | All titles unique | Replace duplicates |
| Angle coverage | At least 1 idea per angle | Generate missing angle ideas |
After passing checks, update shared state:
- Append new ideas to .msg/meta.json generated_ideas
- Each entry: id, title, round, revised flag

View File

@@ -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 | <session>/ideas/*.md files | Yes |
| All critiques | <session>/critiques/*.md files | Yes |
| GC rounds completed | <session>/.msg/meta.json gc_round | Yes |
1. Extract session path from task description (match "Session: <path>")
2. Glob all idea files from <session>/ideas/
3. Glob all critique files from <session>/critiques/
4. Read all idea and critique files for synthesis
5. Read .msg/meta.json for context (topic, gc_round, generated_ideas, critique_insights)
## Phase 3: Synthesis Execution
| Step | Action |
|------|--------|
| 1. Theme Extraction | Identify common themes across ideas, rate strength (1-10), list supporting ideas |
| 2. Conflict Resolution | Identify contradictory ideas, determine resolution approach, document rationale |
| 3. Complementary Grouping | Group complementary ideas together |
| 4. Gap Identification | Discover uncovered perspectives |
| 5. Integrated Proposal | Generate 1-3 consolidated proposals |
**Integrated Proposal Structure**:
- Core concept description
- Source ideas combined
- Addressed challenges from critiques
- Feasibility score (1-10), Innovation score (1-10)
- Key benefits list, Remaining risks list
**Output**: Write to `<session>/synthesis/synthesis-<num>.md`
- Sections: Input summary, Extracted Themes, Conflict Resolution, Integrated Proposals, Coverage Analysis
## Phase 4: Quality Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Proposal count | >= 1 proposal | Generate at least one proposal |
| Theme count | >= 2 themes | Look for more patterns |
| Conflict resolution | All conflicts documented | Address unresolved conflicts |
After passing checks, update shared state:
- Set .msg/meta.json synthesis_themes
- Each entry: name, strength, supporting_ideas

View File

@@ -15,7 +15,7 @@
- 仅处理 `CHALLENGE-*` 前缀的任务
- 所有输出必须带 `[challenger]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 critique_insights
- Phase 2 读取 .msg/meta.jsonPhase 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: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
session_id: <session-id>,
from: "challenger",
to: "coordinator",
type: "critique_ready",
summary: "[challenger] Critique complete: <critical>C/<high>H/<medium>M/<low>L -- Signal: <signal>",
ref: <output-path>
data: {ref: <output-path>}
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from challenger --to coordinator --type critique_ready --summary \"[challenger] Critique complete\" --ref <output-path> --json")
Bash("ccw team log --session-id <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: <path>")
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
---

View File

@@ -47,20 +47,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., BRS-xxx-date), NOT team name. Extract from Session: field.
session_id: <session-id>,
from: "coordinator",
to: <recipient>,
type: <message-type>,
summary: "[coordinator] <action> complete: <subject>",
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] <action> complete\" --ref <artifact-path> --json")
```
**CLI fallback**: `ccw team log --session-id <session-id> --from coordinator --type <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

View File

@@ -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: "<TASK-ID>",
owner: "<role>",
description: "PURPOSE: <what this task achieves> | Success: <completion criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Topic: <topic>
- Angles: <angle-list>
- Upstream artifacts: <artifact-list>
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits>
---
InnerLoop: false",
blockedBy: [<dependency-list>],
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: <session-folder>
- Topic: <topic>
- Angles: <angle-list>
EXPECTED: <session>/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: <session-folder>
- Upstream artifacts: ideas/idea-001.md
EXPECTED: <session>/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: <session-folder>
- Upstream artifacts: ideas/*.md, critiques/*.md
EXPECTED: <session>/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: <session-folder>
- Upstream artifacts: critiques/critique-001.md
EXPECTED: <session>/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: <session-folder>
- Upstream artifacts: ideas/idea-002.md
EXPECTED: <session>/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: <session-folder>
- Upstream artifacts: synthesis/synthesis-001.md
EXPECTED: <session>/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

View File

@@ -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>/session.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, 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: "<task-id>", status: "completed" })
```
3. Record completion in session state
4. **Generator-Critic check** (when challenger completes):
- If completed task is CHALLENGE-* AND pipeline is deep or full:
- Read critique file for GC signal
- 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 <role> worker for <task-id>",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
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 (<pipeline-mode>):
[DONE] IDEA-001 (ideator) -> ideas/idea-001.md
[DONE] CHALLENGE-001 (challenger) -> critiques/critique-001.md
[RUN] SYNTH-001 (synthesizer) -> synthesizing...
[WAIT] EVAL-001 (evaluator) -> blocked by SYNTH-001
GC Rounds: <gc_round>/<max_gc_rounds>
Session: <session-id>
```
### 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

View File

@@ -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/<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 [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-<topic-slug>-<date>`
2. Create session folder structure:
```
Bash("mkdir -p .workflow/.team/<session-id>/ideas .workflow/.team/<session-id>/critiques .workflow/.team/<session-id>/synthesis .workflow/.team/<session-id>/evaluation .workflow/.team/<session-id>/wisdom .workflow/.team/<session-id>/.msg")
```
3. Write session.json:
```json
{
"status": "active",
"team_name": "brainstorm",
"topic": "<topic>",
"pipeline": "<quick|deep|full>",
"angles": ["<angle1>", "<angle2>"],
"gc_round": 0,
"max_gc_rounds": 2,
"timestamp": "<ISO-8601>"
}
```
4. Initialize .msg/meta.json:
```json
{
"session_id": "<session-id>",
"team_name": "brainstorm",
"topic": "<topic>",
"pipeline": "<mode>",
"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-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
For **Full pipeline** with parallel ideators, spawn N team-worker agents:
```
// For each parallel IDEA task (IDEA-001, IDEA-002, IDEA-003)
Task({
subagent_type: "team-worker",
description: "Spawn ideator worker for IDEA-<N>",
team_name: "brainstorm",
name: "ideator-<N>",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
**STOP** after spawning. Wait for worker callback.
All subsequent coordination handled by `commands/monitor.md` handlers.
---
## Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration
2. List deliverables:
| Deliverable | Path |
|-------------|------|
| Ideas | <session>/ideas/*.md |
| Critiques | <session>/critiques/*.md |
| Synthesis | <session>/synthesis/*.md |
| Evaluation | <session>/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 |

View File

@@ -15,7 +15,7 @@
- 仅处理 `EVAL-*` 前缀的任务
- 所有输出必须带 `[evaluator]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 evaluation_scores
- Phase 2 读取 .msg/meta.jsonPhase 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: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
session_id: <session-id>,
from: "evaluator",
to: "coordinator",
type: "evaluation_ready",
summary: "[evaluator] Evaluation complete: Top pick \"<title>\" (<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
---

View File

@@ -15,7 +15,7 @@
- 仅处理 `IDEA-*` 前缀的任务
- 所有输出SendMessage、team_msg、日志必须带 `[ideator]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 generated_ideas
- Phase 2 读取 .msg/meta.jsonPhase 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
---

View File

@@ -15,7 +15,7 @@
- 仅处理 `SYNTH-*` 前缀的任务
- 所有输出必须带 `[synthesizer]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 synthesis_themes
- Phase 2 读取 .msg/meta.jsonPhase 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
---

View File

@@ -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

View File

@@ -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>
---

View File

@@ -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

View File

@@ -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.

View File

@@ -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
```

View File

@@ -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

View File

@@ -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)
```
---

View File

@@ -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 |

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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 |

View File

@@ -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 |

View File

@@ -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 |

View File

@@ -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 &#124;&#124; 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.

View File

@@ -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

View File

@@ -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 |

View File

@@ -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 |

View File

@@ -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 |

View File

@@ -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 |

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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`
---

View File

@@ -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 |

View File

@@ -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

View File

@@ -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 |

View File

@@ -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")
```
---

View File

@@ -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>)"
})
```

View File

@@ -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"
})
```

View File

@@ -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>"
})
```

View File

@@ -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")
```
---

View File

@@ -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)

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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"
})
```

View File

@@ -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")
```
---

View File

@@ -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.

View File

@@ -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 |

View File

@@ -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>"
})
```

View File

@@ -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"
})
```

View File

@@ -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>%"
})
```

View File

@@ -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

View File

@@ -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 } }`

View File

@@ -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) |

View File

@@ -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

View File

@@ -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 } }`

View File

@@ -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
{

View File

@@ -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
---

View File

@@ -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
---

View File

@@ -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:

View File

@@ -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**:

View File

@@ -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

View File

@@ -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

View File

@@ -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 |

View File

@@ -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:
```
{

View File

@@ -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

View File

@@ -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. |

View File

@@ -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`

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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 |

View File

@@ -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}`
})
}
```

View File

@@ -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 = {

View File

@@ -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"

Some files were not shown because too many files have changed in this diff Show More