Add role and skill router templates for v3 style execution

- Introduced a comprehensive role template for generating per-role execution detail files, including purpose, style rules, and structured phases.
- Added a skill router template to facilitate role-based routing in SKILL.md, detailing input parsing, role registry, orchestration mode, and shared infrastructure.
- Both templates adhere to v3 conventions, emphasizing clarity and structured decision-making through markdown tables and diagrams.
This commit is contained in:
catlog22
2026-02-26 16:32:17 +08:00
parent 653ad10475
commit 1a1ca389f4
15 changed files with 5438 additions and 1723 deletions

View File

@@ -0,0 +1,820 @@
# Role Command Template
Template for generating command files in `roles/<role-name>/commands/<command>.md` (v3 style).
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand command file structure |
| Phase 3 | Apply with role-specific content |
## Style Rules
Generated output follows v3 conventions:
| Rule | Description |
|------|-------------|
| No JS pseudocode | All logic uses text + decision tables + flow symbols |
| Code blocks = tool calls only | Only Task(), Bash(), Read(), Grep() etc. |
| `<placeholder>` in output | Not `${variable}` in generated content |
| Decision tables | Strategy selection, error routing all use tables |
| Self-contained | Each command executable independently |
> **Note**: The template itself uses `{{handlebars}}` for variable substitution during Phase 3 generation. The **generated output** must not contain `{{handlebars}}` or JS pseudocode.
---
## Template
```markdown
# Command: {{command_name}}
## Purpose
{{command_description}}
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
{{#each context_inputs}}
| {{this.name}} | {{this.source}} | {{this.required}} |
{{/each}}
## Phase 3: Core Work
{{core_work_content}}
## Phase 4: Validation
{{validation_content}}
## Error Handling
| Scenario | Resolution |
|----------|------------|
{{#each error_handlers}}
| {{this.scenario}} | {{this.resolution}} |
{{/each}}
```
---
## 7 Pre-built Command Patterns
Each pattern below provides the complete v3-style structure. During Phase 3 generation, select the matching pattern and customize with team-specific content.
### 1. explore.md (Multi-angle Exploration)
**Maps to**: Orchestration roles, Phase 2
**Delegation**: Subagent Fan-out
```markdown
# Command: explore
## Purpose
Multi-angle codebase exploration using parallel exploration agents. Discovers patterns, dependencies, and architecture before planning.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task description | TaskGet result | Yes |
| Project root | `git rev-parse --show-toplevel` | Yes |
| Existing explorations | <session-folder>/explorations/ | No |
| Wisdom | <session-folder>/wisdom/ | No |
## Phase 3: Core Work
### Angle Selection
Determine exploration angles from task description:
| Signal in Description | Angle |
|-----------------------|-------|
| architect, structure, design | architecture |
| pattern, convention, style | patterns |
| depend, import, module | dependencies |
| test, spec, coverage | testing |
| No signals matched | general + patterns (default) |
### Execution Strategy
| Angle Count | Strategy |
|-------------|----------|
| 1 angle | Single agent exploration |
| 2-4 angles | Parallel agents, one per angle |
**Per-angle agent spawn**:
\`\`\`
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore: <angle>",
prompt: "Explore the codebase from the perspective of <angle>.
Focus on: <task-description>
Project root: <project-root>
Report findings as structured markdown with file references."
})
\`\`\`
### Result Aggregation
After all agents complete:
1. Merge key findings across all angles (deduplicate)
2. Collect relevant file paths (deduplicate)
3. Extract discovered patterns
4. Write aggregated results to `<session-folder>/explorations/<task-id>.md`
### Output Format
\`\`\`
## Exploration Results
### Angles Explored: [list]
### Key Findings
- [finding with file:line reference]
### Relevant Files
- [file path with relevance note]
### Patterns Found
- [pattern name: description]
\`\`\`
## Phase 4: Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| All angles covered | Compare planned vs completed | All planned angles explored |
| Findings non-empty | Check result count | At least 1 finding per angle |
| File references valid | Verify referenced files exist | >= 80% files exist |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Agent returns no results | Retry with broader search scope |
| Agent timeout | Use partial results, note incomplete angles |
| Project root not found | Fall back to current directory |
| Exploration cache exists | Load cached, skip re-exploration |
```
### 2. analyze.md (Multi-perspective Analysis)
**Maps to**: Read-only analysis roles, Phase 3
**Delegation**: CLI Fan-out
```markdown
# Command: analyze
## Purpose
Multi-perspective code analysis using parallel CLI calls. Each perspective produces severity-ranked findings with file:line references.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Target files | `git diff --name-only HEAD~1` or `--cached` | Yes |
| Plan file | <session-folder>/plan/plan.json | No |
| Wisdom | <session-folder>/wisdom/ | No |
**File discovery**:
\`\`\`
Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")
\`\`\`
## Phase 3: Core Work
### Perspective Selection
Determine analysis perspectives from task description:
| Signal in Description | Perspective |
|-----------------------|-------------|
| security, auth, inject, xss | security |
| performance, speed, optimize, memory | performance |
| quality, clean, maintain, debt | code-quality |
| architect, pattern, structure | architecture |
| No signals matched | code-quality + architecture (default) |
### Execution Strategy
| Perspective Count | Strategy |
|-------------------|----------|
| 1 perspective | Single CLI call |
| 2-4 perspectives | Parallel CLI calls, one per perspective |
**Per-perspective CLI call**:
\`\`\`
Bash("ccw cli -p \"PURPOSE: Analyze code from <perspective> perspective
TASK: Review changes in: <file-list>
MODE: analysis
CONTEXT: @<file-patterns>
EXPECTED: Findings with severity, file:line references, remediation
CONSTRAINTS: Focus on <perspective>\" --tool gemini --mode analysis", { run_in_background: true })
\`\`\`
### Finding Aggregation
After all perspectives complete:
1. Parse findings from each CLI response
2. Classify by severity: Critical / High / Medium / Low
3. Deduplicate across perspectives
4. Sort by severity then by file location
### Output Format
\`\`\`
## Analysis Results
### Perspectives Analyzed: [list]
### Findings by Severity
#### Critical
- [finding with file:line]
#### High
- [finding]
#### Medium
- [finding]
#### Low
- [finding]
\`\`\`
## Phase 4: Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| All perspectives covered | Compare planned vs completed | All perspectives analyzed |
| Findings have file refs | Check file:line format | >= 90% findings have references |
| No duplicate findings | Dedup check | No identical findings |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| CLI tool unavailable | Fall back to secondary tool |
| CLI returns empty | Retry with broader scope |
| Too many findings | Prioritize critical/high, summarize medium/low |
| Target files empty | Report no changes to analyze |
```
### 3. implement.md (Code Implementation)
**Maps to**: Code generation roles, Phase 3
**Delegation**: Sequential Delegation
```markdown
# Command: implement
## Purpose
Code implementation via subagent delegation with batch routing. Reads plan tasks and executes code changes, grouping by module for efficiency.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Plan file | <session-folder>/plan/plan.json | Yes |
| Task files | <session-folder>/plan/.task/<task-id>.json | Yes |
| Wisdom conventions | <session-folder>/wisdom/conventions.md | No |
**Loading steps**:
1. Extract plan path from task description
2. Read plan.json -> get task list
3. Read each task file for detailed specs
4. Load coding conventions from wisdom
## Phase 3: Core Work
### Strategy Selection
| Task Count | Strategy | Description |
|------------|----------|-------------|
| <= 2 | Direct | Inline Edit/Write by this role |
| 3-5 | Single agent | One code-developer subagent for all tasks |
| > 5 | Batch agent | Group by module, one agent per batch |
### Direct Strategy (1-2 tasks)
For each task, for each file in task spec:
1. Read existing file (if modifying)
2. Apply changes via Edit or Write
3. Verify file saved
### Agent Strategy (3+ tasks)
**Single agent spawn**:
\`\`\`
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Implement <N> tasks",
prompt: "## Goal
<plan-summary>
## Tasks
<task-list-with-descriptions>
Complete each task according to its convergence criteria."
})
\`\`\`
**Batch agent** (> 5 tasks): Group tasks by module/directory, spawn one agent per batch using the template above.
### Output Tracking
After implementation:
1. Get list of changed files: `Bash("git diff --name-only")`
2. Count completed vs total tasks
3. Record changed file paths for validation phase
## Phase 4: Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Syntax clean | Language-specific check (tsc, python -c, etc.) | No syntax errors |
| All files created | Verify plan-specified files exist | All files present |
| Import resolution | Check for broken imports | All imports resolve |
**Auto-fix on failure** (max 2 attempts):
| Attempt | Action |
|---------|--------|
| 1 | Parse error, apply targeted fix |
| 2 | Delegate fix to code-developer subagent |
| Failed | Report remaining issues to coordinator |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Plan file not found | Notify coordinator, request plan path |
| Agent fails on task | Retry once, then mark task as blocked |
| Syntax errors after impl | Attempt auto-fix, report if unresolved |
| File conflict | Check git status, resolve or report |
```
### 4. validate.md (Test-Fix Cycle)
**Maps to**: Validation roles, Phase 3
**Delegation**: Sequential Delegation
```markdown
# Command: validate
## Purpose
Iterative test-fix cycle with max iteration control. Runs tests, identifies failures, delegates fixes, and re-validates until passing or max iterations reached.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Test command | Auto-detect from project config | Yes |
| Changed files | `git diff --name-only` | Yes |
| Plan file | <session-folder>/plan/plan.json | No |
**Test command detection**:
| Detection Signal | Test Command |
|-----------------|--------------|
| package.json has "test" script | `npm test` |
| pytest.ini or conftest.py exists | `pytest` |
| Makefile has "test" target | `make test` |
| go.mod exists | `go test ./...` |
| No signal detected | Notify coordinator |
## Phase 3: Core Work
### Test-Fix Cycle
| Step | Action | Exit Condition |
|------|--------|----------------|
| 1. Run tests | `Bash("<test-command> 2>&1 || true")` | - |
| 2. Parse results | Extract pass/fail counts | - |
| 3. Check pass rate | Compare against threshold | Pass rate >= 95% -> exit SUCCESS |
| 4. Extract failures | Parse failing test names and errors | - |
| 5. Delegate fix | Spawn code-developer subagent | - |
| 6. Increment counter | iteration++ | iteration >= 5 -> exit MAX_REACHED |
| 7. Loop | Go to Step 1 | - |
**Fix delegation**:
\`\`\`
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Fix test failures (iteration <N>)",
prompt: "Test failures:
<test-output>
Fix the failing tests. Changed files: <file-list>"
})
\`\`\`
### Outcome Routing
| Outcome | Action |
|---------|--------|
| SUCCESS (pass rate >= 95%) | Proceed to Phase 4 |
| MAX_REACHED (5 iterations) | Report failures, mark for manual intervention |
| ENV_ERROR (test env broken) | Report environment issue to coordinator |
## Phase 4: Validation
| Metric | Source | Threshold |
|--------|--------|-----------|
| Pass rate | Final test run | >= 95% |
| Iterations used | Counter | Report count |
| Remaining failures | Last test output | List details |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No test command found | Notify coordinator |
| Max iterations exceeded | Report failures, suggest manual intervention |
| Test environment broken | Report environment issue |
| Flaky tests detected | Re-run once to confirm, exclude if consistently flaky |
```
### 5. review.md (Multi-dimensional Review)
**Maps to**: Read-only analysis roles (reviewer type), Phase 3
**Delegation**: CLI Fan-out
```markdown
# Command: review
## Purpose
Multi-dimensional code review producing a verdict (BLOCK/CONDITIONAL/APPROVE) with categorized findings across quality, security, architecture, and requirements dimensions.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Plan file | <session-folder>/plan/plan.json | Yes |
| Git diff | `git diff HEAD~1` or `git diff --cached` | Yes |
| Modified files | From git diff --name-only | Yes |
| Test results | Tester output (if available) | No |
| Wisdom | <session-folder>/wisdom/ | No |
## Phase 3: Core Work
### Dimension Overview
| Dimension | Focus | What to Detect |
|-----------|-------|----------------|
| Quality | Code correctness, type safety, clean code | Empty catch, ts-ignore, any type, console.log |
| Security | Vulnerability patterns, secret exposure | Hardcoded secrets, SQL injection, eval, XSS |
| Architecture | Module structure, coupling, file size | Circular deps, deep imports, large files |
| Requirements | Acceptance criteria coverage | Unmet criteria, missing error handling, missing tests |
### Per-Dimension Detection
For each dimension, scan modified files using pattern detection:
**Example: Quality scan for console statements**:
\`\`\`
Grep(pattern="console\\.(log|debug|info)", path="<file-path>", output_mode="content", "-n"=true)
\`\`\`
**Example: Architecture scan for deep imports**:
\`\`\`
Grep(pattern="from\\s+['\"](\\.\\./){3,}", path="<file-path>", output_mode="content", "-n"=true)
\`\`\`
### Requirements Verification
1. Read plan file -> extract acceptance criteria section
2. For each criterion -> extract keywords (4+ char meaningful words)
3. Search modified files for keyword matches
4. Score coverage:
| Match Rate | Status |
|------------|--------|
| >= 70% | Met |
| 40-69% | Partial |
| < 40% | Unmet |
### Verdict Routing
| Verdict | Criteria | Action |
|---------|----------|--------|
| BLOCK | Any critical-severity issues found | Must fix before merge |
| CONDITIONAL | High or medium issues, no critical | Should address, can merge with tracking |
| APPROVE | Only low issues or none | Ready to merge |
### Report Format
\`\`\`
# Code Review Report
**Verdict**: <BLOCK|CONDITIONAL|APPROVE>
## Blocking Issues (if BLOCK)
- **<type>** (<file>:<line>): <message>
## Review Dimensions
### Quality Issues
**CRITICAL** (<count>)
- <message> (<file>:<line>)
### Security Issues
(same format per severity)
### Architecture Issues
(same format per severity)
### Requirements Issues
(same format per severity)
## Recommendations
1. <actionable recommendation>
\`\`\`
## Phase 4: Validation
| Field | Description |
|-------|-------------|
| Total issues | Sum across all dimensions and severities |
| Critical count | Must be 0 for APPROVE |
| Blocking issues | Listed explicitly in report header |
| Dimensions covered | Must be 4/4 |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Plan file not found | Skip requirements dimension, note in report |
| Git diff empty | Report no changes to review |
| File read fails | Skip file, note in report |
| No modified files | Report empty review |
| Codex unavailable | Skip codex review dimension, report 3-dimension review |
```
### 6. dispatch.md (Task Distribution)
**Maps to**: Coordinator role, Phase 3
**Delegation**: Direct (coordinator acts directly)
```markdown
# Command: dispatch
## Purpose
Task chain creation with dependency management. Creates all pipeline tasks with correct blockedBy relationships and role-based ownership.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Pipeline definition | SKILL.md Pipeline Definitions | Yes |
| Task metadata | SKILL.md Task Metadata Registry | Yes |
| Session folder | From Phase 2 initialization | Yes |
| Mode | From Phase 1 requirements | Yes |
## Phase 3: Core Work
### Pipeline Selection
Select pipeline based on mode:
| Mode | Pipeline | Task Count |
|------|----------|------------|
{{#each pipeline_modes}}
| {{this.mode}} | {{this.pipeline}} | {{this.task_count}} |
{{/each}}
### Task Creation Flow
For each task in the selected pipeline (in dependency order):
1. **Create task**:
\`\`\`
TaskCreate({
subject: "<TASK-ID>: <description>",
description: "<detailed-description>\n\nSession: <session-folder>",
activeForm: "<TASK-ID> in progress"
})
\`\`\`
2. **Set owner and dependencies**:
\`\`\`
TaskUpdate({
taskId: <new-task-id>,
owner: "<role-name>",
addBlockedBy: [<dependency-task-ids>]
})
\`\`\`
3. Record created task ID for downstream dependency references
### Dependency Mapping
Follow SKILL.md Task Metadata Registry for:
- Task ID naming convention
- Role assignment (owner field)
- Dependencies (blockedBy relationships)
- Task description with session folder reference
### Parallel Task Handling
| Condition | Action |
|-----------|--------|
| Tasks share same blockedBy and no mutual dependency | Create both, they run in parallel |
| N parallel tasks for same role | Use instance-specific owner: `<role>-1`, `<role>-2` |
## Phase 4: Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| All tasks created | Compare pipeline spec vs TaskList | Count matches |
| Dependencies correct | Verify blockedBy for each task | All deps point to valid tasks |
| Owners assigned | Check owner field | Every task has valid role owner |
| No orphan tasks | Verify all tasks reachable from pipeline start | No disconnected tasks |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Task creation fails | Retry, then report to user |
| Dependency cycle detected | Flatten dependencies, warn |
| Role not spawned yet | Queue task, spawn role first |
| Task prefix conflict | Log warning, proceed |
```
### 7. monitor.md (Message-Driven Coordination)
**Maps to**: Coordinator role, Phase 4
**Delegation**: Message-Driven (no polling)
```markdown
# Command: monitor
## Purpose
Message-driven coordination. Team members (spawned in Phase 2) execute tasks autonomously and report via SendMessage. Coordinator receives messages and routes next actions.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Pipeline state | TaskList() | Yes |
| Session file | <session-folder>/team-session.json | Yes |
| Team config | Team member list | Yes |
## Phase 3: Core Work
### Design Principles
| Principle | Description |
|-----------|-------------|
| No re-spawning | Team members already spawned in Phase 2 -- do NOT spawn again here |
| No polling loops | No `while` + `sleep` + status check (wastes API turns) |
| Event-driven | Worker SendMessage is the trigger signal |
| One beat per wake | Coordinator processes one event then STOPs |
### Entry Handlers
When coordinator wakes, route based on Entry Router detection:
| Handler | Trigger | Actions |
|---------|---------|---------|
| handleCallback | Worker `[role-name]` message received | 1. Log received message 2. Check task status 3. Route to next action |
| handleCheck | User says "check"/"status" | 1. Load TaskList 2. Output status graph 3. STOP (no advancement) |
| handleResume | User says "resume"/"continue" | 1. Load TaskList 2. Find ready tasks 3. Spawn/notify workers 4. STOP |
### handleCallback Flow
1. Identify sender role from message tag `[role-name]`
2. Log received message via team_msg
3. Load TaskList for current state
4. Route based on message content:
| Message Content | Action |
|-----------------|--------|
| Contains "fix_required" or "error" | Assess severity -> escalate to user if critical |
| Normal completion | Check pipeline progress (see below) |
5. Check pipeline progress:
| State | Condition | Action |
|-------|-----------|--------|
| All done | completed count >= total pipeline tasks | -> Phase 5 |
| Tasks unblocked | pending tasks with empty blockedBy | Notify/spawn workers for unblocked tasks |
| Checkpoint | Pipeline at spec->impl transition | Pause, ask user to `resume` |
| Stalled | No ready + no running + has pending | Report blocking point |
6. Output status summary -> STOP
### handleCheck Flow (Status Only)
1. Load all tasks via TaskList
2. Build status overview:
\`\`\`
Pipeline Status:
Completed: <N>/<total>
In Progress: <list>
Pending: <list>
Blocked: <list with blockedBy details>
\`\`\`
3. STOP (no pipeline advancement)
### handleResume Flow
1. Load TaskList
2. Find tasks with: status=pending, blockedBy all resolved
3. For each ready task:
| Condition | Action |
|-----------|--------|
| Worker already spawned and idle | SendMessage to worker: "Task <subject> unblocked, please proceed" |
| Worker not spawned | Spawn worker using SKILL.md Spawn Template |
4. Output status summary -> STOP
### Status Graph Format
\`\`\`
Pipeline Progress: <completed>/<total>
[DONE] TASK-001 (role) - description
[DONE] TASK-002 (role) - description
[>> ] TASK-003 (role) - description <- in_progress
[ ] TASK-004 (role) - description <- blocked by TASK-003
...
\`\`\`
## Phase 4: Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Message routed | Verify handler executed | Handler completed without error |
| State consistent | TaskList reflects actions taken | Tasks updated correctly |
| No orphan workers | All spawned workers have assigned tasks | No idle workers without tasks |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Teammate reports error | Assess severity -> retry SendMessage or escalate to user |
| Task stuck (no callback) | Send follow-up to teammate, 2x -> suggest respawn |
| Critical issue beyond scope | AskUserQuestion: retry/skip/terminate |
| Session file corrupted | Rebuild state from TaskList |
```
---
## Variable Reference
| Variable | Source | Description |
|----------|--------|-------------|
| `{{command_name}}` | Command identifier | e.g., "explore", "analyze" |
| `{{command_description}}` | One-line description | What this command does |
| `{{context_inputs}}` | Array of {name, source, required} | Context loading table rows |
| `{{core_work_content}}` | Generated from pattern | Phase 3 content |
| `{{validation_content}}` | Generated from pattern | Phase 4 content |
| `{{error_handlers}}` | Array of {scenario, resolution} | Error handling table rows |
| `{{pipeline_modes}}` | config.pipeline_modes | Array of {mode, pipeline, task_count} for dispatch |
## Self-Containment Rules
1. **No cross-command references**: Each command.md must be executable independently
2. **Include all context inputs**: List all required context (files, configs) in Phase 2
3. **Complete error handling**: Every command handles its own failures
4. **Explicit output format**: Define what the command produces
5. **Strategy in decision tables**: All routing logic in tables, not code
## Key Differences from v1
| Aspect | v1 (old) | v2 (this template) |
|--------|----------|---------------------|
| Strategy logic | JS `if/else` + regex matching | Decision tables |
| Execution steps | JS code blocks (pseudocode) | Step lists + actual tool call templates |
| Result processing | JS object construction | Text aggregation description |
| Output format | Embedded in JS template literals | Standalone markdown format block |
| Error handling | JS try/catch with fallbacks | Decision table with clear routing |
| Context prep | JS variable assignments | Phase 2 table + loading steps |
| Monitor design | JS while loop + polling | Event-driven handlers + STOP pattern |

