feat: add Discuss and Explore subagents for dynamic critique and code exploration

- Implement Discuss Subagent for multi-perspective critique with dynamic perspectives.
- Create Explore Subagent for shared codebase exploration with centralized caching.
- Add tests for CcwToolsMcpCard component to ensure enabled tools are preserved on config save.
- Introduce SessionPreviewPanel component for previewing and selecting sessions for Memory V2 extraction.
- Develop CommandCreateDialog component for creating/importing commands with import and CLI generate modes.
This commit is contained in:
catlog22
2026-02-27 17:25:52 +08:00
parent 3db74cc7b0
commit 3b92bfae8c
45 changed files with 6508 additions and 128 deletions

View File

@@ -0,0 +1,442 @@
---
name: team-coordinate
description: Universal team coordination skill with dynamic role generation. Only coordinator is built-in -- all worker roles are generated at runtime based on task analysis. Beat/cadence model for orchestration. Triggers on "team coordinate".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Coordinate
Universal team coordination skill: analyze task -> generate roles -> dispatch -> execute -> deliver. Only the **coordinator** is built-in. All worker roles are **dynamically generated** based on task analysis.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-coordinate") |
| args="task description" |
| args="--role=coordinator" |
| args="--role=<dynamic> --session=<path>" |
+-------------------+-------------------------------+
| Role Router
+---- --role present? ----+
| NO | YES
v v
Orchestration Mode Role Dispatch
(auto -> coordinator) (route to role file)
| |
coordinator +-------+-------+
(built-in) | --role=coordinator?
| |
YES | | NO
v | v
built-in | Dynamic Role
role.md | <session>/roles/<role>.md
Subagents (callable by any role, not team members):
[discuss-subagent] - multi-perspective critique (dynamic perspectives)
[explore-subagent] - codebase exploration with cache
```
## Role Router
### Input Parsing
Parse `$ARGUMENTS` to extract `--role` and `--session`. If no `--role` -> Orchestration Mode (auto route to coordinator).
### Role Registry
Only coordinator is statically registered. All other roles are dynamic, stored in `team-session.json#roles`.
| Role | File | Type |
|------|------|------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | built-in orchestrator |
| (dynamic) | `<session>/roles/<role-name>.md` | runtime-generated worker |
> **COMPACT PROTECTION**: Role files are execution documents. After context compression, role instructions become summaries only -- **MUST immediately `Read` the role.md to reload before continuing**. Never execute any Phase based on summaries.
### Subagent Registry
| Subagent | Spec | Callable By | Purpose |
|----------|------|-------------|---------|
| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | any role | Multi-perspective critique (dynamic perspectives) |
| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | any role | Codebase exploration with cache |
### Dispatch
1. Extract `--role` and `--session` from arguments
2. If no `--role` -> route to coordinator (Orchestration Mode)
3. If `--role=coordinator` -> Read built-in `roles/coordinator/role.md` -> Execute its phases
4. If `--role=<other>` -> Read `<session>/roles/<role>.md` -> Execute its phases
5. If session path not provided -> auto-discover from `.workflow/.team/TC-*/team-session.json`
### Orchestration Mode
When invoked without `--role`, coordinator auto-starts. User just provides task description.
**Invocation**: `Skill(skill="team-coordinate", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1: task analysis (detect capabilities, build dependency graph)
-> coordinator Phase 2: generate roles + initialize session
-> coordinator Phase 3: create task chain from dependency graph
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances next step
-> Loop until pipeline complete -> Phase 5 report
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Shared Infrastructure
The following templates apply to all worker roles. Each generated role.md only needs to define **Phase 2-4** role-specific logic.
### Worker Phase 1: Task Discovery (all workers shared)
Each worker on startup executes the same task discovery flow:
1. Call `TaskList()` to get all tasks
2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty
3. No tasks -> idle wait
4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress
**Resume Artifact Check** (prevent duplicate output after resume):
- Check if this task's output artifacts already exist
- Artifacts complete -> skip to Phase 5 report completion
- Artifacts incomplete or missing -> normal Phase 2-4 execution
### Worker Phase 5: Report + Fast-Advance (all workers shared)
Task completion with optional fast-advance to skip coordinator round-trip:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Params: operation="log", team=<team-name>, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path>
- **CLI fallback**: When MCP unavailable -> `ccw team log --team <team> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
2. **TaskUpdate**: Mark task completed
3. **Fast-Advance Check**:
- Call `TaskList()`, find pending tasks whose blockedBy are ALL completed
- If exactly 1 ready task AND its owner matches a simple successor pattern -> **spawn it directly** (skip coordinator)
- Otherwise -> **SendMessage** to coordinator for orchestration
4. **Loop**: Back to Phase 1 to check for next task
**Fast-Advance Rules**:
| Condition | Action |
|-----------|--------|
| Same-prefix successor (Inner Loop role) | Do not spawn, main agent inner loop (Phase 5-L) |
| 1 ready task, simple linear successor, different prefix | Spawn directly via Task(run_in_background: true) |
| Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) |
| No ready tasks + others running | SendMessage to coordinator (status update) |
| No ready tasks + nothing running | SendMessage to coordinator (pipeline may be complete) |
**Fast-advance failure recovery**: If a fast-advanced task fails, the coordinator detects it as an orphaned in_progress task on next `resume`/`check` and resets it to pending for re-spawn. Self-healing. See [monitor.md](roles/coordinator/commands/monitor.md).
### Worker Inner Loop (roles with multiple same-prefix serial tasks)
When a role has **2+ serial same-prefix tasks**, it loops internally instead of spawning new agents:
**Inner Loop flow**:
```
Phase 1: Discover task (first time)
|
+- Found task -> Phase 2-3: Load context + Execute work
| |
| v
| Phase 4: Validation (+ optional Inline Discuss)
| |
| v
| Phase 5-L: Loop Completion
| |
| +- TaskUpdate completed
| +- team_msg log
| +- Accumulate summary to context_accumulator
| |
| +- More same-prefix tasks?
| | +- YES -> back to Phase 1 (inner loop)
| | +- NO -> Phase 5-F: Final Report
| |
| +- Interrupt conditions?
| +- consensus_blocked HIGH -> SendMessage -> STOP
| +- Errors >= 3 -> SendMessage -> STOP
|
+- Phase 5-F: Final Report
+- SendMessage (all task summaries)
+- STOP
```
**Phase 5-L vs Phase 5-F**:
| Step | Phase 5-L (looping) | Phase 5-F (final) |
|------|---------------------|-------------------|
| TaskUpdate completed | YES | YES |
| team_msg log | YES | YES |
| Accumulate summary | YES | - |
| SendMessage to coordinator | NO | YES (all tasks summary) |
| Fast-Advance to next prefix | - | YES (check cross-prefix successors) |
### Inline Discuss Protocol (optional for any role)
After completing primary output, roles may call the discuss subagent inline. Unlike v4's fixed perspective definitions, team-coordinate uses **dynamic perspectives** specified by the coordinator when generating each role.
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: <see subagents/discuss-subagent.md for prompt template>
})
```
**Consensus handling**:
| Verdict | Severity | Role Action |
|---------|----------|-------------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | SendMessage with structured format. Do NOT self-revise. |
| consensus_blocked | MEDIUM | SendMessage with warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
### Shared Explore Utility
Any role needing codebase context calls the explore subagent:
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: <see subagents/explore-subagent.md for prompt template>
})
```
**Cache**: Results stored in `explorations/` with `cache-index.json`. Before exploring, always check cache first.
### Wisdom Accumulation (all roles)
Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session init.
**Directory**:
```
<session-folder>/wisdom/
+-- learnings.md # Patterns and insights
+-- decisions.md # Design and strategy decisions
+-- issues.md # Known risks and issues
```
**Worker load** (Phase 2): Extract `Session: <path>` from task description, read wisdom files.
**Worker contribute** (Phase 4/5): Write discoveries to corresponding wisdom files.
### Role Isolation Rules
| Allowed | Prohibited |
|---------|-----------|
| Process own prefix tasks | Process other role's prefix tasks |
| SendMessage to coordinator | Directly communicate with other workers |
| Use tools appropriate to responsibility | Create tasks for other roles |
| Call discuss/explore subagents | Modify resources outside own scope |
| Fast-advance simple successors | Spawn parallel worker batches |
| Report capability_gap to coordinator | Attempt work outside scope |
Coordinator additionally prohibited: directly write/modify deliverable artifacts, call implementation subagents directly, directly execute analysis/test/review.
---
## Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
```
Beat Cycle (single beat)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check pipeline |
+- handleSpawnNext -+
| find ready tasks |
| spawn workers ---+--> [Worker A] Phase 1-5
| (parallel OK) --+--> [Worker B] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
(next beat) SendMessage + TaskUpdate(completed)
======================================================================
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor? --> spawn Worker B directly
+- complex case? --> SendMessage to coordinator
======================================================================
```
**Pipelines are dynamic**: Unlike v4's predefined pipeline beat views (spec-only, impl-only, etc.), team-coordinate pipelines are generated per-task from the dependency graph. The beat model is the same -- only the pipeline shape varies.
---
## Coordinator Spawn Template
### Standard Worker (single-task role)
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `You are team "<team-name>" <ROLE>.
## Primary Instruction
All your work MUST be executed by calling Skill to get role definition:
Skill(skill="team-coordinate", args="--role=<role> --session=<session-folder>")
Current requirement: <task-description>
Session: <session-folder>
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] tag
- Only communicate with coordinator
- Do not use TaskCreate to create tasks for other roles
- Before each SendMessage, call mcp__ccw-tools__team_msg to log
- After task completion, check for fast-advance opportunity (see SKILL.md Phase 5)
## Workflow
1. Call Skill -> get role definition and execution logic
2. Follow role.md 5-Phase flow
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task or fast-advance`
})
```
### Inner Loop Worker (multi-task role)
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker (inner loop)",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `You are team "<team-name>" <ROLE>.
## Primary Instruction
All your work MUST be executed by calling Skill to get role definition:
Skill(skill="team-coordinate", args="--role=<role> --session=<session-folder>")
Current requirement: <task-description>
Session: <session-folder>
## Inner Loop Mode
You will handle ALL <PREFIX>-* tasks in this session, not just the first one.
After completing each task, loop back to find the next <PREFIX>-* task.
Only SendMessage to coordinator when:
- All <PREFIX>-* tasks are done
- A consensus_blocked HIGH occurs
- Errors accumulate (>= 3)
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] tag
- Only communicate with coordinator
- Do not use TaskCreate to create tasks for other roles
- Before each SendMessage, call mcp__ccw-tools__team_msg to log
- Use subagent calls for heavy work, retain summaries in context`
})
```
---
## Session Directory
```
.workflow/.team/TC-<slug>-<date>/
+-- team-session.json # Session state + dynamic role registry
+-- task-analysis.json # Phase 1 output: capabilities, dependency graph
+-- roles/ # Dynamic role definitions (generated Phase 2)
| +-- <role-1>.md
| +-- <role-2>.md
+-- artifacts/ # All MD deliverables from workers
| +-- <artifact>.md
+-- shared-memory.json # Cross-role state store
+-- wisdom/ # Cross-task knowledge
| +-- learnings.md
| +-- decisions.md
| +-- issues.md
+-- explorations/ # Shared explore cache
| +-- cache-index.json
| +-- explore-<angle>.json
+-- discussions/ # Inline discuss records
| +-- <round>.md
+-- .msg/ # Team message bus logs
```
### team-session.json Schema
```json
{
"session_id": "TC-<slug>-<date>",
"task_description": "<original user input>",
"status": "active | paused | completed",
"team_name": "<team-name>",
"roles": [
{
"name": "<role-name>",
"prefix": "<PREFIX>",
"responsibility_type": "<type>",
"inner_loop": false,
"role_file": "roles/<role-name>.md"
}
],
"pipeline": {
"dependency_graph": {},
"tasks_total": 0,
"tasks_completed": 0
},
"active_workers": [],
"completed_tasks": [],
"created_at": "<timestamp>"
}
```
---
## Session Resume
Coordinator supports `--resume` / `--continue` for interrupted sessions:
1. Scan `.workflow/.team/TC-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion for selection
3. Audit TaskList -> reconcile session state <-> task status
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team and spawn needed workers only
6. Create missing tasks with correct blockedBy
7. Kick first executable task -> Phase 4 coordination loop
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Check if `<session>/roles/<role>.md` exists; error with message if not |
| Missing --role arg | Orchestration Mode -> coordinator |
| Dynamic role file not found | Error with expected path, coordinator may need to regenerate |
| Built-in role file not found | Error with expected path |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Role proceeds without discuss, logs warning |
| Explore cache corrupt | Clear cache, re-explore |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| Session path not provided | Auto-discover from `.workflow/.team/TC-*/team-session.json` |
| capability_gap reported | Coordinator generates new role via handleAdapt |

View File

@@ -0,0 +1,175 @@
# Command: analyze-task
## Purpose
Parse user task description -> detect required capabilities -> build dependency graph -> design dynamic roles. This replaces v4's static mode selection with intelligent task decomposition.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task description | User input from Phase 1 | Yes |
| Clarification answers | AskUserQuestion results (if any) | No |
| Session folder | From coordinator Phase 2 | Yes |
## Phase 3: Task Analysis
### Step 1: Signal Detection
Scan task description for capability keywords:
| Signal | Keywords | Capability | Prefix | Responsibility Type |
|--------|----------|------------|--------|---------------------|
| Research | investigate, explore, compare, survey, find, research, discover, benchmark, study | researcher | RESEARCH | orchestration |
| Writing | write, draft, document, article, report, blog, describe, explain, summarize, content | writer | DRAFT | code-gen (docs) |
| Coding | implement, build, code, fix, refactor, develop, create app, program, migrate, port | developer | IMPL | code-gen (code) |
| Design | design, architect, plan, structure, blueprint, model, schema, wireframe, layout | designer | DESIGN | orchestration |
| Analysis | analyze, review, audit, assess, evaluate, inspect, examine, diagnose, profile | analyst | ANALYSIS | read-only |
| Testing | test, verify, validate, QA, quality, check, assert, coverage, regression | tester | TEST | validation |
| Planning | plan, breakdown, organize, schedule, decompose, roadmap, strategy, prioritize | planner | PLAN | orchestration |
**Multi-match**: A task may trigger multiple capabilities. E.g., "research and write a technical article" triggers both `researcher` and `writer`.
**No match**: If no keywords match, default to a single `general` capability with `TASK` prefix.
### Step 2: Artifact Inference
Each capability produces default output artifacts:
| Capability | Default Artifact | Format |
|------------|-----------------|--------|
| researcher | Research findings | `<session>/artifacts/research-findings.md` |
| writer | Written document(s) | `<session>/artifacts/<doc-name>.md` |
| developer | Code implementation | Source files + `<session>/artifacts/implementation-summary.md` |
| designer | Design document | `<session>/artifacts/design-spec.md` |
| analyst | Analysis report | `<session>/artifacts/analysis-report.md` |
| tester | Test results | `<session>/artifacts/test-report.md` |
| planner | Execution plan | `<session>/artifacts/execution-plan.md` |
### Step 3: Dependency Graph Construction
Build a DAG of work streams using these inference rules:
| Pattern | Shape | Example |
|---------|-------|---------|
| Knowledge -> Creation | research blockedBy nothing, creation blockedBy research | RESEARCH-001 -> DRAFT-001 |
| Design -> Build | design first, build after | DESIGN-001 -> IMPL-001 |
| Build -> Validate | build first, test/review after | IMPL-001 -> TEST-001 + ANALYSIS-001 |
| Plan -> Execute | plan first, execute after | PLAN-001 -> IMPL-001 |
| Independent parallel | no dependency between them | DRAFT-001 || IMPL-001 |
| Analysis -> Revise | analysis finds issues, revise artifact | ANALYSIS-001 -> DRAFT-002 |
**Graph construction algorithm**:
1. Group capabilities by natural ordering: knowledge-gathering -> design/planning -> creation -> validation
2. Within same tier: capabilities are parallel unless task description implies sequence
3. Between tiers: downstream blockedBy upstream
4. Single-capability tasks: one node, no dependencies
**Natural ordering tiers**:
| Tier | Capabilities | Description |
|------|-------------|-------------|
| 0 | researcher, planner | Knowledge gathering / planning |
| 1 | designer | Design (requires context from tier 0 if present) |
| 2 | writer, developer | Creation (requires design/plan if present) |
| 3 | analyst, tester | Validation (requires artifacts to validate) |
### Step 4: Complexity Scoring
| Factor | Weight | Condition |
|--------|--------|-----------|
| Capability count | +1 each | Number of distinct capabilities |
| Cross-domain factor | +2 | Capabilities span 3+ tiers |
| Parallel tracks | +1 each | Independent parallel work streams |
| Serial depth | +1 per level | Longest dependency chain length |
| Total Score | Complexity | Role Limit |
|-------------|------------|------------|
| 1-3 | Low | 1-2 roles |
| 4-6 | Medium | 2-3 roles |
| 7+ | High | 3-5 roles |
### Step 5: Role Minimization
Apply merging rules to reduce role count:
| Rule | Condition | Action |
|------|-----------|--------|
| Absorb trivial | Capability has exactly 1 task AND no explore needed | Merge into nearest related role |
| Merge overlap | Two capabilities share >50% keywords from task description | Combine into single role |
| Coordinator inline | Planner capability with 1 task, no explore | Coordinator handles inline, no separate role |
| Cap at 5 | More than 5 roles after initial assignment | Merge lowest-priority pairs (priority: researcher > designer > developer > writer > analyst > planner > tester) |
**Merge priority** (when two must merge, keep the higher-priority one as the role name):
1. developer (code-gen is hardest to merge)
2. researcher (context-gathering is foundational)
3. writer (document generation has specific patterns)
4. designer (design has specific outputs)
5. analyst (analysis can be absorbed by reviewer pattern)
6. planner (can be absorbed by coordinator)
7. tester (can be absorbed by developer or analyst)
## Phase 4: Output
Write `<session-folder>/task-analysis.json`:
```json
{
"task_description": "<original user input>",
"capabilities": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"tasks": [
{ "id": "RESEARCH-001", "description": "..." }
],
"artifacts": ["research-findings.md"]
}
],
"dependency_graph": {
"RESEARCH-001": [],
"DRAFT-001": ["RESEARCH-001"],
"ANALYSIS-001": ["DRAFT-001"]
},
"roles": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"task_count": 1,
"inner_loop": false
},
{
"name": "writer",
"prefix": "DRAFT",
"responsibility_type": "code-gen (docs)",
"task_count": 1,
"inner_loop": false
}
],
"complexity": {
"capability_count": 2,
"cross_domain_factor": false,
"parallel_tracks": 0,
"serial_depth": 2,
"total_score": 3,
"level": "low"
},
"artifacts": [
{ "name": "research-findings.md", "producer": "researcher", "path": "artifacts/research-findings.md" },
{ "name": "article-draft.md", "producer": "writer", "path": "artifacts/article-draft.md" }
]
}
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No capabilities detected | Default to single `general` role with TASK prefix |
| Circular dependency in graph | Break cycle at lowest-tier edge, warn |
| Task description too vague | Return minimal analysis, coordinator will AskUserQuestion |
| All capabilities merge into one | Valid -- single-role execution, no team overhead |

