mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-03-11 17:21:03 +08:00
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:
@@ -0,0 +1,71 @@
|
||||
# Analyze Task
|
||||
|
||||
Parse user task -> detect review capabilities -> build dependency graph -> design pipeline.
|
||||
|
||||
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
|
||||
|
||||
## Signal Detection
|
||||
|
||||
| Keywords | Capability | Prefix |
|
||||
|----------|------------|--------|
|
||||
| scan, lint, static analysis, toolchain | scanner | SCAN |
|
||||
| review, analyze, audit, findings | reviewer | REV |
|
||||
| fix, repair, remediate, patch | fixer | FIX |
|
||||
|
||||
## Pipeline Mode Detection
|
||||
|
||||
| Condition | Mode |
|
||||
|-----------|------|
|
||||
| Flag `--fix` | fix-only |
|
||||
| Flag `--full` | full |
|
||||
| Flag `-q` or `--quick` | quick |
|
||||
| (none) | default |
|
||||
|
||||
## Dependency Graph
|
||||
|
||||
Natural ordering for review pipeline:
|
||||
- Tier 0: scanner (toolchain + semantic scan, no upstream dependency)
|
||||
- Tier 1: reviewer (deep analysis, requires scan findings)
|
||||
- Tier 2: fixer (apply fixes, requires reviewed findings + user confirm)
|
||||
|
||||
## Pipeline Definitions
|
||||
|
||||
```
|
||||
quick: SCAN(quick=true)
|
||||
default: SCAN -> REV
|
||||
full: SCAN -> REV -> [user confirm] -> FIX
|
||||
fix-only: FIX
|
||||
```
|
||||
|
||||
## Complexity Scoring
|
||||
|
||||
| Factor | Points |
|
||||
|--------|--------|
|
||||
| Per capability | +1 |
|
||||
| Large target scope (>20 files) | +2 |
|
||||
| Multiple dimensions | +1 |
|
||||
| Fix phase included | +1 |
|
||||
|
||||
Results: 1-2 Low, 3-4 Medium, 5+ High
|
||||
|
||||
## Role Minimization
|
||||
|
||||
- Cap at 4 roles (coordinator + 3 workers)
|
||||
- Sequential pipeline: scanner -> reviewer -> fixer
|
||||
|
||||
## Output
|
||||
|
||||
Write <session>/task-analysis.json:
|
||||
```json
|
||||
{
|
||||
"task_description": "<original>",
|
||||
"pipeline_mode": "<quick|default|full|fix-only>",
|
||||
"target": "<path>",
|
||||
"dimensions": ["sec", "cor", "prf", "mnt"],
|
||||
"auto_confirm": false,
|
||||
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>" }],
|
||||
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."] } },
|
||||
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
|
||||
"complexity": { "score": 0, "level": "Low|Medium|High" }
|
||||
}
|
||||
```
|
||||
@@ -1,143 +1,91 @@
|
||||
# Command: dispatch
|
||||
# Dispatch Tasks
|
||||
|
||||
> Task chain creation based on pipeline mode. Creates SCAN/REV/FIX tasks with dependencies.
|
||||
Create task chains from pipeline mode with proper blockedBy relationships.
|
||||
|
||||
## When to Use
|
||||
## Workflow
|
||||
|
||||
- Phase 3 of Coordinator
|
||||
- Pipeline mode detected, need to create task chain
|
||||
- Session initialized
|
||||
1. Read task-analysis.json -> extract pipeline_mode and parameters
|
||||
2. Read specs/pipelines.md -> get task registry for selected pipeline
|
||||
3. Topological sort tasks (respect blockedBy)
|
||||
4. Validate all owners exist in role registry (SKILL.md)
|
||||
5. For each task (in order):
|
||||
- TaskCreate with structured description (see template below)
|
||||
- TaskUpdate with blockedBy + owner assignment
|
||||
6. Update session meta.json with pipeline.tasks_total
|
||||
7. Validate chain (no orphans, no cycles, all refs valid)
|
||||
|
||||
**Trigger conditions**:
|
||||
- Coordinator Phase 2 complete
|
||||
- Mode switch requires chain rebuild
|
||||
## Task Description Template
|
||||
|
||||
## Strategy
|
||||
|
||||
### Delegation Mode
|
||||
|
||||
**Mode**: Direct (coordinator operates TaskCreate/TaskUpdate directly)
|
||||
|
||||
### Decision Logic
|
||||
|
||||
```javascript
|
||||
// Build pipeline based on mode
|
||||
function buildPipeline(pipelineMode) {
|
||||
const pipelines = {
|
||||
'default': [
|
||||
{ prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Multi-dimension code scan', blockedBy: [], meta: {} },
|
||||
{ prefix: 'REV', suffix: '001', owner: 'reviewer', desc: 'Deep finding analysis and review', blockedBy: ['SCAN-001'], meta: {} }
|
||||
],
|
||||
'full': [
|
||||
{ prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Multi-dimension code scan', blockedBy: [], meta: {} },
|
||||
{ prefix: 'REV', suffix: '001', owner: 'reviewer', desc: 'Deep finding analysis and review', blockedBy: ['SCAN-001'], meta: {} },
|
||||
{ prefix: 'FIX', suffix: '001', owner: 'fixer', desc: 'Plan and execute fixes', blockedBy: ['REV-001'], meta: {} }
|
||||
],
|
||||
'fix-only': [
|
||||
{ prefix: 'FIX', suffix: '001', owner: 'fixer', desc: 'Execute fixes from manifest', blockedBy: [], meta: {} }
|
||||
],
|
||||
'quick': [
|
||||
{ prefix: 'SCAN', suffix: '001', owner: 'scanner', desc: 'Quick scan (fast mode)', blockedBy: [], meta: { quick: true } }
|
||||
]
|
||||
}
|
||||
return pipelines[pipelineMode] || pipelines['default']
|
||||
}
|
||||
```
|
||||
PURPOSE: <goal> | Success: <criteria>
|
||||
TASK:
|
||||
- <step 1>
|
||||
- <step 2>
|
||||
CONTEXT:
|
||||
- Session: <session-folder>
|
||||
- Target: <target>
|
||||
- Dimensions: <dimensions>
|
||||
- Upstream artifacts: <list>
|
||||
EXPECTED: <artifact path> + <quality criteria>
|
||||
CONSTRAINTS: <scope limits>
|
||||
---
|
||||
InnerLoop: <true|false>
|
||||
RoleSpec: .claude/skills/team-review/roles/<role>/role.md
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
## Pipeline Task Registry
|
||||
|
||||
### Step 1: Session Initialization
|
||||
|
||||
```javascript
|
||||
// Session directory already created in Phase 2
|
||||
// Write pipeline config to shared memory
|
||||
const sharedMemory = JSON.parse(Read(`${sessionFolder}/.msg/meta.json`))
|
||||
sharedMemory.pipeline_mode = pipelineMode
|
||||
sharedMemory.pipeline_stages = buildPipeline(pipelineMode).map(s => `${s.prefix}-${s.suffix}`)
|
||||
Write(`${sessionFolder}/.msg/meta.json`, JSON.stringify(sharedMemory, null, 2))
|
||||
### default Mode
|
||||
```
|
||||
SCAN-001 (scanner): Multi-dimension code scan
|
||||
blockedBy: [], meta: target=<target>, dimensions=<dims>
|
||||
REV-001 (reviewer): Deep finding analysis and review
|
||||
blockedBy: [SCAN-001]
|
||||
```
|
||||
|
||||
### Step 2: Create Task Chain
|
||||
|
||||
```javascript
|
||||
const pipeline = buildPipeline(pipelineMode)
|
||||
const taskIds = {}
|
||||
|
||||
for (const stage of pipeline) {
|
||||
const taskSubject = `${stage.prefix}-${stage.suffix}: ${stage.desc}`
|
||||
|
||||
// Build task description with session context
|
||||
const fullDesc = [
|
||||
stage.desc,
|
||||
`\nsession: ${sessionFolder}`,
|
||||
`\ntarget: ${target}`,
|
||||
`\ndimensions: ${dimensions.join(',')}`,
|
||||
stage.meta?.quick ? `\nquick: true` : '',
|
||||
`\n\nGoal: ${taskDescription || target}`
|
||||
].join('')
|
||||
|
||||
// Create task
|
||||
TaskCreate({
|
||||
subject: taskSubject,
|
||||
description: fullDesc,
|
||||
activeForm: `${stage.desc} in progress`
|
||||
})
|
||||
|
||||
// Record task ID
|
||||
const allTasks = TaskList()
|
||||
const newTask = allTasks.find(t => t.subject.startsWith(`${stage.prefix}-${stage.suffix}`))
|
||||
taskIds[`${stage.prefix}-${stage.suffix}`] = newTask.id
|
||||
|
||||
// Set owner and dependencies
|
||||
const blockedByIds = stage.blockedBy
|
||||
.map(dep => taskIds[dep])
|
||||
.filter(Boolean)
|
||||
|
||||
TaskUpdate({
|
||||
taskId: newTask.id,
|
||||
owner: stage.owner,
|
||||
addBlockedBy: blockedByIds
|
||||
})
|
||||
}
|
||||
### full Mode
|
||||
```
|
||||
SCAN-001 (scanner): Multi-dimension code scan
|
||||
blockedBy: [], meta: target=<target>, dimensions=<dims>
|
||||
REV-001 (reviewer): Deep finding analysis and review
|
||||
blockedBy: [SCAN-001]
|
||||
FIX-001 (fixer): Plan and execute fixes
|
||||
blockedBy: [REV-001]
|
||||
```
|
||||
|
||||
### Step 3: Verify Chain
|
||||
### fix-only Mode
|
||||
```
|
||||
FIX-001 (fixer): Execute fixes from manifest
|
||||
blockedBy: [], meta: input=<fix-manifest>
|
||||
```
|
||||
|
||||
```javascript
|
||||
const allTasks = TaskList()
|
||||
const chainTasks = pipeline.map(s => taskIds[`${s.prefix}-${s.suffix}`]).filter(Boolean)
|
||||
const chainValid = chainTasks.length === pipeline.length
|
||||
### quick Mode
|
||||
```
|
||||
SCAN-001 (scanner): Quick scan (fast mode)
|
||||
blockedBy: [], meta: target=<target>, quick=true
|
||||
```
|
||||
|
||||
if (!chainValid) {
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log", session_id: sessionId, from: "coordinator",
|
||||
type: "error",
|
||||
})
|
||||
}
|
||||
## InnerLoop Flag Rules
|
||||
|
||||
- true: fixer role (iterative fix cycles)
|
||||
- false: scanner, reviewer roles
|
||||
|
||||
## Dependency Validation
|
||||
|
||||
- No orphan tasks (all tasks have valid owner)
|
||||
- No circular dependencies
|
||||
- All blockedBy references exist
|
||||
- Session reference in every task description
|
||||
- RoleSpec reference in every task description
|
||||
|
||||
## Log After Creation
|
||||
|
||||
```
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log", session_id: sessionId, from: "coordinator",
|
||||
to: "all", type: "dispatch_ready",
|
||||
operation: "log",
|
||||
session_id: <session-id>,
|
||||
from: "coordinator",
|
||||
type: "dispatch_ready",
|
||||
data: { pipeline: "<mode>", task_count: <N>, target: "<target>" }
|
||||
})
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
## Task Chain Created
|
||||
|
||||
### Mode: [default|full|fix-only|quick]
|
||||
### Pipeline Stages: [count]
|
||||
- [prefix]-[suffix]: [description] (owner: [role], blocked by: [deps])
|
||||
|
||||
### Verification: PASS/FAIL
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Task creation fails | Retry once, then report to user |
|
||||
| Dependency cycle | Flatten dependencies, warn coordinator |
|
||||
| Invalid pipelineMode | Default to 'default' mode |
|
||||
| Missing session folder | Re-create, log warning |
|
||||
|
||||
@@ -1,276 +1,184 @@
|
||||
# Command: Monitor
|
||||
# Monitor Pipeline
|
||||
|
||||
Handle all coordinator monitoring events for the review pipeline using the async Spawn-and-Stop pattern. One operation per invocation, then STOP and wait for the next callback.
|
||||
Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP.
|
||||
|
||||
## Constants
|
||||
|
||||
| Key | Value | Description |
|
||||
|-----|-------|-------------|
|
||||
| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` |
|
||||
| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS |
|
||||
| WORKER_AGENT | team-worker | All workers spawned as team-worker agents |
|
||||
- SPAWN_MODE: background
|
||||
- ONE_STEP_PER_INVOCATION: true
|
||||
- FAST_ADVANCE_AWARE: true
|
||||
- WORKER_AGENT: team-worker
|
||||
|
||||
### Role-Worker Map
|
||||
## Handler Router
|
||||
|
||||
| Source | Handler |
|
||||
|--------|---------|
|
||||
| Message contains [scanner], [reviewer], [fixer] | handleCallback |
|
||||
| "capability_gap" | handleAdapt |
|
||||
| "check" or "status" | handleCheck |
|
||||
| "resume" or "continue" | handleResume |
|
||||
| All tasks completed | handleComplete |
|
||||
| Default | handleSpawnNext |
|
||||
|
||||
## Role-Worker Map
|
||||
|
||||
| Prefix | Role | Role Spec | inner_loop |
|
||||
|--------|------|-----------|------------|
|
||||
| SCAN | scanner | `.claude/skills/team-review/role-specs/scanner.md` | false |
|
||||
| REV | reviewer | `.claude/skills/team-review/role-specs/reviewer.md` | false |
|
||||
| FIX | fixer | `.claude/skills/team-review/role-specs/fixer.md` | false |
|
||||
| SCAN-* | scanner | `.claude/skills/team-review/roles/scanner/role.md` | false |
|
||||
| REV-* | reviewer | `.claude/skills/team-review/roles/reviewer/role.md` | false |
|
||||
| FIX-* | fixer | `.claude/skills/team-review/roles/fixer/role.md` | true |
|
||||
|
||||
### Pipeline Modes
|
||||
## handleCallback
|
||||
|
||||
| Mode | Stages |
|
||||
|------|--------|
|
||||
| scan-only | SCAN-001 |
|
||||
| default | SCAN-001 -> REV-001 |
|
||||
| full | SCAN-001 -> REV-001 -> FIX-001 |
|
||||
| fix-only | FIX-001 |
|
||||
Worker completed. Verify completion, check pipeline conditions, advance.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
1. Parse message to identify role and task ID:
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Session file | `<session-folder>/.msg/meta.json` | Yes |
|
||||
| Task list | `TaskList()` | Yes |
|
||||
| Active workers | session.active_workers[] | Yes |
|
||||
| Pipeline mode | session.pipeline_mode | Yes |
|
||||
| Message Pattern | Role Detection |
|
||||
|----------------|---------------|
|
||||
| `[scanner]` or task ID `SCAN-*` | scanner |
|
||||
| `[reviewer]` or task ID `REV-*` | reviewer |
|
||||
| `[fixer]` or task ID `FIX-*` | fixer |
|
||||
|
||||
```
|
||||
Load session state:
|
||||
1. Read <session-folder>/.msg/meta.json -> session
|
||||
2. TaskList() -> allTasks
|
||||
3. Extract pipeline_mode from session
|
||||
4. Extract active_workers[] from session (default: [])
|
||||
5. Parse $ARGUMENTS to determine trigger event
|
||||
6. autoYes = /\b(-y|--yes)\b/.test(args)
|
||||
```
|
||||
2. Check if progress update (inner loop) or final completion
|
||||
3. Progress -> update session state, STOP
|
||||
4. Completion -> mark task done via TaskUpdate(status="completed"), remove from active_workers
|
||||
5. Check for checkpoints:
|
||||
- scanner completes -> read meta.json for findings_count:
|
||||
- findings_count === 0 -> delete remaining REV-*/FIX-* tasks -> handleComplete
|
||||
- findings_count > 0 -> proceed to handleSpawnNext
|
||||
- reviewer completes AND pipeline_mode === 'full':
|
||||
- autoYes flag set -> write fix-manifest.json, set fix_scope='all' -> handleSpawnNext
|
||||
- NO autoYes -> AskUserQuestion:
|
||||
```
|
||||
question: "<N> findings reviewed. Proceed with fix?"
|
||||
options:
|
||||
- "Fix all": set fix_scope='all'
|
||||
- "Fix critical/high only": set fix_scope='critical,high'
|
||||
- "Skip fix": delete FIX-* tasks -> handleComplete
|
||||
```
|
||||
Write fix_scope to meta.json, write fix-manifest.json, -> handleSpawnNext
|
||||
- fixer completes -> handleSpawnNext (checks for completion naturally)
|
||||
|
||||
## Phase 3: Event Handlers
|
||||
6. -> handleSpawnNext
|
||||
|
||||
### Wake-up Source Detection
|
||||
## handleCheck
|
||||
|
||||
Parse `$ARGUMENTS` to determine handler:
|
||||
|
||||
| Priority | Condition | Handler |
|
||||
|----------|-----------|---------|
|
||||
| 1 | Message contains `[scanner]`, `[reviewer]`, or `[fixer]` | handleCallback |
|
||||
| 2 | Contains "check" or "status" | handleCheck |
|
||||
| 3 | Contains "resume", "continue", or "next" | handleResume |
|
||||
| 4 | Pipeline detected as complete (no pending, no in_progress) | handleComplete |
|
||||
| 5 | None of the above (initial spawn after dispatch) | handleSpawnNext |
|
||||
|
||||
---
|
||||
|
||||
### Handler: handleCallback
|
||||
|
||||
Worker completed a task. Verify completion, check pipeline conditions, advance.
|
||||
|
||||
```
|
||||
Receive callback from [<role>]
|
||||
+- Find matching active worker by role tag
|
||||
+- Task status = completed?
|
||||
| +- YES -> remove from active_workers -> update session
|
||||
| | +- role = scanner?
|
||||
| | | +- Read session.findings_count from meta.json
|
||||
| | | +- findings_count === 0?
|
||||
| | | | +- YES -> Skip remaining stages:
|
||||
| | | | | Delete all REV-* and FIX-* tasks (TaskUpdate status='deleted')
|
||||
| | | | | Log: "0 findings, skipping review/fix stages"
|
||||
| | | | | -> handleComplete
|
||||
| | | | +- NO -> normal advance
|
||||
| | | +- -> handleSpawnNext
|
||||
| | +- role = reviewer?
|
||||
| | | +- pipeline_mode === 'full'?
|
||||
| | | | +- YES -> Need fix confirmation gate
|
||||
| | | | | +- autoYes?
|
||||
| | | | | | +- YES -> Set fix_scope='all' in meta.json
|
||||
| | | | | | +- Write fix-manifest.json
|
||||
| | | | | | +- -> handleSpawnNext
|
||||
| | | | | +- NO -> AskUserQuestion:
|
||||
| | | | | question: "<N> findings reviewed. Proceed with fix?"
|
||||
| | | | | header: "Fix Confirmation"
|
||||
| | | | | options:
|
||||
| | | | | - "Fix all": Set fix_scope='all'
|
||||
| | | | | - "Fix critical/high only": Set fix_scope='critical,high'
|
||||
| | | | | - "Skip fix": Delete FIX-* tasks -> handleComplete
|
||||
| | | | | +- Write fix_scope to meta.json
|
||||
| | | | | +- Write fix-manifest.json:
|
||||
| | | | | { source: "<session>/review/review-report.json",
|
||||
| | | | | scope: fix_scope, session: sessionFolder }
|
||||
| | | | | +- -> handleSpawnNext
|
||||
| | | | +- NO -> normal advance -> handleSpawnNext
|
||||
| | +- role = fixer?
|
||||
| | +- -> handleSpawnNext (checks for completion naturally)
|
||||
| +- NO -> progress message, do not advance -> STOP
|
||||
+- No matching worker found
|
||||
+- Scan all active workers for completed tasks
|
||||
+- Found completed -> process each -> handleSpawnNext
|
||||
+- None completed -> STOP
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Handler: handleSpawnNext
|
||||
|
||||
Find all ready tasks, spawn one team-worker agent in background, update session, STOP.
|
||||
|
||||
```
|
||||
Collect task states from TaskList()
|
||||
+- completedSubjects: status = completed
|
||||
+- inProgressSubjects: status = in_progress
|
||||
+- deletedSubjects: status = deleted
|
||||
+- readySubjects: status = pending
|
||||
AND (no blockedBy OR all blockedBy in completedSubjects)
|
||||
|
||||
Ready tasks found?
|
||||
+- NONE + work in progress -> report waiting -> STOP
|
||||
+- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete
|
||||
+- HAS ready tasks -> take first ready task:
|
||||
+- Determine role from prefix:
|
||||
| SCAN-* -> scanner
|
||||
| REV-* -> reviewer
|
||||
| FIX-* -> fixer
|
||||
+- TaskUpdate -> in_progress
|
||||
+- team_msg log -> task_unblocked (team_session_id=<session-id>)
|
||||
+- Spawn team-worker (see spawn call below)
|
||||
+- Add to session.active_workers
|
||||
+- Update session file
|
||||
+- Output: "[coordinator] Spawned <role> for <subject>"
|
||||
+- STOP
|
||||
```
|
||||
|
||||
**Spawn worker tool call**:
|
||||
|
||||
```
|
||||
Agent({
|
||||
agent_type: "team-worker",
|
||||
description: "Spawn <role> worker for <subject>",
|
||||
team_name: "review",
|
||||
name: "<role>",
|
||||
run_in_background: true,
|
||||
prompt: `## Role Assignment
|
||||
role: <role>
|
||||
role_spec: .claude/skills/team-review/role-specs/<role>.md
|
||||
session: <session-folder>
|
||||
session_id: <session-id>
|
||||
team_name: review
|
||||
requirement: <task-description>
|
||||
inner_loop: false
|
||||
|
||||
## Current Task
|
||||
- Task ID: <task-id>
|
||||
- Task: <subject>
|
||||
|
||||
Read role_spec file to load Phase 2-4 domain instructions.
|
||||
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Handler: handleCheck
|
||||
|
||||
Read-only status report. No pipeline advancement.
|
||||
|
||||
**Output format**:
|
||||
Read-only status report, then STOP.
|
||||
|
||||
Output:
|
||||
```
|
||||
[coordinator] Review Pipeline Status
|
||||
[coordinator] Mode: <pipeline_mode>
|
||||
[coordinator] Progress: <completed>/<total> (<percent>%)
|
||||
|
||||
[coordinator] Pipeline Graph:
|
||||
SCAN-001: <status-icon> <summary>
|
||||
REV-001: <status-icon> <summary>
|
||||
FIX-001: <status-icon> <summary>
|
||||
SCAN-001: <done|run|wait|deleted> <summary>
|
||||
REV-001: <done|run|wait|deleted> <summary>
|
||||
FIX-001: <done|run|wait|deleted> <summary>
|
||||
|
||||
done=completed >>>=running o=pending x=deleted .=not created
|
||||
|
||||
[coordinator] Active Workers:
|
||||
> <subject> (<role>) - running
|
||||
done=completed >>>=running o=pending x=deleted
|
||||
|
||||
[coordinator] Active Workers: <list with elapsed time>
|
||||
[coordinator] Ready to spawn: <subjects>
|
||||
[coordinator] Commands: 'resume' to advance | 'check' to refresh
|
||||
```
|
||||
|
||||
Then STOP.
|
||||
|
||||
---
|
||||
## handleResume
|
||||
|
||||
### Handler: handleResume
|
||||
1. No active workers -> handleSpawnNext
|
||||
2. Has active -> check each status
|
||||
- completed -> mark done via TaskUpdate
|
||||
- in_progress -> still running
|
||||
- other -> worker failure -> reset to pending
|
||||
3. Some completed -> handleSpawnNext
|
||||
4. All running -> report status, STOP
|
||||
|
||||
Check active worker completion, process results, advance pipeline.
|
||||
## handleSpawnNext
|
||||
|
||||
Find ready tasks, spawn workers, STOP.
|
||||
|
||||
1. Collect from TaskList():
|
||||
- completedSubjects: status = completed
|
||||
- inProgressSubjects: status = in_progress
|
||||
- deletedSubjects: status = deleted
|
||||
- readySubjects: status = pending AND all blockedBy in completedSubjects
|
||||
|
||||
2. No ready + work in progress -> report waiting, STOP
|
||||
3. No ready + nothing in progress -> handleComplete
|
||||
4. Has ready -> take first ready task:
|
||||
a. Determine role from prefix (use Role-Worker Map)
|
||||
b. TaskUpdate -> in_progress
|
||||
c. team_msg log -> task_unblocked
|
||||
d. Spawn team-worker:
|
||||
|
||||
```
|
||||
Load active_workers from session
|
||||
+- No active workers -> handleSpawnNext
|
||||
+- Has active workers -> check each:
|
||||
+- status = completed -> mark done, remove from active_workers, log
|
||||
+- status = in_progress -> still running, log
|
||||
+- other status -> worker failure -> reset to pending
|
||||
After processing:
|
||||
+- Some completed -> handleSpawnNext
|
||||
+- All still running -> report status -> STOP
|
||||
+- All failed -> handleSpawnNext (retry)
|
||||
Agent({
|
||||
subagent_type: "team-worker",
|
||||
description: "Spawn <role> worker for <subject>",
|
||||
team_name: "review",
|
||||
name: "<role>",
|
||||
run_in_background: true,
|
||||
prompt: `## Role Assignment
|
||||
role: <role>
|
||||
role_spec: .claude/skills/team-review/roles/<role>/role.md
|
||||
session: <session-folder>
|
||||
session_id: <session-id>
|
||||
team_name: review
|
||||
requirement: <task-description>
|
||||
inner_loop: <true|false>
|
||||
|
||||
## Current Task
|
||||
- Task ID: <task-id>
|
||||
- Task: <subject>
|
||||
|
||||
Read role_spec file to load Phase 2-4 domain instructions.
|
||||
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
e. Add to active_workers
|
||||
5. Update session meta.json, output summary, STOP
|
||||
|
||||
### Handler: handleComplete
|
||||
## handleComplete
|
||||
|
||||
Pipeline complete. Generate summary and finalize session.
|
||||
Pipeline done. Generate report and completion action.
|
||||
|
||||
```
|
||||
All tasks completed or deleted (no pending, no in_progress)
|
||||
+- Read final session state from meta.json
|
||||
+- Generate pipeline summary:
|
||||
| - Pipeline mode
|
||||
| - Findings count
|
||||
| - Stages completed
|
||||
| - Fix results (if applicable)
|
||||
| - Deliverable paths
|
||||
|
|
||||
+- Update session:
|
||||
| session.pipeline_status = 'complete'
|
||||
| session.completed_at = <timestamp>
|
||||
| Write meta.json
|
||||
|
|
||||
+- team_msg log -> pipeline_complete
|
||||
+- Output summary to user
|
||||
+- STOP
|
||||
```
|
||||
1. All tasks completed or deleted (no pending, no in_progress)
|
||||
2. Read final session state from meta.json
|
||||
3. Generate pipeline summary: mode, target, findings_count, stages_completed, fix results (if applicable), deliverable paths
|
||||
4. Update session: pipeline_status='complete', completed_at=<timestamp>
|
||||
5. Read session.completion_action:
|
||||
- interactive -> AskUserQuestion (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean (status=completed, TeamDelete)
|
||||
- auto_keep -> Keep Active (status=paused)
|
||||
|
||||
---
|
||||
## handleAdapt
|
||||
|
||||
### Worker Failure Handling
|
||||
Capability gap reported mid-pipeline.
|
||||
|
||||
When a worker has unexpected status (not completed, not in_progress):
|
||||
1. Parse gap description
|
||||
2. Check if existing role covers it -> redirect
|
||||
3. Role count < 4 -> generate dynamic role-spec in <session>/role-specs/
|
||||
4. Create new task, spawn worker
|
||||
5. Role count >= 4 -> merge or pause
|
||||
|
||||
1. Reset task -> pending via TaskUpdate
|
||||
2. Remove from active_workers
|
||||
3. Log via team_msg (type: error)
|
||||
4. Report to user: task reset, will retry on next resume
|
||||
## Fast-Advance Reconciliation
|
||||
|
||||
On every coordinator wake:
|
||||
1. Read team_msg entries with type="fast_advance"
|
||||
2. Sync active_workers with spawned successors
|
||||
3. No duplicate spawns
|
||||
|
||||
## Phase 4: State Persistence
|
||||
|
||||
After every handler action, before STOP:
|
||||
|
||||
| Check | Action |
|
||||
|-------|--------|
|
||||
| Session state consistent | active_workers matches TaskList in_progress tasks |
|
||||
| No orphaned tasks | Every in_progress task has an active_worker entry |
|
||||
| Meta.json updated | Write updated session state |
|
||||
| Completion detection | readySubjects=0 + inProgressSubjects=0 -> handleComplete |
|
||||
|
||||
```
|
||||
Persist:
|
||||
1. Reconcile active_workers with actual TaskList states
|
||||
2. Remove entries for completed/deleted tasks
|
||||
3. Write updated meta.json
|
||||
4. Verify consistency
|
||||
5. STOP (wait for next callback)
|
||||
```
|
||||
After every handler execution:
|
||||
1. Reconcile active_workers with actual TaskList states
|
||||
2. Remove entries for completed/deleted tasks
|
||||
3. Write updated meta.json
|
||||
4. STOP (wait for next callback)
|
||||
|
||||
## Error Handling
|
||||
|
||||
@@ -278,7 +186,7 @@ Persist:
|
||||
|----------|------------|
|
||||
| Session file not found | Error, suggest re-initialization |
|
||||
| Worker callback from unknown role | Log info, scan for other completions |
|
||||
| All workers still running on resume | Report status, suggest check later |
|
||||
| Pipeline stall (no ready, no running, has pending) | Check blockedBy chains, report to user |
|
||||
| 0 findings after scan | Delete remaining stages, complete pipeline |
|
||||
| User declines fix | Delete FIX tasks, complete with review-only results |
|
||||
| User declines fix | Delete FIX-* tasks, complete with review-only results |
|
||||
| Pipeline stall | Check blockedBy chains, report to user |
|
||||
| Worker failure | Reset task to pending, respawn on next resume |
|
||||
|
||||
@@ -1,152 +1,62 @@
|
||||
# Coordinator Role
|
||||
|
||||
Code review team coordinator. Orchestrates the scan-review-fix pipeline (CP-1 Linear): parse target, detect mode, dispatch task chain, drive sequential stage execution via Stop-Wait, aggregate results.
|
||||
Orchestrate team-review: parse target -> detect mode -> dispatch task chain -> monitor -> report.
|
||||
|
||||
## Identity
|
||||
|
||||
- **Name**: `coordinator` | **Tag**: `[coordinator]`
|
||||
- **Task Prefix**: RC-* (coordinator creates tasks, doesn't receive them)
|
||||
- **Responsibility**: Orchestration
|
||||
- Name: coordinator | Tag: [coordinator]
|
||||
- Responsibility: Target parsing, mode detection, task creation/dispatch, stage monitoring, result aggregation
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
|
||||
- All output (SendMessage, team_msg, logs) prefixed with `[coordinator]`
|
||||
- Only: target parsing, mode detection, task creation/dispatch, stage monitoring, result aggregation
|
||||
- Create tasks via TaskCreate and assign to worker roles
|
||||
- Drive pipeline stages via Stop-Wait (synchronous Skill() calls)
|
||||
- Parse user requirements and clarify ambiguous inputs via AskUserQuestion
|
||||
- Maintain session state persistence
|
||||
- All output prefixed with `[coordinator]`
|
||||
- Parse task description and detect pipeline mode
|
||||
- Create team and spawn team-worker agents in background
|
||||
- Dispatch task chain with proper dependencies
|
||||
- Monitor progress via callbacks and route messages
|
||||
- Maintain session state
|
||||
- Execute completion action when pipeline finishes
|
||||
|
||||
### MUST NOT
|
||||
|
||||
- Run analysis tools directly (semgrep, eslint, tsc, etc.)
|
||||
- Modify source code files
|
||||
- Perform code review analysis
|
||||
- Bypass worker roles to do delegated work
|
||||
- Omit `[coordinator]` prefix on any output
|
||||
- Call implementation CLI tools directly
|
||||
|
||||
> **Core principle**: coordinator is the orchestrator, not the executor. All actual work delegated to scanner/reviewer/fixer via task chain.
|
||||
|
||||
---
|
||||
- Perform code review or scanning directly
|
||||
- Bypass worker roles
|
||||
- Spawn workers with general-purpose agent (MUST use team-worker)
|
||||
|
||||
## Command Execution Protocol
|
||||
|
||||
When coordinator needs to execute a command (dispatch, monitor):
|
||||
|
||||
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
|
||||
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
|
||||
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
|
||||
4. **Execute synchronously** -- complete the command workflow before proceeding
|
||||
|
||||
Example:
|
||||
```
|
||||
Phase 3 needs task dispatch
|
||||
-> Read roles/coordinator/commands/dispatch.md
|
||||
-> Execute Phase 2 (Context Loading)
|
||||
-> Execute Phase 3 (Task Chain Creation)
|
||||
-> Execute Phase 4 (Validation)
|
||||
-> Continue to Phase 4
|
||||
```
|
||||
|
||||
---
|
||||
When coordinator needs to execute a specific phase:
|
||||
1. Read `commands/<command>.md`
|
||||
2. Follow the workflow defined in the command
|
||||
3. Commands are inline execution guides, NOT separate agents
|
||||
4. Execute synchronously, complete before proceeding
|
||||
|
||||
## Entry Router
|
||||
|
||||
When coordinator is invoked, detect invocation type:
|
||||
|
||||
| Detection | Condition | Handler |
|
||||
|-----------|-----------|---------|
|
||||
| Worker callback | Message contains role tag [scanner], [reviewer], [fixer] | -> handleCallback |
|
||||
| Status check | Arguments contain "check" or "status" | -> handleCheck |
|
||||
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
|
||||
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
|
||||
| Interrupted session | Active/paused session exists | -> Phase 0 (Session Resume Check) |
|
||||
| New session | None of above | -> Phase 1 (Parse Arguments) |
|
||||
| Worker callback | Message contains [scanner], [reviewer], [fixer] | -> handleCallback (monitor.md) |
|
||||
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
|
||||
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
|
||||
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
|
||||
| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) |
|
||||
| Interrupted session | Active session in .workflow/.team/RV-* | -> Phase 0 |
|
||||
| New session | None of above | -> Phase 1 |
|
||||
|
||||
For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP.
|
||||
For callback/check/resume/adapt/complete: load commands/monitor.md, execute handler, STOP.
|
||||
|
||||
### Router Implementation
|
||||
## Phase 0: Session Resume Check
|
||||
|
||||
1. **Load session context** (if exists):
|
||||
- Scan `.workflow/.team-review/RC-*/.msg/meta.json` for active/paused sessions
|
||||
- If found, extract session folder path, status, and pipeline mode
|
||||
1. Scan .workflow/.team/RV-*/.msg/meta.json for active/paused sessions
|
||||
2. No sessions -> Phase 1
|
||||
3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task)
|
||||
4. Multiple -> AskUserQuestion for selection
|
||||
|
||||
2. **Parse $ARGUMENTS** for detection keywords:
|
||||
- Check for role name tags in message content
|
||||
- Check for "check", "status", "resume", "continue" keywords
|
||||
## Phase 1: Requirement Clarification
|
||||
|
||||
3. **Route to handler**:
|
||||
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
|
||||
- For Phase 0: Execute Session Resume Check
|
||||
- For Phase 1: Execute Parse Arguments below
|
||||
TEXT-LEVEL ONLY. No source code reading.
|
||||
|
||||
---
|
||||
|
||||
## Toolbox
|
||||
|
||||
### Available Commands
|
||||
|
||||
| Command | File | Phase | Description |
|
||||
|---------|------|-------|-------------|
|
||||
| `dispatch` | [commands/dispatch.md](commands/dispatch.md) | Phase 3 | Task chain creation based on mode |
|
||||
| `monitor` | [commands/monitor.md](commands/monitor.md) | Phase 4 | Stop-Wait stage execution loop |
|
||||
|
||||
### Tool Capabilities
|
||||
|
||||
| Tool | Type | Used By | Purpose |
|
||||
|------|------|---------|---------|
|
||||
| `TaskCreate` | Built-in | coordinator | Create tasks for workers |
|
||||
| `TaskUpdate` | Built-in | coordinator | Update task status |
|
||||
| `TaskList` | Built-in | coordinator | Check task states |
|
||||
| `AskUserQuestion` | Built-in | coordinator | Clarify requirements |
|
||||
| `Skill` | Built-in | coordinator | Spawn workers |
|
||||
| `SendMessage` | Built-in | coordinator | Receive worker callbacks |
|
||||
| `team_msg` | MCP | coordinator | Log communication |
|
||||
|
||||
---
|
||||
|
||||
## Message Types
|
||||
|
||||
| Type | Direction | Trigger | Description |
|
||||
|------|-----------|---------|-------------|
|
||||
| `dispatch_ready` | coordinator -> all | Phase 3 done | Task chain created, pipeline ready |
|
||||
| `stage_transition` | coordinator -> worker | Stage unblocked | Next stage starting |
|
||||
| `pipeline_complete` | coordinator -> user | All stages done | Pipeline finished, summary ready |
|
||||
| `error` | coordinator -> user | Stage failure | Blocking issue requiring attention |
|
||||
|
||||
## Message Bus
|
||||
|
||||
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
|
||||
|
||||
```
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log",
|
||||
session_id: <session-id>,
|
||||
from: "coordinator",
|
||||
type: "dispatch_ready"
|
||||
})
|
||||
```
|
||||
|
||||
**CLI fallback** (when MCP unavailable):
|
||||
|
||||
```
|
||||
Bash("ccw team log --session-id <session-id> --from coordinator --type dispatch_ready --json")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution (5-Phase)
|
||||
|
||||
### Phase 1: Parse Arguments & Detect Mode
|
||||
|
||||
**Objective**: Parse user input and gather execution parameters.
|
||||
|
||||
**Workflow**:
|
||||
|
||||
1. **Parse arguments** for explicit settings:
|
||||
1. Parse arguments for explicit settings:
|
||||
|
||||
| Flag | Mode | Description |
|
||||
|------|------|-------------|
|
||||
@@ -155,147 +65,65 @@ Bash("ccw team log --session-id <session-id> --from coordinator --type dispatch_
|
||||
| `-q` / `--quick` | quick | Quick scan only, no review/fix |
|
||||
| (none) | default | scan + review pipeline |
|
||||
|
||||
2. **Extract parameters**:
|
||||
2. Extract parameters: target, dimensions, auto-confirm flag
|
||||
3. Clarify if ambiguous (AskUserQuestion for target path)
|
||||
4. Delegate to commands/analyze.md
|
||||
5. Output: task-analysis.json
|
||||
6. CRITICAL: Always proceed to Phase 2, never skip team workflow
|
||||
|
||||
| Parameter | Extraction Method | Default |
|
||||
|-----------|-------------------|---------|
|
||||
| Target | Task description minus flags | `.` |
|
||||
| Dimensions | `--dimensions=sec,cor,perf,maint` | All 4 |
|
||||
| Auto-confirm | `-y` / `--yes` flag | false |
|
||||
## Phase 2: Create Team + Initialize Session
|
||||
|
||||
3. **Ask for missing parameters** via AskUserQuestion (if not auto-confirm):
|
||||
1. Generate session ID: RV-<slug>-<date>
|
||||
2. Create session folder structure (scan/, review/, fix/, wisdom/)
|
||||
3. TeamCreate with team name "review"
|
||||
4. Read specs/pipelines.md -> select pipeline based on mode
|
||||
5. Initialize pipeline via team_msg state_update:
|
||||
```
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log", session_id: "<id>", from: "coordinator",
|
||||
type: "state_update", summary: "Session initialized",
|
||||
data: {
|
||||
pipeline_mode: "<default|full|fix-only|quick>",
|
||||
pipeline_stages: ["scanner", "reviewer", "fixer"],
|
||||
team_name: "review",
|
||||
target: "<target>",
|
||||
dimensions: "<dimensions>",
|
||||
auto_confirm: "<auto_confirm>"
|
||||
}
|
||||
})
|
||||
```
|
||||
6. Write session meta.json
|
||||
|
||||
| Question | Options |
|
||||
|----------|---------|
|
||||
| "What code should be reviewed?" | Custom path, Uncommitted changes, Full project scan |
|
||||
## Phase 3: Create Task Chain
|
||||
|
||||
**Success**: All parameters captured, mode finalized.
|
||||
Delegate to commands/dispatch.md:
|
||||
1. Read specs/pipelines.md for selected pipeline's task registry
|
||||
2. Create tasks via TaskCreate with blockedBy
|
||||
3. Update session meta.json with pipeline.tasks_total
|
||||
|
||||
---
|
||||
## Phase 4: Spawn-and-Stop
|
||||
|
||||
### Phase 2: Initialize Session
|
||||
Delegate to commands/monitor.md#handleSpawnNext:
|
||||
1. Find ready tasks (pending + blockedBy resolved)
|
||||
2. Spawn team-worker agents (see SKILL.md Spawn Template)
|
||||
3. Output status summary
|
||||
4. STOP
|
||||
|
||||
**Objective**: Initialize team, session file, and shared memory.
|
||||
## Phase 5: Report + Completion Action
|
||||
|
||||
**Workflow**:
|
||||
|
||||
1. Generate session ID: `RC-<target-slug>-<date>`
|
||||
2. Create session folder structure:
|
||||
|
||||
```
|
||||
.workflow/.team-review/<workflow_id>/
|
||||
├── scan/
|
||||
├── review/
|
||||
├── fix/
|
||||
├── wisdom/
|
||||
│ ├── learnings.md
|
||||
│ ├── decisions.md
|
||||
│ ├── conventions.md
|
||||
│ └── issues.md
|
||||
├── .msg/
|
||||
│ ├── messages.jsonl
|
||||
│ └── meta.json
|
||||
```
|
||||
|
||||
3. Initialize .msg/meta.json with pipeline metadata:
|
||||
```typescript
|
||||
// Use team_msg to write pipeline metadata to .msg/meta.json
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log",
|
||||
session_id: "<session-id>",
|
||||
from: "coordinator",
|
||||
type: "state_update",
|
||||
summary: "Session initialized",
|
||||
data: {
|
||||
pipeline_mode: "<default|full|fix-only|quick>",
|
||||
pipeline_stages: ["scanner", "reviewer", "fixer"],
|
||||
roles: ["coordinator", "scanner", "reviewer", "fixer"],
|
||||
team_name: "review",
|
||||
target: "<target>",
|
||||
dimensions: "<dimensions>",
|
||||
auto_confirm: "<auto_confirm>"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Success**: Session folder created, shared memory initialized.
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Create Task Chain
|
||||
|
||||
**Objective**: Dispatch tasks based on mode with proper dependencies.
|
||||
|
||||
Delegate to `commands/dispatch.md` which creates the full task chain.
|
||||
|
||||
**Task Chain by Mode**:
|
||||
|
||||
| Mode | Chain | Description |
|
||||
|------|-------|-------------|
|
||||
| default | SCAN-001 -> REV-001 | scan + review |
|
||||
| full | SCAN-001 -> REV-001 -> FIX-001 | scan + review + fix |
|
||||
| fix-only | FIX-001 | fix only |
|
||||
| quick | SCAN-001 (quick=true) | quick scan only |
|
||||
|
||||
**Success**: Task chain created with correct blockedBy dependencies.
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Sequential Stage Execution (Stop-Wait)
|
||||
|
||||
**Objective**: Spawn workers sequentially via Skill(), synchronous blocking until return.
|
||||
|
||||
> **Strategy**: Spawn-and-Stop + Callback pattern.
|
||||
> - Spawn workers with synchronous `Skill()` call -> blocking wait for return
|
||||
> - Worker return = stage complete. No polling.
|
||||
> - FORBIDDEN: `while` loop + `sleep` + check status
|
||||
> - REQUIRED: Synchronous `Skill()` call = natural callback
|
||||
|
||||
**Workflow**:
|
||||
|
||||
1. Load `commands/monitor.md`
|
||||
2. Find next executable task (pending + blockedBy resolved)
|
||||
3. Spawn worker via Skill()
|
||||
4. Wait for worker return
|
||||
5. Process result -> advance to next stage
|
||||
6. Repeat until pipeline complete
|
||||
|
||||
**Stage Flow**:
|
||||
|
||||
| Stage | Worker | On Complete |
|
||||
|-------|--------|-------------|
|
||||
| SCAN-001 | scanner | Check findings count -> start REV |
|
||||
| REV-001 | reviewer | Generate review report -> [user confirm] -> start FIX |
|
||||
| FIX-001 | fixer | Execute fixes -> verify |
|
||||
|
||||
---
|
||||
|
||||
### Phase 5: Aggregate Results & Report
|
||||
|
||||
> See SKILL.md Shared Infrastructure -> Coordinator Phase 5
|
||||
|
||||
**Objective**: Completion report and follow-up options.
|
||||
|
||||
**Workflow**:
|
||||
|
||||
1. Load session state -> count completed tasks, duration
|
||||
2. Calculate fix rate: (fixed_count / findings_count) * 100
|
||||
3. Build summary report with: mode, target, dimensions, findings_total, by_severity, by_dimension, fixed_count, fix_rate
|
||||
4. Log via team_msg
|
||||
5. SendMessage with `[coordinator]` prefix
|
||||
6. AskUserQuestion for next steps (unless auto-confirm)
|
||||
|
||||
---
|
||||
1. Generate summary (mode, target, findings_total, by_severity, fix_rate if applicable)
|
||||
2. Execute completion action per session.completion_action:
|
||||
- interactive -> AskUserQuestion (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean
|
||||
- auto_keep -> Keep Active
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| Task too vague | AskUserQuestion for clarification |
|
||||
| Session corruption | Attempt recovery, fallback to manual |
|
||||
| Worker crash | Reset task to pending, respawn |
|
||||
| Scanner finds 0 findings | Report clean, skip review + fix stages |
|
||||
| Worker returns incomplete | Ask user: retry / skip / abort |
|
||||
| Fix verification fails | Log warning, report partial results |
|
||||
| Session folder missing | Re-create and log warning |
|
||||
| Target path invalid | AskUserQuestion for corrected path |
|
||||
| Task timeout | Log, mark failed, ask user to retry or skip |
|
||||
| Worker crash | Respawn worker, reassign task |
|
||||
| Dependency cycle | Detect, report to user, halt |
|
||||
|
||||
76
.claude/skills/team-review/roles/fixer/role.md
Normal file
76
.claude/skills/team-review/roles/fixer/role.md
Normal file
@@ -0,0 +1,76 @@
|
||||
---
|
||||
role: fixer
|
||||
prefix: FIX
|
||||
inner_loop: true
|
||||
message_types:
|
||||
success: fix_complete
|
||||
error: fix_failed
|
||||
---
|
||||
|
||||
# Code Fixer
|
||||
|
||||
Fix code based on reviewed findings. Load manifest, plan fix groups, apply with rollback-on-failure, verify. Code-generation role -- modifies source files.
|
||||
|
||||
## Phase 2: Context & Scope Resolution
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Task description | From task subject/description | Yes |
|
||||
| Session path | Extracted from task description | Yes |
|
||||
| Fix manifest | <session>/fix/fix-manifest.json | Yes |
|
||||
| Review report | <session>/review/review-report.json | Yes |
|
||||
| .msg/meta.json | <session>/.msg/meta.json | No |
|
||||
|
||||
1. Extract session path, input path from task description
|
||||
2. Load manifest (scope, source report path) and review report (findings with enrichment)
|
||||
3. Filter fixable findings: severity in scope AND fix_strategy !== 'skip'
|
||||
4. If 0 fixable -> report complete immediately
|
||||
5. Detect quick path: findings <= 5 AND no cross-file dependencies
|
||||
6. Detect verification tools: tsc (tsconfig.json), eslint (package.json), jest (package.json), pytest (pyproject.toml), semgrep (semgrep available)
|
||||
7. Load wisdom files from `<session>/wisdom/`
|
||||
|
||||
## Phase 3: Plan + Execute
|
||||
|
||||
### 3A: Plan Fixes (deterministic, no CLI)
|
||||
1. Group findings by primary file
|
||||
2. Merge groups with cross-file dependencies (union-find)
|
||||
3. Topological sort within each group (respect fix_dependencies, append cycles at end)
|
||||
4. Sort groups by max severity (critical first)
|
||||
5. Determine execution path: quick_path (<=5 findings, <=1 group) or standard
|
||||
6. Write `<session>/fix/fix-plan.json`: `{plan_id, quick_path, groups[{id, files[], findings[], max_severity}], execution_order[], total_findings, total_groups}`
|
||||
|
||||
### 3B: Execute Fixes
|
||||
**Quick path**: Single code-developer agent for all findings.
|
||||
**Standard path**: One code-developer agent per group, in execution_order.
|
||||
|
||||
Agent prompt includes: finding list (dependency-sorted), file contents (truncated 8K), critical rules:
|
||||
1. Apply each fix using Edit tool in order
|
||||
2. After each fix, run related tests
|
||||
3. Tests PASS -> finding is "fixed"
|
||||
4. Tests FAIL -> `git checkout -- {file}` -> mark "failed" -> continue
|
||||
5. No retry on failure. Rollback and move on
|
||||
6. If finding depends on previously failed finding -> mark "skipped"
|
||||
|
||||
Agent returns JSON: `{results:[{id, status: fixed|failed|skipped, file, error?}]}`
|
||||
Fallback: check git diff per file if no structured output.
|
||||
|
||||
Write `<session>/fix/execution-results.json`: `{fixed[], failed[], skipped[]}`
|
||||
|
||||
## Phase 4: Post-Fix Verification
|
||||
|
||||
1. Run available verification tools on modified files:
|
||||
|
||||
| Tool | Command | Pass Criteria |
|
||||
|------|---------|---------------|
|
||||
| tsc | `npx tsc --noEmit` | 0 errors |
|
||||
| eslint | `npx eslint <files>` | 0 errors |
|
||||
| jest | `npx jest --passWithNoTests` | Tests pass |
|
||||
| pytest | `pytest --tb=short` | Tests pass |
|
||||
| semgrep | `semgrep --config auto <files> --json` | 0 results |
|
||||
|
||||
2. If verification fails critically -> rollback last batch
|
||||
3. Write `<session>/fix/verify-results.json`
|
||||
4. Generate `<session>/fix/fix-summary.json`: `{fix_id, fix_date, scope, total, fixed, failed, skipped, fix_rate, verification}`
|
||||
5. Generate `<session>/fix/fix-summary.md` (human-readable)
|
||||
6. Update `<session>/.msg/meta.json` with fix results
|
||||
7. Contribute discoveries to `<session>/wisdom/` files
|
||||
67
.claude/skills/team-review/roles/reviewer/role.md
Normal file
67
.claude/skills/team-review/roles/reviewer/role.md
Normal file
@@ -0,0 +1,67 @@
|
||||
---
|
||||
role: reviewer
|
||||
prefix: REV
|
||||
inner_loop: false
|
||||
message_types:
|
||||
success: review_complete
|
||||
error: error
|
||||
---
|
||||
|
||||
# Finding Reviewer
|
||||
|
||||
Deep analysis on scan findings: triage, root cause / impact / optimization enrichment via CLI fan-out, cross-correlation, and structured review report generation. Read-only -- never modifies source code.
|
||||
|
||||
## Phase 2: Context & Triage
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Task description | From task subject/description | Yes |
|
||||
| Session path | Extracted from task description | Yes |
|
||||
| Scan results | <session>/scan/scan-results.json | Yes |
|
||||
| .msg/meta.json | <session>/.msg/meta.json | No |
|
||||
|
||||
1. Extract session path, input path, dimensions from task description
|
||||
2. Load scan results. If missing or empty -> report clean, complete immediately
|
||||
3. Load wisdom files from `<session>/wisdom/`
|
||||
4. Triage findings into two buckets:
|
||||
|
||||
| Bucket | Criteria | Action |
|
||||
|--------|----------|--------|
|
||||
| deep_analysis | severity in [critical, high, medium], max 15, sorted critical-first | Enrich with root cause, impact, optimization |
|
||||
| pass_through | remaining (low, info, or overflow) | Include in report without enrichment |
|
||||
|
||||
If deep_analysis empty -> skip Phase 3, go to Phase 4.
|
||||
|
||||
## Phase 3: Deep Analysis (CLI Fan-out)
|
||||
|
||||
Split deep_analysis into two domain groups, run parallel CLI agents:
|
||||
|
||||
| Group | Dimensions | Focus |
|
||||
|-------|-----------|-------|
|
||||
| A | Security + Correctness | Root cause tracing, fix dependencies, blast radius |
|
||||
| B | Performance + Maintainability | Optimization approaches, refactor tradeoffs |
|
||||
|
||||
If either group empty -> skip that agent.
|
||||
|
||||
Build prompt per group requesting 6 enrichment fields per finding:
|
||||
- `root_cause`: `{description, related_findings[], is_symptom}`
|
||||
- `impact`: `{scope: low/medium/high, affected_files[], blast_radius}`
|
||||
- `optimization`: `{approach, alternative, tradeoff}`
|
||||
- `fix_strategy`: minimal / refactor / skip
|
||||
- `fix_complexity`: low / medium / high
|
||||
- `fix_dependencies`: finding IDs that must be fixed first
|
||||
|
||||
Execute via `ccw cli --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause` (fallback: qwen -> codex). Parse JSON array responses, merge with originals (CLI-enriched replace originals, unenriched get defaults). Write `<session>/review/enriched-findings.json`.
|
||||
|
||||
## Phase 4: Report Generation
|
||||
|
||||
1. Combine enriched + pass_through findings
|
||||
2. Cross-correlate:
|
||||
- **Critical files**: file appears in >=2 dimensions -> list with finding_count, severities
|
||||
- **Root cause groups**: cluster findings sharing related_findings -> identify primary
|
||||
- **Optimization suggestions**: from root cause groups + standalone enriched findings
|
||||
3. Compute metrics: by_dimension, by_severity, dimension_severity_matrix, fixable_count, auto_fixable_count
|
||||
4. Write `<session>/review/review-report.json`: `{review_id, review_date, findings[], critical_files[], optimization_suggestions[], root_cause_groups[], summary}`
|
||||
5. Write `<session>/review/review-report.md`: Executive summary, metrics matrix (dimension x severity), critical/high findings table, critical files list, optimization suggestions, recommended fix scope
|
||||
6. Update `<session>/.msg/meta.json` with review summary
|
||||
7. Contribute discoveries to `<session>/wisdom/` files
|
||||
71
.claude/skills/team-review/roles/scanner/role.md
Normal file
71
.claude/skills/team-review/roles/scanner/role.md
Normal file
@@ -0,0 +1,71 @@
|
||||
---
|
||||
role: scanner
|
||||
prefix: SCAN
|
||||
inner_loop: false
|
||||
message_types:
|
||||
success: scan_complete
|
||||
error: error
|
||||
---
|
||||
|
||||
# Code Scanner
|
||||
|
||||
Toolchain + LLM semantic scan producing structured findings. Static analysis tools in parallel, then LLM for issues tools miss. Read-only -- never modifies source code. 4-dimension system: security (SEC), correctness (COR), performance (PRF), maintainability (MNT).
|
||||
|
||||
## Phase 2: Context & Toolchain Detection
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Task description | From task subject/description | Yes |
|
||||
| Session path | Extracted from task description | Yes |
|
||||
| .msg/meta.json | <session>/.msg/meta.json | No |
|
||||
|
||||
1. Extract session path, target, dimensions, quick flag from task description
|
||||
2. Resolve target files (glob pattern or directory -> `**/*.{ts,tsx,js,jsx,py,go,java,rs}`)
|
||||
3. If no source files found -> report empty, complete task cleanly
|
||||
4. Detect toolchain availability:
|
||||
|
||||
| Tool | Detection | Dimension |
|
||||
|------|-----------|-----------|
|
||||
| tsc | `tsconfig.json` exists | COR |
|
||||
| eslint | `.eslintrc*` or `eslint` in package.json | COR/MNT |
|
||||
| semgrep | `.semgrep.yml` exists | SEC |
|
||||
| ruff | `pyproject.toml` + ruff available | SEC/COR/MNT |
|
||||
| mypy | mypy available + `pyproject.toml` | COR |
|
||||
| npmAudit | `package-lock.json` exists | SEC |
|
||||
|
||||
5. Load wisdom files from `<session>/wisdom/` if they exist
|
||||
|
||||
## Phase 3: Scan Execution
|
||||
|
||||
**Quick mode**: Single CLI call with analysis mode, max 20 findings, skip toolchain.
|
||||
|
||||
**Standard mode** (sequential):
|
||||
|
||||
### 3A: Toolchain Scan
|
||||
Run detected tools in parallel via Bash backgrounding. Each tool writes to `<session>/scan/tmp/<tool>.{json|txt}`. After `wait`, parse each output into normalized findings:
|
||||
- tsc: `file(line,col): error TSxxxx: msg` -> dimension=correctness, source=tool:tsc
|
||||
- eslint: JSON array -> severity 2=correctness/high, else=maintainability/medium
|
||||
- semgrep: `{results[]}` -> dimension=security, severity from extra.severity
|
||||
- ruff: `[{code,message,filename}]` -> S*=security, F*/B*=correctness, else=maintainability
|
||||
- mypy: `file:line: error: msg [code]` -> dimension=correctness
|
||||
- npm audit: `{vulnerabilities:{}}` -> dimension=security, category=dependency
|
||||
|
||||
Write `<session>/scan/toolchain-findings.json`.
|
||||
|
||||
### 3B: Semantic Scan (LLM via CLI)
|
||||
Build prompt with target file patterns, toolchain dedup summary, and per-dimension focus areas:
|
||||
- SEC: Business logic vulnerabilities, privilege escalation, sensitive data flow, auth bypass
|
||||
- COR: Logic errors, unhandled exception paths, state management bugs, race conditions
|
||||
- PRF: Algorithm complexity, N+1 queries, unnecessary sync, memory leaks, missing caching
|
||||
- MNT: Architectural coupling, abstraction leaks, convention violations, dead code
|
||||
|
||||
Execute via `ccw cli --tool gemini --mode analysis --rule analysis-review-code-quality` (fallback: qwen -> codex). Parse JSON array response, validate required fields (dimension, title, location.file), enforce per-dimension limit (max 5 each), filter minimum severity (medium+). Write `<session>/scan/semantic-findings.json`.
|
||||
|
||||
## Phase 4: Aggregate & Output
|
||||
|
||||
1. Merge toolchain + semantic findings, deduplicate (same file + line + dimension = duplicate)
|
||||
2. Assign dimension-prefixed IDs: SEC-001, COR-001, PRF-001, MNT-001
|
||||
3. Write `<session>/scan/scan-results.json` with schema: `{scan_date, target, dimensions, quick_mode, total_findings, by_severity, by_dimension, findings[]}`
|
||||
4. Each finding: `{id, dimension, category, severity, title, description, location:{file,line}, source, suggested_fix, effort, confidence}`
|
||||
5. Update `<session>/.msg/meta.json` with scan summary (findings_count, by_severity, by_dimension)
|
||||
6. Contribute discoveries to `<session>/wisdom/` files
|
||||
Reference in New Issue
Block a user