Auto Mode
When --yes or -y: Auto-confirm task decomposition, skip interactive validation, use defaults.
Team Coordinate
Usage
$team-coordinate "Implement user authentication with JWT tokens"
$team-coordinate -c 4 "Refactor payment module and write API documentation"
$team-coordinate -y "Analyze codebase security and fix vulnerabilities"
$team-coordinate --continue "tc-auth-jwt-20260308"
Flags:
-y, --yes: Skip all confirmations (auto mode)
-c, --concurrency N: Max concurrent agents within each wave (default: 3)
--continue: Resume existing session
Output Directory: .workflow/.csv-wave/{session-id}/
Core Output: tasks.csv (master state) + results.csv (final) + discoveries.ndjson (shared exploration) + context.md (human-readable report)
Overview
Universal team coordination: analyze task -> detect capabilities -> generate dynamic role instructions -> decompose into dependency-ordered CSV tasks -> execute wave-by-wave -> deliver results. Only the coordinator (this orchestrator) is built-in. All worker roles are dynamically generated as CSV agent instructions at runtime.
Execution Model: Hybrid -- CSV wave pipeline (primary) + individual agent spawn (secondary)
+-------------------------------------------------------------------+
| TEAM COORDINATE WORKFLOW |
+-------------------------------------------------------------------+
| |
| Phase 0: Pre-Wave Interactive (Requirement Clarification) |
| +- Parse user task description |
| +- Clarify ambiguous requirements (AskUserQuestion) |
| +- Output: refined requirements for decomposition |
| |
| Phase 1: Requirement -> CSV + Classification |
| +- Signal detection: keyword scan -> capability inference |
| +- Dependency graph construction (DAG) |
| +- Role minimization (cap at 5 roles) |
| +- Classify tasks: csv-wave | interactive (exec_mode) |
| +- Compute dependency waves (topological sort) |
| +- Generate tasks.csv with wave + exec_mode columns |
| +- Generate per-role agent instructions dynamically |
| +- User validates task breakdown (skip if -y) |
| |
| Phase 2: Wave Execution Engine (Extended) |
| +- For each wave (1..N): |
| | +- Execute pre-wave interactive tasks (if any) |
| | +- Build wave CSV (filter csv-wave tasks for this wave) |
| | +- Inject previous findings into prev_context column |
| | +- spawn_agents_on_csv(wave CSV) |
| | +- Execute post-wave interactive tasks (if any) |
| | +- Merge all results into master tasks.csv |
| | +- Check: any failed? -> skip dependents |
| +- discoveries.ndjson shared across all modes (append-only) |
| |
| Phase 3: Post-Wave Interactive (Completion Action) |
| +- Pipeline completion report |
| +- Interactive completion choice (Archive/Keep/Export) |
| +- Final aggregation / report |
| |
| Phase 4: Results Aggregation |
| +- Export final results.csv |
| +- Generate context.md with all findings |
| +- Display summary: completed/failed/skipped per wave |
| +- Offer: view results | retry failed | done |
| |
+-------------------------------------------------------------------+
Task Classification Rules
Each task is classified by exec_mode:
| exec_mode |
Mechanism |
Criteria |
csv-wave |
spawn_agents_on_csv |
One-shot, structured I/O, no multi-round interaction |
interactive |
spawn_agent/wait/send_input/close_agent |
Multi-round, needs clarification, revision cycles |
Classification Decision:
| Task Property |
Classification |
| Single-pass code implementation |
csv-wave |
| Single-pass analysis or documentation |
csv-wave |
| Research with defined scope |
csv-wave |
| Testing with known targets |
csv-wave |
| Design requiring iterative refinement |
interactive |
| Plan requiring user approval checkpoint |
interactive |
| Revision cycle (fix-verify loop) |
interactive |
CSV Schema
tasks.csv (Master State)
id,title,description,role,responsibility_type,output_type,deps,context_from,exec_mode,wave,status,findings,artifacts_produced,error
"RESEARCH-001","Investigate auth patterns","Research JWT authentication patterns and best practices","researcher","orchestration","artifact","","","csv-wave","1","pending","","",""
"IMPL-001","Implement auth module","Build JWT authentication middleware","developer","code-gen","codebase","RESEARCH-001","RESEARCH-001","csv-wave","2","pending","","",""
"TEST-001","Validate auth implementation","Write and run tests for auth module","tester","validation","artifact","IMPL-001","IMPL-001","csv-wave","3","pending","","",""
Columns:
| Column |
Phase |
Description |
id |
Input |
Unique task identifier (PREFIX-NNN format) |
title |
Input |
Short task title |
description |
Input |
Detailed task description with goal, steps, success criteria |
role |
Input |
Dynamic role name (researcher, developer, analyst, etc.) |
responsibility_type |
Input |
orchestration, read-only, code-gen, code-gen-docs, validation |
output_type |
Input |
artifact (session files), codebase (project files), mixed |
deps |
Input |
Semicolon-separated dependency task IDs |
context_from |
Input |
Semicolon-separated task IDs whose findings this task needs |
exec_mode |
Input |
csv-wave or interactive |
wave |
Computed |
Wave number (computed by topological sort, 1-based) |
status |
Output |
pending -> completed / failed / skipped |
findings |
Output |
Key discoveries or implementation notes (max 500 chars) |
artifacts_produced |
Output |
Semicolon-separated paths of produced artifacts |
error |
Output |
Error message if failed (empty if success) |
Per-Wave CSV (Temporary)
Each wave generates a temporary wave-{N}.csv with extra prev_context column (csv-wave tasks only).
Agent Registry (Interactive Agents)
| Agent |
Role File |
Pattern |
Responsibility |
Position |
| Plan Reviewer |
agents/plan-reviewer.md |
2.3 (send_input cycle) |
Review and approve plans before execution waves |
pre-wave |
| Completion Handler |
agents/completion-handler.md |
2.3 (send_input cycle) |
Handle pipeline completion action (Archive/Keep/Export) |
standalone |
COMPACT PROTECTION: Agent files are execution documents. When context compression occurs, you MUST immediately Read the corresponding agent.md to reload.
Output Artifacts
| File |
Purpose |
Lifecycle |
tasks.csv |
Master state -- all tasks with status/findings |
Updated after each wave |
wave-{N}.csv |
Per-wave input (temporary, csv-wave tasks only) |
Created before wave, deleted after |
results.csv |
Final export of all task results |
Created in Phase 4 |
discoveries.ndjson |
Shared exploration board (all agents, both modes) |
Append-only, carries across waves |
context.md |
Human-readable execution report |
Created in Phase 4 |
task-analysis.json |
Phase 0/1 output: capabilities, dependency graph, roles |
Created in Phase 1 |
role-instructions/ |
Dynamically generated per-role instruction templates |
Created in Phase 1 |
interactive/{id}-result.json |
Results from interactive tasks |
Created per interactive task |
Session Structure
.workflow/.csv-wave/{session-id}/
+-- tasks.csv # Master state (all tasks, both modes)
+-- results.csv # Final results export
+-- discoveries.ndjson # Shared discovery board (all agents)
+-- context.md # Human-readable report
+-- task-analysis.json # Phase 1 analysis output
+-- wave-{N}.csv # Temporary per-wave input (csv-wave only)
+-- role-instructions/ # Dynamically generated instruction templates
| +-- researcher.md
| +-- developer.md
| +-- ...
+-- artifacts/ # All deliverables from workers
| +-- research-findings.md
| +-- implementation-summary.md
| +-- ...
+-- interactive/ # Interactive task artifacts
| +-- {id}-result.json
+-- wisdom/ # Cross-task knowledge
+-- learnings.md
+-- decisions.md
Implementation
Session Initialization
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
const AUTO_YES = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const continueMode = $ARGUMENTS.includes('--continue')
const concurrencyMatch = $ARGUMENTS.match(/(?:--concurrency|-c)\s+(\d+)/)
const maxConcurrency = concurrencyMatch ? parseInt(concurrencyMatch[1]) : 3
const requirement = $ARGUMENTS
.replace(/--yes|-y|--continue|--concurrency\s+\d+|-c\s+\d+/g, '')
.trim()
const slug = requirement.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 40)
const dateStr = getUtc8ISOString().substring(0, 10).replace(/-/g, '')
const sessionId = `tc-${slug}-${dateStr}`
const sessionFolder = `.workflow/.csv-wave/${sessionId}`
Bash(`mkdir -p ${sessionFolder}/artifacts ${sessionFolder}/role-instructions ${sessionFolder}/interactive ${sessionFolder}/wisdom`)
// Initialize discoveries.ndjson
Write(`${sessionFolder}/discoveries.ndjson`, '')
// Initialize wisdom files
Write(`${sessionFolder}/wisdom/learnings.md`, '# Learnings\n')
Write(`${sessionFolder}/wisdom/decisions.md`, '# Decisions\n')
Phase 0: Pre-Wave Interactive (Requirement Clarification)
Objective: Parse user task, clarify ambiguities, prepare for decomposition.
Workflow:
Parse user task description from $ARGUMENTS
Check for existing sessions (continue mode):
- Scan
.workflow/.csv-wave/tc-*/tasks.csv for sessions with pending tasks
- If
--continue: resume the specified or most recent session, skip to Phase 2
- If active session found: ask user whether to resume or start new
Clarify if ambiguous (skip if AUTO_YES):
AskUserQuestion({
questions: [{
question: "Please confirm the task scope and deliverables:",
header: "Task Clarification",
multiSelect: false,
options: [
{ label: "Proceed as described", description: "Task is clear enough" },
{ label: "Narrow scope", description: "Specify files/modules/areas" },
{ label: "Add constraints", description: "Timeline, tech stack, style" }
]
}]
})
Output: Refined requirement string for Phase 1
Success Criteria:
- Refined requirements available for Phase 1 decomposition
- Existing session detected and handled if applicable
Phase 1: Requirement -> CSV + Classification
Objective: Analyze task, detect capabilities, build dependency graph, generate tasks.csv and role instructions.
Decomposition Rules:
- Signal Detection -- scan task description for capability keywords:
| Signal |
Keywords |
Capability |
Prefix |
Responsibility Type |
| Research |
investigate, explore, compare, survey, find, research, discover |
researcher |
RESEARCH |
orchestration |
| Writing |
write, draft, document, article, report, summarize |
writer |
DRAFT |
code-gen-docs |
| Coding |
implement, build, code, fix, refactor, develop, create, migrate |
developer |
IMPL |
code-gen |
| Design |
design, architect, plan, structure, blueprint, schema |
designer |
DESIGN |
orchestration |
| Analysis |
analyze, review, audit, assess, evaluate, inspect, diagnose |
analyst |
ANALYSIS |
read-only |
| Testing |
test, verify, validate, QA, quality, check, coverage |
tester |
TEST |
validation |
| Planning |
plan, breakdown, organize, schedule, decompose, roadmap |
planner |
PLAN |
orchestration |
- Dependency Graph -- build DAG using natural ordering tiers:
| Tier |
Capabilities |
Description |
| 0 |
researcher, planner |
Knowledge gathering / planning |
| 1 |
designer |
Design (requires tier 0 if present) |
| 2 |
writer, developer |
Creation (requires design/plan if present) |
| 3 |
analyst, tester |
Validation (requires artifacts to validate) |
Role Minimization -- merge overlapping capabilities, cap at 5 roles
Key File Inference -- extract nouns from task description, map to likely file paths
output_type derivation:
| Task Signal |
output_type |
| "write report", "analyze", "research" |
artifact |
| "update code", "modify", "fix bug" |
codebase |
| "implement feature + write summary" |
mixed |
Classification Rules:
| Task Property |
exec_mode |
| Single-pass implementation/analysis/documentation |
csv-wave |
| Needs iterative user approval |
interactive |
| Fix-verify revision cycle |
interactive |
| Standard research, coding, testing |
csv-wave |
Wave Computation: Kahn's BFS topological sort with depth tracking.
// After task analysis, generate dynamic role instruction templates
for (const role of analysisResult.roles) {
const instruction = generateRoleInstruction(role, sessionFolder)
Write(`${sessionFolder}/role-instructions/${role.name}.md`, instruction)
}
// Generate tasks.csv from dependency graph
const tasks = buildTasksCsv(analysisResult)
Write(`${sessionFolder}/tasks.csv`, toCsv(tasks))
Write(`${sessionFolder}/task-analysis.json`, JSON.stringify(analysisResult, null, 2))
User Validation: Display task breakdown with wave + exec_mode assignment (skip if AUTO_YES).
Success Criteria:
- tasks.csv created with valid schema, wave, and exec_mode assignments
- Role instruction templates generated in role-instructions/
- task-analysis.json written
- No circular dependencies
- User approved (or AUTO_YES)
Phase 2: Wave Execution Engine (Extended)
Objective: Execute tasks wave-by-wave with hybrid mechanism support and cross-wave context propagation.
const masterCsv = Read(`${sessionFolder}/tasks.csv`)
let tasks = parseCsv(masterCsv)
const maxWave = Math.max(...tasks.map(t => t.wave))
for (let wave = 1; wave <= maxWave; wave++) {
console.log(`\nWave ${wave}/${maxWave}`)
// 1. Separate tasks by exec_mode
const waveTasks = tasks.filter(t => t.wave === wave && t.status === 'pending')
const csvTasks = waveTasks.filter(t => t.exec_mode === 'csv-wave')
const interactiveTasks = waveTasks.filter(t => t.exec_mode === 'interactive')
// 2. Check dependencies -- skip tasks whose deps failed
for (const task of waveTasks) {
const depIds = (task.deps || '').split(';').filter(Boolean)
const depStatuses = depIds.map(id => tasks.find(t => t.id === id)?.status)
if (depStatuses.some(s => s === 'failed' || s === 'skipped')) {
task.status = 'skipped'
task.error = `Dependency failed: ${depIds.filter((id, i) =>
['failed','skipped'].includes(depStatuses[i])).join(', ')}`
}
}
// 3. Execute pre-wave interactive tasks (e.g., plan approval)
const preWaveInteractive = interactiveTasks.filter(t => t.status === 'pending')
for (const task of preWaveInteractive) {
// Read agent definition
Read(`agents/plan-reviewer.md`)
const agent = spawn_agent({
message: `## TASK ASSIGNMENT\n\n### MANDATORY FIRST STEPS\n1. Read: ${sessionFolder}/discoveries.ndjson\n\nGoal: ${task.description}\nScope: ${task.title}\nSession: ${sessionFolder}\n\n### Previous Context\n${buildPrevContext(task, tasks)}`
})
const result = wait({ ids: [agent], timeout_ms: 600000 })
if (result.timed_out) {
send_input({ id: agent, message: "Please finalize and output current findings." })
wait({ ids: [agent], timeout_ms: 120000 })
}
Write(`${sessionFolder}/interactive/${task.id}-result.json`, JSON.stringify({
task_id: task.id, status: "completed", findings: parseFindings(result),
timestamp: getUtc8ISOString()
}))
close_agent({ id: agent })
task.status = 'completed'
task.findings = parseFindings(result)
}
// 4. Build prev_context for csv-wave tasks
const pendingCsvTasks = csvTasks.filter(t => t.status === 'pending')
for (const task of pendingCsvTasks) {
task.prev_context = buildPrevContext(task, tasks)
}
if (pendingCsvTasks.length > 0) {
// 5. Write wave CSV
Write(`${sessionFolder}/wave-${wave}.csv`, toCsv(pendingCsvTasks))
// 6. Determine instruction for this wave (use role-specific instruction)
// Group tasks by role, build combined instruction
const waveInstruction = buildWaveInstruction(pendingCsvTasks, sessionFolder, wave)
// 7. Execute wave via spawn_agents_on_csv
spawn_agents_on_csv({
csv_path: `${sessionFolder}/wave-${wave}.csv`,
id_column: "id",
instruction: waveInstruction,
max_concurrency: maxConcurrency,
max_runtime_seconds: 900,
output_csv_path: `${sessionFolder}/wave-${wave}-results.csv`,
output_schema: {
type: "object",
properties: {
id: { type: "string" },
status: { type: "string", enum: ["completed", "failed"] },
findings: { type: "string" },
artifacts_produced: { type: "string" },
error: { type: "string" }
}
}
})
// 8. Merge results into master CSV
const results = parseCsv(Read(`${sessionFolder}/wave-${wave}-results.csv`))
for (const r of results) {
const t = tasks.find(t => t.id === r.id)
if (t) Object.assign(t, r)
}
}
// 9. Update master CSV
Write(`${sessionFolder}/tasks.csv`, toCsv(tasks))
// 10. Cleanup temp files
Bash(`rm -f ${sessionFolder}/wave-${wave}.csv ${sessionFolder}/wave-${wave}-results.csv`)
// 11. Display wave summary
const completed = waveTasks.filter(t => t.status === 'completed').length
const failed = waveTasks.filter(t => t.status === 'failed').length
const skipped = waveTasks.filter(t => t.status === 'skipped').length
console.log(`Wave ${wave} Complete: ${completed} completed, ${failed} failed, ${skipped} skipped`)
}
Success Criteria:
- All waves executed in order
- Both csv-wave and interactive tasks handled per wave
- Each wave's results merged into master CSV before next wave starts
- Dependent tasks skipped when predecessor failed
- discoveries.ndjson accumulated across all waves and mechanisms
Phase 3: Post-Wave Interactive (Completion Action)
Objective: Pipeline completion report and interactive completion choice.
// 1. Generate pipeline summary
const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
const completed = tasks.filter(t => t.status === 'completed')
const failed = tasks.filter(t => t.status === 'failed')
console.log(`
============================================
TASK COMPLETE
Deliverables:
${completed.map(t => ` - ${t.id}: ${t.title} (${t.role})`).join('\n')}
Pipeline: ${completed.length}/${tasks.length} tasks
Duration: <elapsed>
Session: ${sessionFolder}
============================================
`)
// 2. Completion action
if (!AUTO_YES) {
const 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, output final summary" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Retry Failed", description: "Re-run failed tasks" }
]
}]
})
// Handle choice accordingly
}
Success Criteria:
- Post-wave interactive processing complete
- User informed of results
Phase 4: Results Aggregation
Objective: Generate final results and human-readable report.
// 1. Export results.csv
Bash(`cp ${sessionFolder}/tasks.csv ${sessionFolder}/results.csv`)
// 2. Generate context.md
const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
let contextMd = `# Team Coordinate Report\n\n`
contextMd += `**Session**: ${sessionId}\n`
contextMd += `**Date**: ${getUtc8ISOString().substring(0, 10)}\n\n`
contextMd += `## Summary\n`
contextMd += `| Status | Count |\n|--------|-------|\n`
contextMd += `| Completed | ${tasks.filter(t => t.status === 'completed').length} |\n`
contextMd += `| Failed | ${tasks.filter(t => t.status === 'failed').length} |\n`
contextMd += `| Skipped | ${tasks.filter(t => t.status === 'skipped').length} |\n\n`
const maxWave = Math.max(...tasks.map(t => t.wave))
contextMd += `## Wave Execution\n\n`
for (let w = 1; w <= maxWave; w++) {
const waveTasks = tasks.filter(t => t.wave === w)
contextMd += `### Wave ${w}\n\n`
for (const t of waveTasks) {
const icon = t.status === 'completed' ? '[DONE]' : t.status === 'failed' ? '[FAIL]' : '[SKIP]'
contextMd += `${icon} **${t.title}** [${t.role}] ${t.findings || ''}\n\n`
}
}
Write(`${sessionFolder}/context.md`, contextMd)
// 3. Display final summary
console.log(`Results exported to: ${sessionFolder}/results.csv`)
console.log(`Report generated at: ${sessionFolder}/context.md`)
Success Criteria:
- results.csv exported (all tasks, both modes)
- context.md generated
- Summary displayed to user
Shared Discovery Board Protocol
All agents (csv-wave and interactive) share a single discoveries.ndjson file for cross-task knowledge exchange.
Format: One JSON object per line (NDJSON):
{"ts":"2026-03-08T10:00:00Z","worker":"RESEARCH-001","type":"pattern_found","data":{"pattern_name":"Repository Pattern","location":"src/repos/","description":"Data access layer uses repository pattern"}}
{"ts":"2026-03-08T10:05:00Z","worker":"IMPL-001","type":"file_modified","data":{"file":"src/auth/jwt.ts","change":"Added JWT middleware","lines_added":45}}
Discovery Types:
| Type |
Data Schema |
Description |
pattern_found |
{pattern_name, location, description} |
Design pattern identified |
file_modified |
{file, change, lines_added} |
File change recorded |
dependency_found |
{from, to, type} |
Dependency relationship discovered |
issue_found |
{file, line, severity, description} |
Issue or bug discovered |
decision_made |
{decision, rationale, impact} |
Design decision recorded |
artifact_produced |
{name, path, producer, type} |
Deliverable created |
Protocol:
- Agents MUST read discoveries.ndjson at start of execution
- Agents MUST append relevant discoveries during execution
- Agents MUST NOT modify or delete existing entries
- Deduplication by
{type, data.file, data.pattern_name} key
Dynamic Role Instruction Generation
The coordinator generates role-specific instruction templates during Phase 1. Each template is written to role-instructions/{role-name}.md and used as the instruction parameter for spawn_agents_on_csv.
Generation Rules:
- Each instruction must be self-contained (agent has no access to master CSV)
- Use
{column_name} placeholders for CSV column substitution
- Include session folder path as literal (not placeholder)
- Include mandatory discovery board read/write steps
- Include role-specific execution guidance based on responsibility_type
- Include output schema matching tasks.csv output columns
See instructions/agent-instruction.md for the base instruction template that is customized per role.
Error Handling
| Error |
Resolution |
| Circular dependency |
Detect in wave computation, abort with error message |
| CSV agent timeout |
Mark as failed in results, continue with wave |
| CSV agent failed |
Mark as failed, skip dependent tasks in later waves |
| Interactive agent timeout |
Urge convergence via send_input, then close if still timed out |
| Interactive agent failed |
Mark as failed, skip dependents |
| All agents in wave failed |
Log error, offer retry or abort |
| CSV parse error |
Validate CSV format before execution, show line number |
| discoveries.ndjson corrupt |
Ignore malformed lines, continue with valid entries |
| No capabilities detected |
Default to single general role with TASK prefix |
| All capabilities merge to one |
Valid: single-role execution, reduced overhead |
| Task description too vague |
AskUserQuestion for clarification in Phase 0 |
| Continue mode: no session found |
List available sessions, prompt user to select |
| Role instruction generation fails |
Fall back to generic instruction template |
Core Rules
- Start Immediately: First action is session initialization, then Phase 0/1
- Wave Order is Sacred: Never execute wave N before wave N-1 completes and results are merged
- CSV is Source of Truth: Master tasks.csv holds all state (both csv-wave and interactive)
- CSV First: Default to csv-wave for tasks; only use interactive when interaction pattern requires it
- Context Propagation: prev_context built from master CSV, not from memory
- Discovery Board is Append-Only: Never clear, modify, or recreate discoveries.ndjson
- Skip on Failure: If a dependency failed, skip the dependent task
- Dynamic Roles: All worker roles are generated at runtime from task analysis -- no static role registry
- Cleanup Temp Files: Remove wave-{N}.csv after results are merged
- DO NOT STOP: Continuous execution until all waves complete or all remaining tasks are skipped
Coordinator Role Constraints (Main Agent)
CRITICAL: The coordinator (main agent executing this skill) is responsible for orchestration only, NOT implementation.
Coordinator Does NOT Execute Code: The main agent MUST NOT write, modify, or implement any code directly. All implementation work is delegated to spawned team agents. The coordinator only:
- Spawns agents with task assignments
- Waits for agent callbacks
- Merges results and coordinates workflow
- Manages workflow transitions between phases
Patient Waiting is Mandatory: Agent execution takes significant time (typically 10-30 minutes per phase, sometimes longer). The coordinator MUST:
- Wait patiently for
wait() calls to complete
- NOT skip workflow steps due to perceived delays
- NOT assume agents have failed just because they're taking time
- Trust the timeout mechanisms defined in the skill
Use send_input for Clarification: When agents need guidance or appear stuck, the coordinator MUST:
- Use
send_input() to ask questions or provide clarification
- NOT skip the agent or move to next phase prematurely
- Give agents opportunity to respond before escalating
- Example:
send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })
No Workflow Shortcuts: The coordinator MUST NOT:
- Skip phases or stages defined in the workflow
- Bypass required approval or review steps
- Execute dependent tasks before prerequisites complete
- Assume task completion without explicit agent callback
- Make up or fabricate agent results
Respect Long-Running Processes: This is a complex multi-agent workflow that requires patience:
- Total execution time may range from 30-90 minutes or longer
- Each phase may take 10-30 minutes depending on complexity
- The coordinator must remain active and attentive throughout the entire process
- Do not terminate or skip steps due to time concerns
1---2name: team-coordinate3description: Universal team coordination skill with dynamic role generation. Analyzes task, generates worker roles at runtime, decomposes into CSV tasks with dependency waves, dispatches parallel CSV agents per wave. Coordinator is orchestrator; all workers are CSV or interactive agents with dynamically generated instructions.4---5
6## Auto Mode
7
8When `--yes` or `-y`: Auto-confirm task decomposition, skip interactive validation, use defaults.
9
10# Team Coordinate
11
12## Usage
13
14```bash
15$team-coordinate "Implement user authentication with JWT tokens"
16$team-coordinate -c 4 "Refactor payment module and write API documentation"
17$team-coordinate -y "Analyze codebase security and fix vulnerabilities"
18$team-coordinate --continue "tc-auth-jwt-20260308"
19```
20
21**Flags**:
22- `-y, --yes`: Skip all confirmations (auto mode)
23- `-c, --concurrency N`: Max concurrent agents within each wave (default: 3)
24- `--continue`: Resume existing session
25
26**Output Directory**: `.workflow/.csv-wave/{session-id}/`
27**Core Output**: `tasks.csv` (master state) + `results.csv` (final) + `discoveries.ndjson` (shared exploration) + `context.md` (human-readable report)
28
29---
30
31## Overview
32
33Universal team coordination: analyze task -> detect capabilities -> generate dynamic role instructions -> decompose into dependency-ordered CSV tasks -> execute wave-by-wave -> deliver results. Only the **coordinator** (this orchestrator) is built-in. All worker roles are **dynamically generated** as CSV agent instructions at runtime.
34
35**Execution Model**: Hybrid -- CSV wave pipeline (primary) + individual agent spawn (secondary)
36
37```
38+-------------------------------------------------------------------+
39| TEAM COORDINATE WORKFLOW |
40+-------------------------------------------------------------------+
41| |
42| Phase 0: Pre-Wave Interactive (Requirement Clarification) |
43| +- Parse user task description |
44| +- Clarify ambiguous requirements (AskUserQuestion) |
45| +- Output: refined requirements for decomposition |
46| |
47| Phase 1: Requirement -> CSV + Classification |
48| +- Signal detection: keyword scan -> capability inference |
49| +- Dependency graph construction (DAG) |
50| +- Role minimization (cap at 5 roles) |
51| +- Classify tasks: csv-wave | interactive (exec_mode) |
52| +- Compute dependency waves (topological sort) |
53| +- Generate tasks.csv with wave + exec_mode columns |
54| +- Generate per-role agent instructions dynamically |
55| +- User validates task breakdown (skip if -y) |
56| |
57| Phase 2: Wave Execution Engine (Extended) |
58| +- For each wave (1..N): |
59| | +- Execute pre-wave interactive tasks (if any) |
60| | +- Build wave CSV (filter csv-wave tasks for this wave) |
61| | +- Inject previous findings into prev_context column |
62| | +- spawn_agents_on_csv(wave CSV) |
63| | +- Execute post-wave interactive tasks (if any) |
64| | +- Merge all results into master tasks.csv |
65| | +- Check: any failed? -> skip dependents |
66| +- discoveries.ndjson shared across all modes (append-only) |
67| |
68| Phase 3: Post-Wave Interactive (Completion Action) |
69| +- Pipeline completion report |
70| +- Interactive completion choice (Archive/Keep/Export) |
71| +- Final aggregation / report |
72| |
73| Phase 4: Results Aggregation |
74| +- Export final results.csv |
75| +- Generate context.md with all findings |
76| +- Display summary: completed/failed/skipped per wave |
77| +- Offer: view results | retry failed | done |
78| |
79+-------------------------------------------------------------------+
80```
81
82---
83
84## Task Classification Rules
85
86Each task is classified by `exec_mode`:
87
88| exec_mode | Mechanism | Criteria |
89|-----------|-----------|----------|
90| `csv-wave` | `spawn_agents_on_csv` | One-shot, structured I/O, no multi-round interaction |
91| `interactive` | `spawn_agent`/`wait`/`send_input`/`close_agent` | Multi-round, needs clarification, revision cycles |
92
93**Classification Decision**:
94
95| Task Property | Classification |
96|---------------|---------------|
97| Single-pass code implementation | `csv-wave` |
98| Single-pass analysis or documentation | `csv-wave` |
99| Research with defined scope | `csv-wave` |
100| Testing with known targets | `csv-wave` |
101| Design requiring iterative refinement | `interactive` |
102| Plan requiring user approval checkpoint | `interactive` |
103| Revision cycle (fix-verify loop) | `interactive` |
104
105---
106
107## CSV Schema
108
109### tasks.csv (Master State)
110
111```csv
112id,title,description,role,responsibility_type,output_type,deps,context_from,exec_mode,wave,status,findings,artifacts_produced,error
113"RESEARCH-001","Investigate auth patterns","Research JWT authentication patterns and best practices","researcher","orchestration","artifact","","","csv-wave","1","pending","","",""
114"IMPL-001","Implement auth module","Build JWT authentication middleware","developer","code-gen","codebase","RESEARCH-001","RESEARCH-001","csv-wave","2","pending","","",""
115"TEST-001","Validate auth implementation","Write and run tests for auth module","tester","validation","artifact","IMPL-001","IMPL-001","csv-wave","3","pending","","",""
116```
117
118**Columns**:
119
120| Column | Phase | Description |
121|--------|-------|-------------|
122| `id` | Input | Unique task identifier (PREFIX-NNN format) |
123| `title` | Input | Short task title |
124| `description` | Input | Detailed task description with goal, steps, success criteria |
125| `role` | Input | Dynamic role name (researcher, developer, analyst, etc.) |
126| `responsibility_type` | Input | `orchestration`, `read-only`, `code-gen`, `code-gen-docs`, `validation` |
127| `output_type` | Input | `artifact` (session files), `codebase` (project files), `mixed` |
128| `deps` | Input | Semicolon-separated dependency task IDs |
129| `context_from` | Input | Semicolon-separated task IDs whose findings this task needs |
130| `exec_mode` | Input | `csv-wave` or `interactive` |
131| `wave` | Computed | Wave number (computed by topological sort, 1-based) |
132| `status` | Output | `pending` -> `completed` / `failed` / `skipped` |
133| `findings` | Output | Key discoveries or implementation notes (max 500 chars) |
134| `artifacts_produced` | Output | Semicolon-separated paths of produced artifacts |
135| `error` | Output | Error message if failed (empty if success) |
136
137### Per-Wave CSV (Temporary)
138
139Each wave generates a temporary `wave-{N}.csv` with extra `prev_context` column (csv-wave tasks only).
140
141---
142
143## Agent Registry (Interactive Agents)
144
145| Agent | Role File | Pattern | Responsibility | Position |
146|-------|-----------|---------|----------------|----------|
147| Plan Reviewer | agents/plan-reviewer.md | 2.3 (send_input cycle) | Review and approve plans before execution waves | pre-wave |
148| Completion Handler | agents/completion-handler.md | 2.3 (send_input cycle) | Handle pipeline completion action (Archive/Keep/Export) | standalone |
149
150> **COMPACT PROTECTION**: Agent files are execution documents. When context compression occurs, **you MUST immediately `Read` the corresponding agent.md** to reload.
151
152---
153
154## Output Artifacts
155
156| File | Purpose | Lifecycle |
157|------|---------|-----------|
158| `tasks.csv` | Master state -- all tasks with status/findings | Updated after each wave |
159| `wave-{N}.csv` | Per-wave input (temporary, csv-wave tasks only) | Created before wave, deleted after |
160| `results.csv` | Final export of all task results | Created in Phase 4 |
161| `discoveries.ndjson` | Shared exploration board (all agents, both modes) | Append-only, carries across waves |
162| `context.md` | Human-readable execution report | Created in Phase 4 |
163| `task-analysis.json` | Phase 0/1 output: capabilities, dependency graph, roles | Created in Phase 1 |
164| `role-instructions/` | Dynamically generated per-role instruction templates | Created in Phase 1 |
165| `interactive/{id}-result.json` | Results from interactive tasks | Created per interactive task |
166
167---
168
169## Session Structure
170
171```
172.workflow/.csv-wave/{session-id}/
173+-- tasks.csv # Master state (all tasks, both modes)
174+-- results.csv # Final results export
175+-- discoveries.ndjson # Shared discovery board (all agents)
176+-- context.md # Human-readable report
177+-- task-analysis.json # Phase 1 analysis output
178+-- wave-{N}.csv # Temporary per-wave input (csv-wave only)
179+-- role-instructions/ # Dynamically generated instruction templates
180| +-- researcher.md
181| +-- developer.md
182| +-- ...
183+-- artifacts/ # All deliverables from workers
184| +-- research-findings.md
185| +-- implementation-summary.md
186| +-- ...
187+-- interactive/ # Interactive task artifacts
188| +-- {id}-result.json
189+-- wisdom/ # Cross-task knowledge
190 +-- learnings.md
191 +-- decisions.md
192```
193
194---
195
196## Implementation
197
198### Session Initialization
199
200```javascript
201const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
202
203const AUTO_YES = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
204const continueMode = $ARGUMENTS.includes('--continue')
205const concurrencyMatch = $ARGUMENTS.match(/(?:--concurrency|-c)\s+(\d+)/)
206const maxConcurrency = concurrencyMatch ? parseInt(concurrencyMatch[1]) : 3
207
208const requirement = $ARGUMENTS
209 .replace(/--yes|-y|--continue|--concurrency\s+\d+|-c\s+\d+/g, '')
210 .trim()
211
212const slug = requirement.toLowerCase()
213 .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
214 .substring(0, 40)
215const dateStr = getUtc8ISOString().substring(0, 10).replace(/-/g, '')
216const sessionId = `tc-${slug}-${dateStr}`
217const sessionFolder = `.workflow/.csv-wave/${sessionId}`
218
219Bash(`mkdir -p ${sessionFolder}/artifacts ${sessionFolder}/role-instructions ${sessionFolder}/interactive ${sessionFolder}/wisdom`)
220
221// Initialize discoveries.ndjson
222Write(`${sessionFolder}/discoveries.ndjson`, '')
223
224// Initialize wisdom files
225Write(`${sessionFolder}/wisdom/learnings.md`, '# Learnings\n')
226Write(`${sessionFolder}/wisdom/decisions.md`, '# Decisions\n')
227```
228
229---
230
231### Phase 0: Pre-Wave Interactive (Requirement Clarification)
232
233**Objective**: Parse user task, clarify ambiguities, prepare for decomposition.
234
235**Workflow**:
236
2371. **Parse user task description** from $ARGUMENTS
238
2392. **Check for existing sessions** (continue mode):
240 - Scan `.workflow/.csv-wave/tc-*/tasks.csv` for sessions with pending tasks
241 - If `--continue`: resume the specified or most recent session, skip to Phase 2
242 - If active session found: ask user whether to resume or start new
243
2443. **Clarify if ambiguous** (skip if AUTO_YES):
245 ```javascript
246 AskUserQuestion({
247 questions: [{
248 question: "Please confirm the task scope and deliverables:",
249 header: "Task Clarification",
250 multiSelect: false,
251 options: [
252 { label: "Proceed as described", description: "Task is clear enough" },
253 { label: "Narrow scope", description: "Specify files/modules/areas" },
254 { label: "Add constraints", description: "Timeline, tech stack, style" }
255 ]
256 }]
257 })
258 ```
259
2604. **Output**: Refined requirement string for Phase 1
261
262**Success Criteria**:
263- Refined requirements available for Phase 1 decomposition
264- Existing session detected and handled if applicable
265
266---
267
268### Phase 1: Requirement -> CSV + Classification
269
270**Objective**: Analyze task, detect capabilities, build dependency graph, generate tasks.csv and role instructions.
271
272**Decomposition Rules**:
273
2741. **Signal Detection** -- scan task description for capability keywords:
275
276| Signal | Keywords | Capability | Prefix | Responsibility Type |
277|--------|----------|------------|--------|---------------------|
278| Research | investigate, explore, compare, survey, find, research, discover | researcher | RESEARCH | orchestration |
279| Writing | write, draft, document, article, report, summarize | writer | DRAFT | code-gen-docs |
280| Coding | implement, build, code, fix, refactor, develop, create, migrate | developer | IMPL | code-gen |
281| Design | design, architect, plan, structure, blueprint, schema | designer | DESIGN | orchestration |
282| Analysis | analyze, review, audit, assess, evaluate, inspect, diagnose | analyst | ANALYSIS | read-only |
283| Testing | test, verify, validate, QA, quality, check, coverage | tester | TEST | validation |
284| Planning | plan, breakdown, organize, schedule, decompose, roadmap | planner | PLAN | orchestration |
285
2862. **Dependency Graph** -- build DAG using natural ordering tiers:
287
288| Tier | Capabilities | Description |
289|------|-------------|-------------|
290| 0 | researcher, planner | Knowledge gathering / planning |
291| 1 | designer | Design (requires tier 0 if present) |
292| 2 | writer, developer | Creation (requires design/plan if present) |
293| 3 | analyst, tester | Validation (requires artifacts to validate) |
294
2953. **Role Minimization** -- merge overlapping capabilities, cap at 5 roles
296
2974. **Key File Inference** -- extract nouns from task description, map to likely file paths
298
2995. **output_type derivation**:
300
301| Task Signal | output_type |
302|-------------|-------------|
303| "write report", "analyze", "research" | `artifact` |
304| "update code", "modify", "fix bug" | `codebase` |
305| "implement feature + write summary" | `mixed` |
306
307**Classification Rules**:
308
309| Task Property | exec_mode |
310|---------------|-----------|
311| Single-pass implementation/analysis/documentation | `csv-wave` |
312| Needs iterative user approval | `interactive` |
313| Fix-verify revision cycle | `interactive` |
314| Standard research, coding, testing | `csv-wave` |
315
316**Wave Computation**: Kahn's BFS topological sort with depth tracking.
317
318```javascript
319// After task analysis, generate dynamic role instruction templates
320for (const role of analysisResult.roles) {
321 const instruction = generateRoleInstruction(role, sessionFolder)
322 Write(`${sessionFolder}/role-instructions/${role.name}.md`, instruction)
323}
324
325// Generate tasks.csv from dependency graph
326const tasks = buildTasksCsv(analysisResult)
327Write(`${sessionFolder}/tasks.csv`, toCsv(tasks))
328Write(`${sessionFolder}/task-analysis.json`, JSON.stringify(analysisResult, null, 2))
329```
330
331**User Validation**: Display task breakdown with wave + exec_mode assignment (skip if AUTO_YES).
332
333**Success Criteria**:
334- tasks.csv created with valid schema, wave, and exec_mode assignments
335- Role instruction templates generated in role-instructions/
336- task-analysis.json written
337- No circular dependencies
338- User approved (or AUTO_YES)
339
340---
341
342### Phase 2: Wave Execution Engine (Extended)
343
344**Objective**: Execute tasks wave-by-wave with hybrid mechanism support and cross-wave context propagation.
345
346```javascript
347const masterCsv = Read(`${sessionFolder}/tasks.csv`)
348let tasks = parseCsv(masterCsv)
349const maxWave = Math.max(...tasks.map(t => t.wave))
350
351for (let wave = 1; wave <= maxWave; wave++) {
352 console.log(`\nWave ${wave}/${maxWave}`)
353
354 // 1. Separate tasks by exec_mode
355 const waveTasks = tasks.filter(t => t.wave === wave && t.status === 'pending')
356 const csvTasks = waveTasks.filter(t => t.exec_mode === 'csv-wave')
357 const interactiveTasks = waveTasks.filter(t => t.exec_mode === 'interactive')
358
359 // 2. Check dependencies -- skip tasks whose deps failed
360 for (const task of waveTasks) {
361 const depIds = (task.deps || '').split(';').filter(Boolean)
362 const depStatuses = depIds.map(id => tasks.find(t => t.id === id)?.status)
363 if (depStatuses.some(s => s === 'failed' || s === 'skipped')) {
364 task.status = 'skipped'
365 task.error = `Dependency failed: ${depIds.filter((id, i) =>
366 ['failed','skipped'].includes(depStatuses[i])).join(', ')}`
367 }
368 }
369
370 // 3. Execute pre-wave interactive tasks (e.g., plan approval)
371 const preWaveInteractive = interactiveTasks.filter(t => t.status === 'pending')
372 for (const task of preWaveInteractive) {
373 // Read agent definition
374 Read(`agents/plan-reviewer.md`)
375
376 const agent = spawn_agent({
377 message: `## TASK ASSIGNMENT\n\n### MANDATORY FIRST STEPS\n1. Read: ${sessionFolder}/discoveries.ndjson\n\nGoal: ${task.description}\nScope: ${task.title}\nSession: ${sessionFolder}\n\n### Previous Context\n${buildPrevContext(task, tasks)}`
378 })
379 const result = wait({ ids: [agent], timeout_ms: 600000 })
380 if (result.timed_out) {
381 send_input({ id: agent, message: "Please finalize and output current findings." })
382 wait({ ids: [agent], timeout_ms: 120000 })
383 }
384 Write(`${sessionFolder}/interactive/${task.id}-result.json`, JSON.stringify({
385 task_id: task.id, status: "completed", findings: parseFindings(result),
386 timestamp: getUtc8ISOString()
387 }))
388 close_agent({ id: agent })
389 task.status = 'completed'
390 task.findings = parseFindings(result)
391 }
392
393 // 4. Build prev_context for csv-wave tasks
394 const pendingCsvTasks = csvTasks.filter(t => t.status === 'pending')
395 for (const task of pendingCsvTasks) {
396 task.prev_context = buildPrevContext(task, tasks)
397 }
398
399 if (pendingCsvTasks.length > 0) {
400 // 5. Write wave CSV
401 Write(`${sessionFolder}/wave-${wave}.csv`, toCsv(pendingCsvTasks))
402
403 // 6. Determine instruction for this wave (use role-specific instruction)
404 // Group tasks by role, build combined instruction
405 const waveInstruction = buildWaveInstruction(pendingCsvTasks, sessionFolder, wave)
406
407 // 7. Execute wave via spawn_agents_on_csv
408 spawn_agents_on_csv({
409 csv_path: `${sessionFolder}/wave-${wave}.csv`,
410 id_column: "id",
411 instruction: waveInstruction,
412 max_concurrency: maxConcurrency,
413 max_runtime_seconds: 900,
414 output_csv_path: `${sessionFolder}/wave-${wave}-results.csv`,
415 output_schema: {
416 type: "object",
417 properties: {
418 id: { type: "string" },
419 status: { type: "string", enum: ["completed", "failed"] },
420 findings: { type: "string" },
421 artifacts_produced: { type: "string" },
422 error: { type: "string" }
423 }
424 }
425 })
426
427 // 8. Merge results into master CSV
428 const results = parseCsv(Read(`${sessionFolder}/wave-${wave}-results.csv`))
429 for (const r of results) {
430 const t = tasks.find(t => t.id === r.id)
431 if (t) Object.assign(t, r)
432 }
433 }
434
435 // 9. Update master CSV
436 Write(`${sessionFolder}/tasks.csv`, toCsv(tasks))
437
438 // 10. Cleanup temp files
439 Bash(`rm -f ${sessionFolder}/wave-${wave}.csv ${sessionFolder}/wave-${wave}-results.csv`)
440
441 // 11. Display wave summary
442 const completed = waveTasks.filter(t => t.status === 'completed').length
443 const failed = waveTasks.filter(t => t.status === 'failed').length
444 const skipped = waveTasks.filter(t => t.status === 'skipped').length
445 console.log(`Wave ${wave} Complete: ${completed} completed, ${failed} failed, ${skipped} skipped`)
446}
447```
448
449**Success Criteria**:
450- All waves executed in order
451- Both csv-wave and interactive tasks handled per wave
452- Each wave's results merged into master CSV before next wave starts
453- Dependent tasks skipped when predecessor failed
454- discoveries.ndjson accumulated across all waves and mechanisms
455
456---
457
458### Phase 3: Post-Wave Interactive (Completion Action)
459
460**Objective**: Pipeline completion report and interactive completion choice.
461
462```javascript
463// 1. Generate pipeline summary
464const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
465const completed = tasks.filter(t => t.status === 'completed')
466const failed = tasks.filter(t => t.status === 'failed')
467
468console.log(`
469============================================
470TASK COMPLETE
471
472Deliverables:
473${completed.map(t => ` - ${t.id}: ${t.title} (${t.role})`).join('\n')}
474
475Pipeline: ${completed.length}/${tasks.length} tasks
476Duration: <elapsed>
477Session: ${sessionFolder}
478============================================
479`)
480
481// 2. Completion action
482if (!AUTO_YES) {
483 const choice = AskUserQuestion({
484 questions: [{
485 question: "Team pipeline complete. What would you like to do?",
486 header: "Completion",
487 multiSelect: false,
488 options: [
489 { label: "Archive & Clean (Recommended)", description: "Archive session, output final summary" },
490 { label: "Keep Active", description: "Keep session for follow-up work" },
491 { label: "Retry Failed", description: "Re-run failed tasks" }
492 ]
493 }]
494 })
495 // Handle choice accordingly
496}
497```
498
499**Success Criteria**:
500- Post-wave interactive processing complete
501- User informed of results
502
503---
504
505### Phase 4: Results Aggregation
506
507**Objective**: Generate final results and human-readable report.
508
509```javascript
510// 1. Export results.csv
511Bash(`cp ${sessionFolder}/tasks.csv ${sessionFolder}/results.csv`)
512
513// 2. Generate context.md
514const tasks = parseCsv(Read(`${sessionFolder}/tasks.csv`))
515let contextMd = `# Team Coordinate Report\n\n`
516contextMd += `**Session**: ${sessionId}\n`
517contextMd += `**Date**: ${getUtc8ISOString().substring(0, 10)}\n\n`
518
519contextMd += `## Summary\n`
520contextMd += `| Status | Count |\n|--------|-------|\n`
521contextMd += `| Completed | ${tasks.filter(t => t.status === 'completed').length} |\n`
522contextMd += `| Failed | ${tasks.filter(t => t.status === 'failed').length} |\n`
523contextMd += `| Skipped | ${tasks.filter(t => t.status === 'skipped').length} |\n\n`
524
525const maxWave = Math.max(...tasks.map(t => t.wave))
526contextMd += `## Wave Execution\n\n`
527for (let w = 1; w <= maxWave; w++) {
528 const waveTasks = tasks.filter(t => t.wave === w)
529 contextMd += `### Wave ${w}\n\n`
530 for (const t of waveTasks) {
531 const icon = t.status === 'completed' ? '[DONE]' : t.status === 'failed' ? '[FAIL]' : '[SKIP]'
532 contextMd += `${icon} **${t.title}** [${t.role}] ${t.findings || ''}\n\n`
533 }
534}
535
536Write(`${sessionFolder}/context.md`, contextMd)
537
538// 3. Display final summary
539console.log(`Results exported to: ${sessionFolder}/results.csv`)
540console.log(`Report generated at: ${sessionFolder}/context.md`)
541```
542
543**Success Criteria**:
544- results.csv exported (all tasks, both modes)
545- context.md generated
546- Summary displayed to user
547
548---
549
550## Shared Discovery Board Protocol
551
552All agents (csv-wave and interactive) share a single `discoveries.ndjson` file for cross-task knowledge exchange.
553
554**Format**: One JSON object per line (NDJSON):
555
556```jsonl
557{"ts":"2026-03-08T10:00:00Z","worker":"RESEARCH-001","type":"pattern_found","data":{"pattern_name":"Repository Pattern","location":"src/repos/","description":"Data access layer uses repository pattern"}}
558{"ts":"2026-03-08T10:05:00Z","worker":"IMPL-001","type":"file_modified","data":{"file":"src/auth/jwt.ts","change":"Added JWT middleware","lines_added":45}}
559```
560
561**Discovery Types**:
562
563| Type | Data Schema | Description |
564|------|-------------|-------------|
565| `pattern_found` | `{pattern_name, location, description}` | Design pattern identified |
566| `file_modified` | `{file, change, lines_added}` | File change recorded |
567| `dependency_found` | `{from, to, type}` | Dependency relationship discovered |
568| `issue_found` | `{file, line, severity, description}` | Issue or bug discovered |
569| `decision_made` | `{decision, rationale, impact}` | Design decision recorded |
570| `artifact_produced` | `{name, path, producer, type}` | Deliverable created |
571
572**Protocol**:
5731. Agents MUST read discoveries.ndjson at start of execution
5742. Agents MUST append relevant discoveries during execution
5753. Agents MUST NOT modify or delete existing entries
5764. Deduplication by `{type, data.file, data.pattern_name}` key
577
578---
579
580## Dynamic Role Instruction Generation
581
582The coordinator generates role-specific instruction templates during Phase 1. Each template is written to `role-instructions/{role-name}.md` and used as the `instruction` parameter for `spawn_agents_on_csv`.
583
584**Generation Rules**:
5851. Each instruction must be self-contained (agent has no access to master CSV)
5862. Use `{column_name}` placeholders for CSV column substitution
5873. Include session folder path as literal (not placeholder)
5884. Include mandatory discovery board read/write steps
5895. Include role-specific execution guidance based on responsibility_type
5906. Include output schema matching tasks.csv output columns
591
592See `instructions/agent-instruction.md` for the base instruction template that is customized per role.
593
594---
595
596## Error Handling
597
598| Error | Resolution |
599|-------|------------|
600| Circular dependency | Detect in wave computation, abort with error message |
601| CSV agent timeout | Mark as failed in results, continue with wave |
602| CSV agent failed | Mark as failed, skip dependent tasks in later waves |
603| Interactive agent timeout | Urge convergence via send_input, then close if still timed out |
604| Interactive agent failed | Mark as failed, skip dependents |
605| All agents in wave failed | Log error, offer retry or abort |
606| CSV parse error | Validate CSV format before execution, show line number |
607| discoveries.ndjson corrupt | Ignore malformed lines, continue with valid entries |
608| No capabilities detected | Default to single `general` role with TASK prefix |
609| All capabilities merge to one | Valid: single-role execution, reduced overhead |
610| Task description too vague | AskUserQuestion for clarification in Phase 0 |
611| Continue mode: no session found | List available sessions, prompt user to select |
612| Role instruction generation fails | Fall back to generic instruction template |
613
614---
615
616## Core Rules
617
6181. **Start Immediately**: First action is session initialization, then Phase 0/1
6192. **Wave Order is Sacred**: Never execute wave N before wave N-1 completes and results are merged
6203. **CSV is Source of Truth**: Master tasks.csv holds all state (both csv-wave and interactive)
6214. **CSV First**: Default to csv-wave for tasks; only use interactive when interaction pattern requires it
6225. **Context Propagation**: prev_context built from master CSV, not from memory
6236. **Discovery Board is Append-Only**: Never clear, modify, or recreate discoveries.ndjson
6247. **Skip on Failure**: If a dependency failed, skip the dependent task
6258. **Dynamic Roles**: All worker roles are generated at runtime from task analysis -- no static role registry
6269. **Cleanup Temp Files**: Remove wave-{N}.csv after results are merged
62710. **DO NOT STOP**: Continuous execution until all waves complete or all remaining tasks are skipped
628
629
630---
631
632## Coordinator Role Constraints (Main Agent)
633
634**CRITICAL**: The coordinator (main agent executing this skill) is responsible for **orchestration only**, NOT implementation.
635
63615. **Coordinator Does NOT Execute Code**: The main agent MUST NOT write, modify, or implement any code directly. All implementation work is delegated to spawned team agents. The coordinator only:
637 - Spawns agents with task assignments
638 - Waits for agent callbacks
639 - Merges results and coordinates workflow
640 - Manages workflow transitions between phases
641
64216. **Patient Waiting is Mandatory**: Agent execution takes significant time (typically 10-30 minutes per phase, sometimes longer). The coordinator MUST:
643 - Wait patiently for `wait()` calls to complete
644 - NOT skip workflow steps due to perceived delays
645 - NOT assume agents have failed just because they're taking time
646 - Trust the timeout mechanisms defined in the skill
647
64817. **Use send_input for Clarification**: When agents need guidance or appear stuck, the coordinator MUST:
649 - Use `send_input()` to ask questions or provide clarification
650 - NOT skip the agent or move to next phase prematurely
651 - Give agents opportunity to respond before escalating
652 - Example: `send_input({ id: agent_id, message: "Please provide status update or clarify blockers" })`
653
65418. **No Workflow Shortcuts**: The coordinator MUST NOT:
655 - Skip phases or stages defined in the workflow
656 - Bypass required approval or review steps
657 - Execute dependent tasks before prerequisites complete
658 - Assume task completion without explicit agent callback
659 - Make up or fabricate agent results
660
66119. **Respect Long-Running Processes**: This is a complex multi-agent workflow that requires patience:
662 - Total execution time may range from 30-90 minutes or longer
663 - Each phase may take 10-30 minutes depending on complexity
664 - The coordinator must remain active and attentive throughout the entire process
665 - Do not terminate or skip steps due to time concerns