View File

@@ -0,0 +1,85 @@
# Command: dispatch
## Purpose
Create task chains from dynamic dependency graphs. Unlike v4's static mode-to-pipeline mapping, team-coordinate builds pipelines from the task-analysis.json produced by Phase 1.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task analysis | `<session-folder>/task-analysis.json` | Yes |
| Session file | `<session-folder>/team-session.json` | Yes |
| Role registry | `team-session.json#roles` | Yes |
| Scope | User requirements description | Yes |
## Phase 3: Task Chain Creation
### Workflow
1. **Read dependency graph** from `task-analysis.json#dependency_graph`
2. **Topological sort** tasks to determine creation order
3. **Validate** all task owners exist in role registry
4. **For each task** (in topological order):
```
TaskCreate({
subject: "<PREFIX>-<NNN>",
owner: "<role-name>",
description: "<task description from task-analysis>\nSession: <session-folder>\nScope: <scope>\nInnerLoop: <true|false>",
blockedBy: [<dependency-list from graph>],
status: "pending"
})
```
5. **Update team-session.json** with pipeline and tasks_total
6. **Validate** created chain
### Task Description Template
Every task description includes session path and inner loop flag:
```
<task description>
Session: <session-folder>
Scope: <scope>
InnerLoop: <true|false>
```
### InnerLoop Flag Rules
| Condition | InnerLoop |
|-----------|-----------|
| Role has 2+ serial same-prefix tasks | true |
| Role has 1 task | false |
| Tasks are parallel (no dependency between them) | false |
### Dependency Validation
| Check | Criteria |
|-------|----------|
| No orphan tasks | Every task is reachable from at least one root |
| No circular deps | Topological sort succeeds without cycle |
| All owners valid | Every task owner exists in team-session.json#roles |
| All blockedBy valid | Every blockedBy references an existing task subject |
| Session reference | Every task description contains `Session: <session-folder>` |
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Task count | Matches dependency_graph node count |
| Dependencies | Every blockedBy references an existing task subject |
| Owner assignment | Each task owner is in role registry |
| Session reference | Every task description contains `Session:` |
| Pipeline integrity | No disconnected subgraphs (warn if found) |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Circular dependency detected | Report cycle, halt task creation |
| Owner not in role registry | Error, coordinator must fix roles first |
| TaskCreate fails | Log error, report to coordinator |
| Duplicate task subject | Skip creation, log warning |
| Empty dependency graph | Error, task analysis may have failed |

