
Team Coordinate
- 46 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Support for team-coordinate
About
Provides workflow support for team-coordinate. Solo builders use this to streamline development.
- team-coordinate
Team Coordinate by the numbers
- 46 all-time installs (skills.sh)
- Ranked #1,663 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill team-coordinateAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 46 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Support for team-coordinate
Files
Team Coordinate
Universal team coordination skill: analyze task -> generate role-specs -> dispatch -> execute -> deliver. Only the coordinator is built-in. All worker roles are dynamically generated as lightweight role-spec files and spawned via the team-worker agent.
Architecture
+---------------------------------------------------+
| Skill(skill="team-coordinate") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (built-in)
Phase 0-5 orchestration
|
+-------+-------+-------+-------+
v v v v v
[team-worker agents, each loaded with a dynamic role-spec]
(roles generated at runtime from task analysis)
CLI Tools (callable by any worker):
ccw cli --mode analysis - analysis and exploration
ccw cli --mode write - code generation and modificationShared Constants
| Constant | Value |
|---|---|
| Session prefix | TC |
| Session path | .workflow/.team/TC-<slug>-<date>/ |
| Worker agent | team-worker |
| Message bus | mcp__ccw-tools__team_msg(session_id=<session-id>, ...) |
| CLI analysis | ccw cli --mode analysis |
| CLI write | ccw cli --mode write |
| Max roles | 5 |
Role Router
This skill is coordinator-only. Workers do NOT invoke this skill -- they are spawned as team-worker agents directly.
Input Parsing
Parse $ARGUMENTS. No --role needed -- always routes to coordinator.
Role Registry
Only coordinator is statically registered. All other roles are dynamic, stored as role-specs in session.
| Role | File | Type |
|---|---|---|
| coordinator | roles/coordinator/role.md | built-in orchestrator |
| (dynamic) | <session>/role-specs/<role-name>.md | runtime-generated role-spec |
Tech Profile Scan: When generating role-specs for analysis/exploration roles (responsibility_type includes "analysis", "exploration", or "research"), append to Phase 3:
After exploration, includetech_profilein state_update with detected signals (e.g.,sql_detected,auth_detected,perf_sensitive) and evidence file paths. This enables coordinator to evaluate specialist injection needs.
CLI Tool Usage
Workers can use CLI tools for analysis and code operations:
| Tool | Purpose |
|---|---|
| ccw cli --mode analysis | Analysis, exploration, pattern discovery |
| ccw cli --mode write | Code generation, modification, refactoring |
Dispatch
Always route to coordinator. Coordinator reads roles/coordinator/role.md and executes its phases.
Orchestration Mode
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 role-specs + 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 + completion actionUser Commands (wake paused coordinator):
| Command | Action |
|---|---|
check / status | Output execution status graph, no advancement |
resume / continue | Check worker states, advance next step |
revise <TASK-ID> [feedback] | Revise specific task with optional feedback |
feedback <text> | Inject feedback into active pipeline |
improve [dimension] | Auto-improve weakest quality dimension |
---
Coordinator Spawn Template
v2 Worker Spawn (all roles)
When coordinator spawns workers, use team-worker agent with role-spec path:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})Inner Loop: Determined per-task from task description InnerLoop: field, not per-role:
- Serial chain (2+ tasks, each blockedBy previous):
inner_loop: true— single worker loops - Parallel tasks (no mutual blockedBy):
inner_loop: false— separate workers per task - Single-task roles:
inner_loop: false
---
Completion Action
When pipeline completes (all tasks done), coordinator presents an interactive choice:
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Export Results", description: "Export deliverables to target directory, then clean" }
]
}]
})Action Handlers
| Choice | Steps |
|---|---|
| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-coordinate', args='resume')" |
| Export Results | AskUserQuestion(target path) -> copy artifacts to target -> Archive & Clean |
---
Specs Reference
| Spec | Purpose |
|---|---|
| specs/pipelines.md | Dynamic pipeline model, task naming, dependency graph |
| specs/role-spec-template.md | Template for dynamic role-spec generation |
| specs/quality-gates.md | Quality thresholds and scoring dimensions |
| specs/knowledge-transfer.md | Context transfer protocols between roles |
---
Session Directory
.workflow/.team/TC-<slug>-<date>/
+-- team-session.json # Session state + dynamic role registry
+-- task-analysis.json # Phase 1 output: capabilities, dependency graph
+-- role-specs/ # Dynamic role-spec definitions (generated Phase 2)
| +-- <role-1>.md # Lightweight: frontmatter + Phase 2-4 only
| +-- <role-2>.md
+-- artifacts/ # All MD deliverables from workers
| +-- <artifact>.md
+-- .msg/ # Team message bus + state
| +-- messages.jsonl # Message log
| +-- meta.json # Session metadata + cross-role state
+-- 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>.mdteam-session.json Schema
{
"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_spec": "role-specs/<role-name>.md"
}
],
"pipeline": {
"dependency_graph": {},
"tasks_total": 0,
"tasks_completed": 0
},
"active_workers": [],
"completed_tasks": [],
"completion_action": "interactive",
"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, set dependencies via TaskUpdate({ addBlockedBy }) 7. Kick first executable task -> Phase 4 coordination loop
---
Error Handling
| Scenario | Resolution |
|---|---|
| Unknown command | Error with available command list |
| Dynamic role-spec not found | Error, coordinator may need to regenerate |
| Command file not found | Fallback to inline execution |
| CLI tool fails | Worker proceeds with direct implementation, logs warning |
| Explore cache corrupt | Clear cache, re-explore |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| capability_gap reported | Coordinator generates new role-spec via handleAdapt |
| Completion action fails | Default to Keep Active, log warning |
Command: analyze-task
Purpose
Parse user task description -> detect required capabilities -> build dependency graph -> design dynamic roles with role-spec metadata. Outputs structured task-analysis.json with frontmatter fields for role-spec generation.
CRITICAL CONSTRAINT
TEXT-LEVEL analysis only. MUST NOT read source code or explore codebase.
Allowed:
- Parse user task description text
- AskUserQuestion for clarification
- Keyword-to-capability mapping
- Write
task-analysis.json
If task context requires codebase knowledge, set needs_research: true. Phase 2 will spawn researcher worker.
When to Use
| Trigger | Condition |
|---|---|
| New task | Coordinator Phase 1 receives task description |
| Re-analysis | User provides revised requirements |
| Adapt | handleAdapt extends analysis for new capability |
Strategy
- Delegation: Inline execution (coordinator processes directly)
- Mode: Text-level analysis only (no codebase reading)
- Output:
<session>/task-analysis.json
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.
No 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 2.5: Key File Inference
For each task, infer relevant files based on capability type and task keywords:
| Capability | File Inference Strategy |
|---|---|
| researcher | Extract domain keywords → map to likely directories (e.g., "auth" → src/auth/**, middleware/auth.ts) |
| developer | Extract feature/module keywords → map to source files (e.g., "payment" → src/payments/**, types/payment.ts) |
| designer | Look for architecture/config keywords → map to config/schema files |
| analyst | Extract target keywords → map to files under analysis |
| tester | Extract test target keywords → map to source + test files |
| writer | Extract documentation target → map to relevant source files for context |
| planner | No specific files (planning is abstract) |
Inference rules:
- Extract nouns and verbs from task description
- Match against common directory patterns (src/, lib/, components/, services/, utils/)
- Include related type definition files (types/, *.d.ts)
- For "fix bug" tasks, include error-prone areas (error handlers, validation)
- For "implement feature" tasks, include similar existing features as reference
Step 3: Dependency Graph Construction
Build a DAG of work streams using 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 (cap at 5).
Step 6: Role-Spec Metadata Assignment
For each role, determine frontmatter and generation hints:
| Field | Derivation |
|---|---|
prefix | From capability prefix (e.g., RESEARCH, DRAFT, IMPL) |
inner_loop | true if role has 2+ same-prefix tasks AND they form a serial chain (each blockedBy the previous). false if tasks are parallel (no mutual blockedBy) or role has only 1 task |
CLI tools | Suggested, not mandatory — coordinator may adjust based on task needs |
pattern_hint | Reference pattern name from role-spec-template (research/document/code/analysis/validation) — guides coordinator's Phase 2-4 composition, NOT a rigid template selector |
output_type | artifact (new files in session/artifacts/) / codebase (modify existing project files) / mixed (both) — determines verification strategy in Behavioral Traits |
message_types.success | <prefix>_complete |
message_types.error | error |
output_type derivation:
| Task Signal | output_type | Example |
|---|---|---|
| "write report", "analyze", "research" | artifact | New analysis-report.md in session |
| "update docs", "modify code", "fix bug" | codebase | Modify existing project files |
| "implement feature + write summary" | mixed | Code changes + implementation summary |
Phase 4: Output
Write <session-folder>/task-analysis.json:
{
"task_description": "<original user input>",
"capabilities": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"tasks": [
{
"id": "RESEARCH-001",
"goal": "What this task achieves and why",
"steps": [
"step 1: specific action with clear verb",
"step 2: specific action with clear verb",
"step 3: specific action with clear verb"
],
"key_files": [
"src/path/to/relevant.ts",
"src/path/to/other.ts"
],
"upstream_artifacts": [],
"success_criteria": "Measurable completion condition",
"constraints": "Scope limits, focus areas"
}
],
"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,
"role_spec_metadata": {
"CLI tools": ["explore"],
"pattern_hint": "research",
"output_type": "artifact",
"message_types": {
"success": "research_complete",
"error": "error"
}
}
}
],
"complexity": {
"capability_count": 2,
"cross_domain_factor": false,
"parallel_tracks": 0,
"serial_depth": 2,
"total_score": 3,
"level": "low"
},
"needs_research": false,
"artifacts": [
{ "name": "research-findings.md", "producer": "researcher", "path": "artifacts/research-findings.md" }
]
}Complexity Interpretation
CRITICAL: Complexity score is for role design optimization, NOT for skipping team workflow.
| Complexity | Team Structure | Coordinator Action |
|---|---|---|
| Low (1-2 roles) | Minimal team | Generate 1-2 role-specs, create team, spawn workers |
| Medium (2-3 roles) | Standard team | Generate role-specs, create team, spawn workers |
| High (3-5 roles) | Full team | Generate role-specs, create team, spawn workers |
All complexity levels use team-worker architecture:
- Single-role tasks still spawn team-worker agent
- Coordinator NEVER executes task work directly
- Team infrastructure provides session management, message bus, fast-advance
Purpose of complexity score:
- ✅ Determine optimal role count (merge vs separate)
- ✅ Guide dependency graph design
- ✅ Inform user about task scope
- ❌ NOT for deciding whether to use team workflow
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 via team-worker |
Command: dispatch
Purpose
Create task chains from dynamic dependency graphs. Builds pipelines from the task-analysis.json produced by Phase 1. Workers are spawned as team-worker agents with role-spec paths.
When to Use
| Trigger | Condition |
|---|---|
| After analysis | Phase 1 complete, task-analysis.json exists |
| After adapt | handleAdapt created new roles, needs new tasks |
| Re-dispatch | Pipeline restructuring (rare) |
Strategy
- Delegation: Inline execution (coordinator processes directly)
- Inputs: task-analysis.json + team-session.json
- Output: TaskCreate calls with dependency chains
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>",
description: "PURPOSE: <goal> | Success: <success_criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: <artifact-1.md>, <artifact-2.md>
- Key files: <file1>, <file2>
- Shared state: team_msg(operation="get_state", session_id=<session-id>)
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits>
---
InnerLoop: <true|false>
RoleSpec: <session-folder>/role-specs/<role-name>.md"
})
TaskUpdate({ taskId: "<PREFIX>-<NNN>", addBlockedBy: [<dependency-list from graph>], owner: "<role-name>" })5. Update team-session.json with pipeline and tasks_total 6. Validate created chain
Task Description Template
Every task description includes structured fields for clarity:
PURPOSE: <goal from task-analysis.json#tasks[].goal> | Success: <success_criteria from task-analysis.json#tasks[].success_criteria>
TASK:
- <step 1 from task-analysis.json#tasks[].steps[]>
- <step 2 from task-analysis.json#tasks[].steps[]>
- <step 3 from task-analysis.json#tasks[].steps[]>
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: <comma-separated list from task-analysis.json#tasks[].upstream_artifacts[]>
- Key files: <comma-separated list from task-analysis.json#tasks[].key_files[]>
- Shared state: team_msg(operation="get_state", session_id=<session-id>)
EXPECTED: <artifact path from task-analysis.json#capabilities[].artifacts[]> + <quality criteria based on capability type>
CONSTRAINTS: <constraints from task-analysis.json#tasks[].constraints>
---
InnerLoop: <true|false>
RoleSpec: <session-folder>/role-specs/<role-name>.mdField Mapping:
PURPOSE: Fromtask-analysis.json#capabilities[].tasks[].goal+success_criteriaTASK: Fromtask-analysis.json#capabilities[].tasks[].steps[]CONTEXT.Upstream artifacts: Fromtask-analysis.json#capabilities[].tasks[].upstream_artifacts[]CONTEXT.Key files: Fromtask-analysis.json#capabilities[].tasks[].key_files[]EXPECTED: Fromtask-analysis.json#capabilities[].artifacts[]+ quality criteriaCONSTRAINTS: Fromtask-analysis.json#capabilities[].tasks[].constraints
InnerLoop Flag Rules
| Condition | InnerLoop |
|---|---|
| Role has 2+ same-prefix tasks forming a serial chain (each blockedBy the previous) | true |
| Role has 1 task | false |
| Role has 2+ same-prefix tasks but they are parallel (no mutual blockedBy) | false |
| Mixed: some serial, some parallel within same role | Set per-task: true for serial chain members, false for parallel members |
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> |
| RoleSpec reference | Every task description contains RoleSpec: <path> |
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 |
Command: monitor
Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. Role names are read from team-session.json#roles. Workers are spawned as team-worker agents with role-spec paths. Includes handleComplete for pipeline completion action and handleAdapt for mid-pipeline capability gap handling.
When to Use
| Trigger | Condition |
|---|---|
| Worker callback | Message contains [role-name] from session roles |
| User command | "check", "status", "resume", "continue" |
| Capability gap | Worker reports capability_gap |
| Pipeline spawn | After dispatch, initial spawn needed |
| Pipeline complete | All tasks done |
Strategy
- Delegation: Inline execution with handler routing
- Beat model: ONE_STEP_PER_INVOCATION — one handler then STOP
- Workers: Spawned as team-worker via Agent() in background
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 |
| WORKER_AGENT | team-worker | All workers spawned as team-worker agents |
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. Role-spec paths are in session.roles[].role_spec.
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 | Pipeline detected as complete | handleComplete |
| 6 | 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 -> STOPFast-advance reconciliation: A worker may have already spawned its successor via fast-advance. When processing any callback or resume: 1. Read recent fast_advance messages from team_msg (type="fast_advance") 2. For each fast_advance message: add the spawned successor to active_workers if not already present 3. Check if the expected next task is already in_progress (fast-advanced) 4. If yes -> skip spawning that task (already running) 5. If no -> normal handleSpawnNext
---
Handler: handleCheck
Read-only status report. No pipeline advancement.
Worker Progress (from message bus):
Before generating status output, read worker milestones:
const progressMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "progress", last: 50
})
const blockerMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "blocker", last: 10
})
// Aggregate latest milestone per task
const taskProgress = {}
for (const msg of (progressMsgs.result?.messages || [])) {
const tid = msg.data?.task_id
if (tid && (!taskProgress[tid] || msg.ts > taskProgress[tid].ts)) {
taskProgress[tid] = { phase: msg.data.phase, pct: msg.data.progress_pct, ts: msg.ts }
}
}Include in status output:
- Per-worker latest milestone (phase + progress_pct) next to task status
- Active blockers section (if any blockerMsgs found)
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 refreshThen 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 team-worker agents 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 -> handleComplete
+- HAS ready tasks -> for each:
+- Parse task description `InnerLoop:` field (NOT session.roles[].inner_loop)
+- InnerLoop: true AND same-role worker already in active_workers?
| +- YES -> SKIP spawn (existing worker will pick it up via inner loop)
| +- NO -> normal spawn below (InnerLoop: false OR no active same-role worker)
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked (session_id=<session-id>)
+- Spawn team-worker (see spawn tool call below)
+- Add to session.active_workers
Update session file -> output summary -> STOPSpawn worker tool call (one per ready task):
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file to load Phase 2-4 domain instructions.`
})---
Handler: handleComplete
Pipeline complete. Execute completion action based on session configuration.
All tasks completed (no pending, no in_progress)
+- Generate pipeline summary:
| - Deliverables list with paths
| - Pipeline stats (tasks completed, duration)
| - Discussion verdicts (if any)
|
+- Read session.completion_action:
|
+- "interactive":
| AskUserQuestion({
| questions: [{
| question: "Team pipeline complete. What would you like to do?",
| header: "Completion",
| multiSelect: false,
| options: [
| { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" },
| { label: "Keep Active", description: "Keep session for follow-up work" },
| { label: "Export Results", description: "Export deliverables to target directory" }
| ]
| }]
| })
| +- "Archive & Clean":
| | Update session status="completed"
| | TeamDelete()
| | Output final summary with artifact paths
| +- "Keep Active":
| | Update session status="paused"
| | Output: "Resume with: Skill(skill='team-coordinate', args='resume')"
| +- "Export Results":
| AskUserQuestion for target directory
| Copy deliverables to target
| Execute Archive & Clean flow
|
+- "auto_archive":
| Execute Archive & Clean without prompt
|
+- "auto_keep":
Execute Keep Active without promptFallback: If completion action fails, default to Keep Active (session status="paused"), log warning.
---
Handler: handleAdapt
Handle mid-pipeline capability gap discovery. A worker reports capability_gap when it encounters work outside its scope.
CONSTRAINT: Maximum 5 worker roles per session. handleAdapt MUST enforce this limit.
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-spec generation
+- CHECK ROLE COUNT LIMIT (MAX 5 ROLES):
+- Count current roles in session.roles
+- If count >= 5:
+- Attempt to merge new capability into existing role
+- If merge NOT possible -> PAUSE, report to user
+- Generate new role-spec:
1. Read specs/role-spec-template.md
2. Fill template with: frontmatter (role, prefix, inner_loop, message_types) + Phase 2-4 content
3. Write to <session-folder>/role-specs/<new-role>.md
4. Add to session.roles[]
+- Create new task(s) via TaskCreate
+- Update team-session.json
+- Spawn new team-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:
handleCallback / handleResume detects:
+- Task is in_progress (was fast-advanced by predecessor)
+- No active_worker entry for this task
+- Resolution:
1. TaskUpdate -> reset task to pending
2. Remove stale active_worker entry (if any)
3. Log via team_msg (type: error)
4. -> handleSpawnNext (will re-spawn the task normally)Fast-Advance State Sync
On every coordinator wake (handleCallback, handleResume, handleCheck): 1. Read team_msg entries with type="fast_advance" since last coordinator wake 2. For each entry: sync active_workers with the spawned successor 3. This ensures coordinator's state reflects fast-advance decisions even before the successor's callback arrives
Consensus-Blocked Handling
handleCallback receives message with consensus_blocked flag
+- Route by severity:
+- severity = HIGH
| +- Create REVISION task (same role, incremented suffix)
| +- Max 1 revision per task. If already revised -> PAUSE, escalate to user
+- severity = MEDIUM
| +- Proceed with warning, log to wisdom/issues.md
| +- Normal handleSpawnNext
+- severity = LOW
+- Proceed normally, treat as consensus_reached with notesPhase 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 |
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 |
| Dynamic role-spec file not found | Error, coordinator must regenerate from task-analysis |
| capability_gap when role limit (5) reached | Attempt merge, else pause for user |
| Completion action fails | Default to Keep Active, log warning |
Coordinator Role
Orchestrate the team-coordinate workflow: task analysis, dynamic role-spec generation, task dispatching, progress monitoring, session state, and completion action. The sole built-in role -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent.
Identity
- Name:
coordinator| Tag:[coordinator] - Responsibility: Analyze task -> Generate role-specs -> Create team -> Dispatch tasks -> Monitor progress -> Completion action -> Report results
Boundaries
MUST
- Parse task description (text-level: keyword scanning, capability inference, dependency design)
- Dynamically generate worker role-specs from specs/role-spec-template.md
- Create team and spawn team-worker agents 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 role-specs mid-pipeline)
- Handle consensus_blocked HIGH verdicts (create revision tasks or pause)
- Detect fast-advance orphans on resume/check and reset to pending
- Execute completion action when pipeline finishes
MUST NOT
- Read source code or perform codebase exploration (delegate to worker roles)
- Execute task work directly (delegate to workers)
- Modify task output artifacts (workers own their deliverables)
- Call implementation agents (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
- Spawn workers with
general-purposeagent (MUST useteam-worker)
---
Message Types
| Type | Direction | Trigger |
|---|---|---|
| state_update | outbound | Session init, pipeline progress |
| task_unblocked | outbound | Task ready for execution |
| fast_advance | inbound | Worker skipped coordinator |
| capability_gap | inbound | Worker needs new capability |
| error | inbound | Worker failure |
| impl_complete | inbound | Worker task done |
| consensus_blocked | inbound | Discussion verdict conflict |
Message Bus Protocol
All coordinator state changes MUST be logged to team_msg BEFORE SendMessage:
1. team_msg(operation="log", ...) — log the event 2. SendMessage(...) — communicate to worker/user 3. TaskUpdate(...) — update task state
Read state before every handler: team_msg(operation="get_state", session_id=<session-id>)
---
Command Execution Protocol
When coordinator needs to execute a command (analyze-task, 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 1 needs task analysis
-> Read roles/coordinator/commands/analyze-task.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Analysis)
-> Execute Phase 4 (Output)
-> Continue to Phase 2Toolbox
| Tool | Type | Purpose |
|---|---|---|
| commands/analyze-task.md | Command | Task analysis and role design |
| commands/dispatch.md | Command | Task chain creation |
| commands/monitor.md | Command | Pipeline monitoring and handlers |
| team-worker | Subagent | Worker spawning |
| TeamCreate / TeamDelete | System | Team lifecycle |
| TaskCreate / TaskList / TaskGet / TaskUpdate | System | Task lifecycle |
| team_msg | System | Message bus operations |
| SendMessage | System | Inter-agent communication |
| AskUserQuestion | System | User interaction |
---
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 |
| Pipeline complete | All tasks completed, no pending/in_progress | -> handleComplete |
| Interrupted session | Active/paused session exists in .workflow/.team/TC-* | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Task Analysis) |
For callback/check/resume/adapt/complete: load @commands/monitor.md and execute the appropriate handler, then STOP.
Router Implementation
1. Load session context (if exists):
- Scan
.workflow/.team/TC-*/team-session.jsonfor active/paused sessions - If found, extract
session.roles[].namefor callback detection
2. Parse $ARGUMENTS for detection keywords
3. Route to handler:
- For monitor handlers: Read
commands/monitor.md, execute matched handler section, STOP - For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Task Analysis below
---
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, set dependencies via TaskUpdate({ addBlockedBy }) 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.
Constraint: This is TEXT-LEVEL analysis only. No source code reading, no codebase exploration.
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
- Role-spec metadata: Generate frontmatter fields (prefix, inner_loop, additional_members, message_types)
4. Output: Write <session>/task-analysis.json
5. If `needs_research: true`: Phase 2 will spawn researcher worker first
Success: Task analyzed, capabilities detected, dependency graph built, roles designed with role-spec metadata.
CRITICAL - Team Workflow Enforcement:
Regardless of complexity score or role count, coordinator MUST:
- ✅ Always proceed to Phase 2 (generate role-specs)
- ✅ Always create team and spawn workers via team-worker agent
- ❌ NEVER execute task work directly, even for single-role low-complexity tasks
- ❌ NEVER skip team workflow based on complexity assessment
Single-role execution is still team-based - just with one worker. The team architecture provides:
- Consistent message bus communication
- Session state management
- Artifact tracking
- Fast-advance capability
- Resume/recovery mechanisms
---
Phase 2: Generate Role-Specs + Initialize Session
Objective: Create session, generate dynamic role-spec files, initialize shared infrastructure.
Workflow:
1. Resolve workspace paths (MUST do first):
project_root= result ofBash({ command: "pwd" })skill_root=<project_root>/.claude/skills/team-coordinate
2. Generate session ID: TC-<slug>-<date> (slug from first 3 meaningful words of task)
3. Create session folder structure:
.workflow/.team/<session-id>/
+-- role-specs/
+-- artifacts/
+-- wisdom/
+-- explorations/
+-- discussions/
+-- .msg/4. Call TeamCreate with team name derived from session ID
5. Read `specs/role-spec-template.md` for Behavioral Traits + Reference Patterns
6. For each role in task-analysis.json#roles:
- Fill YAML frontmatter: role, prefix, inner_loop, additional_members, message_types
- Compose Phase 2-4 content (NOT copy from template):
- Phase 2: Derive input sources and context loading steps from task description + upstream dependencies
- Phase 3: Describe execution goal (WHAT to achieve) from task description — do NOT prescribe specific CLI tool or approach
- Phase 4: Combine Behavioral Traits (from template) + output_type (from task analysis) to compose verification steps
- Reference Patterns may guide phase structure, but task description determines specific content
- Write generated role-spec to
<session>/role-specs/<role-name>.md
7. Register roles in team-session.json#roles (with role_spec path instead of role_file)
8. Initialize shared infrastructure:
wisdom/learnings.md,wisdom/decisions.md,wisdom/issues.md(empty with headers)explorations/cache-index.json({ "entries": [] })discussions/(empty directory)
9. Initialize pipeline metadata via team_msg:
// 使用 team_msg 将 pipeline 元数据写入 .msg/meta.json
// 注意: 此处为动态角色,执行时需将 <placeholders> 替换为 task-analysis.json 中生成的实际角色列表
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<mode>",
pipeline_stages: ["<role1>", "<role2>", "<...dynamic-roles>"],
roles: ["coordinator", "<role1>", "<role2>", "<...dynamic-roles>"],
team_name: "<team-name>" // 从 session ID 或任务描述中提取
}
})10. Write team-session.json with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], completion_action="interactive", created_at
11. Check `needs_research` flag from task-analysis.json:
- If
true: Spawn researcher worker (role-spec now exists from step 6) to gather codebase context - Wait for researcher callback
- Merge research findings into task context
- Update task-analysis.json with enriched context
- If
false: Skip, proceed to Phase 3
Success: Session created, role-spec 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, then sets dependencies via TaskUpdate({ addBlockedBy }) 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.
Workflow: 1. Load @commands/monitor.md 2. Find tasks with: status=pending, blockedBy all resolved, owner assigned 3. For each ready task -> spawn team-worker (see SKILL.md Coordinator Spawn Template) 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 + Completion Action
Objective: Completion report, interactive completion choice, 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. Output report:
[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] ============================================6. Execute Completion Action (based on session.completion_action):
| Mode | Behavior |
|---|---|
interactive | AskUserQuestion with Archive/Keep/Export options |
auto_archive | Execute Archive & Clean without prompt |
auto_keep | Execute Keep Active without prompt |
Interactive handler: See SKILL.md Completion Action section.
---
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-spec generation fails | Fall back to single general-purpose role |
| capability_gap reported | handleAdapt: generate new role-spec, 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 |
| Completion action fails | Default to Keep Active, log warning |
Knowledge Transfer Protocols
1. Transfer Channels
| Channel | Scope | Mechanism | When to Use |
|---|---|---|---|
| Artifacts | Producer -> Consumer | Write to <session>/artifacts/<name>.md, consumer reads in Phase 2 | Structured deliverables (reports, plans, specs) |
| State Updates | Cross-role | team_msg(operation="log", type="state_update", data={...}) / team_msg(operation="get_state", session_id=<session-id>) | Key findings, decisions, metadata (small, structured data) |
| Wisdom | Cross-task | Append to <session>/wisdom/{learnings,decisions,conventions,issues}.md | Patterns, conventions, risks discovered during execution |
| Context Accumulator | Intra-role (inner loop) | In-memory array, passed to each subsequent task in same-prefix loop | Prior task summaries within same role's inner loop |
| Exploration Cache | Cross-role | <session>/explorations/cache-index.json + per-angle JSON | Codebase discovery results, prevents duplicate exploration |
2. Context Loading Protocol (Phase 2)
Every role MUST load context in this order before starting work.
| Step | Action | Required |
|---|---|---|
| 1 | Extract session path from task description | Yes |
| 2 | team_msg(operation="get_state", session_id=<session-id>) | Yes |
| 3 | Read artifact files from upstream state's ref paths | Yes |
| 4 | Read <session>/wisdom/*.md if exists | Yes |
| 5 | Check <session>/explorations/cache-index.json before new exploration | If exploring |
| 6 | For inner_loop roles: load context_accumulator from prior tasks | If inner_loop |
Loading rules:
- Never skip step 2 -- state contains key decisions and findings
- If
refpath in state does not exist, log warning and continue - Wisdom files are append-only -- read all entries, newest last
3. Context Publishing Protocol (Phase 4)
| Step | Action | Required |
|---|---|---|
| 1 | Write deliverable to <session>/artifacts/<task-id>-<name>.md | Yes |
| 2 | Send team_msg(type="state_update") with payload (see schema below) | Yes |
| 3 | Append wisdom entries for learnings, decisions, issues found | If applicable |
4. State Update Schema
Sent via team_msg(type="state_update") on task completion.
{
"status": "task_complete",
"task_id": "<TASK-NNN>",
"ref": "<session>/artifacts/<filename>",
"key_findings": [
"Finding 1",
"Finding 2"
],
"decisions": [
"Decision with rationale"
],
"files_modified": [
"path/to/file.ts"
],
"verification": "self-validated | peer-reviewed | tested"
}Field rules:
ref: Always an artifact path, never inline contentkey_findings: Max 5 items, each under 100 charsdecisions: Include rationale, not just the choicefiles_modified: Only for implementation tasksverification: One ofself-validated,peer-reviewed,tested
Write state (namespaced by role):
team_msg(operation="log", session_id=<session-id>, from=<role>, type="state_update", data={
"<role_name>": { "key_findings": [...], "scope": "..." }
})Read state:
team_msg(operation="get_state", session_id=<session-id>)
// Returns merged state from all state_update messages5. Exploration Cache Protocol
Prevents redundant research across tasks and discussion rounds.
| Step | Action |
|---|---|
| 1 | Read <session>/explorations/cache-index.json |
| 2 | If angle already explored, read cached result from explore-<angle>.json |
| 3 | If not cached, perform exploration |
| 4 | Write result to <session>/explorations/explore-<angle>.json |
| 5 | Update cache-index.json with new entry |
cache-index.json format:
{
"entries": [
{
"angle": "competitor-analysis",
"file": "explore-competitor-analysis.json",
"created_by": "RESEARCH-001",
"timestamp": "2026-01-15T10:30:00Z"
}
]
}Rules:
- Cache key is the exploration
angle(normalized to kebab-case) - Cache entries never expire within a session
- Any role can read cached explorations; only the creator updates them
Pipeline Definitions — Team Coordinate
Dynamic Pipeline Model
team-coordinate does NOT have a static pipeline. All pipelines are generated at runtime from task-analysis.json based on the user's task description.
Pipeline Generation Process
Phase 1: analyze-task.md
-> Signal detection -> capability mapping -> dependency graph
-> Output: task-analysis.json
Phase 2: dispatch.md
-> Read task-analysis.json dependency graph
-> Create TaskCreate entries per dependency node
-> Set blockedBy chains from graph edges
-> Output: TaskList with correct DAG
Phase 3-N: monitor.md
-> handleSpawnNext: spawn ready tasks as team-worker agents
-> handleCallback: mark completed, advance pipeline
-> Repeat until all tasks doneDynamic Task Naming
| Capability | Prefix | Example |
|---|---|---|
| researcher | RESEARCH | RESEARCH-001 |
| developer | IMPL | IMPL-001 |
| analyst | ANALYSIS | ANALYSIS-001 |
| designer | DESIGN | DESIGN-001 |
| tester | TEST | TEST-001 |
| writer | DRAFT | DRAFT-001 |
| planner | PLAN | PLAN-001 |
| (default) | TASK | TASK-001 |
Dependency Graph Structure
task-analysis.json encodes the pipeline as adjacency list (task ID -> blockedBy array):
{
"dependency_graph": {
"RESEARCH-001": [],
"IMPL-001": ["RESEARCH-001"],
"TEST-001": ["IMPL-001"]
}
}Role mapping comes from task-analysis.json#capabilities[].tasks[], not from the dependency graph itself.
Role-Worker Map
Dynamic — loaded from session role-specs at runtime:
<session>/role-specs/<role-name>.md -> team-worker agentRole-spec files contain YAML frontmatter:
---
role: <role-name>
prefix: <PREFIX>
inner_loop: <true|false>
output_tag: "[<role-name>]"
message_types:
success: <type>
error: error
---Checkpoint
| Trigger | Behavior |
|---|---|
| capability_gap reported | handleAdapt: generate new role-spec, spawn new worker |
| consensus_blocked HIGH | Create REVISION task or pause for user |
| All tasks complete | handleComplete: interactive completion action |
Specs Reference
- role-spec-template.md — Template for generating dynamic role-specs
- quality-gates.md — Quality thresholds and scoring dimensions
- knowledge-transfer.md — Context transfer protocols between roles
Quality Gate Integration
Dynamic pipelines reference quality thresholds from specs/quality-gates.md.
| Gate Point | Trigger | Criteria Source |
|---|---|---|
| After artifact production | Producer role Phase 4 | Behavioral Traits in role-spec |
| After validation tasks | Tester/analyst completion | quality-gates.md thresholds |
| Pipeline completion | All tasks done | Aggregate scoring |
Issue classification: Error (blocks) > Warning (proceed with justification) > Info (log for future).
Quality Gates
1. Quality Thresholds
| Result | Score | Action |
|---|---|---|
| Pass | >= 80% | Report completed |
| Review | 60-79% | Report completed with warnings |
| Fail | < 60% | Retry Phase 3 (max 2 retries) |
2. Scoring Dimensions
| Dimension | Weight | Criteria |
|---|---|---|
| Completeness | 25% | All required outputs present with substantive content |
| Consistency | 25% | Terminology, formatting, cross-references are uniform |
| Accuracy | 25% | Outputs are factually correct and verifiable against sources |
| Depth | 25% | Sufficient detail for downstream consumers to act on deliverables |
Score = weighted average of all dimensions (0-100 per dimension).
3. Dynamic Role Quality Checks
Quality checks vary by output_type (from task-analysis.json role metadata).
output_type: artifact
| Check | Pass Criteria |
|---|---|
| Artifact exists | File written to <session>/artifacts/ |
| Content non-empty | Substantive content, not just headers |
| Format correct | Expected format (MD, JSON) matches deliverable |
| Cross-references | All references to upstream artifacts resolve |
output_type: codebase
| Check | Pass Criteria |
|---|---|
| Files modified | Claimed files actually changed (Read to confirm) |
| Syntax valid | No syntax errors in modified files |
| No regressions | Existing functionality preserved |
| Summary artifact | Implementation summary written to artifacts/ |
output_type: mixed
All checks from both artifact and codebase apply.
4. Verification Protocol
Derived from Behavioral Traits in role-spec-template.md.
| Step | Action | Required |
|---|---|---|
| 1 | Verify all claimed files exist via Read | Yes |
| 2 | Confirm artifact written to <session>/artifacts/ | Yes |
| 3 | Check verification summary fields present | Yes |
| 4 | Score against quality dimensions | Yes |
| 5 | Apply threshold -> Pass/Review/Fail | Yes |
On Fail: Retry Phase 3 (max 2 retries). After 2 retries, report partial_completion.
On Review: Proceed with warnings logged to <session>/wisdom/issues.md.
5. Code Review Dimensions
For REVIEW-* or validation tasks during implementation pipelines.
Quality
| Check | Severity |
|---|---|
| Empty catch blocks | Error |
as any type casts | Warning |
@ts-ignore / @ts-expect-error | Warning |
console.log in production code | Warning |
| Unused imports/variables | Info |
Security
| Check | Severity |
|---|---|
| Hardcoded secrets/credentials | Error |
| SQL injection vectors | Error |
eval() or Function() usage | Error |
innerHTML assignment | Warning |
| Missing input validation | Warning |
Architecture
| Check | Severity |
|---|---|
| Circular dependencies | Error |
| Deep cross-boundary imports (3+ levels) | Warning |
| Files > 500 lines | Warning |
| Functions > 50 lines | Info |
Requirements Coverage
| Check | Severity |
|---|---|
| Core functionality implemented | Error if missing |
| Acceptance criteria covered | Error if missing |
| Edge cases handled | Warning |
| Error states handled | Warning |
6. Issue Classification
| Class | Label | Action |
|---|---|---|
| Error | Must fix | Blocks progression, must resolve before proceeding |
| Warning | Should fix | Should resolve, can proceed with justification |
| Info | Nice to have | Optional improvement, log for future |
Dynamic Role-Spec Template
Template used by coordinator to generate lightweight worker role-spec files at runtime. Each generated role-spec is written to <session>/role-specs/<role-name>.md.
Key difference from v1: Role-specs contain ONLY Phase 2-4 domain logic + YAML frontmatter. All shared behavior (Phase 1 Task Discovery, Phase 5 Report/Fast-Advance, Message Bus, Consensus, Inner Loop) is built into the team-worker agent.
Template
---
role: <role_name>
prefix: <PREFIX>
inner_loop: <true|false>
output_tag: "[<role_name>]"
CLI tools: [<CLI tool-names>]
message_types:
success: <prefix>_complete
error: error
---
# <Role Name> — Phase 2-4
## Phase 2: <phase2_name>
<phase2_content>
## Phase 3: <phase3_name>
<phase3_content>
## Phase 4: <phase4_name>
<phase4_content>
## Error Handling
| Scenario | Resolution |
|----------|------------|
<error_entries>Frontmatter Fields
| Field | Required | Description |
|---|---|---|
role | Yes | Role name matching session registry |
prefix | Yes | Task prefix to filter (e.g., RESEARCH, DRAFT, IMPL) |
inner_loop | Yes | Whether team-worker loops through same-prefix tasks |
CLI tools | No | Array of CLI tool types this role may call |
output_tag | Yes | Output tag for all messages, e.g., [researcher] |
message_types | Yes | Message type mapping for team_msg |
message_types.success | Yes | Type string for successful completion |
message_types.error | Yes | Type string for errors (usually "error") |
Design Rules
| Rule | Description |
|---|---|
| Phase 2-4 only | No Phase 1 (Task Discovery) or Phase 5 (Report) — team-worker handles these |
| No message bus code | No team_msg calls — team-worker handles logging |
| No consensus handling | No consensus_reached/blocked logic — team-worker handles routing |
| No inner loop logic | No Phase 5-L/5-F — team-worker handles looping |
| ~80 lines target | Lightweight, domain-focused |
| No pseudocode | Decision tables + text + tool calls only |
<placeholder> notation | Use angle brackets for variable substitution |
| Reference CLI tools by name | team-worker resolves invocation from its delegation templates |
Generated Role-Spec Structure
Every generated role-spec MUST include these blocks:
Identity Block (mandatory — first section of generated spec)
Tag: [<role_name>] | Prefix: <PREFIX>-*
Responsibility: <one-line from task analysis>Boundaries Block (mandatory — after Identity)
### MUST
- <3-5 rules derived from task analysis>
### MUST NOT
- Execute work outside assigned prefix
- Modify artifacts from other roles
- Skip Phase 4 verificationBehavioral Traits
All dynamically generated role-specs MUST embed these traits into Phase 4. Coordinator copies this section verbatim into every generated role-spec as a Phase 4 appendix.
Design principle: Constrain behavioral characteristics (accuracy, feedback, quality gates), NOT specific actions (which tool, which CLI tool, which path). Tasks are diverse — the coordinator composes task-specific Phase 2-3 instructions, while these traits ensure execution quality regardless of task type.
Accuracy — outputs must be verifiable
- Files claimed as created → Read to confirm file exists and has content
- Files claimed as modified → Read to confirm content actually changed
- Analysis claimed as complete → artifact file exists in
<session>/artifacts/
Feedback Contract — completion report must include evidence
Phase 4 must produce a verification summary with these fields:
| Field | When Required | Content |
|---|---|---|
files_produced | New files created | Path list |
files_modified | Existing files changed | Path + before/after line count |
artifacts_written | Always | Paths in <session>/artifacts/ |
verification_method | Always | How verified: Read confirm / syntax check / diff |
Quality Gate — verify before reporting complete
- Phase 4 MUST verify Phase 3's actual output (not planned output)
- Verification fails → retry Phase 3 (max 2 retries)
- Still fails → report
partial_completionwith details, NOTcompleted - Update shared state via
team_msg(operation="log", type="state_update", data={...})after verification passes
Quality thresholds from specs/quality-gates.md:
- Pass >= 80%: report completed
- Review 60-79%: report completed with warnings
- Fail < 60%: retry Phase 3 (max 2)
Error Protocol
- Primary approach fails → try alternative (different CLI tool / different tool)
- 2 retries exhausted → escalate to coordinator with failure details
- NEVER: skip verification and report completed
---
Reference Patterns
Coordinator MAY reference these patterns when composing Phase 2-4 content for a role-spec. These are structural guidance, not mandatory templates. The task description determines specific behavior — patterns only suggest common phase structures.
Research / Exploration
- Phase 2: Define exploration scope + load prior knowledge from shared state and wisdom
- Phase 3: Explore via CLI tools, direct tool calls, or codebase search — approach chosen by agent
- Phase 4: Verify findings documented (Behavioral Traits) + update shared state
Document / Content
- Phase 2: Load upstream artifacts + read target files (if modifying existing docs)
- Phase 3: Create new documents OR modify existing documents — determined by task, not template
- Phase 4: Verify documents exist with expected content (Behavioral Traits) + update shared state
Code Implementation
- Phase 2: Load design/spec artifacts from upstream
- Phase 3: Implement code changes — CLI tool choice and approach determined by task complexity
- Phase 4: Syntax check + file verification (Behavioral Traits) + update shared state
Analysis / Audit
- Phase 2: Load analysis targets (artifacts or source files)
- Phase 3: Multi-dimension analysis — perspectives and depth determined by task
- Phase 4: Verify report exists + severity classification (Behavioral Traits) + update shared state
Tech Profile Scan: When generating role-specs for analysis/exploration roles (responsibility_type includes "analysis", "exploration", or "research"), append to Phase 3:
After exploration, includetech_profilein state_update with detected signals (e.g.,sql_detected,auth_detected,perf_sensitive) and evidence file paths. This enables coordinator to evaluate specialist injection needs.
Validation / Testing
- Phase 2: Detect test framework + identify changed files from upstream
- Phase 3: Run test-fix cycle — iteration count and strategy determined by task
- Phase 4: Verify pass rate + coverage (Behavioral Traits) + update shared state
---
Knowledge Transfer Protocol
Full protocol: specs/knowledge-transfer.md
Generated role-specs Phase 2 MUST declare which upstream sources to load. Generated role-specs Phase 4 MUST include state update and artifact publishing.
---
Generated Role-Spec Validation
Coordinator verifies before writing each role-spec:
| Check | Criteria |
|---|---|
| Frontmatter complete | All required fields present (role, prefix, inner_loop, output_tag, message_types, CLI tools) |
| Identity block | Tag, prefix, responsibility defined |
| Boundaries | MUST and MUST NOT rules present |
| Phase 2 | Context loading sources specified |
| Phase 3 | Execution goal clear, not prescriptive about tools |
| Phase 4 | Behavioral Traits copied verbatim |
| Error Handling | Table with 3+ scenarios |
| Line count | Target ~80 lines (max 120) |
| No built-in overlap | No Phase 1/5, no message bus code, no consensus handling |