View File

@@ -0,0 +1,586 @@
# Role File Template
Template for generating per-role execution detail files in `roles/<role-name>/role.md` (v3 style).
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand role file structure |
| Phase 3 | Apply with role-specific content |
## Style Rules
Generated output follows v3 conventions:
| Rule | Description |
|------|-------------|
| Phase 1/5 shared | Reference "See SKILL.md Shared Infrastructure" instead of inline code |
| No JS pseudocode | Message Bus, Task Lifecycle all use text + tool call templates |
| Decision tables | All branching logic uses `| Condition | Action |` tables |
| Code blocks = tool calls only | Only actual executable calls (Read(), TaskList(), SendMessage(), etc.) |
| `<placeholder>` in output | Not `${variable}` in generated content |
| Phase 2-4 only | Role files define Phase 2-4 role-specific logic |
> **Note**: The template itself uses `{{handlebars}}` for variable substitution during Phase 3 generation. The **generated output** must not contain `{{handlebars}}` or JS pseudocode.
---
## Template
### Worker Role Template
```markdown
# {{display_name}} Role
{{role_description}}
## Identity
- **Name**: `{{role_name}}` | **Tag**: `[{{role_name}}]`
- **Task Prefix**: `{{task_prefix}}-*`
- **Responsibility**: {{responsibility_type}}
## Boundaries
### MUST
- Only process `{{task_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
{{#each must_rules}}
- {{this}}
{{/each}}
### 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 responsibility
- Omit `[{{role_name}}]` identifier in any output
{{#each must_not_rules}}
- {{this}}
{{/each}}
---
## Toolbox
### Available Commands
| Command | File | Phase | Description |
|---------|------|-------|-------------|
{{#each commands}}
| `{{this.name}}` | [commands/{{this.name}}.md](commands/{{this.name}}.md) | Phase {{this.phase}} | {{this.description}} |
{{/each}}
{{#if has_no_commands}}
> No command files -- all phases execute inline.
{{/if}}
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
{{#each tool_capabilities}}
| `{{this.tool}}` | {{this.type}} | {{this.used_by}} | {{this.purpose}} |
{{/each}}
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
{{#each message_types}}
| `{{this.type}}` | {{this.direction}} | {{this.trigger}} | {{this.description}} |
{{/each}}
## 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}}] <task-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}}] <task-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 `{{task_prefix}}-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
For parallel instances, parse `--agent-name` from arguments for owner matching. Falls back to `{{role_name}}` for single-instance roles.
### Phase 2: {{phase2_name}}
{{phase2_content}}
### Phase 3: {{phase3_name}}
{{phase3_content}}
### Phase 4: {{phase4_name}}
{{phase4_content}}
### Phase 5: Report to Coordinator
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
Standard report flow: team_msg log -> SendMessage with `[{{role_name}}]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No {{task_prefix}}-* tasks available | Idle, wait for coordinator assignment |
| Context/Plan file not found | Notify coordinator, request location |
{{#if has_commands}}
| Command file not found | Fall back to inline execution |
{{/if}}
{{#each additional_error_handlers}}
| {{this.scenario}} | {{this.resolution}} |
{{/each}}
| Critical issue beyond scope | SendMessage fix_required to coordinator |
| Unexpected error | Log error via team_msg, report to coordinator |
```
---
### Coordinator Role Template
The coordinator role is special and always generated. Its template differs from worker roles:
```markdown
# Coordinator Role
Orchestrate the {{team_display_name}} workflow: team creation, task dispatching, progress monitoring, session state.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- Parse user requirements and clarify ambiguous inputs via AskUserQuestion
- Create team and spawn worker subagents in background
- Dispatch tasks with proper dependency chains (see SKILL.md Task Metadata Registry)
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence
{{#each coordinator_must_rules}}
- {{this}}
{{/each}}
### MUST NOT
- Execute {{team_purpose}} work directly (delegate to workers)
- Modify task outputs (workers own their deliverables)
- Call implementation subagents directly
- Skip dependency validation when creating task chains
{{#each coordinator_must_not_rules}}
- {{this}}
{{/each}}
> **Core principle**: coordinator is the orchestrator, not the executor. All actual work must be delegated to worker roles via TaskCreate.
---
## Entry Router
When coordinator is invoked, first detect the invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline |
| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline |
| New session | None of the above | -> Phase 0 (Session Resume Check) |
For callback/check/resume: load `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 session directory for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session state <-> TaskList status (bidirectional sync)
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Determine remaining pipeline from reconciled state
5. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
6. Create missing tasks with correct blockedBy dependencies
7. Verify dependency chain integrity
8. Update session file with reconciled state
9. Kick first executable task's worker -> Phase 4
---
## Phase 1: Requirement Clarification
**Objective**: Parse user input and gather execution parameters.
**Workflow**:
1. **Parse arguments** for explicit settings: mode, scope, focus areas
2. **Ask for missing parameters** via AskUserQuestion:
{{phase1_questions}}
3. **Store requirements**: mode, scope, focus, constraints
**Success**: All parameters captured, mode finalized.
---
## Phase 2: Create Team + Initialize Session
**Objective**: Initialize team, session file, and wisdom directory.
**Workflow**:
1. Generate session ID
2. Create session folder
3. Call TeamCreate with team name
4. Initialize wisdom directory (learnings.md, decisions.md, conventions.md, issues.md)
5. Write session file with: session_id, mode, scope, status="active"
6. Spawn worker roles (see SKILL.md Coordinator Spawn Template)
**Success**: Team created, session file written, wisdom initialized, workers spawned.
---
## Phase 3: Create Task Chain
**Objective**: Dispatch tasks based on mode with proper dependencies.
{{#if has_dispatch_command}}
Delegate to `commands/dispatch.md` which creates the full task chain:
1. Reads SKILL.md Task Metadata Registry for task definitions
2. Creates tasks via TaskCreate with correct blockedBy
3. Assigns owner based on role mapping
4. Includes `Session: <session-folder>` in every task description
{{else}}
{{phase3_dispatch_content}}
{{/if}}
---
## Phase 4: Spawn-and-Stop
**Objective**: Spawn first batch of ready workers in background, then STOP.
**Design**: Spawn-and-Stop + Callback pattern.
- Spawn workers with `Task(run_in_background: true)` -> immediately return
- Worker completes -> SendMessage callback -> auto-advance
- User can use "check" / "resume" to manually advance
- Coordinator does one operation per invocation, then STOPS
**Workflow**:
{{#if has_monitor_command}}
1. Load `commands/monitor.md`
{{/if}}
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
3. For each ready task -> spawn worker (see SKILL.md Spawn Template)
4. Output status summary
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 deliverables with output paths
3. Update session status -> "completed"
4. Offer next steps to user
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report to user, halt |
| Invalid mode | Reject with error, ask to clarify |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
{{#each coordinator_error_handlers}}
| {{this.error}} | {{this.resolution}} |
{{/each}}
```
---
## Phase 2-4 Content by Responsibility Type
The following sections provide Phase 2-4 content templates based on `responsibility_type`. During Phase 3 generation, select the matching section and fill into `{{phase2_content}}`, `{{phase3_content}}`, `{{phase4_content}}`.
### Read-only Analysis
**Phase 2: Context Loading**
```
| Input | Source | Required |
|-------|--------|----------|
| Plan file | <session-folder>/plan/plan.json | Yes |
| Git diff | `git diff HEAD~1` or `git diff --cached` | Yes |
| Modified files | From git diff --name-only | Yes |
| Wisdom | <session-folder>/wisdom/ | No |
**Loading steps**:
1. Extract session path from task description
2. Read plan file for criteria reference
3. Get changed files list
\`\`\`
Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")
\`\`\`
4. Read file contents for analysis (limit to 20 files)
5. Load wisdom files if available
```
**Phase 3: Analysis Execution**
```
Delegate to `commands/<analysis-command>.md` if available, otherwise execute inline.
Analysis strategy selection:
| Condition | Strategy |
|-----------|----------|
| Single dimension analysis | Direct inline scan |
| Multi-dimension analysis | Per-dimension sequential scan |
| Deep analysis needed | CLI Fan-out to external tool |
For each dimension, scan modified files for patterns. Record findings with severity levels.
```
**Phase 4: Finding Summary**
```
Classify findings by severity:
| Severity | Criteria |
|----------|----------|
| Critical | Must fix before merge |
| High | Should fix, may merge with tracking |
| Medium | Recommended improvement |
| Low | Informational, optional |
Generate structured report with file:line references and remediation suggestions.
```
### Code Generation
**Phase 2: Task & Plan Loading**
```
**Loading steps**:
1. Extract session path from task description
2. Read plan file -> extract task list and acceptance criteria
3. Read individual task files from `.task/` directory
4. Load wisdom files for conventions and patterns
Fail-safe: If plan file not found -> SendMessage to coordinator requesting location.
```
**Phase 3: Code Implementation**
```
Implementation strategy selection:
| Task Count | Complexity | Strategy |
|------------|------------|----------|
| <= 2 tasks | Low | Direct: inline Edit/Write |
| 3-5 tasks | Medium | Single agent: one code-developer for all |
| > 5 tasks | High | Batch agent: group by module, one agent per batch |
{{#if phase3_command}}
Delegate to `commands/{{phase3_command}}.md`.
{{else}}
Execute inline based on strategy selection above.
{{/if}}
```
**Phase 4: Self-Validation**
```
Validation checks:
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Syntax | `Bash("tsc --noEmit 2>&1 || true")` or equivalent | No errors |
| File existence | Verify all planned files exist | All files present |
| Import resolution | Check no broken imports | All imports resolve |
If validation fails -> attempt auto-fix (max 2 attempts) -> report remaining issues.
```
### Orchestration
**Phase 2: Context & Complexity Assessment**
```
Complexity assessment:
| Signal | Weight | Keywords |
|--------|--------|----------|
| Structural change | +2 | refactor, architect, restructure, module, system |
| Cross-cutting | +2 | multiple, across, cross |
| Integration | +1 | integrate, api, database |
| Non-functional | +1 | security, performance |
| Score | Complexity | Approach |
|-------|------------|----------|
| >= 4 | High | Multi-stage with sub-orchestration |
| 2-3 | Medium | Standard pipeline |
| 0-1 | Low | Simplified flow |
```
**Phase 3: Orchestrated Execution**
```
Launch execution based on complexity:
| Complexity | Execution Pattern |
|------------|-------------------|
| High | Parallel sub-agents + synchronization barriers |
| Medium | Sequential stages with dependency tracking |
| Low | Direct delegation to single worker |
```
**Phase 4: Result Aggregation**
```
Merge and summarize sub-agent results:
1. Collect all sub-agent outputs
2. Deduplicate findings across agents
3. Prioritize by severity/importance
4. Generate consolidated summary
```
### Validation
**Phase 2: Environment Detection**
```
**Detection steps**:
1. Get changed files from git diff
2. Detect test framework from project files
| Detection | Method |
|-----------|--------|
| Changed files | `Bash("git diff --name-only HEAD~1 2>/dev/null || git diff --name-only --cached")` |
| Test command | Check package.json scripts, pytest.ini, Makefile |
| Coverage tool | Check for nyc, coverage.py, jest --coverage config |
```
**Phase 3: Execution & Fix Cycle**
```
Iterative test-fix cycle:
| Step | Action |
|------|--------|
| 1 | Run test command |
| 2 | Parse results -> check pass rate |
| 3 | Pass rate >= 95% -> exit loop (success) |
| 4 | Extract failing test details |
| 5 | Delegate fix to code-developer subagent |
| 6 | Increment iteration counter |
| 7 | iteration >= MAX (5) -> exit loop (report failures) |
| 8 | Go to Step 1 |
```
**Phase 4: Result Analysis**
```
Analyze test outcomes:
| Metric | Source | Threshold |
|--------|--------|-----------|
| Pass rate | Test output parser | >= 95% |
| Coverage | Coverage tool output | >= 80% |
| Flaky tests | Compare runs | 0 flaky |
Generate test report with: pass/fail counts, coverage data, failure details, fix attempts made.
```
---
## Variable Reference
| Variable | Source | Description |
|----------|--------|-------------|
| `{{role_name}}` | config.role_name | Role identifier |
| `{{display_name}}` | config.display_name | Human-readable role name |
| `{{task_prefix}}` | config.task_prefix | UPPERCASE task prefix |
| `{{responsibility_type}}` | config.responsibility_type | Role type (read-only analysis, code generation, orchestration, validation) |
| `{{role_description}}` | config.role_description | One-line role description |
| `{{phase2_name}}` | patterns.phase_structure.phase2 | Phase 2 label |
| `{{phase3_name}}` | patterns.phase_structure.phase3 | Phase 3 label |
| `{{phase4_name}}` | patterns.phase_structure.phase4 | Phase 4 label |
| `{{phase2_content}}` | Generated from responsibility template | Phase 2 text content |
| `{{phase3_content}}` | Generated from responsibility template | Phase 3 text content |
| `{{phase4_content}}` | Generated from responsibility template | Phase 4 text content |
| `{{message_types}}` | config.message_types | Array of message type definitions |
| `{{commands}}` | config.commands | Array of command definitions |
| `{{has_commands}}` | config.commands.length > 0 | Boolean: has extracted commands |
| `{{has_no_commands}}` | config.commands.length === 0 | Boolean: all phases inline |
| `{{tool_capabilities}}` | config.tool_capabilities | Array of tool/subagent/CLI capabilities |
| `{{must_rules}}` | config.must_rules | Additional MUST rules |
| `{{must_not_rules}}` | config.must_not_rules | Additional MUST NOT rules |
| `{{additional_error_handlers}}` | config.additional_error_handlers | Array of {scenario, resolution} |
## Key Differences from v1
| Aspect | v1 (old) | v2 (this template) |
|--------|----------|---------------------|
| Phase 1/5 | Inline JS code | Reference SKILL.md Shared Infrastructure |
| Message Bus | JS function call pseudocode | Text description + actual tool call template |
| Task Lifecycle | JS filter/map code | Step list description |
| Phase 2-4 | JS code per responsibility_type | Text + decision tables per responsibility_type |
| Command delegation | JS try/catch block | Text "Delegate to commands/xxx.md" |
| Coordinator template | JS spawn loops | Text phases with decision tables |

View File

@@ -0,0 +1,360 @@
# Skill Router Template
Template for the generated SKILL.md with role-based routing (v3 style).
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand generated SKILL.md structure |
| Phase 3 | Apply with team-specific content |
## Style Rules
Generated output follows v3 conventions:
| Rule | Description |
|------|-------------|
| No pseudocode | Flow uses text + decision tables + flow symbols |
| Code blocks = tool calls only | Only Task(), TaskCreate(), Bash(), Read() etc. |
| `<placeholder>` in output | Not `${variable}` or `{{handlebars}}` in generated content |
| Decision tables | All branching logic uses `| Condition | Action |` tables |
| Cadence Control | Beat diagram + checkpoint definitions |
| Compact Protection | Phase Reference with Compact column |
> **Note**: The template itself uses `{{handlebars}}` for variable substitution during Phase 3 generation. The **generated output** must not contain `{{handlebars}}` or JS pseudocode.
---
## Template
```markdown
---
name: team-{{team_name}}
description: Unified team skill for {{team_name}}. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team {{team_name}}".
allowed-tools: {{all_roles_tools_union}}
---
# Team {{team_display_name}}
Unified team skill: {{team_purpose}}. All team members invoke with `--role=xxx` to route to role-specific execution.
## Architecture
\`\`\`
{{architecture_diagram}}
\`\`\`
## Role Router
### Input Parsing
Parse `$ARGUMENTS` to extract `--role`. If absent -> Orchestration Mode (auto route to coordinator).
### Role Registry
| Role | File | Task Prefix | Type | Compact |
|------|------|-------------|------|---------|
{{#each roles}}
| {{this.name}} | [roles/{{this.name}}/role.md](roles/{{this.name}}/role.md) | {{this.task_prefix}}-* | {{this.type}} | Compress after must re-read |
{{/each}}
> **COMPACT PROTECTION**: Role files are execution documents, not reference material. When context compression occurs and role instructions are reduced to summaries, **you MUST immediately `Read` the corresponding role.md to reload before continuing execution**. Do not execute any Phase based on summaries.
### Dispatch
1. Extract `--role` from arguments
2. If no `--role` -> route to coordinator (Orchestration Mode)
3. Look up role in registry -> Read the role file -> Execute its phases
### Orchestration Mode
When invoked without `--role`, coordinator auto-starts. User just provides task description.
**Invocation**: `Skill(skill="team-{{team_name}}", args="<task-description>")`
**Lifecycle**:
\`\`\`
User provides task description
-> coordinator Phase 1-3: Requirement clarification -> TeamCreate -> Create task chain
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances next step
-> Loop until pipeline complete -> Phase 5 report
\`\`\`
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Shared Infrastructure
The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic.
### Worker Phase 1: Task Discovery (shared by all workers)
Every worker executes the same task discovery flow on startup:
1. Call `TaskList()` to get all tasks
2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty
3. No tasks -> idle wait
4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress
**Resume Artifact Check** (prevent duplicate output after resume):
- Check whether this task's output artifact already exists
- Artifact complete -> skip to Phase 5 report completion
- Artifact incomplete or missing -> normal Phase 2-4 execution
### Worker Phase 5: Report (shared by all workers)
Standard reporting flow after task completion:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Parameters: operation="log", 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. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`)
3. **TaskUpdate**: Mark task completed
4. **Loop**: Return to Phase 1 to check next task
### Wisdom Accumulation (all roles)
Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization.
**Directory**:
\`\`\`
<session-folder>/wisdom/
+-- learnings.md # Patterns and insights
+-- decisions.md # Architecture and design decisions
+-- conventions.md # Codebase conventions
+-- issues.md # Known risks and issues
\`\`\`
**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files.
**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files.
### Role Isolation Rules
| Allowed | Forbidden |
|---------|-----------|
| Process tasks with own prefix | Process tasks with other role prefixes |
| SendMessage to coordinator | Communicate directly with other workers |
| Use tools declared in Toolbox | Create tasks for other roles |
| Delegate to commands/ files | Modify resources outside own responsibility |
Coordinator additional restrictions: Do not write/modify code directly, do not call implementation subagents, do not execute analysis/test/review directly.
---
## Pipeline Definitions
### Pipeline Diagram
\`\`\`
{{pipeline_diagram}}
\`\`\`
### 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)
========================================================
\`\`\`
{{cadence_beat_view}}
**Checkpoints**:
{{checkpoint_table}}
**Stall Detection** (coordinator `handleCheck` executes):
| Check | Condition | Resolution |
|-------|-----------|------------|
| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` |
| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point |
{{#if has_gc_loop}}
| GC loop exceeded | iteration > max_rounds | Terminate loop, output latest report |
{{/if}}
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
{{#each task_metadata}}
| {{this.task_id}} | {{this.role}} | {{this.phase}} | {{this.dependencies}} | {{this.description}} |
{{/each}}
## Coordinator Spawn Template
When coordinator spawns workers, use background mode (Spawn-and-Stop):
\`\`\`
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 Directive
All your work must be executed through Skill to load role definition:
Skill(skill="team-{{team_name}}", args="--role=<role>")
Current requirement: <task-description>
Session: <session-folder>
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] identifier
- Only communicate with coordinator
- Do not use TaskCreate for other roles
- Call mcp__ccw-tools__team_msg before every SendMessage
## Workflow
1. Call Skill -> load 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`
})
\`\`\`
{{#if has_parallel_spawn}}
### Parallel Spawn (N agents for same role)
> When pipeline has parallel tasks assigned to the same role, spawn N distinct agents with unique names. A single agent can only process tasks serially.
**Parallel detection**:
| Condition | Action |
|-----------|--------|
| N parallel tasks for same role prefix | Spawn N agents named `<role>-1`, `<role>-2` ... |
| Single task for role | Standard spawn (single agent) |
**Parallel spawn template**:
\`\`\`
Task({
subagent_type: "general-purpose",
description: "Spawn <role>-<N> worker",
team_name: <team-name>,
name: "<role>-<N>",
run_in_background: true,
prompt: `You are team "<team-name>" <ROLE> (<role>-<N>).
Your agent name is "<role>-<N>", use this name for task discovery owner matching.
## Primary Directive
Skill(skill="team-{{team_name}}", args="--role=<role> --agent-name=<role>-<N>")
## Role Guidelines
- Only process tasks where owner === "<role>-<N>" with <PREFIX>-* prefix
- All output prefixed with [<role>] identifier
## Workflow
1. TaskList -> find tasks where owner === "<role>-<N>" with <PREFIX>-* prefix
2. Skill -> execute role definition
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task`
})
\`\`\`
**Dispatch must match agent names**: In dispatch, parallel tasks use instance-specific owner: `<role>-<N>`. In role.md, task discovery uses --agent-name for owner matching.
{{/if}}
## Session Directory
\`\`\`
{{session_directory_tree}}
\`\`\`
{{#if has_session_resume}}
## Session Resume
Coordinator supports `--resume` / `--continue` for interrupted sessions:
1. Scan session directory for sessions with status "active" or "paused"
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
{{/if}}
{{#if shared_resources}}
## Shared Resources
| Resource | Path | Usage |
|----------|------|-------|
{{#each shared_resources}}
| {{this.name}} | [{{this.path}}]({{this.path}}) | {{this.usage}} |
{{/each}}
{{/if}}
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Error with available role list |
| Missing --role arg | Orchestration Mode -> auto route to coordinator |
| Role file not found | Error with expected path (roles/<name>/role.md) |
| Command file not found | Fallback to inline execution in role.md |
{{#each additional_error_handlers}}
| {{this.scenario}} | {{this.resolution}} |
{{/each}}
```
---
## Variable Reference
| Variable | Source | Description |
|----------|--------|-------------|
| `{{team_name}}` | config.team_name | Team identifier (lowercase) |
| `{{team_display_name}}` | config.team_display_name | Human-readable team name |
| `{{team_purpose}}` | config.team_purpose | One-line team purpose |
| `{{all_roles_tools_union}}` | Union of all roles' allowed-tools | Combined tool list |
| `{{roles}}` | config.roles[] | Array of role definitions |
| `{{architecture_diagram}}` | Generated from role structure | ASCII architecture diagram |
| `{{pipeline_diagram}}` | Generated from task chain | ASCII pipeline diagram |
| `{{cadence_beat_view}}` | Generated from pipeline | Pipeline beat view diagram |
| `{{checkpoint_table}}` | Generated from pipeline | Checkpoint trigger/location/behavior table |
| `{{task_metadata}}` | Generated from pipeline | Task metadata registry entries |
| `{{session_directory_tree}}` | Generated from session structure | Session directory tree |
| `{{has_parallel_spawn}}` | config.has_parallel_spawn | Boolean: pipeline has parallel same-role tasks |
| `{{has_session_resume}}` | config.has_session_resume | Boolean: supports session resume |
| `{{has_gc_loop}}` | config.has_gc_loop | Boolean: has guard-and-correct loops |
| `{{shared_resources}}` | config.shared_resources | Array of shared resource definitions |
| `{{additional_error_handlers}}` | config.additional_error_handlers | Array of {scenario, resolution} |
## Key Differences from v1
| Aspect | v1 (old) | v2 (this template) |
|--------|----------|---------------------|
| Role lookup | `VALID_ROLES` JS object | Role Registry decision table with markdown links |
| Routing | JS regex + if/else | Text dispatch flow (3 steps) |
| Spawn template | JS code with `${variable}` | Text template with `<placeholder>` |
| Infrastructure | Inline JS per role | Shared Infrastructure section (Phase 1/5 templates) |
| Pipeline | ASCII only | Cadence Control + beat view + checkpoints |
| Compact safety | None | Compact Protection with re-read mandate |
| Orchestration Mode | JS if/else block | Decision table + lifecycle flow diagram |