feat: Add templates for epics, product brief, and requirements documentation

- Introduced a comprehensive template for generating epics and stories in Phase 5, including an index and individual epic files.
- Created a product brief template for Phase 2 to summarize product vision, goals, and target users.
- Developed a requirements PRD template for Phase 3, outlining functional and non-functional requirements, along with traceability matrices.

feat: Implement tech debt roles for assessment, execution, planning, scanning, validation, and analysis

- Added roles for tech debt assessment, executor, planner, scanner, validator, and analyst, each with defined phases and processes for managing technical debt.
- Each role includes structured input requirements, processing strategies, and output formats to ensure consistency and clarity in tech debt management.
This commit is contained in:
catlog22
2026-03-07 13:32:04 +08:00
parent 7ee9b579fa
commit 29a1fea467
255 changed files with 14407 additions and 21120 deletions

View File

@@ -1,366 +1,73 @@
---
name: team-uidesign
description: Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation.
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*), WebFetch(*), WebSearch(*)
description: Unified team skill for UI design team. Research -> design tokens -> audit -> implementation. Uses team-worker agent architecture with roles/ for domain logic. Coordinator orchestrates dual-track pipeline with GC loops and sync points. Triggers on "team ui design", "ui design team".
allowed-tools: Agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, TaskList, TaskGet, TaskUpdate, TaskCreate, TeamCreate, TeamDelete, SendMessage, mcp__ace-tool__search_context, mcp__ccw-tools__read_file, mcp__ccw-tools__write_file, mcp__ccw-tools__edit_file, mcp__ccw-tools__team_msg
---
# Team UI Design
Unified team skill: design system analysis, token definition, component specification, accessibility audit, and code implementation via CP-9 Dual-Track (design+implementation). All team members invoke with `--role=xxx` to route to role-specific execution.
Systematic UI design pipeline: research -> design tokens -> review -> implementation. Built on **team-worker agent architecture** — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from `roles/<role>/role.md`.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-uidesign") |
| args="<task-description>" |
+-------------------+-------------------------------+
Skill(skill="team-uidesign", args="task description")
|
Orchestration Mode (auto -> coordinator)
SKILL.md (this file) = Router
|
Coordinator (inline)
Phase 0-5 orchestration
|
+-------+-------+-------+-------+
v v v v
[tw] [tw] [tw] [tw]
resear- design- review- imple-
cher er er menter
(tw) = team-worker agent
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze → dispatch → spawn workers → STOP
|
+-------+-------+-------+-------+
v v v v
[team-worker agents, each loads roles/<role>/role.md]
researcher designer reviewer implementer
```
## Command Execution Protocol
## Role Registry
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
| Role | Path | Prefix | Inner Loop |
|------|------|--------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — |
| researcher | [roles/researcher/role.md](roles/researcher/role.md) | RESEARCH-* | false |
| designer | [roles/designer/role.md](roles/designer/role.md) | DESIGN-* | false |
| reviewer | [roles/reviewer/role.md](roles/reviewer/role.md) | AUDIT-* | false |
| implementer | [roles/implementer/role.md](roles/implementer/role.md) | BUILD-* | false |
## Role Router
### Input Parsing
Parse `$ARGUMENTS`:
- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4
- No `--role` → Read `roles/coordinator/role.md`, execute entry router
Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator).
## Shared Constants
### Role Registry
- **Session prefix**: `UDS`
- **Session path**: `.workflow/.team/UDS-<slug>-<date>/`
- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications)
- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)`
- **Max GC rounds**: 2
| Role | Spec | Task Prefix | Inner Loop |
|------|------|-------------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - |
| researcher | [role-specs/researcher.md](role-specs/researcher.md) | RESEARCH-* | false |
| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | false |
| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | AUDIT-* | false |
| implementer | [role-specs/implementer.md](role-specs/implementer.md) | BUILD-* | false |
## Worker Spawn Template
> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。
### Dispatch
1. Extract `--role` from arguments
2. If no `--role` → route to coordinator (Orchestration Mode)
3. Look up role in registry → Read the role file → Execute its phases
### Orchestration Mode
When invoked without `--role`, coordinator auto-starts. User just provides task description.
**Invocation**: `Skill(skill="team-uidesign", args="<task-description>")`
**Lifecycle**:
```
User provides task description
→ coordinator Phase 1-3: Scope assessment → TeamCreate → Create task chain (dual-track)
→ coordinator Phase 4: spawn first batch workers (background) → STOP
→ Worker executes → SendMessage callback → coordinator advances next step
→ Loop until pipeline complete → Phase 5 report
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Shared Infrastructure
The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic.
### Worker Phase 1: Task Discovery (shared by all workers)
Every worker executes the same task discovery flow on startup:
1. Call `TaskList()` to get all tasks
2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty
3. No tasks → idle wait
4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress
**Resume Artifact Check** (prevent duplicate output after resume):
- Check whether this task's output artifact already exists
- Artifact complete → skip to Phase 5 report completion
- Artifact incomplete or missing → normal Phase 2-4 execution
### Worker Phase 5: Report (shared by all workers)
Standard reporting flow after task completion:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
- `to` and `summary` auto-defaulted -- do NOT specify explicitly
- **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json`
2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`)
3. **TaskUpdate**: Mark task completed
4. **Loop**: Return to Phase 1 to check next task
### Wisdom Accumulation (all roles)
Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization.
**Directory**:
```
<session-folder>/wisdom/
├── learnings.md # Patterns and insights
├── decisions.md # Architecture and design decisions
├── conventions.md # Codebase conventions
└── issues.md # Known risks and issues
```
**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files.
**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files.
### Role Isolation Rules
| Allowed | Forbidden |
|---------|-----------|
| Process tasks with own prefix | Process tasks with other role prefixes |
| SendMessage to coordinator | Communicate directly with other workers |
| Share state via team_msg(type='state_update') | Create tasks for other roles |
| Delegate to commands/ files | Modify resources outside own responsibility |
Coordinator additional restrictions: Do not write/modify code directly, do not spawn implementation workers directly, do not execute analysis/audits, do not bypass workers.
### Output Tagging
All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary.
### Message Bus (All Roles)
Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log:
**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
> `to` and `summary` are auto-defaulted by the tool.
**CLI fallback**: When MCP unavailable → `ccw team log --session-id <session-id> --from <role> --type <type> --json`
**Message types by role**:
| Role | Types |
|------|-------|
| coordinator | `task_unblocked`, `sync_checkpoint`, `fix_required`, `error`, `shutdown` |
| researcher | `research_ready`, `research_progress`, `error` |
| designer | `design_ready`, `design_revision`, `design_progress`, `error` |
| reviewer | `audit_result`, `audit_passed`, `fix_required`, `error` |
| implementer | `build_complete`, `build_progress`, `error` |
### Shared State
All roles share state via `team_msg(type='state_update')` + `meta.json`:
| Role | Field |
|------|-------|
| researcher | `design_intelligence`, `component_inventory`, `industry_context` |
| designer | `design_token_registry`, `style_decisions` |
| reviewer | `audit_history`, `accessibility_patterns` |
| implementer | (reads all fields, writes build artifacts to session dir) |
### Design Intelligence (ui-ux-pro-max)
Researcher obtains design intelligence via `Skill(skill="ui-ux-pro-max", args="...")`, writes to `design-intelligence.json`. Downstream roles consume:
```
researcher (Stream 4)
| Skill("ui-ux-pro-max", args="<industry> <keywords> --design-system")
| Skill("ui-ux-pro-max", args="accessibility animation responsive --domain ux")
| Skill("ui-ux-pro-max", args="<keywords> --stack <detected-stack>")
design-intelligence.json
|-> designer: recommended colors/typography/style → token values, anti-patterns → component specs
|-> reviewer: anti-patterns → Industry Compliance audit dimension (20% weight)
|-> implementer: stack guidelines → code generation, anti-patterns → validation
```
**Data flow**:
- `design_system.colors/typography/style` → designer token defaults (recommended-first mode)
- `recommendations.anti_patterns[]` → reviewer compliance check, designer/implementer avoidance
- `stack_guidelines` → implementer code generation constraints
- `ux_guidelines[]` → designer component spec implementation hints
**Degradation strategy**: When ui-ux-pro-max unavailable, use LLM general knowledge for defaults, mark `_source` as `"llm-general-knowledge"`.
### Team Configuration
| Setting | Value |
|---------|-------|
| Team name | uidesign |
| Session directory | `.workflow/.team/UDS-<slug>-<date>/` |
---
## Three-Pipeline Architecture
### CP-9 Dual-Track Concept
```
Track A (Design): RESEARCH → DESIGN(tokens) → DESIGN(components) → ...
| |
Sync Point 1 Sync Point 2
| |
Track B (Build): BUILD(tokens) ──→ BUILD(components) → ...
```
Design and implementation proceed in parallel after sync checkpoints. Each sync point validates that design artifacts are stable enough for implementation to consume.
### Pipeline Modes
```
component (single component):
RESEARCH-001 → DESIGN-001 → AUDIT-001 → BUILD-001
system (design system - dual-track):
Track A: RESEARCH-001 → DESIGN-001(tokens) → DESIGN-002(components)
Sync-1: AUDIT-001 (token audit)
Track B: BUILD-001(tokens, blockedBy AUDIT-001) || DESIGN-002(components)
Sync-2: AUDIT-002 (component audit)
Track B: BUILD-002(components, blockedBy AUDIT-002)
full-system (complete design system):
RESEARCH-001 → DESIGN-001(tokens) → AUDIT-001
→ [DESIGN-002(components) + BUILD-001(tokens)](parallel, blockedBy AUDIT-001)
→ AUDIT-002 → BUILD-002(components) → AUDIT-003(final)
```
### Generator-Critic Loop
designer <-> reviewer loop, ensuring design consistency and accessibility:
```
DESIGN → AUDIT → (if audit.score < 8 or critical_count > 0) → DESIGN-fix → AUDIT-2
(if audit.score >= 8 and critical_count === 0) → next stage or BUILD
Convergence: audit.score >= 8 && audit.critical_count === 0
Max 2 rounds
```
### Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. UI Design beat: research → design → review → implement.
```
Beat Cycle (single beat)
═══════════════════════════════════════════════════════════
Event Coordinator Workers
───────────────────────────────────────────────────────────
callback/resume ──→ ┌─ handleCallback ─┐
│ mark completed │
│ check pipeline │
├─ handleSpawnNext ─┤
│ find ready tasks │
│ spawn workers ───┼──→ [Worker A] Phase 1-5
│ (parallel OK) ──┼──→ [Worker B] Phase 1-5
└─ STOP (idle) ─────┘ │
callback ←─────────────────────────────────────────┘
(next beat) SendMessage + TaskUpdate(completed)
═══════════════════════════════════════════════════════════
```
**Pipeline beat views**:
```
Component (4 beats, strictly serial)
──────────────────────────────────────────────────────────
Beat 1 2 3 4
| | | |
RESEARCH → DESIGN → AUDIT ──→ BUILD
^ ^
pipeline pipeline
start done
RESEARCH=researcher DESIGN=designer AUDIT=reviewer BUILD=implementer
System (dual-track, 5-6 beats with parallel windows)
──────────────────────────────────────────────────────────
Beat 1 2 3 4 5 6
| | | ┌────┴────┐ | |
RESEARCH → DESIGN-tokens → AUDIT-1 → BUILD-tokens ∥ DESIGN-comp → AUDIT-2 → BUILD-comp
^ ^
sync point 1 sync point 2
Full-system (7+ beats with dual-track parallel)
──────────────────────────────────────────────────────────
Beat 1 2 3 4 5 6 7
| | | ┌────┴────┐ | | |
RESEARCH → DESIGN-tokens → AUDIT-1 → DESIGN-comp ∥ BUILD-tokens → AUDIT-2 → BUILD-comp → AUDIT-3
^ ^
parallel final
window audit
```
**Checkpoints**:
| Trigger | Location | Behavior |
|---------|----------|----------|
| Sync Point (token audit) | After AUDIT on tokens | If passed → unblock BUILD(tokens) + DESIGN(components); else GC loop |
| Sync Point (component audit) | After AUDIT on components | If passed → unblock BUILD(components); else GC loop |
| GC loop limit | Max 2 rounds | Exceeds limit → coordinator escalates to user |
| Pipeline stall | No ready + no running | Check missing tasks, report to user |
**Stall Detection** (coordinator `handleCheck` executes):
| Check | Condition | Resolution |
|-------|-----------|------------|
| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` |
| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point |
| GC loop exceeded | designer/reviewer iteration > 2 rounds | Terminate loop, escalate to user |
| Dual-track sync failure | BUILD waiting on AUDIT that never completes | Fall back to single-track sequential execution |
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| RESEARCH-001 | researcher | research | (none) | Design system analysis, component inventory, accessibility audit |
| DESIGN-001 | designer | design | RESEARCH-001 | Design token definition (colors, typography, spacing) |
| AUDIT-001 | reviewer | review | DESIGN-001 | Token design consistency and accessibility audit |
| BUILD-001 | implementer | implement | AUDIT-001 | Token code implementation (CSS variables, JS constants) |
| DESIGN-002 | designer | design | AUDIT-001 | Component specification and layout design |
| AUDIT-002 | reviewer | review | DESIGN-002 | Component design audit |
| BUILD-002 | implementer | implement | AUDIT-002 | Component code implementation |
| AUDIT-003 | reviewer | review | BUILD-002 | Final integrated audit (full-system only) |
---
## Coordinator Spawn Template
### v5 Worker Spawn (all roles)
When coordinator spawns workers, use `team-worker` agent with role-spec path:
Coordinator spawns workers using this template:
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
description: "Spawn <role> worker for <task-id>",
team_name: "uidesign",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-uidesign/role-specs/<role>.md
role_spec: .claude/skills/team-uidesign/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: uidesign
@@ -368,81 +75,52 @@ requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})
```
**All roles** (researcher, designer, reviewer, implementer): Set `inner_loop: false`.
## User Commands
---
| Command | Action |
|---------|--------|
| `check` / `status` | View execution status graph |
| `resume` / `continue` | Advance to next step |
## Completion Action
## Specs Reference
When the pipeline completes (all tasks done, coordinator Phase 5):
- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry
## Session Directory
```
AskUserQuestion({
questions: [{
question: "UI Design pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
| Choice | Action |
|--------|--------|
| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary |
| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-uidesign", args="resume")` |
| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean |
---
## Unified Session Directory
```
.workflow/.team/UDS-<slug>-<YYYY-MM-DD>/
├── .msg/messages.jsonl # Message bus log
├── .msg/meta.json # Session metadata
├── wisdom/ # Cross-task knowledge
│ ├── learnings.md
│ ├── decisions.md
│ ├── conventions.md
│ └── issues.md
├── research/ # Researcher output
.workflow/.team/UDS-<slug>-<date>/
├── .msg/
├── messages.jsonl # Team message bus
└── meta.json # Pipeline config + GC state
├── research/ # Researcher output
│ ├── design-system-analysis.json
│ ├── component-inventory.json
│ ├── accessibility-audit.json
── design-intelligence.json # ui-ux-pro-max design intelligence
│ └── design-intelligence-raw.md # ui-ux-pro-max raw output
├── design/ # Designer output
── design-intelligence.json
── design/ # Designer output
│ ├── design-tokens.json
│ ├── component-specs/
│ │ └── {component-name}.md
│ └── layout-specs/
│ └── {layout-name}.md
── audit/ # Reviewer output
│ └── audit-{NNN}.md
└── build/ # Implementer output
── token-files/
└── component-files/
├── audit/ # Reviewer output
│ └── audit-*.md
├── build/ # Implementer output
│ ├── token-files/
── component-files/
└── wisdom/ # Cross-task knowledge
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Error with available role list |
| Missing --role arg | Orchestration Mode → auto route to coordinator |
| Role file not found | Error with expected path (roles/<name>.md) |
| AUDIT score < 6 after 2 GC rounds | Coordinator escalates to user |
| Dual-track sync failure | Fall back to single-track sequential execution |
| Design token conflict | Reviewer arbitrates, coordinator intervenes |
| BUILD cannot find design files | Wait for Sync Point or escalate |
| ui-ux-pro-max unavailable | Degrade to LLM general knowledge, `_source: "llm-general-knowledge"` |
| Industry anti-pattern check failure | Reviewer marks Industry Compliance dimension as N/A |
| Unknown command | Error with available command list |
| Role not found | Error with role registry |
| Session corruption | Attempt recovery, fallback to manual |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
| GC loop stuck > 2 rounds | Escalate to user: accept / retry / terminate |

View File

@@ -0,0 +1,59 @@
# Analyze Task
Parse user task -> detect UI design scope -> build dependency graph -> design pipeline mode.
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
## Signal Detection
| Keywords | Capability | Pipeline Hint |
|----------|------------|---------------|
| component, button, card, input, modal | component | component |
| design system, token, theme | system | system |
| complete, full, all components, redesign | full | full-system |
| accessibility, a11y, wcag | accessibility | component or system |
| implement, build, code | implementation | component |
## Scope Determination
| Signal | Pipeline Mode |
|--------|---------------|
| Single component mentioned | component |
| Multiple components or "design system" | system |
| "Full design system" or "complete redesign" | full-system |
| Unclear | ask user |
## Complexity Scoring
| Factor | Points |
|--------|--------|
| Single component | +1 |
| Component system | +2 |
| Full design system | +3 |
| Accessibility required | +1 |
| Multiple industries/constraints | +1 |
Results: 1-2 Low (component), 3-4 Medium (system), 5+ High (full-system)
## Industry Detection
| Keywords | Industry |
|----------|----------|
| saas, dashboard, analytics | SaaS/Tech |
| shop, cart, checkout, e-commerce | E-commerce |
| medical, patient, healthcare | Healthcare |
| bank, finance, payment | Finance |
| edu, course, learning | Education/Content |
| Default | SaaS/Tech |
## Output
Write scope context to coordinator memory:
```json
{
"pipeline_mode": "<component|system|full-system>",
"scope": "<description>",
"industry": "<detected-industry>",
"complexity": { "score": 0, "level": "Low|Medium|High" }
}
```

View File

@@ -12,7 +12,7 @@ Create the UI design task chain with correct dependencies and structured task de
| Industry config | From session.json `industry` | Yes |
1. Load user requirement and design scope from session.json
2. Load pipeline stage definitions from SKILL.md Task Metadata Registry
2. Load pipeline stage definitions from specs/pipelines.md
3. Read `pipeline` and `industry` from session.json
## Phase 3: Task Chain Creation (Mode-Branched)

View File

@@ -1,71 +1,122 @@
# Command: Monitor
# Monitor Pipeline
Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, and completion. Supports component, system, and full-system pipeline modes with sync point and Generator-Critic loop management.
Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP.
## Phase 2: Context Loading
## Constants
| Input | Source | Required |
|-------|--------|----------|
| Session state | <session>/session.json | Yes |
| Task list | TaskList() | Yes |
| Trigger event | From Entry Router detection | Yes |
| Pipeline definition | From SKILL.md | Yes |
- SPAWN_MODE: background
- ONE_STEP_PER_INVOCATION: true
- FAST_ADVANCE_AWARE: true
- WORKER_AGENT: team-worker
- MAX_GC_ROUNDS: 2
1. Load session.json for current state, `pipeline`, `gc_state`, `sync_points`
2. Run TaskList() to get current task statuses
3. Identify trigger event type from Entry Router
## Handler Router
## Phase 3: Event Handlers
| Source | Handler |
|--------|---------|
| Message contains [researcher], [designer], [reviewer], [implementer] | handleCallback |
| "capability_gap" | handleAdapt |
| "check" or "status" | handleCheck |
| "resume" or "continue" | handleResume |
| All tasks completed | handleComplete |
| Default | handleSpawnNext |
### handleCallback
## handleCallback
Triggered when a worker sends completion message.
Worker completed. Process and advance.
1. Parse message to identify role and task ID:
| Message Pattern | Role Detection |
|----------------|---------------|
| `[researcher]` or task ID `RESEARCH-*` | researcher |
| `[designer]` or task ID `DESIGN-*` | designer |
| `[reviewer]` or task ID `AUDIT-*` | reviewer |
| `[implementer]` or task ID `BUILD-*` | implementer |
2. Mark task as completed:
```
TaskUpdate({ taskId: "<task-id>", status: "completed" })
```
| Message Pattern | Role |
|----------------|------|
| `[researcher]` or `RESEARCH-*` | researcher |
| `[designer]` or `DESIGN-*` | designer |
| `[reviewer]` or `AUDIT-*` | reviewer |
| `[implementer]` or `BUILD-*` | implementer |
2. Mark task completed: `TaskUpdate({ taskId: "<task-id>", status: "completed" })`
3. Record completion in session state
4. Check if checkpoint feedback is configured for this stage:
4. Check checkpoint for completed task:
| Completed Task | Checkpoint | Action |
|---------------|------------|--------|
| RESEARCH-001 | - | Notify user: research complete |
| DESIGN-001 (tokens) | - | Proceed to AUDIT-001 |
| AUDIT-001 | Sync Point 1 | Check audit signal -> GC loop or unblock parallel (see below) |
| DESIGN-002 (components) | - | Proceed to AUDIT-002 |
| AUDIT-002 | Sync Point 2 | Check audit signal -> GC loop or unblock BUILD-002 |
| AUDIT-* | QUALITY-001: Sync Point | Check audit signal -> GC loop or unblock parallel |
| BUILD-001 (tokens) | - | Check if BUILD-002 ready |
| BUILD-002 (components) | - | Check if AUDIT-003 exists (full-system) or handleComplete |
| AUDIT-003 | Final | Notify user: final audit complete |
5. **Sync Point handling** (AUDIT task completed):
- Read audit signal from message: `audit_passed`, `audit_result`, or `fix_required`
- Route to GC loop control (see below)
Read audit signal from message: `audit_passed`, `audit_result`, or `fix_required`
6. Proceed to handleSpawnNext
| Signal | Condition | Action |
|--------|-----------|--------|
| `audit_passed` | Score >= 8, critical === 0 | GC converged -> record sync_point -> unblock downstream |
| `audit_result` | Score 6-7, no critical | gc_rounds < max -> create DESIGN-fix task |
| `fix_required` | Score < 6 or critical > 0 | gc_rounds < max -> create DESIGN-fix task (CRITICAL) |
| Any | gc_rounds >= max | Escalate to user |
### handleSpawnNext
**GC Fix Task Creation**:
```
TaskCreate({ subject: "DESIGN-fix-<round>",
description: "PURPOSE: Address audit feedback | Success: All critical/high issues resolved
TASK:
- Parse audit feedback for specific issues
- Apply targeted fixes
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: audit/audit-<NNN>.md" })
TaskUpdate({ taskId: "DESIGN-fix-<round>", owner: "designer" })
```
Then create new AUDIT task blocked by fix. Increment gc_state.round.
Find and spawn the next ready tasks.
**GC Escalation Options** (when max rounds exceeded):
1. Accept current design - skip review, continue implementation
2. Try one more round
3. Terminate
1. Scan task list for tasks where:
- Status is "pending"
- All blockedBy tasks have status "completed"
6. -> handleSpawnNext
2. For each ready task, spawn team-worker:
## handleCheck
Read-only status report, then STOP.
```
Pipeline Status (<pipeline-mode>):
[DONE] RESEARCH-001 (researcher) -> research/*.json
[DONE] DESIGN-001 (designer) -> design-tokens.json
[RUN] AUDIT-001 (reviewer) -> auditing tokens...
[WAIT] BUILD-001 (implementer) -> blocked by AUDIT-001
[WAIT] DESIGN-002 (designer) -> blocked by AUDIT-001
GC Rounds: 0/2
Sync Points: 0/<expected>
Session: <session-id>
Commands: 'resume' to advance | 'check' to refresh
```
Output status -- do NOT advance pipeline.
## handleResume
1. Audit task list for inconsistencies:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. -> handleSpawnNext
## handleSpawnNext
Find ready tasks, spawn workers, STOP.
1. Collect: completedSubjects, inProgressSubjects, readySubjects (pending + all blockedBy completed)
2. No ready + work in progress -> report waiting, STOP
3. No ready + nothing in progress -> handleComplete
4. Has ready -> for each:
a. Check inner loop role with active worker -> skip (worker picks up)
b. TaskUpdate -> in_progress
c. team_msg log -> task_unblocked
d. Spawn team-worker:
```
Agent({
@@ -76,7 +127,7 @@ Agent({
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-uidesign/role-specs/<role>.md
role_spec: .claude/skills/team-uidesign/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: uidesign
@@ -84,119 +135,50 @@ requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})
```
3. **Parallel spawn rules by mode**:
**Parallel spawn rules by mode**:
| Mode | Scenario | Spawn Behavior |
|------|----------|---------------|
| Component | Sequential | One task at a time |
| System | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel |
| System | After Sync Point 2 | Spawn BUILD-002 |
| Full-system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel |
| Full-system | After BUILD-002 | Spawn AUDIT-003 |
| component | Sequential | One task at a time |
| system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel |
| system | After Sync Point 2 | Spawn BUILD-002 |
| full-system | After Sync Point 1 | Spawn DESIGN-002 + BUILD-001 in parallel |
| full-system | After BUILD-002 | Spawn AUDIT-003 |
4. STOP after spawning -- wait for next callback
5. Add to active_workers, update session, output summary, STOP
### Generator-Critic Loop Control
## handleComplete
When AUDIT task completes, check signal:
| Signal | Condition | Action |
|--------|-----------|--------|
| `audit_passed` | Score >= 8, critical === 0 | GC converged -> record sync_point -> unblock downstream tasks |
| `audit_result` | Score 6-7, critical === 0 | GC round < max -> create DESIGN-fix task |
| `fix_required` | Score < 6 or critical > 0 | GC round < max -> create DESIGN-fix task (CRITICAL) |
| Any | GC round >= max | Escalate to user |
**GC Fix Task Creation**:
```
TaskCreate({
subject: "DESIGN-fix-<round>",
description: "PURPOSE: Address audit feedback from AUDIT-<NNN> | Success: All critical/high issues resolved
TASK:
- Parse audit feedback for specific issues
- Re-read affected design artifacts
- Apply fixes: token adjustments, missing states, accessibility gaps
- Re-write affected files
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: audit/audit-<NNN>.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: Updated design artifacts | All flagged issues addressed
CONSTRAINTS: Targeted fixes only"
})
TaskUpdate({ taskId: "DESIGN-fix-<round>", owner: "designer" })
```
After fix completes, create new AUDIT task blocked by the fix task. Increment gc_state.round.
**GC Escalation Options**:
1. Accept current design - Skip remaining review, continue implementation
2. Try one more round - Extra GC loop opportunity
3. Terminate - Stop and handle manually
### Dual-Track Sync Point Management
**When AUDIT at sync point passes (audit_passed)**:
1. Record sync point in session.sync_points
2. Unblock parallel tasks on both tracks
3. team_msg log(sync_checkpoint)
**Dual-track failure fallback**:
- Convert remaining parallel tasks to sequential
- Remove parallel dependencies, add sequential blockedBy
- team_msg log(error): "Dual-track sync failed, falling back to sequential"
### handleCheck
Output current pipeline status.
```
Pipeline Status (<pipeline-mode>):
[DONE] RESEARCH-001 (researcher) -> research/*.json
[DONE] DESIGN-001 (designer) -> design-tokens.json
[RUN] AUDIT-001 (reviewer) -> auditing tokens...
[WAIT] BUILD-001 (implementer) -> blocked by AUDIT-001
[WAIT] DESIGN-002 (designer) -> blocked by AUDIT-001
GC Rounds: 0/2
Sync Points: 0/<expected>
Session: <session-id>
```
Output status -- do NOT advance pipeline.
### handleResume
Resume pipeline after user pause or interruption.
1. Audit task list for inconsistencies:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. Proceed to handleSpawnNext
### handleComplete
Triggered when all pipeline tasks are completed.
Pipeline done. Generate report and completion action.
**Completion check by mode**:
| Mode | Completion Condition |
|------|---------------------|
| Component | All 4 tasks (+ any fix/retry tasks) have status "completed" |
| System | All 7 tasks (+ any fix/retry tasks) have status "completed" |
| Full-system | All 8 tasks (+ any fix/retry tasks) have status "completed" |
| component | All 4 tasks (+ fix tasks) completed |
| system | All 7 tasks (+ fix tasks) completed |
| full-system | All 8 tasks (+ fix tasks) completed |
If any tasks not completed, return to handleSpawnNext.
If all completed, transition to coordinator Phase 5.
1. If any tasks not completed -> handleSpawnNext
2. If all completed -> transition to coordinator Phase 5
## Phase 4: State Persistence
## handleAdapt
After every handler execution:
Capability gap reported mid-pipeline.
1. Update session.json with current state (active tasks, gc_state, sync_points, last event)
2. Verify task list consistency
3. STOP and wait for next event
1. Parse gap description
2. Check if existing role covers it -> redirect
3. Role count < 5 -> generate dynamic role spec
4. Create new task, spawn worker
5. Role count >= 5 -> merge or pause
## Fast-Advance Reconciliation
On every coordinator wake:
1. Read team_msg entries with type="fast_advance"
2. Sync active_workers with spawned successors
3. No duplicate spawns

View File

@@ -1,253 +1,131 @@
# Coordinator - UI Design Team
# Coordinator Role
**Role**: coordinator
**Type**: Orchestrator
**Team**: uidesign
UI Design Team coordinator. Orchestrate pipeline: analyze -> dispatch -> spawn -> monitor -> report. Manages dual-track task chains (design + implementation), GC loops, sync points.
Orchestrates the UI design pipeline: manages dual-track task chains (design + implementation), spawns team-worker agents, handles Generator-Critic loops between designer and reviewer, manages sync points, and drives the pipeline to completion.
## Identity
- **Name**: coordinator | **Tag**: [coordinator]
- **Responsibility**: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- All output (SendMessage, team_msg, logs) must carry `[coordinator]` identifier
- Use `team-worker` agent type for all worker spawns (NOT `general-purpose`)
- Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
- Stop after spawning workers -- wait for callbacks
- Dispatch tasks with proper dependency chains and blockedBy
- Monitor worker progress via message bus and route messages
- Handle Generator-Critic loops with max 2 iterations
- Execute completion action in Phase 5
- Maintain session state persistence
### MUST NOT
- Implement domain logic (researching, designing, auditing, building) -- workers handle this
- Spawn workers without creating tasks first
- Skip sync points when configured
- Force-advance pipeline past failed audit
- Modify source code or design artifacts directly -- delegate to workers
---
- Omit `[coordinator]` identifier in any output
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
When coordinator needs to execute a command (analyze, dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
1. Read `commands/<command>.md`
2. Follow the workflow defined in the command
3. Commands are inline execution guides, NOT separate agents
4. Execute synchronously, complete before proceeding
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains role tag [researcher], [designer], [reviewer], [implementer] | -> handleCallback |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Requirement Clarification) |
| Worker callback | Message contains [researcher], [designer], [reviewer], [implementer] | -> handleCallback (monitor.md) |
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) |
| Interrupted session | Active/paused session exists in .workflow/.team/UDS-* | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/UDS-*/.msg/meta.json` for active/paused sessions
- If found, extract session folder path, status, and pipeline mode
2. **Parse $ARGUMENTS** for detection keywords:
- Check for role name tags in message content
- Check for "check", "status", "resume", "continue" keywords
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
- For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Requirement Clarification below
---
For callback/check/resume/adapt/complete: load `commands/monitor.md`, execute matched handler, STOP.
## Phase 0: Session Resume Check
Triggered when an active/paused session is detected on coordinator entry.
1. Load session.json from detected session folder
2. Audit task list:
```
TaskList()
```
3. Reconcile session state vs task status:
| Task Status | Session Expects | Action |
|-------------|----------------|--------|
| in_progress | Should be running | Reset to pending (worker was interrupted) |
| completed | Already tracked | Skip |
| pending + unblocked | Ready to run | Include in spawn list |
4. Rebuild team if not active:
```
TeamCreate({ team_name: "uidesign" })
```
5. Spawn workers for ready tasks -> Phase 4 coordination loop
---
1. Scan `.workflow/.team/UDS-*/.msg/meta.json` for active/paused sessions
2. No sessions -> Phase 1
3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task)
4. Multiple -> AskUserQuestion for selection
## Phase 1: Requirement Clarification
1. Parse user task description from $ARGUMENTS
2. Identify design scope:
TEXT-LEVEL ONLY. No source code reading.
| Signal | Target |
|--------|--------|
| Single component mentioned | Component pipeline |
| Multiple components or "design system" | System pipeline |
| Full redesign or "complete design system" | Full-system pipeline |
1. Parse task description from arguments
2. Detect design scope:
3. If scope is unclear, ask for clarification:
| Signal | Pipeline Mode |
|--------|---------------|
| Single component mentioned | component |
| Multiple components or "design system" | system |
| "Full design system" or "complete redesign" | full-system |
| Unclear | ask user |
```
AskUserQuestion({
questions: [
{ question: "UI design scope?", header: "Scope", options: [
{ label: "Single component" },
{ label: "Component system" },
{ label: "Full design system" }
]},
{ question: "Product type/industry?", header: "Industry", options: [
{ label: "SaaS/Tech" },
{ label: "E-commerce" },
{ label: "Healthcare/Finance" },
{ label: "Education/Content" },
{ label: "Other" }
]}
]
})
```
3. Ask for missing parameters if scope unclear:
```
AskUserQuestion({
questions: [
{ question: "UI design scope?", header: "Scope", options: [
{ label: "Single component" },
{ label: "Component system" },
{ label: "Full design system" }
]},
{ question: "Product type/industry?", header: "Industry", options: [
{ label: "SaaS/Tech" }, { label: "E-commerce" },
{ label: "Healthcare/Finance" }, { label: "Education/Content" }, { label: "Other" }
]}
]
})
```
4. Delegate to `commands/analyze.md` -> output scope context
5. Record: pipeline_mode, industry, complexity
4. Map scope to pipeline: component / system / full-system
5. Record requirement with scope, industry, and pipeline mode
## Phase 2: Create Team + Initialize Session
---
1. Generate session ID: `UDS-<slug>-<YYYY-MM-DD>`
2. Create session folder structure:
```
.workflow/.team/UDS-<slug>-<date>/research/
.workflow/.team/UDS-<slug>-<date>/design/component-specs/
.workflow/.team/UDS-<slug>-<date>/design/layout-specs/
.workflow/.team/UDS-<slug>-<date>/audit/
.workflow/.team/UDS-<slug>-<date>/build/token-files/
.workflow/.team/UDS-<slug>-<date>/build/component-files/
.workflow/.team/UDS-<slug>-<date>/wisdom/
.workflow/.team/UDS-<slug>-<date>/.msg/
```
3. Initialize `.msg/meta.json` via team_msg state_update with pipeline metadata
4. TeamCreate(team_name="uidesign")
5. Do NOT spawn workers yet - deferred to Phase 4
## Phase 2: Session & Team Setup
## Phase 3: Create Task Chain
1. Create session directory:
Delegate to `commands/dispatch.md`. Task chains by mode:
```
Bash("mkdir -p .workflow/.team/UDS-<slug>-<date>/research .workflow/.team/UDS-<slug>-<date>/design/component-specs .workflow/.team/UDS-<slug>-<date>/design/layout-specs .workflow/.team/UDS-<slug>-<date>/audit .workflow/.team/UDS-<slug>-<date>/build/token-files .workflow/.team/UDS-<slug>-<date>/build/component-files .workflow/.team/UDS-<slug>-<date>/wisdom .workflow/.team/UDS-<slug>-<date>/.msg")
```
| Mode | Task Chain |
|------|------------|
| component | RESEARCH-001 -> DESIGN-001 -> AUDIT-001 -> BUILD-001 |
| system | RESEARCH-001 -> DESIGN-001 -> AUDIT-001 -> [DESIGN-002 + BUILD-001] -> AUDIT-002 -> BUILD-002 |
| full-system | system chain + AUDIT-003 after BUILD-002 |
2. Write session.json:
## Phase 4: Spawn-and-Stop
```json
{
"status": "active",
"team_name": "uidesign",
"requirement": "<requirement>",
"timestamp": "<ISO-8601>",
"pipeline": "<component|system|full-system>",
"industry": "<industry>",
"sync_points": [],
"gc_state": { "round": 0, "max_rounds": 2, "converged": false },
"fix_cycles": {}
}
```
3. Initialize .msg/meta.json with pipeline metadata:
```typescript
// Use team_msg to write pipeline metadata to .msg/meta.json
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<component|system|full-system>",
pipeline_stages: ["researcher", "designer", "reviewer", "implementer"],
roles: ["coordinator", "researcher", "designer", "reviewer", "implementer"],
team_name: "uidesign"
}
})
```
4. Create team:
```
TeamCreate({ team_name: "uidesign" })
```
---
## Phase 3: Task Chain Creation
Execute `commands/dispatch.md` inline (Command Execution Protocol):
1. Read `roles/coordinator/commands/dispatch.md`
2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation)
3. Result: all pipeline tasks created with correct blockedBy dependencies
---
## Phase 4: Spawn & Coordination Loop
### Initial Spawn
Find first unblocked task and spawn its worker:
```
Agent({
subagent_type: "team-worker",
description: "Spawn researcher worker",
team_name: "uidesign",
name: "researcher",
run_in_background: true,
prompt: `## Role Assignment
role: researcher
role_spec: .claude/skills/team-uidesign/role-specs/researcher.md
session: <session-folder>
session_id: <session-id>
team_name: uidesign
requirement: <requirement>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
**STOP** after spawning. Wait for worker callback.
### Coordination (via monitor.md handlers)
All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks:
- handleCallback -> mark task done -> check pipeline -> handleSpawnNext
- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP
- handleComplete -> all done -> Phase 5
---
Delegate to `commands/monitor.md#handleSpawnNext`:
1. Find ready tasks (pending + blockedBy resolved)
2. Spawn team-worker agents (see SKILL.md Spawn Template)
3. Output status summary
4. STOP
## Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration
1. Read session state -> collect all results
2. List deliverables:
| Deliverable | Path |
@@ -262,29 +140,26 @@ All subsequent coordination is handled by `commands/monitor.md` handlers trigger
| Token Files | <session>/build/token-files/* |
| Component Files | <session>/build/component-files/* |
3. Output pipeline summary: task count, duration, GC rounds, sync points passed, final audit score
3. Calculate: completed_tasks, gc_rounds, sync_points_passed, final_audit_score
4. Output pipeline summary with [coordinator] prefix
5. Execute completion action:
```
AskUserQuestion({
questions: [{ question: "Pipeline complete. What next?", header: "Completion", options: [
{ label: "Archive & Clean", description: "Archive session and clean up team resources" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Export Results", description: "Export deliverables to specified location" }
]}]
})
```
4. **Completion Action** (interactive):
## Error Handling
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
5. Handle user choice:
| Choice | Steps |
|--------|-------|
| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-uidesign', args='resume')" |
| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow |
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Reset task to pending, respawn worker |
| Dependency cycle | Detect, report to user, halt |
| Invalid scope | Reject with error, ask to clarify |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
| GC loop stuck > 2 rounds | Escalate to user: accept / try one more / terminate |

View File

@@ -0,0 +1,69 @@
---
role: designer
prefix: DESIGN
inner_loop: false
message_types: [state_update]
---
# Design Token & Component Spec Author
Define visual language through design tokens (W3C Design Tokens Format) and component specifications. Consume design intelligence from researcher. Act as Generator in the designer<->reviewer Generator-Critic loop.
## Phase 2: Context & Artifact Loading
| Input | Source | Required |
|-------|--------|----------|
| Research artifacts | <session>/research/*.json | Yes |
| Design intelligence | <session>/research/design-intelligence.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Audit feedback | <session>/audit/audit-*.md | Only for GC fix tasks |
1. Extract session path from task description
2. Read research findings: design-system-analysis.json, component-inventory.json, accessibility-audit.json
3. Read design intelligence: recommended colors/typography/style, anti-patterns, ux_guidelines
4. Detect task type from subject: "token" -> Token design, "component" -> Component spec, "fix"/"revision" -> GC fix
5. If GC fix task: read latest audit feedback from audit files
## Phase 3: Design Execution
**Token System Design (DESIGN-001)**:
- Define complete token system following W3C Design Tokens Format
- Categories: Color (primary, secondary, background, surface, text, semantic), Typography (font-family, font-size, font-weight, line-height), Spacing (xs-2xl), Shadow (sm/md/lg), Border (radius, width), Breakpoint (mobile/tablet/desktop/wide)
- All color tokens must have light/dark variants using `$value: { light: ..., dark: ... }`
- Integrate design intelligence: recommended.colors -> color tokens, recommended.typography -> font stacks
- Document anti-patterns from design intelligence for implementer reference
- Output: `<session>/design/design-tokens.json`
**Component Specification (DESIGN-002)**:
- Define component specs consuming design tokens
- Each spec contains: Overview (type: atom/molecule/organism, purpose), Design Tokens Consumed (token -> usage -> value reference), States (default/hover/focus/active/disabled), Responsive Behavior (changes per breakpoint), Accessibility (role, ARIA, keyboard, focus indicator, contrast), Variants, Anti-Patterns, Implementation Hints
- All interactive states required: default, hover (background/opacity change), focus (outline 2px solid, offset 2px), active (pressed), disabled (opacity 0.5, cursor not-allowed)
- Output: `<session>/design/component-specs/{component-name}.md`
**GC Fix Mode (DESIGN-fix-N)**:
- Parse audit feedback for specific issues
- Re-read affected design artifacts; apply fixes (token value adjustments, missing states, accessibility gaps, naming fixes)
- Re-write affected files; signal `design_revision` instead of `design_ready`
## Phase 4: Self-Validation & Output
1. Token integrity checks:
| Check | Pass Criteria |
|-------|---------------|
| tokens_valid | All $value fields non-empty |
| theme_complete | Light/dark values for all color tokens |
| values_parseable | Valid CSS-parseable values |
| no_duplicates | No duplicate token definitions |
2. Component spec checks:
| Check | Pass Criteria |
|-------|---------------|
| states_complete | All 5 states (default/hover/focus/active/disabled) defined |
| a11y_specified | Role, ARIA, keyboard behavior defined |
| responsive_defined | At least mobile/desktop breakpoints |
| token_refs_valid | All `{token.path}` references resolve to defined tokens |
3. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace:
- Read existing -> merge `{ "designer": { task_type, token_categories, component_count, style_decisions } }` -> write back

View File

@@ -0,0 +1,72 @@
---
role: implementer
prefix: BUILD
inner_loop: false
message_types: [state_update]
---
# Component Code Builder
Translate design tokens and component specifications into production code. Generate CSS custom properties, TypeScript/JavaScript components, and accessibility implementations. Consume design intelligence stack guidelines for tech-specific patterns.
## Phase 2: Context & Artifact Loading
| Input | Source | Required |
|-------|--------|----------|
| Design tokens | <session>/design/design-tokens.json | Yes (token build) |
| Component specs | <session>/design/component-specs/*.md | Yes (component build) |
| Design intelligence | <session>/research/design-intelligence.json | Yes |
| Latest audit report | <session>/audit/audit-*.md | No |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. Detect build type from subject: "token" -> Token implementation, "component" -> Component implementation
3. Read design artifacts: design-tokens.json (token build), component-specs/*.md (component build)
4. Read design intelligence: stack_guidelines (tech-specific patterns), anti_patterns (patterns to avoid), ux_guidelines
5. Read latest audit report for approved changes and feedback
6. Detect project tech stack from package.json
## Phase 3: Implementation Execution
**Token Implementation (BUILD-001)**:
- Convert design tokens to production code
- Output files in `<session>/build/token-files/`:
- `tokens.css`: CSS custom properties with `:root` (light) and `[data-theme="dark"]` selectors, plus `@media (prefers-color-scheme: dark)` fallback
- `tokens.ts`: TypeScript constants and types for programmatic access with autocomplete support
- `README.md`: Token usage guide
- All color tokens must have both light and dark values
- Semantic token names must match design token definitions
**Component Implementation (BUILD-002)**:
- Implement component code from design specifications
- Per-component output in `<session>/build/component-files/`:
- `{ComponentName}.tsx`: React/Vue/Svelte component (match detected stack)
- `{ComponentName}.css`: Styles consuming tokens via `var(--token-name)` only
- `{ComponentName}.test.tsx`: Basic render + state tests
- `index.ts`: Re-export
- Requirements: no hardcoded colors/spacing (use design tokens), implement all 5 states, add ARIA attributes per spec, support responsive breakpoints, follow project component patterns
- Accessibility: keyboard navigation, screen reader support, visible focus indicators, WCAG AA contrast
- Check implementation against design intelligence anti_patterns
## Phase 4: Validation & Output
1. Token build validation:
| Check | Pass Criteria |
|-------|---------------|
| File existence | tokens.css and tokens.ts exist |
| Token coverage | All defined tokens present in CSS |
| Theme support | Light/dark variants exist |
2. Component build validation:
| Check | Pass Criteria |
|-------|---------------|
| File existence | At least 3 files per component (component, style, index) |
| No hardcoded values | No `#xxx` or `rgb()` in component CSS (only in tokens.css) |
| Focus styles | `:focus` or `:focus-visible` defined |
| Responsive | `@media` queries present |
| Anti-pattern clean | No violations of design intelligence anti_patterns |
3. Update `<session>/wisdom/.msg/meta.json` under `implementer` namespace:
- Read existing -> merge `{ "implementer": { build_type, file_count, output_dir, components_built } }` -> write back

View File

@@ -0,0 +1,82 @@
---
role: researcher
prefix: RESEARCH
inner_loop: false
message_types: [state_update]
---
# Design System Researcher
Analyze existing design system, build component inventory, assess accessibility baseline, and retrieve industry-specific design intelligence via ui-ux-pro-max. Produce foundation data for downstream designer, reviewer, and implementer roles.
## Phase 2: Context & Environment Detection
| Input | Source | Required |
|-------|--------|----------|
| Task description | From task subject/description | Yes |
| Session path | Extracted from task description | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | No |
1. Extract session path and target scope from task description
2. Detect project type and tech stack from package.json or equivalent:
| Package | Detected Stack |
|---------|---------------|
| next | nextjs |
| react | react |
| vue | vue |
| svelte | svelte |
| @shadcn/ui | shadcn |
| (default) | html-tailwind |
3. Use CLI tools (e.g., `ccw cli -p "..." --tool gemini --mode analysis`) or direct tools (Glob, Grep, mcp__ace-tool__search_context) to scan for existing design tokens, component files, styling patterns
4. Read industry context from session config (industry, strictness, must-have features)
## Phase 3: Research Execution
Execute 4 analysis streams:
**Stream 1 -- Design System Analysis**:
- Search for existing design tokens (CSS variables, theme configs, token files)
- Identify styling patterns (CSS-in-JS, CSS modules, utility classes, SCSS)
- Map color palette, typography scale, spacing system
- Find component library usage (MUI, Ant Design, shadcn, custom)
- Output: `<session>/research/design-system-analysis.json`
**Stream 2 -- Component Inventory**:
- Find all UI component files; identify props/API surface
- Identify states supported (hover, focus, disabled, etc.)
- Check accessibility attributes (ARIA labels, roles)
- Map inter-component dependencies and usage counts
- Output: `<session>/research/component-inventory.json`
**Stream 3 -- Accessibility Baseline**:
- Check ARIA attribute usage patterns, keyboard navigation support
- Assess color contrast ratios (if design tokens found)
- Find focus management and semantic HTML patterns
- Output: `<session>/research/accessibility-audit.json`
**Stream 4 -- Design Intelligence (ui-ux-pro-max)**:
- Call `Skill(skill="ui-ux-pro-max", args="<industry> <keywords> --design-system")` for design system recommendations
- Call `Skill(skill="ui-ux-pro-max", args="accessibility animation responsive --domain ux")` for UX guidelines
- Call `Skill(skill="ui-ux-pro-max", args="<keywords> --stack <detected-stack>")` for stack guidelines
- Degradation: when unavailable, use LLM general knowledge, mark `_source: "llm-general-knowledge"`
- Output: `<session>/research/design-intelligence.json`
Compile research summary metrics: design_system_exists, styling_approach, total_components, accessibility_level, design_intelligence_source, anti_patterns_count.
## Phase 4: Validation & Output
1. Verify all 4 output files exist and contain valid JSON with required fields:
| File | Required Fields |
|------|----------------|
| design-system-analysis.json | existing_tokens, styling_approach |
| component-inventory.json | components array |
| accessibility-audit.json | wcag_level |
| design-intelligence.json | _source, design_system |
2. If any file missing or invalid, re-run corresponding stream
3. Update `<session>/wisdom/.msg/meta.json` under `researcher` namespace:
- Read existing -> merge `{ "researcher": { detected_stack, component_count, wcag_level, di_source, scope } }` -> write back

View File

@@ -0,0 +1,67 @@
---
role: reviewer
prefix: AUDIT
inner_loop: false
message_types: [state_update]
---
# Design Auditor
Audit design tokens and component specs for consistency, accessibility compliance, completeness, quality, and industry best-practice adherence. Act as Critic in the designer<->reviewer Generator-Critic loop. Serve as sync point gatekeeper in dual-track pipelines.
## Phase 2: Context & Artifact Loading
| Input | Source | Required |
|-------|--------|----------|
| Design artifacts | <session>/design/*.json, <session>/design/component-specs/*.md | Yes |
| Design intelligence | <session>/research/design-intelligence.json | Yes |
| Audit history | .msg/meta.json -> reviewer namespace | No |
| Build artifacts | <session>/build/**/* | Only for final audit |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. Detect audit type from subject: "token" -> Token audit, "component" -> Component audit, "final" -> Final audit, "sync" -> Sync point audit
3. Read design intelligence for anti-patterns and ux_guidelines
4. Read design artifacts: design-tokens.json (token/component audit), component-specs/*.md (component/final audit), build/**/* (final audit only)
5. Load audit_history from meta.json for trend analysis
## Phase 3: Audit Execution
Score 5 dimensions on 1-10 scale:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Consistency | 20% | Token usage, naming conventions, visual uniformity |
| Accessibility | 25% | WCAG AA compliance, ARIA attributes, keyboard nav, contrast |
| Completeness | 20% | All states defined, responsive specs, edge cases |
| Quality | 15% | Token reference integrity, documentation clarity, maintainability |
| Industry Compliance | 20% | Anti-pattern avoidance, UX best practices, design intelligence adherence |
**Token Audit**: Naming convention (kebab-case, semantic names), value patterns (consistent units), theme completeness (light+dark for all colors), contrast ratios (text on background >= 4.5:1), minimum font sizes (>= 12px), all categories present, W3C $type metadata, no duplicates.
**Component Audit**: Token references resolve, naming matches convention, ARIA roles defined, keyboard behavior specified, focus indicator defined, all 5 states present, responsive breakpoints specified, variants documented, clear descriptions.
**Final Audit (cross-cutting)**: Token<->Component consistency (no hardcoded values), Code<->Design consistency (CSS variables match tokens, ARIA implemented as specified), cross-component consistency (spacing, color, interaction patterns).
**Score calculation**: `overallScore = round(consistency*0.20 + accessibility*0.25 + completeness*0.20 + quality*0.15 + industryCompliance*0.20)`
**Signal determination**:
| Condition | Signal |
|-----------|--------|
| Score >= 8 AND critical_count === 0 | `audit_passed` (GC CONVERGED) |
| Score >= 6 AND critical_count === 0 | `audit_result` (GC REVISION NEEDED) |
| Score < 6 OR critical_count > 0 | `fix_required` (CRITICAL FIX NEEDED) |
## Phase 4: Report & Output
1. Write audit report to `<session>/audit/audit-{NNN}.md`:
- Summary: overall score, signal, critical/high/medium counts
- Sync Point Status (if applicable): PASSED/BLOCKED
- Dimension Scores table (score/weight/weighted per dimension)
- Critical/High/Medium issues with descriptions, locations, fix suggestions
- GC Loop Status: signal, action required
- Trend analysis (if audit_history exists): improving/stable/declining
2. Update `<session>/wisdom/.msg/meta.json` under `reviewer` namespace:
- Read existing -> merge `{ "reviewer": { audit_id, score, critical_count, signal, is_sync_point, audit_type, timestamp } }` -> write back

View File

@@ -0,0 +1,76 @@
# Pipeline Definitions
UI design pipeline modes and task registry.
## Pipeline Modes
| Mode | Description | Task Count |
|------|-------------|------------|
| component | Single component: research -> design -> audit -> build | 4 tasks |
| system | Design system: dual-track with 2 sync points | 7 tasks |
| full-system | Full design system + final integrated audit | 8 tasks |
## Component Pipeline Task Registry
| Task ID | Role | blockedBy | Description |
|---------|------|-----------|-------------|
| RESEARCH-001 | researcher | [] | Design system analysis, component inventory, accessibility baseline |
| DESIGN-001 | designer | [RESEARCH-001] | Design tokens + component spec with all 5 interactive states |
| AUDIT-001 | reviewer | [DESIGN-001] | 5-dimension audit: consistency, accessibility, completeness, quality, compliance |
| BUILD-001 | implementer | [AUDIT-001] | CSS custom properties + component code + ARIA + keyboard navigation |
## System Pipeline Task Registry
| Task ID | Role | blockedBy | Description |
|---------|------|-----------|-------------|
| RESEARCH-001 | researcher | [] | Design system analysis across all components |
| DESIGN-001 | designer | [RESEARCH-001] | Token system design |
| AUDIT-001 | reviewer | [DESIGN-001] | Token audit [Sync Point 1: QUALITY-001] |
| DESIGN-002 | designer | [AUDIT-001] | Component specification (parallel) |
| BUILD-001 | implementer | [AUDIT-001] | Token code implementation (parallel) |
| AUDIT-002 | reviewer | [DESIGN-002] | Component audit [Sync Point 2] |
| BUILD-002 | implementer | [AUDIT-002, BUILD-001] | Component code implementation |
## Full-System Pipeline Task Registry
Same as System pipeline, plus:
| Task ID | Role | blockedBy | Description |
|---------|------|-----------|-------------|
| AUDIT-003 | reviewer | [BUILD-002] | Final integrated audit (cross-cutting) |
## Checkpoints / Sync Points
| Checkpoint | Task | Condition | Action |
|------------|------|-----------|--------|
| QUALITY-001: Sync Point 1 | AUDIT-001 completes | Score >= 8, critical == 0 | Unblock DESIGN-002 + BUILD-001 (parallel) |
| QUALITY-001: GC Loop | AUDIT-* completes | Score < 8 or critical > 0 | Create DESIGN-fix task, new AUDIT task (max 2 rounds) |
## GC Loop Behavior
| Signal | Condition | Action |
|--------|-----------|--------|
| audit_passed | Score >= 8, critical == 0 | GC converged -> record sync_point -> unblock downstream |
| audit_result | Score 6-7, no critical | gc_rounds < max -> create DESIGN-fix task |
| fix_required | Score < 6 or critical > 0 | gc_rounds < max -> create DESIGN-fix task (CRITICAL) |
| Any | gc_rounds >= max | Escalate to user: accept / try one more / terminate |
## Parallel Spawn Rules
| Mode | After | Spawn Behavior |
|------|-------|----------------|
| component | Sequential | One task at a time |
| system | Sync Point 1 (AUDIT-001) | Spawn DESIGN-002 + BUILD-001 in parallel |
| system | AUDIT-002 | Spawn BUILD-002 |
| full-system | Sync Point 1 (AUDIT-001) | Spawn DESIGN-002 + BUILD-001 in parallel |
| full-system | BUILD-002 | Spawn AUDIT-003 |
## Output Artifacts
| Task | Output Path |
|------|-------------|
| RESEARCH-001 | <session>/research/*.json |
| DESIGN-001 | <session>/design/design-tokens.json + component-specs/*.md |
| AUDIT-* | <session>/audit/audit-<NNN>.md |
| BUILD-001 | <session>/build/token-files/* |
| BUILD-002 | <session>/build/component-files/* |