View File

@@ -0,0 +1,274 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. Adapted from v4 for dynamic roles -- role names are read from `team-session.json#roles` instead of hardcoded. Includes `handleAdapt` for mid-pipeline capability gap handling.
## Constants
| Constant | 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 |
| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Role registry | session.roles[] | Yes |
**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name` rather than a static list. This is the key difference from v4.
## Phase 3: Handler Routing
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from session roles | handleCallback |
| 2 | Contains "capability_gap" | handleAdapt |
| 3 | Contains "check" or "status" | handleCheck |
| 4 | Contains "resume", "continue", or "next" | handleResume |
| 5 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Verify completion, update state, auto-advance.
```
Receive callback from [<role>]
+- Find matching active worker by role (from session.roles)
+- Is this a progress update (not final)? (Inner Loop intermediate task completion)
| +- YES -> Update session state, do NOT remove from active_workers -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- -> handleSpawnNext
| +- 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
```
**Fast-advance note**: A worker may have already spawned its successor via fast-advance. When processing a callback:
1. Check if the expected next task is already `in_progress` (fast-advanced)
2. If yes -> skip spawning that task, update active_workers to include the fast-advanced worker
3. If no -> normal handleSpawnNext
---
### Handler: handleCheck
Read-only status report. No pipeline advancement.
**Output format**:
```
[coordinator] Pipeline Status
[coordinator] Progress: <completed>/<total> (<percent>%)
[coordinator] Execution Graph:
<visual representation of dependency graph with status icons>
done=completed >>>=running o=pending .=not created
[coordinator] Active Workers:
> <subject> (<role>) - running <elapsed> [inner-loop: N/M tasks done]
[coordinator] Ready to spawn: <subjects>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
**Icon mapping**: completed=done, in_progress=>>>, pending=o, not created=.
**Graph rendering**: Read dependency_graph from task-analysis.json, render each node with status icon. Show parallel branches side-by-side.
Then STOP.
---
### Handler: handleResume
Check active worker completion, process results, advance pipeline.
```
Load active_workers from session
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- status = completed -> mark done, 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)
```
---
### Handler: handleSpawnNext
Find all ready tasks, spawn workers in background, update session, STOP.
```
Collect task states from TaskList()
+- completedSubjects: status = completed
+- inProgressSubjects: status = in_progress
+- readySubjects: pending + all blockedBy in completedSubjects
Ready tasks found?
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing in progress -> PIPELINE_COMPLETE -> Phase 5
+- HAS ready tasks -> for each:
+- Is task owner an Inner Loop role AND that role already has an active_worker?
| +- YES -> SKIP spawn (existing worker will pick it up via inner loop)
| +- NO -> normal spawn below
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked
+- Spawn worker (see spawn tool call below)
+- Add to session.active_workers
Update session file -> output summary -> STOP
```
**Spawn worker tool call** (one per ready task):
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: "<worker prompt from SKILL.md Coordinator Spawn Template>"
})
```
---
### Handler: handleAdapt
Handle mid-pipeline capability gap discovery. A worker reports `capability_gap` when it encounters work outside its scope.
```
Parse capability_gap message:
+- Extract: gap_description, requesting_role, suggested_capability
+- Validate gap is genuine:
+- Check existing roles in session.roles -> does any role cover this?
| +- YES -> redirect: SendMessage to that role's owner -> STOP
| +- NO -> genuine gap, proceed to role generation
+- Generate new role:
1. Read specs/role-template.md
2. Fill template with capability details from gap description
3. Write new role file to <session-folder>/roles/<new-role>.md
4. Add to session.roles[]
+- Create new task(s):
TaskCreate({
subject: "<NEW-PREFIX>-001",
owner: "<new-role>",
description: "<gap_description>\nSession: <session-folder>\nInnerLoop: false",
blockedBy: [<requesting task if sequential>],
status: "pending"
})
+- Update team-session.json: add role, increment tasks_total
+- Spawn new worker -> STOP
```
---
### Worker Failure Handling
When a worker has unexpected status (not completed, not in_progress):
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user: task reset, will retry on next resume
### Fast-Advance Failure Recovery
When coordinator detects a fast-advanced task has failed (task in_progress but no callback and worker gone):
```
handleCallback / handleResume detects:
+- Task is in_progress (was fast-advanced by predecessor)
+- No active_worker entry for this task
+- Original fast-advancing worker has already completed and exited
+- Resolution:
1. TaskUpdate -> reset task to pending
2. Remove stale active_worker entry (if any)
3. Log via team_msg (type: error, summary: "Fast-advanced task <ID> failed, resetting for retry")
4. -> handleSpawnNext (will re-spawn the task normally)
```
**Detection in handleResume**:
```
For each in_progress task in TaskList():
+- Has matching active_worker? -> normal, skip
+- No matching active_worker? -> orphaned (likely fast-advance failure)
+- Check creation time: if > 5 minutes with no progress callback
+- Reset to pending -> handleSpawnNext
```
**Prevention**: Fast-advance failures are self-healing. The coordinator reconciles orphaned tasks on every `resume`/`check` cycle.
### Consensus-Blocked Handling
When a worker reports `consensus_blocked` in its callback:
```
handleCallback receives message with consensus_blocked flag
+- Extract: divergence_severity, blocked_round, action_recommendation
+- Route by severity:
|
+- severity = HIGH
| +- Create REVISION task:
| +- Same role, same doc type, incremented suffix (e.g., DRAFT-001-R1)
| +- Description includes: divergence details + action items from discuss
| +- blockedBy: none (immediate execution)
| +- Max 1 revision per task (DRAFT-001 -> DRAFT-001-R1, no R2)
| +- If already revised once -> PAUSE, escalate to user
| +- Update session: mark task as "revised", log revision chain
|
+- severity = MEDIUM
| +- Proceed with warning: include divergence in next task's context
| +- Log action items to wisdom/issues.md
| +- Normal handleSpawnNext
|
+- severity = LOW
+- Proceed normally: treat as consensus_reached with notes
+- Normal handleSpawnNext
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches TaskList in_progress tasks |
| No orphaned tasks | Every in_progress task has an active_worker entry |
| Dynamic roles valid | All task owners exist in session.roles |
| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE |
| Fast-advance tracking | Detect tasks already in_progress via fast-advance, sync to active_workers |
| Fast-advance orphan check | in_progress tasks without active_worker entry -> reset to pending |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| 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) | Check for missing tasks, report to user |
| Fast-advance conflict | Coordinator reconciles, no duplicate spawns |
| Fast-advance task orphaned | Reset to pending, re-spawn via handleSpawnNext |
| Dynamic role file not found | Error, coordinator must regenerate from task-analysis |
| capability_gap from completed role | Validate gap, generate role if genuine |
| consensus_blocked HIGH | Create revision task (max 1) or pause for user |
| consensus_blocked MEDIUM | Proceed with warning, log to wisdom/issues.md |

