feat(skills): update 12 team skills to v3 design patterns

- Update all 12 team-* SKILL.md files with v3 structure:
  - Replace JS pseudocode with text decision tables
  - Add Role Registry with Compact column
  - Add COMPACT PROTECTION blocks
  - Add Cadence Control sections
  - Add Wisdom Accumulation sections
  - Add Task Metadata Registry
  - Add Orchestration Mode user commands

- Update 58 role files (SKILL.md + roles/*):
  - Flat-file skills: team-brainstorm, team-issue, team-testing,
    team-uidesign, team-planex, team-iterdev
  - Folder-based skills: team-review, team-roadmap-dev, team-frontend,
    team-quality-assurance, team-tech-debt, team-ultra-analyze

- Preserve special architectures:
  - team-planex: 2-member (planner + executor only)
  - team-tech-debt: Stop-Wait strategy (run_in_background:false)
  - team-iterdev: 7 behavior protocol tables in coordinator

- All 12 teams reviewed for content completeness (PASS)
This commit is contained in:
catlog22
2026-02-26 21:14:45 +08:00
parent e228b8b273
commit 430d817e43
73 changed files with 13606 additions and 15439 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,179 +1,263 @@
# Role: architect
# Architect Role
技术架构师。负责技术设计、任务分解、架构决策记录。
Technical architect. Responsible for technical design, task decomposition, and architecture decision records.
## Role Identity
## Identity
- **Name**: `architect`
- **Name**: `architect` | **Tag**: `[architect]`
- **Task Prefix**: `DESIGN-*`
- **Responsibility**: Read-only analysis (技术设计)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[architect]`
- **Responsibility**: Read-only analysis (Technical Design)
## Role Boundaries
## Boundaries
### MUST
- 仅处理 `DESIGN-*` 前缀的任务
- 所有输出必须带 `[architect]` 标识
- Phase 2 读取 shared-memory.jsonPhase 5 写入 architecture_decisions
- Only process `DESIGN-*` prefixed tasks
- All output must carry `[architect]` identifier
- Phase 2: Read shared-memory.json, Phase 5: Write architecture_decisions
- Work strictly within technical design responsibility scope
### MUST NOT
- ❌ 编写实现代码、执行测试或代码审查
- ❌ 直接与其他 worker 通信
- ❌ 为其他角色创建任务
- Execute work outside this role's responsibility scope
- Write implementation code, execute tests, or perform code review
- Communicate directly with other worker roles (must go through coordinator)
- Create tasks for other roles (TaskCreate is coordinator-exclusive)
- Modify files or resources outside this role's responsibility
- Omit `[architect]` identifier in any output
---
## Toolbox
### Tool Capabilities
| Tool | Type | Purpose |
|------|------|---------|
| Task | Agent | Spawn cli-explore-agent for codebase exploration |
| Read | File | Read session files, shared memory, design files |
| Write | File | Write design documents and task breakdown |
| Bash | Shell | Execute shell commands |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `design_ready` | architect coordinator | Design completed | 设计完成 |
| `design_revision` | architect coordinator | Design revised | 设计修订 |
| `error` | architect coordinator | Processing failure | 错误上报 |
| `design_ready` | architect -> coordinator | Design completed | Design ready for implementation |
| `design_revision` | architect -> coordinator | Design revised | Design updated based on feedback |
| `error` | architect -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: "iterdev",
from: "architect",
to: "coordinator",
type: <message-type>,
summary: "[architect] DESIGN complete: <task-subject>",
ref: <design-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team iterdev --from architect --to coordinator --type <message-type> --summary \"[architect] DESIGN complete\" --ref <design-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('DESIGN-') && t.owner === 'architect' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `DESIGN-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Codebase Exploration
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
**Inputs**:
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
| Input | Source | Required |
|-------|--------|----------|
| Session path | Task description (Session: <path>) | Yes |
| Shared memory | <session-folder>/shared-memory.json | Yes |
| Codebase | Project files | Yes |
| Wisdom | <session-folder>/wisdom/ | No |
// Multi-angle codebase exploration
**Loading steps**:
1. Extract session path from task description
2. Read shared-memory.json for context
```
Read(<session-folder>/shared-memory.json)
```
3. Multi-angle codebase exploration via cli-explore-agent:
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore architecture",
prompt: `Explore codebase architecture for: ${task.description}
Focus on: existing patterns, module structure, dependencies, similar implementations.
prompt: `Explore codebase architecture for: <task-description>
Focus on:
- Existing patterns
- Module structure
- Dependencies
- Similar implementations
Report relevant files and integration points.`
})
```
### Phase 3: Technical Design + Task Decomposition
```javascript
const designNum = task.subject.match(/DESIGN-(\d+)/)?.[1] || '001'
const designPath = `${sessionFolder}/design/design-${designNum}.md`
const breakdownPath = `${sessionFolder}/design/task-breakdown.json`
**Design strategy selection**:
// Generate design document
const designContent = `# Technical Design — ${designNum}
| Condition | Strategy |
|-----------|----------|
| Single module change | Direct inline design |
| Cross-module change | Multi-component design with integration points |
| Large refactoring | Phased approach with milestones |
**Requirement**: ${task.description}
**Sprint**: ${sharedMemory.sprint_history?.length + 1 || 1}
**Outputs**:
1. **Design Document** (`<session-folder>/design/design-<num>.md`):
```markdown
# Technical Design — <num>
**Requirement**: <task-description>
**Sprint**: <sprint-number>
## Architecture Decision
**Approach**: ${selectedApproach}
**Rationale**: ${rationale}
**Alternatives Considered**: ${alternatives.join(', ')}
**Approach**: <selected-approach>
**Rationale**: <rationale>
**Alternatives Considered**: <alternatives>
## Component Design
${components.map(c => `### ${c.name}
- **Responsibility**: ${c.responsibility}
- **Dependencies**: ${c.dependencies.join(', ')}
- **Files**: ${c.files.join(', ')}
- **Complexity**: ${c.complexity}
`).join('\n')}
### <Component-1>
- **Responsibility**: <description>
- **Dependencies**: <deps>
- **Files**: <file-list>
- **Complexity**: <low/medium/high>
## Task Breakdown
${taskBreakdown.map((t, i) => `### Task ${i + 1}: ${t.title}
- **Files**: ${t.files.join(', ')}
- **Estimated Complexity**: ${t.complexity}
- **Dependencies**: ${t.dependencies.join(', ') || 'None'}
`).join('\n')}
### Task 1: <title>
- **Files**: <file-list>
- **Estimated Complexity**: <level>
- **Dependencies**: <deps or None>
## Integration Points
${integrationPoints.map(ip => `- **${ip.name}**: ${ip.description}`).join('\n')}
- **<Integration-1>**: <description>
## Risks
${risks.map(r => `- **${r.risk}**: ${r.mitigation}`).join('\n')}
`
- **<Risk-1>**: <mitigation>
```
Write(designPath, designContent)
2. **Task Breakdown JSON** (`<session-folder>/design/task-breakdown.json`):
// Generate task breakdown JSON for developer
const breakdown = {
design_id: `design-${designNum}`,
tasks: taskBreakdown.map((t, i) => ({
id: `task-${i + 1}`,
title: t.title,
files: t.files,
complexity: t.complexity,
dependencies: t.dependencies,
acceptance_criteria: t.acceptance
})),
total_files: [...new Set(taskBreakdown.flatMap(t => t.files))].length,
execution_order: taskBreakdown.map((t, i) => `task-${i + 1}`)
```json
{
"design_id": "design-<num>",
"tasks": [
{
"id": "task-1",
"title": "<title>",
"files": ["<file1>", "<file2>"],
"complexity": "<level>",
"dependencies": [],
"acceptance_criteria": "<criteria>"
}
],
"total_files": <count>,
"execution_order": ["task-1", "task-2"]
}
Write(breakdownPath, JSON.stringify(breakdown, null, 2))
```
### Phase 4: Design Validation
```javascript
// Verify design completeness
const hasComponents = components.length > 0
const hasBreakdown = taskBreakdown.length > 0
const hasDependencies = components.every(c => c.dependencies !== undefined)
**Validation checks**:
| 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 | Check all components have dependencies field | All have dependencies (can be empty) |
| Integration points | Verify integration section | Key integrations documented |
### Phase 5: Report to Coordinator
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
1. **Update shared memory**:
```
sharedMemory.architecture_decisions.push({
design_id: "design-<num>",
approach: <approach>,
rationale: <rationale>,
components: <component-names>,
task_count: <count>
})
Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2))
```
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
sharedMemory.architecture_decisions.push({
design_id: `design-${designNum}`,
approach: selectedApproach,
rationale: rationale,
components: components.map(c => c.name),
task_count: taskBreakdown.length
})
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
2. **Log and send message**:
```
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "architect", to: "coordinator",
operation: "log", team: "iterdev", from: "architect", to: "coordinator",
type: "design_ready",
summary: `[architect] Design complete: ${components.length} components, ${taskBreakdown.length} tasks`,
ref: designPath
summary: "[architect] Design complete: <count> components, <task-count> tasks",
ref: <design-path>
})
SendMessage({
type: "message", recipient: "coordinator",
content: `## [architect] Design Ready\n\n**Components**: ${components.length}\n**Tasks**: ${taskBreakdown.length}\n**Design**: ${designPath}\n**Breakdown**: ${breakdownPath}`,
summary: `[architect] Design: ${taskBreakdown.length} tasks`
})
content: `## [architect] Design Ready
TaskUpdate({ taskId: task.id, status: 'completed' })
**Components**: <count>
**Tasks**: <task-count>
**Design**: <design-path>
**Breakdown**: <breakdown-path>`,
summary: "[architect] Design: <task-count> tasks"
})
```
3. **Mark task complete**:
```
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
4. **Loop to Phase 1** for next task
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No DESIGN-* tasks | Idle |
| No DESIGN-* tasks available | Idle, wait for coordinator assignment |
| Codebase exploration fails | Design based on task description alone |
| Too many components | Simplify, suggest phased approach |
| Too many components identified | Simplify, suggest phased approach |
| Conflicting patterns found | Document in design, recommend resolution |
| Context/Plan file not found | Notify coordinator, request location |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
| Unexpected error | Log error via team_msg, report to coordinator |

View File

@@ -1,292 +1,421 @@
# Role: coordinator
# Coordinator Role
持续迭代开发团队协调者。负责 Sprint 规划、积压管理、任务账本维护、Generator-Critic 循环控制(developerreviewer最多3轮、Sprint 间学习、**冲突处理、并发控制、回滚策略**、**用户反馈循环、技术债务追踪**。
Orchestrate the IterDev workflow: Sprint planning, backlog management, task ledger maintenance, Generator-Critic loop control (developer<->reviewer, max 3 rounds), cross-sprint learning, conflict handling, concurrency control, rollback strategy, user feedback loop, and tech debt tracking.
## Role Identity
## Identity
- **Name**: `coordinator`
- **Task Prefix**: N/A
- **Responsibility**: Orchestration + **Stability Management** + **Quality Tracking**
- **Communication**: SendMessage to all teammates
- **Output Tag**: `[coordinator]`
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Orchestration + Stability Management + Quality Tracking
## Role Boundaries
## Boundaries
### MUST
- 所有输出必须带 `[coordinator]` 标识
- 维护 task-ledger.json 实时进度
- 管理 developerreviewer GC 循环最多3轮
- Sprint 结束时记录学习到 shared-memory.json
- **Phase 1 新增**:
- 检测并协调任务间冲突
- 管理共享资源锁定resource_locks
- 记录回滚点并支持紧急回滚
- **Phase 3 新增**:
- 收集并跟踪用户反馈user_feedback_items
- 识别并记录技术债务tech_debt_items
- 生成技术债务报告
- 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
- Detect and coordinate task conflicts
- Manage shared resource locks (resource_locks)
- Record rollback points and support emergency rollback
- Collect and track user feedback (user_feedback_items)
- Identify and record tech debt (tech_debt_items)
- Generate tech debt reports
### MUST NOT
- ❌ 直接编写代码、设计架构、执行测试或代码审查
- ❌ 直接调用实现类 subagent
- ❌ 修改源代码
- Execute implementation work directly (delegate to workers)
- Write source code directly
- Call implementation-type subagents directly
- Modify task outputs (workers own their deliverables)
- Skip dependency validation when creating task chains
## Execution
> **Core principle**: Coordinator is the orchestrator, not the executor. All actual work must be delegated to worker roles via TaskCreate.
### Phase 1: Sprint Planning
---
```javascript
const args = "$ARGUMENTS"
const teamName = args.match(/--team-name[=\s]+([\w-]+)/)?.[1] || `iterdev-${Date.now().toString(36)}`
const taskDescription = args.replace(/--team-name[=\s]+[\w-]+/, '').replace(/--role[=\s]+\w+/, '').trim()
## Entry Router
// Assess complexity for pipeline selection
function assessComplexity(desc) {
let score = 0
const changedFiles = Bash(`git diff --name-only HEAD~1 2>/dev/null || echo ""`).split('\n').filter(Boolean)
score += changedFiles.length > 10 ? 3 : changedFiles.length > 3 ? 2 : 0
if (/refactor|architect|restructure|system|module/.test(desc)) score += 3
if (/multiple|across|cross/.test(desc)) score += 2
if (/fix|bug|typo|patch/.test(desc)) score -= 2
return { score, fileCount: changedFiles.length }
}
When coordinator is invoked, first detect the invocation type:
const { score, fileCount } = assessComplexity(taskDescription)
const suggestedPipeline = score >= 5 ? 'multi-sprint' : score >= 2 ? 'sprint' : 'patch'
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline |
| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline |
| New session | None of the above | -> Phase 0 (Session Resume Check) |
For callback/check/resume: load monitor logic and execute the appropriate handler, then STOP.
---
## Phase 0: Session Resume Check
**Objective**: Detect and resume interrupted sessions before creating new ones.
**Workflow**:
1. Scan `.workflow/.team/IDS-*/team-session.json` for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session 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. **Assess complexity** for pipeline selection:
| Signal | Weight | Keywords |
|--------|--------|----------|
| Changed files > 10 | +3 | Large changeset |
| Changed files 3-10 | +2 | Medium changeset |
| Structural change | +3 | refactor, architect, restructure, system, module |
| Cross-cutting | +2 | multiple, across, cross |
| Simple fix | -2 | fix, bug, typo, patch |
| Score | Pipeline | Description |
|-------|----------|-------------|
| >= 5 | multi-sprint | Incremental iterative delivery for large features |
| 2-4 | sprint | Standard: Design -> Dev -> Verify + Review |
| 0-1 | patch | Simple: Dev -> Verify |
3. **Ask for missing parameters** via AskUserQuestion:
```
AskUserQuestion({
questions: [{
question: "选择开发模式:",
question: "Select development mode:",
header: "Mode",
multiSelect: false,
options: [
{ label: suggestedPipeline === 'patch' ? "patch (推荐)" : "patch", description: "补丁模式:实现→验证(简单修复)" },
{ label: suggestedPipeline === 'sprint' ? "sprint (推荐)" : "sprint", description: "Sprint模式:设计→实现→验证+审查" },
{ label: suggestedPipeline === 'multi-sprint' ? "multi-sprint (推荐)" : "multi-sprint", description: "多Sprint增量迭代交付大型特性" }
{ label: "patch (recommended)", description: "Patch mode: implement -> verify (simple fixes)" },
{ label: "sprint (recommended)", description: "Sprint mode: design -> implement -> verify + review" },
{ label: "multi-sprint (recommended)", description: "Multi-sprint: incremental iterative delivery (large features)" }
]
}]
})
```
### Phase 2: Create Team + Initialize Ledger
**Success**: All parameters captured, mode finalized.
```javascript
TeamCreate({ team_name: teamName })
---
const topicSlug = taskDescription.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40)
const dateStr = new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().substring(0, 10)
const sessionId = `IDS-${topicSlug}-${dateStr}`
const sessionFolder = `.workflow/.team/${sessionId}`
## Phase 2: Create Team + Initialize Session
Bash(`mkdir -p "${sessionFolder}/design" "${sessionFolder}/code" "${sessionFolder}/verify" "${sessionFolder}/review"`)
**Objective**: Initialize team, session file, task ledger, shared memory, and wisdom directory.
// Initialize task ledger
const taskLedger = {
sprint_id: "sprint-1",
sprint_goal: taskDescription,
pipeline: selectedPipeline,
tasks: [],
metrics: { total: 0, completed: 0, in_progress: 0, blocked: 0, velocity: 0 }
**Workflow**:
1. Generate session ID: `IDS-{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 task-ledger.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 }
}
Write(`${sessionFolder}/task-ledger.json`, JSON.stringify(taskLedger, null, 2))
```
// Initialize shared memory with sprint learning
const sharedMemory = {
sprint_history: [],
architecture_decisions: [],
implementation_context: [],
review_feedback_trends: [],
gc_round: 0,
max_gc_rounds: 3
7. Initialize shared-memory.json:
```
{
"sprint_history": [],
"architecture_decisions": [],
"implementation_context": [],
"review_feedback_trends": [],
"gc_round": 0,
"max_gc_rounds": 3,
"resource_locks": {},
"task_checkpoints": {},
"user_feedback_items": [],
"tech_debt_items": []
}
Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2))
const teamSession = {
session_id: sessionId, team_name: teamName, task: taskDescription,
pipeline: selectedPipeline, status: "active", sprint_number: 1,
created_at: new Date().toISOString(), updated_at: new Date().toISOString(),
completed_tasks: []
}
Write(`${sessionFolder}/team-session.json`, JSON.stringify(teamSession, null, 2))
```
// ⚠️ Workers are NOT pre-spawned here.
// Workers are spawned per-stage in Phase 4 via Stop-Wait Task(run_in_background: false).
// See SKILL.md Coordinator Spawn Template for worker prompt templates.
**Success**: Team created, session file written, wisdom initialized, task ledger and shared memory ready.
### Phase 3: Create Task Chain + Update Ledger
---
#### Patch Pipeline
## Phase 3: Create Task Chain
```javascript
TaskCreate({ subject: "DEV-001: 实现修复", description: `${taskDescription}\n\nSession: ${sessionFolder}`, activeForm: "实现中" })
TaskUpdate({ taskId: devId, owner: "developer" })
**Objective**: Dispatch tasks based on mode with proper dependencies.
TaskCreate({ subject: "VERIFY-001: 验证修复", description: `验证 DEV-001\n\nSession: ${sessionFolder}`, activeForm: "验证中" })
TaskUpdate({ taskId: verifyId, owner: "tester", addBlockedBy: [devId] })
### Patch Pipeline
// Update ledger
updateLedger(sessionFolder, null, {
tasks: [
{ id: "DEV-001", title: "实现修复", owner: "developer", status: "pending", gc_rounds: 0 },
{ id: "VERIFY-001", title: "验证修复", owner: "tester", status: "pending", gc_rounds: 0 }
],
metrics: { total: 2, completed: 0, in_progress: 0, blocked: 0, velocity: 0 }
})
```
| Task ID | Owner | Blocked By | Description |
|---------|-------|------------|-------------|
| DEV-001 | developer | (none) | Implement fix |
| VERIFY-001 | tester | DEV-001 | Verify fix |
#### Sprint Pipeline
### Sprint Pipeline
```javascript
TaskCreate({ subject: "DESIGN-001: 技术设计与任务分解", description: `${taskDescription}\n\nSession: ${sessionFolder}\n输出: ${sessionFolder}/design/design-001.md + task-breakdown.json`, activeForm: "设计中" })
TaskUpdate({ taskId: designId, owner: "architect" })
| Task ID | Owner | Blocked By | Description |
|---------|-------|------------|-------------|
| DESIGN-001 | architect | (none) | Technical design and task breakdown |
| DEV-001 | developer | DESIGN-001 | Implement design |
| VERIFY-001 | tester | DEV-001 | Test execution |
| REVIEW-001 | reviewer | DEV-001 | Code review |
TaskCreate({ subject: "DEV-001: 实现设计方案", description: `按设计方案实现\n\nSession: ${sessionFolder}\n设计: design/design-001.md\n分解: design/task-breakdown.json`, activeForm: "实现中" })
TaskUpdate({ taskId: devId, owner: "developer", addBlockedBy: [designId] })
### Multi-Sprint Pipeline
// VERIFY-001 and REVIEW-001 parallel, both blockedBy DEV-001
TaskCreate({ subject: "VERIFY-001: 测试验证", description: `验证实现\n\nSession: ${sessionFolder}`, activeForm: "验证中" })
TaskUpdate({ taskId: verifyId, owner: "tester", addBlockedBy: [devId] })
Sprint 1: DESIGN-001 -> DEV-001 -> DEV-002(incremental) -> VERIFY-001 -> DEV-fix -> REVIEW-001
TaskCreate({ subject: "REVIEW-001: 代码审查", description: `审查实现\n\nSession: ${sessionFolder}\n设计: design/design-001.md`, activeForm: "审查中" })
TaskUpdate({ taskId: reviewId, owner: "reviewer", addBlockedBy: [devId] })
```
Subsequent sprints created dynamically after Sprint N completes.
#### Multi-Sprint Pipeline
**Task Creation**: Use TaskCreate + TaskUpdate(owner, addBlockedBy) for each task. Include `Session: <session-folder>` in every task description.
```javascript
// Sprint 1 — created dynamically, subsequent sprints created after Sprint N completes
// Each sprint: DESIGN → DEV-1..N(incremental) → VERIFY → DEV-fix → REVIEW
```
---
### Phase 4: Coordination Loop + GC Control + Ledger Updates
## Phase 4: Spawn-and-Stop
> **设计原则Stop-Wait**: 模型执行没有时间概念,禁止任何形式的轮询等待。
> - ❌ 禁止: `while` 循环 + `sleep` + 检查状态
> - ✅ 采用: 同步 `Task(run_in_background: false)` 调用Worker 返回 = 阶段完成信号
>
> 按 Phase 3 创建的任务链顺序,逐阶段 spawn worker 同步执行。
> Worker prompt 使用 SKILL.md Coordinator Spawn Template。
**Objective**: Spawn first batch of ready workers in background, then STOP.
**Design**: Spawn-and-Stop + Callback pattern.
- Spawn workers with `Task(run_in_background: true)` -> immediately return
- Worker completes -> SendMessage callback -> auto-advance
- User can use "check" / "resume" to manually advance
- Coordinator does one operation per invocation, then STOPS
**Workflow**:
1. Find tasks with: status=pending, blockedBy all resolved, owner assigned
2. For each ready task -> spawn worker using Spawn Template
3. Output status summary
4. STOP
### Callback Handler
| Received Message | Action |
|-----------------|--------|
| architect: design_ready | Read design → update ledger unblock DEV |
| developer: dev_complete | Update ledger unblock VERIFY + REVIEW |
| architect: design_ready | Update ledger -> unblock DEV |
| developer: dev_complete | Update ledger -> unblock VERIFY + REVIEW |
| tester: verify_passed | Update ledger (test_pass_rate) |
| tester: verify_failed | Create DEV-fix task |
| tester: fix_required | Create DEV-fix task assign developer |
| reviewer: review_passed | Update ledger (review_score) mark complete |
| reviewer: review_revision | **GC loop** create DEV-fix REVIEW-next |
| reviewer: review_critical | **GC loop** create DEV-fix REVIEW-next |
| tester: fix_required | Create DEV-fix task -> assign developer |
| reviewer: review_passed | Update ledger (review_score) -> mark complete |
| reviewer: review_revision | **GC loop** -> create DEV-fix -> REVIEW-next |
| reviewer: review_critical | **GC loop** -> create DEV-fix -> REVIEW-next |
#### Generator-Critic Loop Control (developer↔reviewer)
### GC Loop Control
```javascript
if (msgType === 'review_revision' || msgType === 'review_critical') {
const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`))
const gcRound = sharedMemory.gc_round || 0
When receiving `review_revision` or `review_critical`:
if (gcRound < sharedMemory.max_gc_rounds) {
sharedMemory.gc_round = gcRound + 1
Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2))
1. Read shared-memory.json -> get gc_round
2. If gc_round < max_gc_rounds (3):
- Increment gc_round
- Create DEV-fix task with review feedback
- Create REVIEW-next task blocked by DEV-fix
- Update ledger
- Log gc_loop_trigger message
3. Else (max rounds reached):
- Accept with warning
- Log sprint_complete message
// Create DEV-fix task
TaskCreate({
subject: `DEV-fix-${gcRound + 1}: 根据审查修订代码`,
description: `审查反馈:\n${reviewFeedback}\n\nSession: ${sessionFolder}\n审查: review/review-${reviewNum}.md`,
activeForm: "修订代码中"
})
TaskUpdate({ taskId: fixId, owner: "developer" })
---
// Create REVIEW-next task
TaskCreate({
subject: `REVIEW-${reviewNum + 1}: 验证修订`,
description: `验证 DEV-fix-${gcRound + 1} 的修订\n\nSession: ${sessionFolder}`,
activeForm: "复审中"
})
TaskUpdate({ taskId: nextReviewId, owner: "reviewer", addBlockedBy: [fixId] })
## Phase 5: Report + Next Steps
// Update ledger
updateLedger(sessionFolder, `DEV-fix-${gcRound + 1}`, { status: 'pending', gc_rounds: gcRound + 1 })
**Objective**: Completion report and follow-up options.
**Workflow**:
1. Load session state -> count completed tasks, duration
2. Record sprint learning to shared-memory.json
3. List deliverables with output paths
4. Update session status -> "completed"
5. Offer next steps via AskUserQuestion
---
## Protocol Implementations
### Resource Lock Protocol
Concurrency control for shared resources. Prevents multiple workers from modifying the same files simultaneously.
| 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. |
| 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. |
| Deadlock detection | Multiple tasks waiting on each other | Abort youngest task, release its locks. Notify coordinator. |
### Conflict Detection Protocol
Detects and resolves file-level conflicts between concurrent development tasks.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Detect conflict | DEV task completes with changed files | Compare changed files against other in_progress/completed tasks. If overlap, update task's conflict_info to status "detected". Log conflict_detected. |
| Resolve conflict | Conflict detected | Set resolution_strategy (manual/auto_merge/abort). Create fix-conflict task for developer. Log conflict_resolved. |
| Skip | No file overlap | No action needed. |
### Rollback Point Protocol
Manages state snapshots for safe recovery.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Create rollback point | Task phase completes | Generate snapshot ID, record rollback_procedure (default: git revert HEAD) in task's rollback_info. |
| Execute rollback | Task failure or user request | Log rollback_initiated. Execute stored procedure. Log rollback_completed or rollback_failed. |
| Validate snapshot | Before rollback | Verify snapshot ID exists and procedure is valid. |
### Dependency Validation Protocol
Validates external dependencies before task execution.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Validate | Task startup with dependencies | Check installed version vs expected. Record status (ok/mismatch/missing) in external_dependencies. |
| Report mismatch | Any dependency has issues | Log dependency_mismatch. Block task until resolved. |
| Update notification | Important update available | Log dependency_update_needed. Add to backlog. |
### Checkpoint Management Protocol
Saves and restores task execution state for interruption recovery.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Save checkpoint | Task reaches milestone | Store checkpoint in task_checkpoints with timestamp. Retain last 5 per task. Log context_checkpoint_saved. |
| Restore checkpoint | Task resumes after interruption | Load latest checkpoint. Log context_restored. |
| Not found | Resume requested but no checkpoints | Return failure. Worker starts fresh. |
### User Feedback Protocol
Collects, categorizes, and tracks user feedback.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Receive feedback | User provides feedback | Create feedback item (FB-xxx) with severity, category. Store in user_feedback_items (max 50). Log user_feedback_received. |
| Link to task | Feedback relates to task | Update source_task_id, set status "reviewed". |
| Triage | High/critical severity | Prioritize in next sprint. Create task if actionable. |
### Tech Debt Management Protocol
Identifies, tracks, and prioritizes technical debt.
| Action | Trigger Condition | Behavior |
|--------|-------------------|----------|
| Identify debt | Worker reports tech debt | Create debt item (TD-xxx) with category, severity, effort. Store in tech_debt_items. Log tech_debt_identified. |
| Generate report | Sprint retrospective | Aggregate by severity and category. Report totals. |
| Prioritize | Sprint planning | Rank by severity. Recommend items for current sprint. |
| Resolve | Developer completes debt task | Update status to "resolved". Record in sprint history. |
---
## Toolbox
### Tool Capabilities
| Tool | Type | Purpose |
|------|------|---------|
| TeamCreate | Team | Create team instance |
| TeamDelete | Team | Disband team |
| SendMessage | Communication | Send messages to workers |
| TaskCreate | Task | Create tasks for workers |
| TaskUpdate | Task | Update task status/owner/dependencies |
| TaskList | Task | List all tasks |
| TaskGet | Task | Get task details |
| Task | Agent | Spawn worker agents |
| AskUserQuestion | Interaction | Ask user for input |
| Read | File | Read session files |
| Write | File | Write session files |
| Bash | Shell | Execute shell commands |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| sprint_started | coordinator -> all | Sprint begins | Sprint initialization |
| gc_loop_trigger | coordinator -> developer | Review needs revision | GC loop iteration |
| sprint_complete | coordinator -> all | Sprint ends | Sprint summary |
| task_unblocked | coordinator -> worker | Task dependencies resolved | Task ready |
| error | coordinator -> all | Error occurred | Error notification |
| shutdown | coordinator -> all | Team disbands | Shutdown notice |
| conflict_detected | coordinator -> all | File conflict found | Conflict alert |
| conflict_resolved | coordinator -> all | Conflict resolved | Resolution notice |
| resource_locked | coordinator -> all | Resource acquired | Lock notification |
| resource_unlocked | coordinator -> all | Resource released | Unlock notification |
| resource_contention | coordinator -> all | Lock denied | Contention alert |
| rollback_initiated | coordinator -> all | Rollback started | Rollback notice |
| rollback_completed | coordinator -> all | Rollback succeeded | Success notice |
| rollback_failed | coordinator -> all | Rollback failed | Failure alert |
| dependency_mismatch | coordinator -> all | Dependency issue | Dependency alert |
| dependency_update_needed | coordinator -> all | Update available | Update notice |
| context_checkpoint_saved | coordinator -> all | Checkpoint created | Checkpoint notice |
| context_restored | coordinator -> all | Checkpoint restored | Restore notice |
| user_feedback_received | coordinator -> all | Feedback recorded | Feedback notice |
| tech_debt_identified | coordinator -> all | Tech debt found | Debt notice |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "coordinator", to: "developer",
type: "gc_loop_trigger",
summary: `[coordinator] GC round ${gcRound + 1}/${sharedMemory.max_gc_rounds}: review requires revision`
})
} else {
// Max rounds — accept with warning
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "coordinator", to: "all",
type: "sprint_complete",
summary: `[coordinator] GC loop exhausted (${gcRound} rounds), accepting current state`
})
}
}
```
### Phase 5: Sprint Retrospective + Persist
```javascript
const ledger = JSON.parse(Read(`${sessionFolder}/task-ledger.json`))
const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`))
// Record sprint learning
const sprintRetro = {
sprint_id: ledger.sprint_id,
velocity: ledger.metrics.velocity,
gc_rounds: sharedMemory.gc_round,
what_worked: [], // extracted from review/verify feedback
what_failed: [], // extracted from failures
patterns_learned: [] // derived from GC loop patterns
}
sharedMemory.sprint_history.push(sprintRetro)
Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2))
SendMessage({
content: `## [coordinator] Sprint 完成
**需求**: ${taskDescription}
**管道**: ${selectedPipeline}
**完成**: ${ledger.metrics.completed}/${ledger.metrics.total}
**GC 轮次**: ${sharedMemory.gc_round}
### 任务账本
${ledger.tasks.map(t => `- ${t.id}: ${t.status} ${t.review_score ? '(Review: ' + t.review_score + '/10)' : ''}`).join('\n')}`,
summary: `[coordinator] Sprint complete: ${ledger.metrics.completed}/${ledger.metrics.total}`
})
AskUserQuestion({
questions: [{
question: "Sprint 已完成。下一步:",
header: "Next",
multiSelect: false,
options: [
{ label: "下一个Sprint", description: "继续迭代(携带学习记忆)" },
{ label: "新需求", description: "新的开发需求" },
{ label: "关闭团队", description: "关闭所有 teammate" }
]
}]
mcp__ccw-tools__team_msg({
operation: "log",
team: "iterdev",
from: "coordinator",
to: "all",
type: <message-type>,
summary: "[coordinator] <summary>",
ref: <artifact-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team iterdev --from coordinator --to all --type <message-type> --summary \"[coordinator] ...\" --ref <artifact-path> --json")
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| GC 循环超限 (3轮) | 接受当前代码,记录到 sprint_history |
| Velocity 低于 50% | 上报用户,建议缩小范围 |
| 任务账本损坏 | 从 TaskList 重建 |
| 设计被拒 3+ 次 | Coordinator 介入简化设计 |
| 测试持续失败 | 创建 DEV-fix developer |
| **Phase 1 新增** | |
| 冲突检测到 | 更新 conflict_info通知 coordinator创建 DEV-fix 任务 |
| 资源锁超时 (5min) | 强制释放锁,通知持有者和 coordinator |
| 回滚请求 | 验证 snapshot_id执行 rollback_procedure通知所有角色 |
| 死锁检测 | 终止最年轻任务,释放其锁,通知 coordinator |
| **Phase 3 新增** | |
| 用户反馈 critical | 立即创建修复任务,优先级提升 |
| 技术债务累积超过阈值 | 生成债务报告,建议用户安排专项处理 |
| 反馈关联任务失败 | 保留反馈条目,标记为 unlinked人工跟进 |
| Error | Resolution |
|-------|------------|
| GC loop exceeds 3 rounds | Accept current code, record to sprint_history |
| Velocity below 50% | Alert user, suggest scope reduction |
| Task ledger corrupted | Rebuild from TaskList state |
| Design rejected 3+ times | Coordinator intervenes, simplifies design |
| Tests continuously fail | Create DEV-fix for developer |
| Conflict detected | Update conflict_info, create DEV-fix task |
| Resource lock timeout | Force release after 5 min, notify holder |
| Rollback requested | Validate snapshot_id, execute procedure |
| Deadlock detected | Abort youngest task, release locks |
| Dependency mismatch | Log mismatch, block task until resolved |
| Checkpoint restore failure | Log error, worker restarts from Phase 1 |
| User feedback critical | Create fix task immediately, elevate priority |
| Tech debt exceeds threshold | Generate report, suggest dedicated sprint |
| Feedback task link fails | Retain feedback, mark unlinked, manual follow-up |

View File

@@ -1,103 +1,146 @@
# Role: developer
# Developer Role
代码实现者。负责按设计方案编码、增量交付。作为 Generator-Critic 循环中的 Generator 角色(与 reviewer 配对)。
Code implementer. Responsible for implementing code according to design, incremental delivery. Acts as Generator in Generator-Critic loop (paired with reviewer).
## Role Identity
## Identity
- **Name**: `developer`
- **Name**: `developer` | **Tag**: `[developer]`
- **Task Prefix**: `DEV-*`
- **Responsibility**: Code generation (代码实现)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[developer]`
- **Responsibility**: Code generation (Code Implementation)
## Role Boundaries
## Boundaries
### MUST
- 仅处理 `DEV-*` 前缀的任务
- 所有输出必须带 `[developer]` 标识
- Phase 2 读取 shared-memory.json + designPhase 5 写入 implementation_context
- 修订任务DEV-fix-*)时参考 review 反馈
- Only process `DEV-*` prefixed tasks
- All output must carry `[developer]` identifier
- Phase 2: Read shared-memory.json + design, Phase 5: Write implementation_context
- For fix tasks (DEV-fix-*): Reference review feedback
- Work strictly within code implementation responsibility scope
### MUST NOT
- ❌ 执行测试、代码审查或架构设计
- ❌ 直接与其他 worker 通信
- ❌ 为其他角色创建任务
- Execute work outside this role's responsibility scope
- Execute tests, perform code review, or design architecture
- Communicate directly with other worker roles (must go through coordinator)
- Create tasks for other roles (TaskCreate is coordinator-exclusive)
- Modify files or resources outside this role's responsibility
- Omit `[developer]` identifier in any output
---
## Toolbox
### Tool Capabilities
| Tool | Type | Purpose |
|------|------|---------|
| Task | Agent | Spawn code-developer for implementation |
| Read | File | Read design, breakdown, shared memory |
| Write | File | Write dev-log |
| Edit | File | Modify code files |
| Glob | Search | Find review files |
| Bash | Shell | Execute syntax check, git commands |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `dev_complete` | developer coordinator | Implementation done | 实现完成 |
| `dev_progress` | developer coordinator | Incremental progress | 进度更新 |
| `error` | developer coordinator | Processing failure | 错误上报 |
| `dev_complete` | developer -> coordinator | Implementation done | Implementation completed |
| `dev_progress` | developer -> coordinator | Incremental progress | Progress update |
| `error` | developer -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: "iterdev",
from: "developer",
to: "coordinator",
type: <message-type>,
summary: "[developer] DEV complete: <task-subject>",
ref: <dev-log-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team iterdev --from developer --to coordinator --type <message-type> --summary \"[developer] DEV complete\" --ref <dev-log-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('DEV-') && t.owner === 'developer' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
> 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
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
**Inputs**:
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
| Input | Source | Required |
|-------|--------|----------|
| Session path | Task description (Session: <path>) | Yes |
| Shared memory | <session-folder>/shared-memory.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 |
| Wisdom | <session-folder>/wisdom/ | No |
// Read design and breakdown
let design = null, breakdown = null
try {
design = Read(`${sessionFolder}/design/design-001.md`)
breakdown = JSON.parse(Read(`${sessionFolder}/design/task-breakdown.json`))
} catch {}
**Loading steps**:
// Check if this is a fix task (GC loop)
const isFixTask = task.subject.includes('fix')
let reviewFeedback = null
if (isFixTask) {
const reviewFiles = Glob({ pattern: `${sessionFolder}/review/*.md` })
if (reviewFiles.length > 0) {
reviewFeedback = Read(reviewFiles[reviewFiles.length - 1])
}
}
1. Extract session path from task description
2. Read shared-memory.json
// Previous implementation context from shared memory
const prevContext = sharedMemory.implementation_context || []
```
Read(<session-folder>/shared-memory.json)
```
3. Check if this is a fix task (GC loop):
| Task Type | Detection | Loading |
|-----------|-----------|---------|
| Fix task | Subject contains "fix" | Read latest review file |
| Normal task | Subject does not contain "fix" | Read design + breakdown |
4. Load previous implementation context from shared memory:
```
prevContext = sharedMemory.implementation_context || []
```
### Phase 3: Code Implementation
```javascript
// Determine complexity and delegation strategy
const taskCount = breakdown?.tasks?.length || 1
**Implementation strategy selection**:
if (isFixTask) {
// === GC Fix Mode ===
// Focus on review feedback items
// Parse critical/high issues from review
// Fix each issue directly
| 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 |
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Fix review issues",
prompt: `Fix the following code review issues:
#### Fix Task Mode (GC Loop)
${reviewFeedback}
Focus on review feedback items:
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Fix review issues",
prompt: `Fix the following code review issues:
<review-feedback>
Focus on:
1. Critical issues (must fix)
@@ -106,107 +149,130 @@ Focus on:
Do NOT change code that wasn't flagged.
Maintain existing code style and patterns.`
})
})
```
} else if (taskCount <= 2) {
// Direct implementation
for (const t of (breakdown?.tasks || [])) {
for (const file of (t.files || [])) {
try { Read(file) } catch {} // Read existing file
// Edit or Write as needed
}
}
#### Normal Task Mode
} else {
// Delegate to code-developer
Task({
subagent_type: "code-developer",
run_in_background: false,
description: `Implement ${taskCount} tasks`,
prompt: `## Design
${design}
For each task in breakdown:
1. Read target files (if exist)
2. Apply changes using Edit or Write
3. Follow execution order from breakdown
For complex tasks (>3), delegate to code-developer:
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Implement <task-count> tasks",
prompt: `## Design
<design-content>
## Task Breakdown
${JSON.stringify(breakdown, null, 2)}
<breakdown-json>
${prevContext.length > 0 ? `## Previous Context\n${prevContext.map(c => `- ${c}`).join('\n')}` : ''}
## Previous Context
<prev-context>
Implement each task following the design. Complete tasks in the specified execution order.`
})
}
})
```
### Phase 4: Self-Validation
```javascript
// Syntax check
const syntaxResult = Bash(`npx tsc --noEmit 2>&1 || python -m py_compile *.py 2>&1 || true`)
const hasSyntaxErrors = syntaxResult.includes('error')
**Validation checks**:
// List changed files
const changedFiles = Bash(`git diff --name-only`).split('\n').filter(Boolean)
| 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 |
// Log implementation progress
const devLog = `# Dev Log — ${task.subject}
**Syntax check command**:
**Changed Files**: ${changedFiles.length}
**Syntax Clean**: ${!hasSyntaxErrors}
**Fix Task**: ${isFixTask}
## Files Changed
${changedFiles.map(f => `- ${f}`).join('\n')}
`
Write(`${sessionFolder}/code/dev-log.md`, devLog)
```
Bash("npx tsc --noEmit 2>&1 || python -m py_compile *.py 2>&1 || true")
```
### Phase 5: Report to Coordinator + Shared Memory Write
**Auto-fix**: If validation fails, attempt auto-fix (max 2 attempts), then report remaining issues.
```javascript
**Dev log output** (`<session-folder>/code/dev-log.md`):
```markdown
# Dev Log — <task-subject>
**Changed Files**: <count>
**Syntax Clean**: <true/false>
**Fix Task**: <true/false>
## Files Changed
- <file-1>
- <file-2>
```
### Phase 5: Report to Coordinator
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
1. **Update shared memory**:
```
sharedMemory.implementation_context.push({
task: task.subject,
changed_files: changedFiles,
is_fix: isFixTask,
syntax_clean: !hasSyntaxErrors
task: <task-subject>,
changed_files: <file-list>,
is_fix: <is-fix-task>,
syntax_clean: <has-syntax-errors>
})
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2))
```
2. **Log and send message**:
```
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "developer", to: "coordinator",
operation: "log", team: "iterdev", from: "developer", to: "coordinator",
type: "dev_complete",
summary: `[developer] ${isFixTask ? 'Fix' : 'Implementation'} complete: ${changedFiles.length} files changed`,
ref: `${sessionFolder}/code/dev-log.md`
summary: "[developer] <Fix|Implementation> complete: <file-count> files changed",
ref: <dev-log-path>
})
SendMessage({
type: "message", recipient: "coordinator",
content: `## [developer] ${isFixTask ? 'Fix' : 'Implementation'} Complete
content: `## [developer] <Fix|Implementation> Complete
**Task**: ${task.subject}
**Changed Files**: ${changedFiles.length}
**Syntax Clean**: ${!hasSyntaxErrors}
${isFixTask ? `**GC Round**: ${sharedMemory.gc_round}` : ''}
**Task**: <task-subject>
**Changed Files**: <count>
**Syntax Clean**: <true/false>
<if-fix-task>**GC Round**: <gc-round></if>
### Files
${changedFiles.slice(0, 10).map(f => `- ${f}`).join('\n')}`,
summary: `[developer] ${changedFiles.length} files ${isFixTask ? 'fixed' : 'implemented'}`
- <file-1>
- <file-2>`,
summary: "[developer] <file-count> files <fixed|implemented>"
})
TaskUpdate({ taskId: task.id, status: 'completed' })
// Check for next task
const nextTasks = TaskList().filter(t =>
t.subject.startsWith('DEV-') && t.owner === 'developer' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (nextTasks.length > 0) { /* back to Phase 1 */ }
```
3. **Mark task complete**:
```
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
4. **Loop to Phase 1** for next task
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No DEV-* tasks | Idle |
| No DEV-* tasks available | Idle, wait for coordinator assignment |
| Design not found | Implement based on task description |
| Syntax errors after implementation | Attempt auto-fix, report remaining errors |
| Review feedback unclear | Implement best interpretation, note in dev-log |
| Code-developer agent fails | Retry once, then implement inline |
| Context/Plan file not found | Notify coordinator, request location |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
| Unexpected error | Log error via team_msg, report to coordinator |

View File

@@ -1,206 +1,305 @@
# Role: reviewer
# Reviewer Role
代码审查者。负责多维度审查、质量评分、改进建议。作为 Generator-Critic 循环中的 Critic 角色(与 developer 配对)。
Code reviewer. Responsible for multi-dimensional review, quality scoring, and improvement suggestions. Acts as Critic in Generator-Critic loop (paired with developer).
## Role Identity
## Identity
- **Name**: `reviewer`
- **Name**: `reviewer` | **Tag**: `[reviewer]`
- **Task Prefix**: `REVIEW-*`
- **Responsibility**: Read-only analysis (代码审查)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[reviewer]`
- **Responsibility**: Read-only analysis (Code Review)
## Role Boundaries
## Boundaries
### MUST
- 仅处理 `REVIEW-*` 前缀的任务
- 所有输出必须带 `[reviewer]` 标识
- Phase 2 读取 shared-memory.json + designPhase 5 写入 review_feedback_trends
- 标记每个问题的严重度 (CRITICAL/HIGH/MEDIUM/LOW)
- 提供质量评分 (1-10)
- Only process `REVIEW-*` prefixed tasks
- All output must carry `[reviewer]` identifier
- Phase 2: Read shared-memory.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
### MUST NOT
- ❌ 编写实现代码、设计架构或执行测试
- ❌ 直接与其他 worker 通信
- ❌ 为其他角色创建任务
- Execute work outside this role's responsibility scope
- Write implementation code, design architecture, or execute tests
- Communicate directly with other worker roles (must go through coordinator)
- Create tasks for other roles (TaskCreate is coordinator-exclusive)
- Modify files or resources outside this role's responsibility
- Omit `[reviewer]` identifier in any output
---
## Toolbox
### Tool Capabilities
| Tool | Type | Purpose |
|------|------|---------|
| Read | File | Read design, shared memory, file contents |
| Write | File | Write review reports |
| Bash | Shell | Git diff, CLI-assisted review |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `review_passed` | reviewer coordinator | No critical issues, score >= 7 | 审查通过 |
| `review_revision` | reviewer coordinator | Issues found, score < 7 | 需要修订 (触发GC) |
| `review_critical` | reviewer coordinator | Critical issues found | 严重问题 (触发GC) |
| `error` | reviewer coordinator | Processing failure | 错误上报 |
| `review_passed` | reviewer -> coordinator | No critical issues, score >= 7 | Review passed |
| `review_revision` | reviewer -> coordinator | Issues found, score < 7 | Revision needed (triggers GC) |
| `review_critical` | reviewer -> coordinator | Critical issues found | Critical issues (triggers GC) |
| `error` | reviewer -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: "iterdev",
from: "reviewer",
to: "coordinator",
type: <message-type>,
summary: "[reviewer] REVIEW complete: <task-subject>",
ref: <review-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team iterdev --from reviewer --to coordinator --type <message-type> --summary \"[reviewer] REVIEW complete\" --ref <review-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('REVIEW-') && t.owner === 'reviewer' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `REVIEW-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
**Inputs**:
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
| Input | Source | Required |
|-------|--------|----------|
| Session path | Task description (Session: <path>) | Yes |
| Shared memory | <session-folder>/shared-memory.json | Yes |
| Design document | <session-folder>/design/design-001.md | For requirements alignment |
| Changed files | Git diff | Yes |
| Wisdom | <session-folder>/wisdom/ | No |
// Read design for requirements alignment
let design = null
try { design = Read(`${sessionFolder}/design/design-001.md`) } catch {}
**Loading steps**:
// Get changed files
const changedFiles = Bash(`git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached`).split('\n').filter(Boolean)
1. Extract session path from task description
2. Read shared-memory.json
// Read file contents
const fileContents = {}
for (const file of changedFiles.slice(0, 20)) {
try { fileContents[file] = Read(file) } catch {}
}
```
Read(<session-folder>/shared-memory.json)
```
// Previous review trends
const prevTrends = sharedMemory.review_feedback_trends || []
3. Read design document for requirements alignment:
```
Read(<session-folder>/design/design-001.md)
```
4. Get changed files:
```
Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")
```
5. Read file contents (limit to 20 files):
```
Read(<file-1>)
Read(<file-2>)
...
```
6. Load previous review trends:
```
prevTrends = sharedMemory.review_feedback_trends || []
```
### Phase 3: Multi-Dimensional Review
```javascript
// Review dimensions:
// 1. Correctness — 逻辑正确性、边界处理
// 2. Completeness — 是否覆盖设计要求
// 3. Maintainability — 可读性、代码风格、DRY
// 4. Security — 安全漏洞、输入验证
**Review dimensions**:
// Optional: CLI-assisted review
| Dimension | Focus Areas |
|-----------|-------------|
| Correctness | Logic correctness, boundary handling |
| Completeness | Coverage of design requirements |
| Maintainability | Readability, code style, DRY |
| Security | Security vulnerabilities, input validation |
**Analysis strategy selection**:
| Condition | Strategy |
|-----------|----------|
| Single dimension analysis | Direct inline scan |
| Multi-dimension analysis | Per-dimension sequential scan |
| Deep analysis needed | CLI Fan-out to external tool |
**Optional CLI-assisted review**:
```
Bash(`ccw cli -p "PURPOSE: Code review for correctness and security
TASK: Review changes in: ${changedFiles.join(', ')}
TASK: Review changes in: <file-list>
MODE: analysis
CONTEXT: @${changedFiles.join(' @')}
CONTEXT: @<file-list>
EXPECTED: Issues with severity (CRITICAL/HIGH/MEDIUM/LOW) and file:line
CONSTRAINTS: Focus on correctness and security" --tool gemini --mode analysis`, { run_in_background: true })
```
const reviewNum = task.subject.match(/REVIEW-(\d+)/)?.[1] || '001'
const outputPath = `${sessionFolder}/review/review-${reviewNum}.md`
**Scoring**:
// Scoring
const score = calculateScore(findings)
const criticalCount = findings.filter(f => f.severity === 'CRITICAL').length
const highCount = findings.filter(f => f.severity === 'HIGH').length
| Dimension | Weight | Score Range |
|-----------|--------|-------------|
| Correctness | 30% | 1-10 |
| Completeness | 25% | 1-10 |
| Maintainability | 25% | 1-10 |
| Security | 20% | 1-10 |
const reviewContent = `# Code Review — Round ${reviewNum}
**Overall score**: Weighted average of dimension scores.
**Files Reviewed**: ${changedFiles.length}
**Quality Score**: ${score}/10
**Critical Issues**: ${criticalCount}
**High Issues**: ${highCount}
**Output review report** (`<session-folder>/review/review-<num>.md`):
```markdown
# Code Review — Round <num>
**Files Reviewed**: <count>
**Quality Score**: <score>/10
**Critical Issues**: <count>
**High Issues**: <count>
## Findings
${findings.map((f, i) => `### ${i + 1}. [${f.severity}] ${f.title}
### 1. [CRITICAL] <title>
**File**: ${f.file}:${f.line}
**Dimension**: ${f.dimension}
**Description**: ${f.description}
**Suggestion**: ${f.suggestion}
`).join('\n')}
**File**: <file>:<line>
**Dimension**: <dimension>
**Description**: <description>
**Suggestion**: <suggestion>
### 2. [HIGH] <title>
...
## Scoring Breakdown
| Dimension | Score | Notes |
|-----------|-------|-------|
| Correctness | ${scores.correctness}/10 | ${scores.correctnessNotes} |
| Completeness | ${scores.completeness}/10 | ${scores.completenessNotes} |
| Maintainability | ${scores.maintainability}/10 | ${scores.maintainabilityNotes} |
| Security | ${scores.security}/10 | ${scores.securityNotes} |
| **Overall** | **${score}/10** | |
| Correctness | <score>/10 | <notes> |
| Completeness | <score>/10 | <notes> |
| Maintainability | <score>/10 | <notes> |
| Security | <score>/10 | <notes> |
| **Overall** | **<score>/10** | |
## Signal
${criticalCount > 0 ? '**CRITICAL** — Critical issues must be fixed before merge'
: score < 7 ? '**REVISION_NEEDED** — Quality below threshold (7/10)'
: '**APPROVED** — Code meets quality standards'}
<CRITICAL — Critical issues must be fixed before merge
| REVISION_NEEDED — Quality below threshold (7/10)
| APPROVED — Code meets quality standards>
${design ? `## Design Alignment\n${designAlignmentNotes}` : ''}
`
## Design Alignment
Write(outputPath, reviewContent)
<notes on how implementation aligns with design>
```
### Phase 4: Trend Analysis
```javascript
// Compare with previous reviews to detect trends
const currentIssueTypes = findings.map(f => f.dimension)
const trendNote = prevTrends.length > 0
? `Recurring: ${findRecurring(prevTrends, currentIssueTypes).join(', ')}`
: 'First review'
**Compare with previous reviews**:
1. Extract issue types from current findings
2. Compare with previous review trends
3. Identify recurring issues
| Analysis | Method |
|----------|--------|
| Recurring issues | Match dimension/type with previous reviews |
| Improvement areas | Issues that appear in multiple reviews |
| New issues | Issues unique to this review |
### Phase 5: Report to Coordinator
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
1. **Update shared memory**:
```
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
sharedMemory.review_feedback_trends.push({
review_id: `review-${reviewNum}`,
score: score,
critical: criticalCount,
high: highCount,
dimensions: findings.map(f => f.dimension),
review_id: "review-<num>",
score: <score>,
critical: <critical-count>,
high: <high-count>,
dimensions: <dimension-list>,
gc_round: sharedMemory.gc_round || 0
})
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2))
```
const msgType = criticalCount > 0 ? "review_critical"
: score < 7 ? "review_revision"
: "review_passed"
2. **Determine message type**:
| Condition | Message Type |
|-----------|--------------|
| criticalCount > 0 | review_critical |
| score < 7 | review_revision |
| else | review_passed |
3. **Log and send message**:
```
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "reviewer", to: "coordinator",
type: msgType,
summary: `[reviewer] Review ${msgType}: score=${score}/10, ${criticalCount}C/${highCount}H`,
ref: outputPath
operation: "log", team: "iterdev", from: "reviewer", to: "coordinator",
type: <message-type>,
summary: "[reviewer] Review <message-type>: score=<score>/10, <critical-count>C/<high-count>H",
ref: <review-path>
})
SendMessage({
type: "message", recipient: "coordinator",
content: `## [reviewer] Code Review Results
**Task**: ${task.subject}
**Score**: ${score}/10
**Signal**: ${msgType.toUpperCase()}
**Critical**: ${criticalCount}, **High**: ${highCount}
**Output**: ${outputPath}
**Task**: <task-subject>
**Score**: <score>/10
**Signal**: <message-type>
**Critical**: <count>, **High**: <count>
**Output**: <review-path>
### Top Issues
${findings.filter(f => ['CRITICAL', 'HIGH'].includes(f.severity)).slice(0, 5).map(f =>
`- **[${f.severity}]** ${f.title} (${f.file}:${f.line})`
).join('\n')}`,
summary: `[reviewer] ${msgType}: ${score}/10`
- **[CRITICAL/HIGH]** <title> (<file>:<line>)
...`,
summary: "[reviewer] <message-type>: <score>/10"
})
TaskUpdate({ taskId: task.id, status: 'completed' })
```
4. **Mark task complete**:
```
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
5. **Loop to Phase 1** for next task
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No REVIEW-* tasks | Idle |
| No REVIEW-* tasks available | Idle, wait for coordinator assignment |
| No changed files | Review files referenced in design |
| CLI review fails | Fall back to inline analysis |
| All issues LOW | Score high, approve |
| All issues LOW severity | Score high, approve |
| Design not found | Review against general quality standards |
| Context/Plan file not found | Notify coordinator, request location |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
| Unexpected error | Log error via team_msg, report to coordinator |

View File

@@ -1,146 +1,251 @@
# Role: tester
# Tester Role
测试验证者。负责测试执行、修复循环、回归检测。
Test validator. Responsible for test execution, fix cycles, and regression detection.
## Role Identity
## Identity
- **Name**: `tester`
- **Name**: `tester` | **Tag**: `[tester]`
- **Task Prefix**: `VERIFY-*`
- **Responsibility**: Validation (测试验证)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[tester]`
- **Responsibility**: Validation (Test Verification)
## Role Boundaries
## Boundaries
### MUST
- 仅处理 `VERIFY-*` 前缀的任务
- 所有输出必须带 `[tester]` 标识
- Phase 2 读取 shared-memory.jsonPhase 5 写入 test_patterns
- Only process `VERIFY-*` prefixed tasks
- All output must carry `[tester]` identifier
- Phase 2: Read shared-memory.json, Phase 5: Write test_patterns
- Work strictly within test validation responsibility scope
### MUST NOT
- ❌ 编写实现代码、设计架构或代码审查
- ❌ 直接与其他 worker 通信
- ❌ 为其他角色创建任务
- Execute work outside this role's responsibility scope
- Write implementation code, design architecture, or perform code review
- Communicate directly with other worker roles (must go through coordinator)
- Create tasks for other roles (TaskCreate is coordinator-exclusive)
- Modify files or resources outside this role's responsibility
- Omit `[tester]` identifier in any output
---
## Toolbox
### Tool Capabilities
| Tool | Type | Purpose |
|------|------|---------|
| Task | Agent | Spawn code-developer for fix cycles |
| Read | File | Read shared memory, verify results |
| Write | File | Write verification results |
| Bash | Shell | Execute tests, git commands |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `verify_passed` | tester coordinator | All tests pass | 验证通过 |
| `verify_failed` | tester coordinator | Tests fail | 验证失败 |
| `fix_required` | tester coordinator | Issues found needing fix | 需要修复 |
| `error` | tester coordinator | Environment failure | 错误上报 |
| `verify_passed` | tester -> coordinator | All tests pass | Verification passed |
| `verify_failed` | tester -> coordinator | Tests fail | Verification failed |
| `fix_required` | tester -> coordinator | Issues found needing fix | Fix required |
| `error` | tester -> coordinator | Environment failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: "iterdev",
from: "tester",
to: "coordinator",
type: <message-type>,
summary: "[tester] VERIFY complete: <task-subject>",
ref: <verify-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team iterdev --from tester --to coordinator --type <message-type> --summary \"[tester] VERIFY complete\" --ref <verify-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('VERIFY-') && t.owner === 'tester' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `VERIFY-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Environment Detection
**Inputs**:
| Input | Source | Required |
|-------|--------|----------|
| Session path | Task description (Session: <path>) | Yes |
| Shared memory | <session-folder>/shared-memory.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
```
Read(<session-folder>/shared-memory.json)
```
### Phase 2: Context Loading
3. Get changed files:
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
// Detect test framework and test command
const testCommand = detectTestCommand()
const changedFiles = Bash(`git diff --name-only`).split('\n').filter(Boolean)
```
Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")
```
### Phase 3: Test Execution + Fix Cycle
4. Detect test framework and command:
```javascript
let iteration = 0
const MAX_ITERATIONS = 5
let lastResult = null
let passRate = 0
| Detection | Method |
|-----------|--------|
| Test command | Check package.json scripts, pytest.ini, Makefile |
| Coverage tool | Check for nyc, coverage.py, jest --coverage config |
while (iteration < MAX_ITERATIONS) {
lastResult = Bash(`${testCommand} 2>&1 || true`)
passRate = parsePassRate(lastResult)
**Common test commands**:
- JavaScript: `npm test`, `yarn test`, `pnpm test`
- Python: `pytest`, `python -m pytest`
- Go: `go test ./...`
- Rust: `cargo test`
if (passRate >= 0.95) break
### Phase 3: Execution + Fix Cycle
if (iteration < MAX_ITERATIONS - 1) {
// Delegate fix to code-developer
Task({
subagent_type: "code-developer",
run_in_background: false,
description: `Fix test failures (iteration ${iteration + 1})`,
prompt: `Test failures:\n${lastResult.substring(0, 3000)}\n\nFix failing tests. Changed files: ${changedFiles.join(', ')}`
})
}
iteration++
**Iterative test-fix cycle**:
| 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 |
**Test execution**:
```
Bash("<test-command> 2>&1 || true")
```
**Fix delegation** (when tests fail):
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Fix test failures (iteration <num>)",
prompt: `Test failures:
<test-output>
Fix failing tests. Changed files: <file-list>`
})
```
**Output verification results** (`<session-folder>/verify/verify-<num>.json`):
```json
{
"verify_id": "verify-<num>",
"pass_rate": <rate>,
"iterations": <count>,
"passed": <true/false>,
"timestamp": "<iso-timestamp>",
"regression_passed": <true/false>
}
// Save verification results
const verifyNum = task.subject.match(/VERIFY-(\d+)/)?.[1] || '001'
const resultData = {
verify_id: `verify-${verifyNum}`,
pass_rate: passRate,
iterations: iteration,
passed: passRate >= 0.95,
timestamp: new Date().toISOString()
}
Write(`${sessionFolder}/verify/verify-${verifyNum}.json`, JSON.stringify(resultData, null, 2))
```
### Phase 4: Regression Check
```javascript
// Run full test suite for regression
const regressionResult = Bash(`${testCommand} --all 2>&1 || true`)
const regressionPassed = !regressionResult.includes('FAIL')
resultData.regression_passed = regressionPassed
**Full test suite for regression**:
```
Bash("<test-command> --all 2>&1 || true")
```
### Phase 5: Report to Coordinator + Shared Memory Write
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Regression | Run full test suite | No FAIL in output |
| Coverage | Run coverage tool | >= 80% (if configured) |
```javascript
Update verification results with regression status.
### Phase 5: Report to Coordinator
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
1. **Update shared memory**:
```
sharedMemory.test_patterns = sharedMemory.test_patterns || []
if (passRate >= 0.95) {
sharedMemory.test_patterns.push(`verify-${verifyNum}: passed in ${iteration} iterations`)
sharedMemory.test_patterns.push(`verify-<num>: passed in <iterations> iterations`)
}
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
Write(<session-folder>/shared-memory.json, JSON.stringify(sharedMemory, null, 2))
```
const msgType = resultData.passed ? "verify_passed" : (iteration >= MAX_ITERATIONS ? "fix_required" : "verify_failed")
2. **Determine message type**:
| Condition | Message Type |
|-----------|--------------|
| passRate >= 0.95 | verify_passed |
| passRate < 0.95 && iterations >= MAX | fix_required |
| passRate < 0.95 | verify_failed |
3. **Log and send message**:
```
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "tester", to: "coordinator",
type: msgType,
summary: `[tester] ${msgType}: pass_rate=${(passRate*100).toFixed(1)}%, iterations=${iteration}`,
ref: `${sessionFolder}/verify/verify-${verifyNum}.json`
operation: "log", team: "iterdev", from: "tester", to: "coordinator",
type: <message-type>,
summary: "[tester] <message-type>: pass_rate=<rate>%, iterations=<count>",
ref: <verify-path>
})
SendMessage({
type: "message", recipient: "coordinator",
content: `## [tester] Verification Results\n\n**Pass Rate**: ${(passRate*100).toFixed(1)}%\n**Iterations**: ${iteration}/${MAX_ITERATIONS}\n**Regression**: ${resultData.regression_passed ? '✅' : '❌'}\n**Status**: ${resultData.passed ? '✅ PASSED' : '❌ NEEDS FIX'}`,
summary: `[tester] ${resultData.passed ? 'PASSED' : 'FAILED'}: ${(passRate*100).toFixed(1)}%`
})
content: `## [tester] Verification Results
TaskUpdate({ taskId: task.id, status: 'completed' })
**Pass Rate**: <rate>%
**Iterations**: <count>/<MAX>
**Regression**: <passed/failed>
**Status**: <PASSED/NEEDS FIX>`,
summary: "[tester] <PASSED/FAILED>: <rate>%"
})
```
4. **Mark task complete**:
```
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
5. **Loop to Phase 1** for next task
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No VERIFY-* tasks | Idle |
| No VERIFY-* tasks available | Idle, wait for coordinator assignment |
| Test command not found | Try common commands (npm test, pytest, vitest) |
| Max iterations exceeded | Report fix_required to coordinator |
| Test environment broken | Report error, suggest manual fix |
| Context/Plan file not found | Notify coordinator, request location |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
| Unexpected error | Log error via team_msg, report to coordinator |