View File

@@ -0,0 +1,233 @@
# Coordinator Role
Orchestrate the team-coordinate workflow: task analysis, dynamic role generation, task dispatching, progress monitoring, session state. The sole built-in role -- all worker roles are generated at runtime.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Analyze task -> Generate roles -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- Analyze user task to detect capabilities and build dependency graph
- Dynamically generate worker roles from specs/role-template.md
- Create team and spawn worker subagents in background
- Dispatch tasks with proper dependency chains from task-analysis.json
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence (team-session.json)
- Handle capability_gap reports (generate new roles mid-pipeline)
- Handle consensus_blocked HIGH verdicts (create revision tasks or pause)
- Detect fast-advance orphans on resume/check and reset to pending
### MUST NOT
- Execute task work directly (delegate to workers)
- Modify task output artifacts (workers own their deliverables)
- Call implementation subagents (code-developer, etc.) directly
- Skip dependency validation when creating task chains
- Generate more than 5 worker roles (merge if exceeded)
- Override consensus_blocked HIGH without user confirmation
> **Core principle**: coordinator is the orchestrator, not the executor. All actual work is delegated to dynamically generated worker roles.
---
## Entry Router
When coordinator is invoked, first detect the invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` from session roles | -> handleCallback |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Capability gap | Message contains "capability_gap" | -> handleAdapt |
| New session | None of above | -> Phase 0 |
For callback/check/resume/adapt: load `commands/monitor.md` 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/TC-*/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.completed_tasks <-> TaskList status (bidirectional sync)
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Detect fast-advance orphans (in_progress without recent activity) -> reset to pending
5. Determine remaining pipeline from reconciled state
6. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
7. Create missing tasks with correct blockedBy dependencies
8. Verify dependency chain integrity
9. Update session file with reconciled state
10. Kick first executable task's worker -> Phase 4
---
## Phase 1: Task Analysis
**Objective**: Parse user task, detect capabilities, build dependency graph, design roles.
**Workflow**:
1. **Parse user task description**
2. **Clarify if ambiguous** via AskUserQuestion:
- What is the scope? (specific files, module, project-wide)
- What deliverables are expected? (documents, code, analysis reports)
- Any constraints? (timeline, technology, style)
3. **Delegate to `commands/analyze-task.md`**:
- Signal detection: scan keywords -> infer capabilities
- Artifact inference: each capability -> default output type (.md)
- Dependency graph: build DAG of work streams
- Complexity scoring: count capabilities, cross-domain factor, parallel tracks
- Role minimization: merge overlapping, absorb trivial, cap at 5
4. **Output**: Write `<session>/task-analysis.json`
**Success**: Task analyzed, capabilities detected, dependency graph built, roles designed.
---
## Phase 2: Generate Roles + Initialize Session
**Objective**: Create session, generate dynamic role files, initialize shared infrastructure.
**Workflow**:
1. **Generate session ID**: `TC-<slug>-<date>` (slug from first 3 meaningful words of task)
2. **Create session folder structure**:
```
.workflow/.team/<session-id>/
+-- roles/
+-- artifacts/
+-- wisdom/
+-- explorations/
+-- discussions/
+-- .msg/
```
3. **Call TeamCreate** with team name derived from session ID
4. **Read `specs/role-template.md`** + `task-analysis.json`
5. **For each role in task-analysis.json#roles**:
- Fill role template with:
- role_name, prefix, responsibility_type from analysis
- Phase 2-4 content from responsibility type reference sections in template
- inner_loop flag from analysis (true if role has 2+ serial tasks)
- Task-specific instructions from task description
- Write generated role file to `<session>/roles/<role-name>.md`
6. **Register roles** in team-session.json#roles
7. **Initialize shared infrastructure**:
- `wisdom/learnings.md`, `wisdom/decisions.md`, `wisdom/issues.md` (empty with headers)
- `explorations/cache-index.json` (`{ "entries": [] }`)
- `shared-memory.json` (`{}`)
- `discussions/` (empty directory)
8. **Write team-session.json** with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], created_at
**Success**: Session created, role files generated, shared infrastructure initialized.
---
## Phase 3: Create Task Chain
**Objective**: Dispatch tasks based on dependency graph with proper dependencies.
Delegate to `commands/dispatch.md` which creates the full task chain:
1. Reads dependency_graph from task-analysis.json
2. Topological sorts tasks
3. Creates tasks via TaskCreate with correct blockedBy
4. Assigns owner based on role mapping from task-analysis.json
5. Includes `Session: <session-folder>` in every task description
6. Sets InnerLoop flag for multi-task roles
7. Updates team-session.json with pipeline and tasks_total
**Success**: All tasks created with correct dependency chains, session updated.
---
## Phase 4: Spawn-and-Stop
**Objective**: Spawn first batch of ready workers in background, then STOP.
**Design**: Spawn-and-Stop + Callback pattern, with worker fast-advance.
- Spawn workers with `Task(run_in_background: true)` -> immediately return
- Worker completes -> may fast-advance to next task OR SendMessage callback -> auto-advance
- User can use "check" / "resume" to manually advance
- Coordinator does one operation per invocation, then STOPS
**Workflow**:
1. Load `commands/monitor.md`
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
3. For each ready task -> spawn worker (see SKILL.md Coordinator Spawn Template)
- Use Standard Worker template for single-task roles
- Use Inner Loop Worker template for multi-task roles
4. Output status summary with execution graph
5. STOP
**Pipeline advancement** driven by three wake sources:
- Worker callback (automatic) -> Entry Router -> handleCallback
- User "check" -> handleCheck (status only)
- User "resume" -> handleResume (advance)
---
## Phase 5: Report + Next Steps
**Objective**: Completion report and follow-up options.
**Workflow**:
1. Load session state -> count completed tasks, duration
2. List all deliverables with output paths in `<session>/artifacts/`
3. Include discussion summaries (if inline discuss was used)
4. Summarize wisdom accumulated during execution
5. Update session status -> "completed"
6. Offer next steps: exit / view artifacts / extend with additional tasks
**Output format**:
```
[coordinator] ============================================
[coordinator] TASK COMPLETE
[coordinator]
[coordinator] Deliverables:
[coordinator] - <artifact-1.md> (<producer role>)
[coordinator] - <artifact-2.md> (<producer role>)
[coordinator]
[coordinator] Pipeline: <completed>/<total> tasks
[coordinator] Roles: <role-list>
[coordinator] Duration: <elapsed>
[coordinator]
[coordinator] Session: <session-folder>
[coordinator] ============================================
```
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect in task analysis, report to user, halt |
| Task description too vague | AskUserQuestion for clarification |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
| Role generation fails | Fall back to single general-purpose role |
| capability_gap reported | handleAdapt: generate new role, create tasks, spawn |
| All capabilities merge to one | Valid: single-role execution, reduced overhead |
| No capabilities detected | Default to single general role with TASK prefix |

View File

@@ -0,0 +1,432 @@
# Dynamic Role Template
Template used by coordinator to generate worker role.md files at runtime. Each generated role is written to `<session>/roles/<role-name>.md`.
## Template
```markdown
# Role: <role_name>
<role_description>
## Identity
- **Name**: `<role_name>` | **Tag**: `[<role_name>]`
- **Task Prefix**: `<prefix>-*`
- **Responsibility**: <responsibility_type>
<if inner_loop>
- **Mode**: Inner Loop (handle all `<prefix>-*` tasks in single agent)
</if>
## Boundaries
### MUST
- Only process `<prefix>-*` prefixed tasks
- All output (SendMessage, team_msg, logs) must carry `[<role_name>]` identifier
- Only communicate with coordinator via SendMessage
- Work strictly within <responsibility_type> responsibility scope
- Use fast-advance for simple linear successors (see SKILL.md Phase 5)
- Produce MD artifacts in `<session>/artifacts/`
<if inner_loop>
- Use subagent for heavy work (do not execute CLI/generation in main agent context)
- Maintain context_accumulator across tasks within the inner loop
- Loop through all `<prefix>-*` tasks before reporting to coordinator
</if>
### MUST NOT
- Execute work outside this role's responsibility scope
- 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 scope
- Omit `[<role_name>]` identifier in any output
- Fast-advance when multiple tasks are ready or at checkpoint boundaries
<if inner_loop>
- Execute heavy work (CLI calls, large document generation) in main agent (delegate to subagent)
- SendMessage to coordinator mid-loop (unless consensus_blocked HIGH or error count >= 3)
</if>
## Toolbox
| Tool | Purpose |
|------|---------|
<tools based on responsibility_type -- see reference sections below>
## Message Types
| Type | Direction | Description |
|------|-----------|-------------|
| `<prefix>_complete` | -> coordinator | Task completed with artifact path |
| `<prefix>_error` | -> coordinator | Error encountered |
| `capability_gap` | -> coordinator | Work outside role scope discovered |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <team-name>,
from: "<role_name>",
to: "coordinator",
type: <message-type>,
summary: "[<role_name>] <prefix> complete: <task-subject>",
ref: <artifact-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <team-name> --from <role_name> --to coordinator --type <message-type> --summary \"[<role_name>] <prefix> complete\" --ref <artifact-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `<prefix>-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: <phase2_name>
<phase2_content -- generated by coordinator based on responsibility type>
### Phase 3: <phase3_name>
<phase3_content -- generated by coordinator based on task specifics>
### Phase 4: <phase4_name>
<phase4_content -- generated by coordinator based on responsibility type>
<if inline_discuss>
### Phase 4b: Inline Discuss (optional)
After primary work, optionally call discuss subagent:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: "## Multi-Perspective Critique: <round-id>
See subagents/discuss-subagent.md for prompt template.
Perspectives: <specified by coordinator when generating this role>"
})
```
| Verdict | Severity | Action |
|---------|----------|--------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | Phase 5 SendMessage includes structured consensus_blocked format. Do NOT self-revise. |
| consensus_blocked | MEDIUM | Phase 5 SendMessage includes warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
</if>
<if inner_loop>
### Phase 5-L: Loop Completion (Inner Loop)
When more same-prefix tasks remain:
1. **TaskUpdate**: Mark current task completed
2. **team_msg**: Log task completion
3. **Accumulate summary**:
```
context_accumulator.append({
task: "<task-id>",
artifact: "<output-path>",
key_decisions: <from subagent return>,
discuss_verdict: <from Phase 4>,
summary: <from subagent return>
})
```
4. **Interrupt check**:
- consensus_blocked HIGH -> SendMessage -> STOP
- Error count >= 3 -> SendMessage -> STOP
5. **Loop**: Back to Phase 1
**Does NOT**: SendMessage to coordinator, Fast-Advance spawn.
### Phase 5-F: Final Report (Inner Loop)
When all same-prefix tasks are done:
1. **TaskUpdate**: Mark last task completed
2. **team_msg**: Log completion
3. **Summary report**: All tasks summary + discuss results + artifact paths
4. **Fast-Advance check**: Check cross-prefix successors
5. **SendMessage** or **spawn successor**
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report + Fast-Advance
<else>
### Phase 5: Report + Fast-Advance
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report + Fast-Advance
Standard report flow: team_msg log -> SendMessage with `[<role_name>]` prefix -> TaskUpdate completed -> Fast-Advance Check -> Loop to Phase 1 for next task.
</if>
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No <prefix>-* tasks available | Idle, wait for coordinator assignment |
| Context file not found | Notify coordinator, request location |
| Subagent fails | Retry once with fallback; still fails -> log error, continue next task |
| Fast-advance spawn fails | Fall back to SendMessage to coordinator |
<if inner_loop>
| Cumulative 3 task failures | SendMessage to coordinator, STOP inner loop |
| Agent crash mid-loop | Coordinator detects orphan on resume -> re-spawn -> resume from interrupted task |
</if>
| Work outside scope discovered | SendMessage capability_gap to coordinator |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
```
---
## Phase 2-4 Content by Responsibility Type
Reference sections for coordinator to fill when generating roles. Select the matching section based on `responsibility_type`.
### orchestration
**Phase 2: Context Assessment**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Shared memory | <session>/shared-memory.json | No |
| Prior artifacts | <session>/artifacts/ | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read shared-memory.json for cross-role context
3. Read prior artifacts (if any exist from upstream tasks)
4. Load wisdom files for accumulated knowledge
5. Optionally call explore subagent for codebase context
```
**Phase 3: Subagent Execution**
```
Delegate to appropriate subagent based on task:
Task({
subagent_type: "general-purpose",
run_in_background: false,
description: "<task-type> for <task-id>",
prompt: "## Task
- <task description>
- Session: <session-folder>
## Context
<prior artifacts + shared memory + explore results>
## Expected Output
Write artifact to: <session>/artifacts/<artifact-name>.md
Return JSON summary: { artifact_path, summary, key_decisions[], warnings[] }"
})
```
**Phase 4: Result Aggregation**
```
1. Verify subagent output artifact exists
2. Read artifact, validate structure/completeness
3. Update shared-memory.json with key findings
4. Write insights to wisdom/ files
```
### code-gen (docs)
**Phase 2: Load Prior Context**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Prior artifacts | <session>/artifacts/ from upstream tasks | Conditional |
| Shared memory | <session>/shared-memory.json | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read upstream artifacts (e.g., research findings for a writer)
3. Read shared-memory.json for cross-role context
4. Load wisdom for accumulated decisions
```
**Phase 3: Document Generation**
```
Task({
subagent_type: "universal-executor",
run_in_background: false,
description: "Generate <doc-type> for <task-id>",
prompt: "## Task
- Generate: <document type>
- Session: <session-folder>
## Prior Context
<upstream artifacts + shared memory>
## Instructions
<task-specific writing instructions from coordinator>
## Expected Output
Write document to: <session>/artifacts/<doc-name>.md
Return JSON: { artifact_path, summary, key_decisions[], sections_generated[], warnings[] }"
})
```
**Phase 4: Structure Validation**
```
1. Verify document artifact exists
2. Check document has expected sections
3. Validate no placeholder text remains
4. Update shared-memory.json with document metadata
```
### code-gen (code)
**Phase 2: Load Plan/Specs**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Plan/design artifacts | <session>/artifacts/ | Conditional |
| Shared memory | <session>/shared-memory.json | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read plan/design artifacts from upstream
3. Load shared-memory.json for implementation context
4. Load wisdom for conventions and patterns
```
**Phase 3: Code Implementation**
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Implement <task-id>",
prompt: "## Task
- <implementation description>
- Session: <session-folder>
## Plan/Design Context
<upstream artifacts>
## Instructions
<task-specific implementation instructions>
## Expected Output
Implement code changes.
Write summary to: <session>/artifacts/implementation-summary.md
Return JSON: { artifact_path, summary, files_changed[], key_decisions[], warnings[] }"
})
```
**Phase 4: Syntax Validation**
```
1. Run syntax check (tsc --noEmit or equivalent)
2. Verify all planned files exist
3. Check no broken imports
4. If validation fails -> attempt auto-fix (max 2 attempts)
5. Write implementation summary to artifacts/
```
### read-only
**Phase 2: Target Loading**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Target artifacts/files | From task description or upstream | Yes |
| Shared memory | <session>/shared-memory.json | No |
Loading steps:
1. Extract session path and target files from task description
2. Read target artifacts or source files for analysis
3. Load shared-memory.json for context
```
**Phase 3: Multi-Dimension Analysis**
```
Task({
subagent_type: "general-purpose",
run_in_background: false,
description: "Analyze <target> for <task-id>",
prompt: "## Task
- Analyze: <target description>
- Dimensions: <analysis dimensions from coordinator>
- Session: <session-folder>
## Target Content
<artifact content or file content>
## Expected Output
Write report to: <session>/artifacts/analysis-report.md
Return JSON: { artifact_path, summary, findings[], severity_counts: {critical, high, medium, low} }"
})
```
**Phase 4: Severity Classification**
```
1. Verify analysis report exists
2. Classify findings by severity (Critical/High/Medium/Low)
3. Update shared-memory.json with key findings
4. Write issues to wisdom/issues.md
```
### validation
**Phase 2: Environment Detection**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Implementation artifacts | Upstream code changes | Yes |
Loading steps:
1. Detect test framework from project files
2. Get changed files from implementation
3. Identify test command and coverage tool
```
**Phase 3: Test-Fix Cycle**
```
Task({
subagent_type: "test-fix-agent",
run_in_background: false,
description: "Test-fix for <task-id>",
prompt: "## Task
- Run tests and fix failures
- Session: <session-folder>
- Max iterations: 5
## Changed Files
<from upstream implementation>
## Expected Output
Write report to: <session>/artifacts/test-report.md
Return JSON: { artifact_path, pass_rate, coverage, iterations_used, remaining_failures[] }"
})
```
**Phase 4: Result Analysis**
```
1. Check pass rate >= 95%
2. Check coverage meets threshold
3. Generate test report with pass/fail counts
4. Update shared-memory.json with test results
```

View File

@@ -0,0 +1,133 @@
# Discuss Subagent
Lightweight multi-perspective critique engine. Called inline by any role needing peer review. Perspectives are dynamic -- specified by the calling role, not pre-defined.
## Design
Unlike team-lifecycle-v4's fixed perspective definitions (product, technical, quality, risk, coverage), team-coordinate uses **dynamic perspectives** passed in the prompt. The calling role decides what viewpoints matter for its artifact.
## Invocation
Called by roles after artifact creation:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: `## Multi-Perspective Critique: <round-id>
### Input
- Artifact: <artifact-path>
- Round: <round-id>
- Session: <session-folder>
### Perspectives
<Dynamic perspective list -- each entry defines: name, cli_tool, role_label, focus_areas>
Example:
| Perspective | CLI Tool | Role | Focus Areas |
|-------------|----------|------|-------------|
| Feasibility | gemini | Engineer | Implementation complexity, technical risks, resource needs |
| Clarity | codex | Editor | Readability, logical flow, completeness of explanation |
| Accuracy | gemini | Domain Expert | Factual correctness, source reliability, claim verification |
### Execution Steps
1. Read artifact from <artifact-path>
2. For each perspective, launch CLI analysis in background:
Bash(command="ccw cli -p 'PURPOSE: Analyze from <role> perspective for <round-id>
TASK: <focus-areas>
MODE: analysis
CONTEXT: Artifact content below
EXPECTED: JSON with strengths[], weaknesses[], suggestions[], rating (1-5)
CONSTRAINTS: Output valid JSON only
Artifact:
<artifact-content>' --tool <cli-tool> --mode analysis", run_in_background=true)
3. Wait for all CLI results
4. Divergence detection:
- High severity: any rating <= 2, critical issue identified
- Medium severity: rating spread (max - min) >= 3, or single perspective rated <= 2 with others >= 3
- Low severity: minor suggestions only, all ratings >= 3
5. Consensus determination:
- No high-severity divergences AND average rating >= 3.0 -> consensus_reached
- Otherwise -> consensus_blocked
6. Synthesize:
- Convergent themes (agreed by 2+ perspectives)
- Divergent views (conflicting assessments)
- Action items from suggestions
7. Write discussion record to: <session-folder>/discussions/<round-id>-discussion.md
### Discussion Record Format
# Discussion Record: <round-id>
**Artifact**: <artifact-path>
**Perspectives**: <list>
**Consensus**: reached / blocked
**Average Rating**: <avg>/5
## Convergent Themes
- <theme>
## Divergent Views
- **<topic>** (<severity>): <description>
## Action Items
1. <item>
## Ratings
| Perspective | Rating |
|-------------|--------|
| <name> | <n>/5 |
### Return Value
**When consensus_reached**:
Return a summary string with:
- Verdict: consensus_reached
- Average rating
- Key action items (top 3)
- Discussion record path
**When consensus_blocked**:
Return a structured summary with:
- Verdict: consensus_blocked
- Severity: HIGH | MEDIUM | LOW
- Average rating
- Divergence summary: top 3 divergent points with perspective attribution
- Action items: prioritized list of required changes
- Recommendation: revise | proceed-with-caution | escalate
- Discussion record path
### Error Handling
- Single CLI fails -> fallback to direct Claude analysis for that perspective
- All CLI fail -> generate basic discussion from direct artifact reading
- Artifact not found -> return error immediately`
})
```
## Integration with Calling Role
The calling role is responsible for:
1. **Before calling**: Complete primary artifact output
2. **Calling**: Invoke discuss subagent with appropriate dynamic perspectives
3. **After calling**:
| Verdict | Severity | Role Action |
|---------|----------|-------------|
| consensus_reached | - | Include action items in Phase 5 report, proceed normally |
| consensus_blocked | HIGH | Include divergence details in Phase 5 SendMessage. Do NOT self-revise -- coordinator decides. |
| consensus_blocked | MEDIUM | Include warning in Phase 5 SendMessage. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. Proceed normally. |
**SendMessage format for consensus_blocked (HIGH or MEDIUM)**:
```
[<role>] <task-id> complete. Discuss <round-id>: consensus_blocked (severity=<severity>)
Divergences: <top-3-divergent-points>
Action items: <prioritized-items>
Recommendation: <revise|proceed-with-caution|escalate>
Artifact: <artifact-path>
Discussion: <discussion-record-path>
```

View File

@@ -0,0 +1,120 @@
# Explore Subagent
Shared codebase exploration utility with centralized caching. Callable by any role needing code context.
## Invocation
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: `Explore codebase for: <query>
Focus angle: <angle>
Keywords: <keyword-list>
Session folder: <session-folder>
## Cache Check
1. Read <session-folder>/explorations/cache-index.json (if exists)
2. Look for entry with matching angle
3. If found AND file exists -> read cached result, return summary
4. If not found -> proceed to exploration
## Exploration
<angle-specific-focus-from-table-below>
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
## Output Schema
{
"angle": "<angle>",
"query": "<query>",
"relevant_files": [
{ "path": "...", "rationale": "...", "role": "...", "discovery_source": "...", "key_symbols": [] }
],
"patterns": [],
"dependencies": [],
"external_refs": [],
"_metadata": { "created_by": "<calling-role>", "timestamp": "...", "cache_key": "..." }
}
Return summary: file count, pattern count, top 5 files, output path`
})
```
## Cache Mechanism
### Cache Index Schema
`<session-folder>/explorations/cache-index.json`:
```json
{
"entries": [
{
"angle": "architecture",
"keywords": ["auth", "middleware"],
"file": "explore-architecture.json",
"created_by": "analyst",
"created_at": "2026-02-27T10:00:00Z",
"file_count": 15
}
]
}
```
### Cache Lookup Rules
| Condition | Action |
|-----------|--------|
| Exact angle match exists | Return cached result |
| No match | Execute exploration, cache result |
| Cache file missing but index has entry | Remove stale entry, re-explore |
### Cache Invalidation
Cache is session-scoped. No explicit invalidation needed -- each session starts fresh. If a role suspects stale data, it can pass `force_refresh: true` in the prompt to bypass cache.
## Angle Focus Guide
| Angle | Focus Points | Typical Caller |
|-------|-------------|----------------|
| architecture | Layer boundaries, design patterns, component responsibilities, ADRs | any |
| dependencies | Import chains, external libraries, circular dependencies, shared utilities | any |
| modularity | Module interfaces, separation of concerns, extraction opportunities | any |
| integration-points | API endpoints, data flow between modules, event systems | any |
| security | Auth/authz logic, input validation, sensitive data handling, middleware | any |
| dataflow | Data transformations, state propagation, validation points | any |
| performance | Bottlenecks, N+1 queries, blocking operations, algorithm complexity | any |
| error-handling | Try-catch blocks, error propagation, recovery strategies, logging | any |
| patterns | Code conventions, design patterns, naming conventions, best practices | any |
| testing | Test files, coverage gaps, test patterns, mocking strategies | any |
| general | Broad semantic search for topic-related code | any |
## Exploration Strategies
### Low Complexity (direct search)
For simple queries, use ACE semantic search:
```
mcp__ace-tool__search_context(project_root_path="<project-root>", query="<query>")
```
ACE failure fallback: `rg -l '<keywords>' --type ts`
### Medium/High Complexity (multi-angle)
For complex queries, call cli-explore-agent per angle. The calling role determines complexity and selects angles.
## Search Tool Priority
| Tool | Priority | Use Case |
|------|----------|----------|
| mcp__ace-tool__search_context | P0 | Semantic search |
| Grep / Glob | P1 | Pattern matching |
| cli-explore-agent | Deep | Multi-angle exploration |
| WebSearch | P3 | External docs |