diff --git a/.claude/skills/team-coordinate-v2/SKILL.md b/.claude/skills/team-coordinate-v2/SKILL.md new file mode 100644 index 00000000..db45c2f1 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/SKILL.md @@ -0,0 +1,274 @@ +--- +name: team-coordinate-v2 +description: Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on "team coordinate v2". +allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +--- + +# Team Coordinate v2 + +Universal team coordination skill: analyze task -> generate role-specs -> dispatch -> execute -> deliver. Only the **coordinator** is built-in. All worker roles are **dynamically generated** as lightweight role-spec files and spawned via the `team-worker` agent. + +## Key Changes from v1 + +| Change | Before (v1) | After (v2) | Impact | +|--------|------------|------------|--------| +| Worker agent | general-purpose + Skill load | team-worker agent (dedicated) | Eliminates Skill indirection | +| Role definitions | `/roles/.md` (~250 lines, includes Phase 1/5) | `/role-specs/.md` (~80 lines, Phase 2-4 only) | -68% worker content | +| Shared behavior | Duplicated in SKILL.md + each role.md | Built into team-worker agent | Single source of truth | +| Coordinator spawn | Skill(team-coordinate, --role=xxx) | Task(team-worker, role_spec=xxx.md) | Direct, no Skill call | +| Completion | Manual cleanup | Interactive completion action | Archive/Keep/Export prompt | + +## Architecture + +``` ++---------------------------------------------------+ +| Skill(skill="team-coordinate") | +| args="task description" | ++-------------------+-------------------------------+ + | + Orchestration Mode (auto -> coordinator) + | + Coordinator (built-in) + Phase 0-5 orchestration + | + +-------+-------+-------+-------+ + v v v v v + [team-worker agents, each loaded with a dynamic role-spec] + (roles generated at runtime from task analysis) + + Subagents (callable by any worker, not team members): + [discuss-subagent] - multi-perspective critique (dynamic perspectives) + [explore-subagent] - codebase exploration with cache +``` + +## Role Router + +This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. + +### Input Parsing + +Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. + +### Role Registry + +Only coordinator is statically registered. All other roles are dynamic, stored as role-specs in session. + +| Role | File | Type | +|------|------|------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | built-in orchestrator | +| (dynamic) | `/role-specs/.md` | runtime-generated role-spec | + +### Subagent Registry + +| Subagent | Spec | Callable By | Purpose | +|----------|------|-------------|---------| +| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | any role | Multi-perspective critique (dynamic perspectives) | +| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | any role | Codebase exploration with cache | + +### Dispatch + +Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. + +### Orchestration Mode + +User just provides task description. + +**Invocation**: `Skill(skill="team-coordinate", args="task description")` + +**Lifecycle**: +``` +User provides task description + -> coordinator Phase 1: task analysis (detect capabilities, build dependency graph) + -> coordinator Phase 2: generate role-specs + initialize session + -> coordinator Phase 3: create task chain from dependency graph + -> coordinator Phase 4: spawn first batch workers (background) -> STOP + -> Worker executes -> SendMessage callback -> coordinator advances next step + -> Loop until pipeline complete -> Phase 5 report + completion action +``` + +**User Commands** (wake paused coordinator): + +| Command | Action | +|---------|--------| +| `check` / `status` | Output execution status graph, no advancement | +| `resume` / `continue` | Check worker states, advance next step | + +--- + +## Coordinator Spawn Template + +### v2 Worker Spawn (all roles) + +When coordinator spawns workers, use `team-worker` agent with role-spec path: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker", + team_name: , + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: /role-specs/.md +session: +session_id: +team_name: +requirement: +inner_loop: + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +}) +``` + +**Inner Loop roles** (role has 2+ serial same-prefix tasks): Set `inner_loop: true`. The team-worker agent handles the loop internally. + +**Single-task roles**: Set `inner_loop: false`. + +--- + +## Completion Action + +When pipeline completes (all tasks done), coordinator presents an interactive choice: + +``` +AskUserQuestion({ + questions: [{ + question: "Team pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory, then clean" } + ] + }] +}) +``` + +### Action Handlers + +| Choice | Steps | +|--------|-------| +| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary with artifact paths | +| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-coordinate', args='resume')" | +| Export Results | AskUserQuestion(target path) -> copy artifacts to target -> Archive & Clean | + +--- + +## 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 ---+--> [team-worker A] Phase 1-5 + | (parallel OK) --+--> [team-worker B] Phase 1-5 + +- STOP (idle) -----+ | + | + callback <-----------------------------------------+ + (next beat) SendMessage + TaskUpdate(completed) +====================================================================== + + Fast-Advance (skips coordinator for simple linear successors) +====================================================================== + [Worker A] Phase 5 complete + +- 1 ready task? simple successor? --> spawn team-worker B directly + +- complex case? --> SendMessage to coordinator +====================================================================== +``` + +**Pipelines are dynamic**: Unlike static pipeline definitions, team-coordinate pipelines are generated per-task from the dependency graph. + +--- + +## Session Directory + +``` +.workflow/.team/TC--/ ++-- team-session.json # Session state + dynamic role registry ++-- task-analysis.json # Phase 1 output: capabilities, dependency graph ++-- role-specs/ # Dynamic role-spec definitions (generated Phase 2) +| +-- .md # Lightweight: frontmatter + Phase 2-4 only +| +-- .md ++-- artifacts/ # All MD deliverables from workers +| +-- .md ++-- shared-memory.json # Cross-role state store ++-- wisdom/ # Cross-task knowledge +| +-- learnings.md +| +-- decisions.md +| +-- issues.md ++-- explorations/ # Shared explore cache +| +-- cache-index.json +| +-- explore-.json ++-- discussions/ # Inline discuss records +| +-- .md ++-- .msg/ # Team message bus logs +``` + +### team-session.json Schema + +```json +{ + "session_id": "TC--", + "task_description": "", + "status": "active | paused | completed", + "team_name": "", + "roles": [ + { + "name": "", + "prefix": "", + "responsibility_type": "", + "inner_loop": false, + "role_spec": "role-specs/.md" + } + ], + "pipeline": { + "dependency_graph": {}, + "tasks_total": 0, + "tasks_completed": 0 + }, + "active_workers": [], + "completed_tasks": [], + "completion_action": "interactive", + "created_at": "" +} +``` + +--- + +## Session Resume + +Coordinator supports `resume` / `continue` for interrupted sessions: + +1. Scan `.workflow/.team/TC-*/team-session.json` for active/paused sessions +2. Multiple matches -> AskUserQuestion for selection +3. Audit TaskList -> reconcile session state <-> task status +4. Reset in_progress -> pending (interrupted tasks) +5. Rebuild team and spawn needed workers only +6. Create missing tasks with correct blockedBy +7. Kick first executable task -> Phase 4 coordination loop + +--- + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Unknown command | Error with available command list | +| Dynamic role-spec not found | Error, coordinator may need to regenerate | +| Command file not found | Fallback to inline execution | +| Discuss subagent fails | Worker proceeds without discuss, logs warning | +| Explore cache corrupt | Clear cache, re-explore | +| Fast-advance spawns wrong task | Coordinator reconciles on next callback | +| capability_gap reported | Coordinator generates new role-spec via handleAdapt | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/analyze-task.md b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/analyze-task.md new file mode 100644 index 00000000..5ab19baf --- /dev/null +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/analyze-task.md @@ -0,0 +1,151 @@ +# Command: analyze-task + +## Purpose + +Parse user task description -> detect required capabilities -> build dependency graph -> design dynamic roles with role-spec metadata. Outputs structured task-analysis.json with frontmatter fields for role-spec generation. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task description | User input from Phase 1 | Yes | +| Clarification answers | AskUserQuestion results (if any) | No | +| Session folder | From coordinator Phase 2 | Yes | + +## Phase 3: Task Analysis + +### Step 1: Signal Detection + +Scan task description for capability keywords: + +| Signal | Keywords | Capability | Prefix | Responsibility Type | +|--------|----------|------------|--------|---------------------| +| Research | investigate, explore, compare, survey, find, research, discover, benchmark, study | researcher | RESEARCH | orchestration | +| Writing | write, draft, document, article, report, blog, describe, explain, summarize, content | writer | DRAFT | code-gen (docs) | +| Coding | implement, build, code, fix, refactor, develop, create app, program, migrate, port | developer | IMPL | code-gen (code) | +| Design | design, architect, plan, structure, blueprint, model, schema, wireframe, layout | designer | DESIGN | orchestration | +| Analysis | analyze, review, audit, assess, evaluate, inspect, examine, diagnose, profile | analyst | ANALYSIS | read-only | +| Testing | test, verify, validate, QA, quality, check, assert, coverage, regression | tester | TEST | validation | +| Planning | plan, breakdown, organize, schedule, decompose, roadmap, strategy, prioritize | planner | PLAN | orchestration | + +**Multi-match**: A task may trigger multiple capabilities. + +**No match**: Default to a single `general` capability with `TASK` prefix. + +### Step 2: Artifact Inference + +Each capability produces default output artifacts: + +| Capability | Default Artifact | Format | +|------------|-----------------|--------| +| researcher | Research findings | `/artifacts/research-findings.md` | +| writer | Written document(s) | `/artifacts/.md` | +| developer | Code implementation | Source files + `/artifacts/implementation-summary.md` | +| designer | Design document | `/artifacts/design-spec.md` | +| analyst | Analysis report | `/artifacts/analysis-report.md` | +| tester | Test results | `/artifacts/test-report.md` | +| planner | Execution plan | `/artifacts/execution-plan.md` | + +### Step 3: Dependency Graph Construction + +Build a DAG of work streams using natural ordering tiers: + +| Tier | Capabilities | Description | +|------|-------------|-------------| +| 0 | researcher, planner | Knowledge gathering / planning | +| 1 | designer | Design (requires context from tier 0 if present) | +| 2 | writer, developer | Creation (requires design/plan if present) | +| 3 | analyst, tester | Validation (requires artifacts to validate) | + +### Step 4: Complexity Scoring + +| Factor | Weight | Condition | +|--------|--------|-----------| +| Capability count | +1 each | Number of distinct capabilities | +| Cross-domain factor | +2 | Capabilities span 3+ tiers | +| Parallel tracks | +1 each | Independent parallel work streams | +| Serial depth | +1 per level | Longest dependency chain length | + +| Total Score | Complexity | Role Limit | +|-------------|------------|------------| +| 1-3 | Low | 1-2 roles | +| 4-6 | Medium | 2-3 roles | +| 7+ | High | 3-5 roles | + +### Step 5: Role Minimization + +Apply merging rules to reduce role count (cap at 5). + +### Step 6: Role-Spec Metadata Assignment + +For each role, determine frontmatter fields: + +| Field | Derivation | +|-------|------------| +| `prefix` | From capability prefix (e.g., RESEARCH, DRAFT, IMPL) | +| `inner_loop` | `true` if role has 2+ serial same-prefix tasks | +| `subagents` | Inferred from responsibility type: orchestration -> [explore], code-gen (docs) -> [explore], validation -> [] | +| `message_types.success` | `_complete` | +| `message_types.error` | `error` | + +## Phase 4: Output + +Write `/task-analysis.json`: + +```json +{ + "task_description": "", + "capabilities": [ + { + "name": "researcher", + "prefix": "RESEARCH", + "responsibility_type": "orchestration", + "tasks": [ + { "id": "RESEARCH-001", "description": "..." } + ], + "artifacts": ["research-findings.md"] + } + ], + "dependency_graph": { + "RESEARCH-001": [], + "DRAFT-001": ["RESEARCH-001"], + "ANALYSIS-001": ["DRAFT-001"] + }, + "roles": [ + { + "name": "researcher", + "prefix": "RESEARCH", + "responsibility_type": "orchestration", + "task_count": 1, + "inner_loop": false, + "role_spec_metadata": { + "subagents": ["explore"], + "message_types": { + "success": "research_complete", + "error": "error" + } + } + } + ], + "complexity": { + "capability_count": 2, + "cross_domain_factor": false, + "parallel_tracks": 0, + "serial_depth": 2, + "total_score": 3, + "level": "low" + }, + "artifacts": [ + { "name": "research-findings.md", "producer": "researcher", "path": "artifacts/research-findings.md" } + ] +} +``` + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| No capabilities detected | Default to single `general` role with TASK prefix | +| Circular dependency in graph | Break cycle at lowest-tier edge, warn | +| Task description too vague | Return minimal analysis, coordinator will AskUserQuestion | +| All capabilities merge into one | Valid -- single-role execution, no team overhead | diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..986d6ba5 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/dispatch.md @@ -0,0 +1,87 @@ +# Command: dispatch + +## Purpose + +Create task chains from dynamic dependency graphs. Builds pipelines from the task-analysis.json produced by Phase 1. Workers are spawned as team-worker agents with role-spec paths. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Task analysis | `/task-analysis.json` | Yes | +| Session file | `/team-session.json` | Yes | +| Role registry | `team-session.json#roles` | Yes | +| Scope | User requirements description | Yes | + +## Phase 3: Task Chain Creation + +### Workflow + +1. **Read dependency graph** from `task-analysis.json#dependency_graph` +2. **Topological sort** tasks to determine creation order +3. **Validate** all task owners exist in role registry +4. **For each task** (in topological order): + +``` +TaskCreate({ + subject: "-", + owner: "", + description: "\nSession: \nScope: \nInnerLoop: \nRoleSpec: /role-specs/.md", + blockedBy: [], + status: "pending" +}) +``` + +5. **Update team-session.json** with pipeline and tasks_total +6. **Validate** created chain + +### Task Description Template + +Every task description includes session path, inner loop flag, and role-spec path: + +``` + +Session: +Scope: +InnerLoop: +RoleSpec: /role-specs/.md +``` + +### InnerLoop Flag Rules + +| Condition | InnerLoop | +|-----------|-----------| +| Role has 2+ serial same-prefix tasks | true | +| Role has 1 task | false | +| Tasks are parallel (no dependency between them) | false | + +### Dependency Validation + +| Check | Criteria | +|-------|----------| +| No orphan tasks | Every task is reachable from at least one root | +| No circular deps | Topological sort succeeds without cycle | +| All owners valid | Every task owner exists in team-session.json#roles | +| All blockedBy valid | Every blockedBy references an existing task subject | +| Session reference | Every task description contains `Session: ` | +| RoleSpec reference | Every task description contains `RoleSpec: ` | + +## Phase 4: Validation + +| Check | Criteria | +|-------|----------| +| Task count | Matches dependency_graph node count | +| Dependencies | Every blockedBy references an existing task subject | +| Owner assignment | Each task owner is in role registry | +| Session reference | Every task description contains `Session:` | +| Pipeline integrity | No disconnected subgraphs (warn if found) | + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Circular dependency detected | Report cycle, halt task creation | +| Owner not in role registry | Error, coordinator must fix roles first | +| TaskCreate fails | Log error, report to coordinator | +| Duplicate task subject | Skip creation, log warning | +| Empty dependency graph | Error, task analysis may have failed | diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..bf36bad1 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/commands/monitor.md @@ -0,0 +1,301 @@ +# Command: monitor + +## Purpose + +Event-driven pipeline coordination with Spawn-and-Stop pattern. Role names are read from `team-session.json#roles`. Workers are spawned as `team-worker` agents with role-spec paths. Includes `handleComplete` for pipeline completion action and `handleAdapt` for mid-pipeline capability gap handling. + +## Constants + +| Constant | Value | Description | +|----------|-------|-------------| +| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` | +| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS | +| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors | +| WORKER_AGENT | team-worker | All workers spawned as team-worker agents | + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session file | `/team-session.json` | Yes | +| Task list | `TaskList()` | Yes | +| Active workers | session.active_workers[] | Yes | +| Role registry | session.roles[] | Yes | + +**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name`. Role-spec paths are in `session.roles[].role_spec`. + +## Phase 3: Handler Routing + +### Wake-up Source Detection + +Parse `$ARGUMENTS` to determine handler: + +| Priority | Condition | Handler | +|----------|-----------|---------| +| 1 | Message contains `[]` from session roles | handleCallback | +| 2 | Contains "capability_gap" | handleAdapt | +| 3 | Contains "check" or "status" | handleCheck | +| 4 | Contains "resume", "continue", or "next" | handleResume | +| 5 | Pipeline detected as complete | handleComplete | +| 6 | None of the above (initial spawn after dispatch) | handleSpawnNext | + +--- + +### Handler: handleCallback + +Worker completed a task. Verify completion, update state, auto-advance. + +``` +Receive callback from [] + +- Find matching active worker by role (from session.roles) + +- Is this a progress update (not final)? (Inner Loop intermediate task completion) + | +- YES -> Update session state, do NOT remove from active_workers -> STOP + +- Task status = completed? + | +- YES -> remove from active_workers -> update session + | | +- -> handleSpawnNext + | +- NO -> progress message, do not advance -> STOP + +- No matching worker found + +- Scan all active workers for completed tasks + +- Found completed -> process each -> handleSpawnNext + +- None completed -> STOP +``` + +**Fast-advance note**: A worker may have already spawned its successor via fast-advance. When processing a callback: +1. Check if the expected next task is already `in_progress` (fast-advanced) +2. If yes -> skip spawning that task, update active_workers to include the fast-advanced worker +3. If no -> normal handleSpawnNext + +--- + +### Handler: handleCheck + +Read-only status report. No pipeline advancement. + +**Output format**: + +``` +[coordinator] Pipeline Status +[coordinator] Progress: / (%) + +[coordinator] Execution Graph: + + + done=completed >>>=running o=pending .=not created + +[coordinator] Active Workers: + > () - running [inner-loop: N/M tasks done] + +[coordinator] Ready to spawn: +[coordinator] Commands: 'resume' to advance | 'check' to refresh +``` + +Then STOP. + +--- + +### Handler: handleResume + +Check active worker completion, process results, advance pipeline. + +``` +Load active_workers from session + +- No active workers -> handleSpawnNext + +- Has active workers -> check each: + +- status = completed -> mark done, log + +- status = in_progress -> still running, log + +- other status -> worker failure -> reset to pending + After processing: + +- Some completed -> handleSpawnNext + +- All still running -> report status -> STOP + +- All failed -> handleSpawnNext (retry) +``` + +--- + +### Handler: handleSpawnNext + +Find all ready tasks, spawn team-worker agents in background, update session, STOP. + +``` +Collect task states from TaskList() + +- completedSubjects: status = completed + +- inProgressSubjects: status = in_progress + +- readySubjects: pending + all blockedBy in completedSubjects + +Ready tasks found? + +- NONE + work in progress -> report waiting -> STOP + +- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete + +- HAS ready tasks -> for each: + +- Is task owner an Inner Loop role AND that role already has an active_worker? + | +- YES -> SKIP spawn (existing worker will pick it up via inner loop) + | +- NO -> normal spawn below + +- TaskUpdate -> in_progress + +- team_msg log -> task_unblocked (team=, NOT team name) + +- Spawn team-worker (see spawn tool call below) + +- Add to session.active_workers + Update session file -> output summary -> STOP +``` + +**Spawn worker tool call** (one per ready task): + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker for ", + team_name: , + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: /role-specs/.md +session: +session_id: +team_name: +requirement: +inner_loop: + +Read role_spec file to load Phase 2-4 domain instructions.` +}) +``` + +--- + +### Handler: handleComplete + +Pipeline complete. Execute completion action based on session configuration. + +``` +All tasks completed (no pending, no in_progress) + +- Generate pipeline summary: + | - Deliverables list with paths + | - Pipeline stats (tasks completed, duration) + | - Discussion verdicts (if any) + | + +- Read session.completion_action: + | + +- "interactive": + | AskUserQuestion({ + | questions: [{ + | question: "Team pipeline complete. What would you like to do?", + | header: "Completion", + | multiSelect: false, + | options: [ + | { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + | { label: "Keep Active", description: "Keep session for follow-up work" }, + | { label: "Export Results", description: "Export deliverables to target directory" } + | ] + | }] + | }) + | +- "Archive & Clean": + | | Update session status="completed" + | | TeamDelete() + | | Output final summary with artifact paths + | +- "Keep Active": + | | Update session status="paused" + | | Output: "Resume with: Skill(skill='team-coordinate', args='resume')" + | +- "Export Results": + | AskUserQuestion for target directory + | Copy deliverables to target + | Execute Archive & Clean flow + | + +- "auto_archive": + | Execute Archive & Clean without prompt + | + +- "auto_keep": + Execute Keep Active without prompt +``` + +**Fallback**: If completion action fails, default to Keep Active (session status="paused"), log warning. + +--- + +### Handler: handleAdapt + +Handle mid-pipeline capability gap discovery. A worker reports `capability_gap` when it encounters work outside its scope. + +**CONSTRAINT**: Maximum 5 worker roles per session. handleAdapt MUST enforce this limit. + +``` +Parse capability_gap message: + +- Extract: gap_description, requesting_role, suggested_capability + +- Validate gap is genuine: + +- Check existing roles in session.roles -> does any role cover this? + | +- YES -> redirect: SendMessage to that role's owner -> STOP + | +- NO -> genuine gap, proceed to role-spec generation + +- CHECK ROLE COUNT LIMIT (MAX 5 ROLES): + +- Count current roles in session.roles + +- If count >= 5: + +- Attempt to merge new capability into existing role + +- If merge NOT possible -> PAUSE, report to user + +- Generate new role-spec: + 1. Read specs/role-spec-template.md + 2. Fill template with: frontmatter (role, prefix, inner_loop, message_types) + Phase 2-4 content + 3. Write to /role-specs/.md + 4. Add to session.roles[] + +- Create new task(s) via TaskCreate + +- Update team-session.json + +- Spawn new team-worker -> STOP +``` + +--- + +### Worker Failure Handling + +When a worker has unexpected status (not completed, not in_progress): + +1. Reset task -> pending via TaskUpdate +2. Log via team_msg (type: error) +3. Report to user: task reset, will retry on next resume + +### Fast-Advance Failure Recovery + +When coordinator detects a fast-advanced task has failed: + +``` +handleCallback / handleResume detects: + +- Task is in_progress (was fast-advanced by predecessor) + +- No active_worker entry for this task + +- Resolution: + 1. TaskUpdate -> reset task to pending + 2. Remove stale active_worker entry (if any) + 3. Log via team_msg (type: error) + 4. -> handleSpawnNext (will re-spawn the task normally) +``` + +### Consensus-Blocked Handling + +``` +handleCallback receives message with consensus_blocked flag + +- Route by severity: + +- severity = HIGH + | +- Create REVISION task (same role, incremented suffix) + | +- Max 1 revision per task. If already revised -> PAUSE, escalate to user + +- severity = MEDIUM + | +- Proceed with warning, log to wisdom/issues.md + | +- Normal handleSpawnNext + +- severity = LOW + +- Proceed normally, treat as consensus_reached with notes +``` + +## Phase 4: Validation + +| Check | Criteria | +|-------|----------| +| Session state consistent | active_workers matches TaskList in_progress tasks | +| No orphaned tasks | Every in_progress task has an active_worker entry | +| Dynamic roles valid | All task owners exist in session.roles | +| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE | +| Fast-advance tracking | Detect tasks already in_progress via fast-advance, sync to active_workers | + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Session file not found | Error, suggest re-initialization | +| Worker callback from unknown role | Log info, scan for other completions | +| All workers still running on resume | Report status, suggest check later | +| Pipeline stall (no ready, no running) | Check for missing tasks, report to user | +| Fast-advance conflict | Coordinator reconciles, no duplicate spawns | +| Dynamic role-spec file not found | Error, coordinator must regenerate from task-analysis | +| capability_gap when role limit (5) reached | Attempt merge, else pause for user | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-coordinate-v2/roles/coordinator/role.md b/.claude/skills/team-coordinate-v2/roles/coordinator/role.md new file mode 100644 index 00000000..a449db34 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/roles/coordinator/role.md @@ -0,0 +1,238 @@ +# Coordinator Role + +Orchestrate the team-coordinate workflow: task analysis, dynamic role-spec generation, task dispatching, progress monitoring, session state, and completion action. The sole built-in role -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. + +## Identity + +- **Name**: `coordinator` | **Tag**: `[coordinator]` +- **Responsibility**: Analyze task -> Generate role-specs -> Create team -> Dispatch tasks -> Monitor progress -> Completion action -> Report results + +## Boundaries + +### MUST +- Analyze user task to detect capabilities and build dependency graph +- Dynamically generate worker role-specs from specs/role-spec-template.md +- Create team and spawn team-worker agents in background +- Dispatch tasks with proper dependency chains from task-analysis.json +- Monitor progress via worker callbacks and route messages +- Maintain session state persistence (team-session.json) +- Handle capability_gap reports (generate new role-specs mid-pipeline) +- Handle consensus_blocked HIGH verdicts (create revision tasks or pause) +- Detect fast-advance orphans on resume/check and reset to pending +- Execute completion action when pipeline finishes + +### MUST NOT +- Execute task work directly (delegate to workers) +- Modify task output artifacts (workers own their deliverables) +- Call implementation subagents (code-developer, etc.) directly +- Skip dependency validation when creating task chains +- Generate more than 5 worker roles (merge if exceeded) +- Override consensus_blocked HIGH without user confirmation +- Spawn workers with `general-purpose` agent (MUST use `team-worker`) + +> **Core principle**: coordinator is the orchestrator, not the executor. All actual work is delegated to dynamically generated worker roles via team-worker agents. + +--- + +## Entry Router + +When coordinator is invoked, first detect the invocation type: + +| Detection | Condition | Handler | +|-----------|-----------|---------| +| Worker callback | Message contains `[role-name]` from session roles | -> handleCallback | +| Status check | Arguments contain "check" or "status" | -> handleCheck | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | +| Capability gap | Message contains "capability_gap" | -> handleAdapt | +| Pipeline complete | All tasks completed, no pending/in_progress | -> handleComplete | +| New session | None of above | -> Phase 0 | + +For callback/check/resume/adapt/complete: load `commands/monitor.md` and execute the appropriate handler, then STOP. + +--- + +## Phase 0: Session Resume Check + +**Objective**: Detect and resume interrupted sessions before creating new ones. + +**Workflow**: +1. Scan `.workflow/.team/TC-*/team-session.json` for sessions with status "active" or "paused" +2. No sessions found -> proceed to Phase 1 +3. Single session found -> resume it (-> Session Reconciliation) +4. Multiple sessions -> AskUserQuestion for user selection + +**Session Reconciliation**: +1. Audit TaskList -> get real status of all tasks +2. Reconcile: session.completed_tasks <-> TaskList status (bidirectional sync) +3. Reset any in_progress tasks -> pending (they were interrupted) +4. Detect fast-advance orphans (in_progress without recent activity) -> reset to pending +5. Determine remaining pipeline from reconciled state +6. Rebuild team if disbanded (TeamCreate + spawn needed workers only) +7. Create missing tasks with correct blockedBy dependencies +8. Verify dependency chain integrity +9. Update session file with reconciled state +10. Kick first executable task's worker -> Phase 4 + +--- + +## Phase 1: Task Analysis + +**Objective**: Parse user task, detect capabilities, build dependency graph, design roles. + +**Workflow**: + +1. **Parse user task description** + +2. **Clarify if ambiguous** via AskUserQuestion: + - What is the scope? (specific files, module, project-wide) + - What deliverables are expected? (documents, code, analysis reports) + - Any constraints? (timeline, technology, style) + +3. **Delegate to `commands/analyze-task.md`**: + - Signal detection: scan keywords -> infer capabilities + - Artifact inference: each capability -> default output type (.md) + - Dependency graph: build DAG of work streams + - Complexity scoring: count capabilities, cross-domain factor, parallel tracks + - Role minimization: merge overlapping, absorb trivial, cap at 5 + - **Role-spec metadata**: Generate frontmatter fields (prefix, inner_loop, subagents, message_types) + +4. **Output**: Write `/task-analysis.json` + +**Success**: Task analyzed, capabilities detected, dependency graph built, roles designed with role-spec metadata. + +--- + +## Phase 2: Generate Role-Specs + Initialize Session + +**Objective**: Create session, generate dynamic role-spec files, initialize shared infrastructure. + +**Workflow**: + +1. **Generate session ID**: `TC--` (slug from first 3 meaningful words of task) + +2. **Create session folder structure**: + ``` + .workflow/.team// + +-- role-specs/ + +-- artifacts/ + +-- wisdom/ + +-- explorations/ + +-- discussions/ + +-- .msg/ + ``` + +3. **Call TeamCreate** with team name derived from session ID + +4. **Read `specs/role-spec-template.md`** + `task-analysis.json` + +5. **For each role in task-analysis.json#roles**: + - Fill role-spec template with: + - YAML frontmatter: role, prefix, inner_loop, subagents, message_types + - Phase 2-4 content from responsibility type reference sections in template + - Task-specific instructions from task description + - Write generated role-spec to `/role-specs/.md` + +6. **Register roles** in team-session.json#roles (with `role_spec` path instead of `role_file`) + +7. **Initialize shared infrastructure**: + - `wisdom/learnings.md`, `wisdom/decisions.md`, `wisdom/issues.md` (empty with headers) + - `explorations/cache-index.json` (`{ "entries": [] }`) + - `shared-memory.json` (`{}`) + - `discussions/` (empty directory) + +8. **Write team-session.json** with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], completion_action="interactive", created_at + +**Success**: Session created, role-spec files generated, shared infrastructure initialized. + +--- + +## Phase 3: Create Task Chain + +**Objective**: Dispatch tasks based on dependency graph with proper dependencies. + +Delegate to `commands/dispatch.md` which creates the full task chain: +1. Reads dependency_graph from task-analysis.json +2. Topological sorts tasks +3. Creates tasks via TaskCreate with correct blockedBy +4. Assigns owner based on role mapping from task-analysis.json +5. Includes `Session: ` in every task description +6. Sets InnerLoop flag for multi-task roles +7. Updates team-session.json with pipeline and tasks_total + +**Success**: All tasks created with correct dependency chains, session updated. + +--- + +## Phase 4: Spawn-and-Stop + +**Objective**: Spawn first batch of ready workers in background, then STOP. + +**Design**: Spawn-and-Stop + Callback pattern, with worker fast-advance. + +**Workflow**: +1. Load `commands/monitor.md` +2. Find tasks with: status=pending, blockedBy all resolved, owner assigned +3. For each ready task -> spawn team-worker (see SKILL.md Coordinator Spawn Template) +4. Output status summary with execution graph +5. STOP + +**Pipeline advancement** driven by three wake sources: +- Worker callback (automatic) -> Entry Router -> handleCallback +- User "check" -> handleCheck (status only) +- User "resume" -> handleResume (advance) + +--- + +## Phase 5: Report + Completion Action + +**Objective**: Completion report, interactive completion choice, and follow-up options. + +**Workflow**: +1. Load session state -> count completed tasks, duration +2. List all deliverables with output paths in `/artifacts/` +3. Include discussion summaries (if inline discuss was used) +4. Summarize wisdom accumulated during execution +5. Output report: + +``` +[coordinator] ============================================ +[coordinator] TASK COMPLETE +[coordinator] +[coordinator] Deliverables: +[coordinator] - () +[coordinator] - () +[coordinator] +[coordinator] Pipeline: / tasks +[coordinator] Roles: +[coordinator] Duration: +[coordinator] +[coordinator] Session: +[coordinator] ============================================ +``` + +6. **Execute Completion Action** (based on session.completion_action): + +| Mode | Behavior | +|------|----------| +| `interactive` | AskUserQuestion with Archive/Keep/Export options | +| `auto_archive` | Execute Archive & Clean without prompt | +| `auto_keep` | Execute Keep Active without prompt | + +**Interactive handler**: See SKILL.md Completion Action section. + +--- + +## Error Handling + +| Error | Resolution | +|-------|------------| +| Task timeout | Log, mark failed, ask user to retry or skip | +| Worker crash | Respawn worker, reassign task | +| Dependency cycle | Detect in task analysis, report to user, halt | +| Task description too vague | AskUserQuestion for clarification | +| Session corruption | Attempt recovery, fallback to manual reconciliation | +| Role-spec generation fails | Fall back to single general-purpose role | +| capability_gap reported | handleAdapt: generate new role-spec, create tasks, spawn | +| All capabilities merge to one | Valid: single-role execution, reduced overhead | +| No capabilities detected | Default to single general role with TASK prefix | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-coordinate-v2/specs/role-spec-template.md b/.claude/skills/team-coordinate-v2/specs/role-spec-template.md new file mode 100644 index 00000000..f9c27816 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/specs/role-spec-template.md @@ -0,0 +1,295 @@ +# Dynamic Role-Spec Template + +Template used by coordinator to generate lightweight worker role-spec files at runtime. Each generated role-spec is written to `/role-specs/.md`. + +**Key difference from v1**: Role-specs contain ONLY Phase 2-4 domain logic + YAML frontmatter. All shared behavior (Phase 1 Task Discovery, Phase 5 Report/Fast-Advance, Message Bus, Consensus, Inner Loop) is built into the `team-worker` agent. + +## Template + +```markdown +--- +role: +prefix: +inner_loop: +subagents: [] +message_types: + success: _complete + error: error +--- + +# — Phase 2-4 + +## Phase 2: + + + +## Phase 3: + + + +## Phase 4: + + + +## Error Handling + +| Scenario | Resolution | +|----------|------------| + +``` + +## Frontmatter Fields + +| Field | Required | Description | +|-------|----------|-------------| +| `role` | Yes | Role name matching session registry | +| `prefix` | Yes | Task prefix to filter (e.g., RESEARCH, DRAFT, IMPL) | +| `inner_loop` | Yes | Whether team-worker loops through same-prefix tasks | +| `subagents` | No | Array of subagent types this role may call | +| `message_types` | Yes | Message type mapping for team_msg | +| `message_types.success` | Yes | Type string for successful completion | +| `message_types.error` | Yes | Type string for errors (usually "error") | + +## Design Rules + +| Rule | Description | +|------|-------------| +| Phase 2-4 only | No Phase 1 (Task Discovery) or Phase 5 (Report) — team-worker handles these | +| No message bus code | No team_msg calls — team-worker handles logging | +| No consensus handling | No consensus_reached/blocked logic — team-worker handles routing | +| No inner loop logic | No Phase 5-L/5-F — team-worker handles looping | +| ~80 lines target | Lightweight, domain-focused | +| No pseudocode | Decision tables + text + tool calls only | +| `` notation | Use angle brackets for variable substitution | +| Reference subagents by name | team-worker resolves invocation from its delegation templates | + +## Phase 2-4 Content by Responsibility Type + +Select the matching section based on `responsibility_type` from task analysis. + +### orchestration + +**Phase 2: Context Assessment** + +``` +| Input | Source | Required | +|-------|--------|----------| +| Task description | From TaskGet | Yes | +| Shared memory | /shared-memory.json | No | +| Prior artifacts | /artifacts/ | No | +| Wisdom | /wisdom/ | No | + +Loading steps: +1. Extract session path from task description +2. Read shared-memory.json for cross-role context +3. Read prior artifacts (if any from upstream tasks) +4. Load wisdom files for accumulated knowledge +5. Optionally call explore subagent for codebase context +``` + +**Phase 3: Subagent Execution** + +``` +Delegate to appropriate subagent based on task: + +Task({ + subagent_type: "general-purpose", + run_in_background: false, + description: " for ", + prompt: "## Task + - + - Session: + ## Context + + ## Expected Output + Write artifact to: /artifacts/.md + Return JSON summary: { artifact_path, summary, key_decisions[], warnings[] }" +}) +``` + +**Phase 4: Result Aggregation** + +``` +1. Verify subagent output artifact exists +2. Read artifact, validate structure/completeness +3. Update shared-memory.json with key findings +4. Write insights to wisdom/ files +``` + +### code-gen (docs) + +**Phase 2: Load Prior Context** + +``` +| Input | Source | Required | +|-------|--------|----------| +| Task description | From TaskGet | Yes | +| Prior artifacts | /artifacts/ from upstream | Conditional | +| Shared memory | /shared-memory.json | No | + +Loading steps: +1. Extract session path from task description +2. Read upstream artifacts +3. Read shared-memory.json for cross-role context +``` + +**Phase 3: Document Generation** + +``` +Task({ + subagent_type: "universal-executor", + run_in_background: false, + description: "Generate for ", + prompt: "## Task + - Generate: + - Session: + ## Prior Context + + ## Expected Output + Write document to: /artifacts/.md + Return JSON: { artifact_path, summary, key_decisions[], warnings[] }" +}) +``` + +**Phase 4: Structure Validation** + +``` +1. Verify document artifact exists +2. Check document has expected sections +3. Validate no placeholder text remains +4. Update shared-memory.json with document metadata +``` + +### code-gen (code) + +**Phase 2: Load Plan/Specs** + +``` +| Input | Source | Required | +|-------|--------|----------| +| Task description | From TaskGet | Yes | +| Plan/design artifacts | /artifacts/ | Conditional | +| Shared memory | /shared-memory.json | No | + +Loading steps: +1. Extract session path from task description +2. Read plan/design artifacts from upstream +3. Load shared-memory.json for implementation context +``` + +**Phase 3: Code Implementation** + +``` +Task({ + subagent_type: "code-developer", + run_in_background: false, + description: "Implement ", + prompt: "## Task + - + - Session: + ## Plan/Design Context + + ## Expected Output + Implement code changes. + Write summary to: /artifacts/implementation-summary.md + Return JSON: { artifact_path, summary, files_changed[], warnings[] }" +}) +``` + +**Phase 4: Syntax Validation** + +``` +1. Run syntax check (tsc --noEmit or equivalent) +2. Verify all planned files exist +3. If validation fails -> attempt auto-fix (max 2 attempts) +4. Write implementation summary to artifacts/ +``` + +### read-only + +**Phase 2: Target Loading** + +``` +| Input | Source | Required | +|-------|--------|----------| +| Task description | From TaskGet | Yes | +| Target artifacts/files | From task description or upstream | Yes | +| Shared memory | /shared-memory.json | No | + +Loading steps: +1. Extract session path and target files from task description +2. Read target artifacts or source files for analysis +3. Load shared-memory.json for context +``` + +**Phase 3: Multi-Dimension Analysis** + +``` +Task({ + subagent_type: "general-purpose", + run_in_background: false, + description: "Analyze for ", + prompt: "## Task + - Analyze: + - Dimensions: + - Session: + ## Target Content + + ## Expected Output + Write report to: /artifacts/analysis-report.md + Return JSON: { artifact_path, summary, findings[], severity_counts }" +}) +``` + +**Phase 4: Severity Classification** + +``` +1. Verify analysis report exists +2. Classify findings by severity (Critical/High/Medium/Low) +3. Update shared-memory.json with key findings +4. Write issues to wisdom/issues.md +``` + +### validation + +**Phase 2: Environment Detection** + +``` +| Input | Source | Required | +|-------|--------|----------| +| Task description | From TaskGet | Yes | +| Implementation artifacts | Upstream code changes | Yes | + +Loading steps: +1. Detect test framework from project files +2. Get changed files from implementation +3. Identify test command and coverage tool +``` + +**Phase 3: Test-Fix Cycle** + +``` +Task({ + subagent_type: "test-fix-agent", + run_in_background: false, + description: "Test-fix for ", + prompt: "## Task + - Run tests and fix failures + - Session: + - Max iterations: 5 + ## Changed Files + + ## Expected Output + Write report to: /artifacts/test-report.md + Return JSON: { artifact_path, pass_rate, coverage, remaining_failures[] }" +}) +``` + +**Phase 4: Result Analysis** + +``` +1. Check pass rate >= 95% +2. Check coverage meets threshold +3. Generate test report with pass/fail counts +4. Update shared-memory.json with test results +``` diff --git a/.claude/skills/team-coordinate-v2/subagents/discuss-subagent.md b/.claude/skills/team-coordinate-v2/subagents/discuss-subagent.md new file mode 100644 index 00000000..fff00818 --- /dev/null +++ b/.claude/skills/team-coordinate-v2/subagents/discuss-subagent.md @@ -0,0 +1,133 @@ +# Discuss Subagent + +Lightweight multi-perspective critique engine. Called inline by any role needing peer review. Perspectives are dynamic -- specified by the calling role, not pre-defined. + +## Design + +Unlike team-lifecycle-v4's fixed perspective definitions (product, technical, quality, risk, coverage), team-coordinate uses **dynamic perspectives** passed in the prompt. The calling role decides what viewpoints matter for its artifact. + +## Invocation + +Called by roles after artifact creation: + +``` +Task({ + subagent_type: "cli-discuss-agent", + run_in_background: false, + description: "Discuss ", + prompt: `## Multi-Perspective Critique: + +### Input +- Artifact: +- Round: +- Session: + +### Perspectives + + +Example: +| Perspective | CLI Tool | Role | Focus Areas | +|-------------|----------|------|-------------| +| Feasibility | gemini | Engineer | Implementation complexity, technical risks, resource needs | +| Clarity | codex | Editor | Readability, logical flow, completeness of explanation | +| Accuracy | gemini | Domain Expert | Factual correctness, source reliability, claim verification | + +### Execution Steps +1. Read artifact from +2. For each perspective, launch CLI analysis in background: + Bash(command="ccw cli -p 'PURPOSE: Analyze from perspective for + TASK: + MODE: analysis + CONTEXT: Artifact content below + EXPECTED: JSON with strengths[], weaknesses[], suggestions[], rating (1-5) + CONSTRAINTS: Output valid JSON only + + Artifact: + ' --tool --mode analysis", run_in_background=true) +3. Wait for all CLI results +4. Divergence detection: + - High severity: any rating <= 2, critical issue identified + - Medium severity: rating spread (max - min) >= 3, or single perspective rated <= 2 with others >= 3 + - Low severity: minor suggestions only, all ratings >= 3 +5. Consensus determination: + - No high-severity divergences AND average rating >= 3.0 -> consensus_reached + - Otherwise -> consensus_blocked +6. Synthesize: + - Convergent themes (agreed by 2+ perspectives) + - Divergent views (conflicting assessments) + - Action items from suggestions +7. Write discussion record to: /discussions/-discussion.md + +### Discussion Record Format +# Discussion Record: + +**Artifact**: +**Perspectives**: +**Consensus**: reached / blocked +**Average Rating**: /5 + +## Convergent Themes +- + +## Divergent Views +- **** (): + +## Action Items +1. + +## Ratings +| Perspective | Rating | +|-------------|--------| +| | /5 | + +### Return Value + +**When consensus_reached**: +Return a summary string with: +- Verdict: consensus_reached +- Average rating +- Key action items (top 3) +- Discussion record path + +**When consensus_blocked**: +Return a structured summary with: +- Verdict: consensus_blocked +- Severity: HIGH | MEDIUM | LOW +- Average rating +- Divergence summary: top 3 divergent points with perspective attribution +- Action items: prioritized list of required changes +- Recommendation: revise | proceed-with-caution | escalate +- Discussion record path + +### Error Handling +- Single CLI fails -> fallback to direct Claude analysis for that perspective +- All CLI fail -> generate basic discussion from direct artifact reading +- Artifact not found -> return error immediately` +}) +``` + +## Integration with Calling Role + +The calling role is responsible for: + +1. **Before calling**: Complete primary artifact output +2. **Calling**: Invoke discuss subagent with appropriate dynamic perspectives +3. **After calling**: + +| Verdict | Severity | Role Action | +|---------|----------|-------------| +| consensus_reached | - | Include action items in Phase 5 report, proceed normally | +| consensus_blocked | HIGH | Include divergence details in Phase 5 SendMessage. Do NOT self-revise -- coordinator decides. | +| consensus_blocked | MEDIUM | Include warning in Phase 5 SendMessage. Proceed normally. | +| consensus_blocked | LOW | Treat as consensus_reached with notes. Proceed normally. | + +**SendMessage format for consensus_blocked (HIGH or MEDIUM)**: + +``` +[] complete. Discuss : consensus_blocked (severity=) +Divergences: +Action items: +Recommendation: +Artifact: +Discussion: +``` diff --git a/.claude/skills/team-coordinate-v2/subagents/explore-subagent.md b/.claude/skills/team-coordinate-v2/subagents/explore-subagent.md new file mode 100644 index 00000000..e934f7ed --- /dev/null +++ b/.claude/skills/team-coordinate-v2/subagents/explore-subagent.md @@ -0,0 +1,120 @@ +# Explore Subagent + +Shared codebase exploration utility with centralized caching. Callable by any role needing code context. + +## Invocation + +``` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: "Explore ", + prompt: `Explore codebase for: + +Focus angle: +Keywords: +Session folder: + +## Cache Check +1. Read /explorations/cache-index.json (if exists) +2. Look for entry with matching angle +3. If found AND file exists -> read cached result, return summary +4. If not found -> proceed to exploration + +## Exploration + + +## Output +Write JSON to: /explorations/explore-.json +Update cache-index.json with new entry + +## Output Schema +{ + "angle": "", + "query": "", + "relevant_files": [ + { "path": "...", "rationale": "...", "role": "...", "discovery_source": "...", "key_symbols": [] } + ], + "patterns": [], + "dependencies": [], + "external_refs": [], + "_metadata": { "created_by": "", "timestamp": "...", "cache_key": "..." } +} + +Return summary: file count, pattern count, top 5 files, output path` +}) +``` + +## Cache Mechanism + +### Cache Index Schema + +`/explorations/cache-index.json`: + +```json +{ + "entries": [ + { + "angle": "architecture", + "keywords": ["auth", "middleware"], + "file": "explore-architecture.json", + "created_by": "analyst", + "created_at": "2026-02-27T10:00:00Z", + "file_count": 15 + } + ] +} +``` + +### Cache Lookup Rules + +| Condition | Action | +|-----------|--------| +| Exact angle match exists | Return cached result | +| No match | Execute exploration, cache result | +| Cache file missing but index has entry | Remove stale entry, re-explore | + +### Cache Invalidation + +Cache is session-scoped. No explicit invalidation needed -- each session starts fresh. If a role suspects stale data, it can pass `force_refresh: true` in the prompt to bypass cache. + +## Angle Focus Guide + +| Angle | Focus Points | Typical Caller | +|-------|-------------|----------------| +| architecture | Layer boundaries, design patterns, component responsibilities, ADRs | any | +| dependencies | Import chains, external libraries, circular dependencies, shared utilities | any | +| modularity | Module interfaces, separation of concerns, extraction opportunities | any | +| integration-points | API endpoints, data flow between modules, event systems | any | +| security | Auth/authz logic, input validation, sensitive data handling, middleware | any | +| dataflow | Data transformations, state propagation, validation points | any | +| performance | Bottlenecks, N+1 queries, blocking operations, algorithm complexity | any | +| error-handling | Try-catch blocks, error propagation, recovery strategies, logging | any | +| patterns | Code conventions, design patterns, naming conventions, best practices | any | +| testing | Test files, coverage gaps, test patterns, mocking strategies | any | +| general | Broad semantic search for topic-related code | any | + +## Exploration Strategies + +### Low Complexity (direct search) + +For simple queries, use ACE semantic search: + +``` +mcp__ace-tool__search_context(project_root_path="", query="") +``` + +ACE failure fallback: `rg -l '' --type ts` + +### Medium/High Complexity (multi-angle) + +For complex queries, call cli-explore-agent per angle. The calling role determines complexity and selects angles. + +## Search Tool Priority + +| Tool | Priority | Use Case | +|------|----------|----------| +| mcp__ace-tool__search_context | P0 | Semantic search | +| Grep / Glob | P1 | Pattern matching | +| cli-explore-agent | Deep | Multi-angle exploration | +| WebSearch | P3 | External docs | diff --git a/.claude/skills/team-executor-v2/SKILL.md b/.claude/skills/team-executor-v2/SKILL.md new file mode 100644 index 00000000..e05c1aec --- /dev/null +++ b/.claude/skills/team-executor-v2/SKILL.md @@ -0,0 +1,224 @@ +--- +name: team-executor-v2 +description: Lightweight session execution skill. Resumes existing team-coordinate-v2 sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on "team executor v2". +allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) +--- + +# Team Executor v2 + +Lightweight session execution skill: load session -> reconcile state -> spawn team-worker agents -> execute -> deliver. **No analysis, no role generation** -- only executes existing team-coordinate sessions. + +## Key Changes from v1 + +| Change | Before (v1) | After (v2) | Impact | +|--------|------------|------------|--------| +| Worker agent | general-purpose + Skill load | team-worker agent (dedicated) | Eliminates Skill indirection | +| Role loading | `/roles/.md` (full role.md) | `/role-specs/.md` (Phase 2-4 only) | Lighter validation | +| Shared behavior | Duplicated in SKILL.md | Built into team-worker agent | Single source of truth | +| Executor spawn | Skill(team-executor, --role=xxx) | Task(team-worker, role_spec=xxx.md) | Direct, no Skill call | +| Completion | Manual cleanup | Interactive completion action | Archive/Keep/Export prompt | + +## Architecture + +``` ++---------------------------------------------------+ +| Skill(skill="team-executor") | +| args="--session=" [REQUIRED] | ++-------------------+-------------------------------+ + | Session Validation + +---- --session valid? ----+ + | NO | YES + v v + Error immediately Orchestration Mode + (no session) -> executor + | + +-------+-------+-------+ + v v v v + [team-worker agents loaded from session role-specs] +``` + +--- + +## Session Validation (BEFORE routing) + +**CRITICAL**: Session validation MUST occur before any execution. + +### Parse Arguments + +Extract from `$ARGUMENTS`: +- `--session=`: Path to team-coordinate session folder (REQUIRED) + +### Validation Steps + +1. **Check `--session` provided**: + - If missing -> **ERROR**: "Session required. Usage: --session=" + +2. **Validate session structure** (see specs/session-schema.md): + - Directory exists at path + - `team-session.json` exists and valid JSON + - `task-analysis.json` exists and valid JSON + - `role-specs/` directory has at least one `.md` file + - Each role in `team-session.json#roles` has corresponding `.md` file in `role-specs/` + +3. **Validation failure**: + - Report specific missing component + - Suggest re-running team-coordinate or checking path + +--- + +## Role Router + +This skill is **executor-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. + +### Dispatch Logic + +| Scenario | Action | +|----------|--------| +| No `--session` | **ERROR** immediately | +| `--session` invalid | **ERROR** with specific reason | +| Valid session | Orchestration Mode -> executor | + +### Orchestration Mode + +**Invocation**: `Skill(skill="team-executor", args="--session=")` + +**Lifecycle**: +``` +Validate session + -> executor Phase 0: Reconcile state (reset interrupted, detect orphans) + -> executor Phase 1: Spawn first batch team-worker agents (background) -> STOP + -> Worker executes -> SendMessage callback -> executor advances next step + -> Loop until pipeline complete -> Phase 2 report + completion action +``` + +**User Commands** (wake paused executor): + +| Command | Action | +|---------|--------| +| `check` / `status` | Output execution status graph, no advancement | +| `resume` / `continue` | Check worker states, advance next step | + +--- + +## Role Registry + +| Role | File | Type | +|------|------|------| +| executor | [roles/executor/role.md](roles/executor/role.md) | built-in orchestrator | +| (dynamic) | `/role-specs/.md` | loaded from session | + +--- + +## Executor Spawn Template + +### v2 Worker Spawn (all roles) + +When executor spawns workers, use `team-worker` agent with role-spec path: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker", + team_name: , + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: /role-specs/.md +session: +session_id: +team_name: +requirement: +inner_loop: + +Read role_spec file to load Phase 2-4 domain instructions.` +}) +``` + +--- + +## Completion Action + +When pipeline completes (all tasks done), executor presents an interactive choice: + +``` +AskUserQuestion({ + questions: [{ + question: "Team pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" }, + { label: "Keep Active", description: "Keep session for follow-up work" }, + { label: "Export Results", description: "Export deliverables to target directory, then clean" } + ] + }] +}) +``` + +### Action Handlers + +| Choice | Steps | +|--------|-------| +| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary with artifact paths | +| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-executor', args='--session=')" | +| Export Results | AskUserQuestion(target path) -> copy artifacts to target -> Archive & Clean | + +--- + +## Cadence Control + +**Beat model**: Event-driven, each beat = executor wake -> process -> spawn -> STOP. + +``` +Beat Cycle (single beat) +====================================================================== + Event Executor Workers +---------------------------------------------------------------------- + callback/resume --> +- handleCallback -+ + | mark completed | + | check pipeline | + +- handleSpawnNext -+ + | find ready tasks | + | spawn workers ---+--> [team-worker A] Phase 1-5 + | (parallel OK) --+--> [team-worker B] Phase 1-5 + +- STOP (idle) -----+ | + | + callback <-----------------------------------------+ + (next beat) SendMessage + TaskUpdate(completed) +====================================================================== + + Fast-Advance (skips executor for simple linear successors) +====================================================================== + [Worker A] Phase 5 complete + +- 1 ready task? simple successor? --> spawn team-worker B directly + +- complex case? --> SendMessage to executor +====================================================================== +``` + +--- + +## Integration with team-coordinate + +| Scenario | Skill | +|----------|-------| +| New task, no session | team-coordinate | +| Existing session, resume execution | **team-executor** | +| Session needs new roles | team-coordinate (with resume) | +| Pure execution, no analysis | **team-executor** | + +--- + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| No --session provided | ERROR immediately with usage message | +| Session directory not found | ERROR with path, suggest checking path | +| team-session.json missing | ERROR, session incomplete, suggest re-run team-coordinate | +| task-analysis.json missing | ERROR, session incomplete, suggest re-run team-coordinate | +| No role-specs in session | ERROR, session incomplete, suggest re-run team-coordinate | +| Role-spec file not found | ERROR with expected path | +| capability_gap reported | Warn only, cannot generate new role-specs | +| Fast-advance spawns wrong task | Executor reconciles on next callback | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md b/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md new file mode 100644 index 00000000..0eea3bf0 --- /dev/null +++ b/.claude/skills/team-executor-v2/roles/executor/commands/monitor.md @@ -0,0 +1,239 @@ +# Command: monitor + +## Purpose + +Event-driven pipeline coordination with Spawn-and-Stop pattern for team-executor v2. Role names are read from `team-session.json#roles`. Workers are spawned as `team-worker` agents with role-spec paths. **handleAdapt is LIMITED**: only warns, cannot generate new role-specs. Includes `handleComplete` for pipeline completion action. + +## Constants + +| Constant | Value | Description | +|----------|-------|-------------| +| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` | +| ONE_STEP_PER_INVOCATION | true | Executor does one operation then STOPS | +| FAST_ADVANCE_AWARE | true | Workers may skip executor for simple linear successors | +| ROLE_GENERATION | disabled | handleAdapt cannot generate new role-specs | +| WORKER_AGENT | team-worker | All workers spawned as team-worker agents | + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session file | `/team-session.json` | Yes | +| Task list | `TaskList()` | Yes | +| Active workers | session.active_workers[] | Yes | +| Role registry | session.roles[] | Yes | + +**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name`. Role-spec paths are in `session.roles[].role_spec`. + +## Phase 3: Handler Routing + +### Wake-up Source Detection + +Parse `$ARGUMENTS` to determine handler: + +| Priority | Condition | Handler | +|----------|-----------|---------| +| 1 | Message contains `[]` from session roles | handleCallback | +| 2 | Contains "capability_gap" | handleAdapt | +| 3 | Contains "check" or "status" | handleCheck | +| 4 | Contains "resume", "continue", or "next" | handleResume | +| 5 | Pipeline detected as complete | handleComplete | +| 6 | None of the above (initial spawn after dispatch) | handleSpawnNext | + +--- + +### Handler: handleCallback + +Worker completed a task. Verify completion, update state, auto-advance. + +``` +Receive callback from [] + +- Find matching active worker by role (from session.roles) + +- Is this a progress update (not final)? + | +- YES -> Update session state, do NOT remove from active_workers -> STOP + +- Task status = completed? + | +- YES -> remove from active_workers -> update session + | | +- -> handleSpawnNext + | +- NO -> progress message, do not advance -> STOP + +- No matching worker found + +- Scan all active workers for completed tasks + +- Found completed -> process each -> handleSpawnNext + +- None completed -> STOP +``` + +**Fast-advance note**: Check if expected next task is already `in_progress` (fast-advanced). If yes -> skip spawning, sync active_workers. + +--- + +### Handler: handleCheck + +Read-only status report. No pipeline advancement. + +``` +[executor] Pipeline Status +[executor] Progress: / (%) + +[executor] Execution Graph: + + + done=completed >>>=running o=pending .=not created + +[executor] Active Workers: + > () - running + +[executor] Ready to spawn: +[executor] Commands: 'resume' to advance | 'check' to refresh +``` + +Then STOP. + +--- + +### Handler: handleResume + +Check active worker completion, process results, advance pipeline. + +``` +Load active_workers from session + +- No active workers -> handleSpawnNext + +- Has active workers -> check each: + +- status = completed -> mark done, log + +- status = in_progress -> still running, log + +- other status -> worker failure -> reset to pending + After processing: + +- Some completed -> handleSpawnNext + +- All still running -> report status -> STOP + +- All failed -> handleSpawnNext (retry) +``` + +--- + +### Handler: handleSpawnNext + +Find all ready tasks, spawn team-worker agents in background, update session, STOP. + +``` +Collect task states from TaskList() + +- completedSubjects: status = completed + +- inProgressSubjects: status = in_progress + +- readySubjects: pending + all blockedBy in completedSubjects + +Ready tasks found? + +- NONE + work in progress -> report waiting -> STOP + +- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete + +- HAS ready tasks -> for each: + +- Is task owner an Inner Loop role AND already has active_worker? + | +- YES -> SKIP spawn (existing worker picks it up) + | +- NO -> normal spawn below + +- TaskUpdate -> in_progress + +- team_msg log -> task_unblocked (team=) + +- Spawn team-worker (see spawn tool call below) + +- Add to session.active_workers + Update session file -> output summary -> STOP +``` + +**Spawn worker tool call**: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker for ", + team_name: , + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: /role-specs/.md +session: +session_id: +team_name: +requirement: +inner_loop: + +Read role_spec file to load Phase 2-4 domain instructions.` +}) +``` + +--- + +### Handler: handleComplete + +Pipeline complete. Execute completion action. + +``` +All tasks completed (no pending, no in_progress) + +- Generate pipeline summary (deliverables, stats, duration) + +- Read session.completion_action: + | + +- "interactive": + | AskUserQuestion -> user choice: + | +- "Archive & Clean": session status="completed" -> TeamDelete -> summary + | +- "Keep Active": session status="paused" -> resume command + | +- "Export Results": copy artifacts -> Archive & Clean + | + +- "auto_archive": Execute Archive & Clean + +- "auto_keep": Execute Keep Active +``` + +**Fallback**: If completion action fails, default to Keep Active, log warning. + +--- + +### Handler: handleAdapt (LIMITED) + +**UNLIKE team-coordinate, executor CANNOT generate new role-specs.** + +``` +Receive capability_gap from [] + +- Log via team_msg (type: warning) + +- Check existing roles -> does any cover this? + | +- YES -> redirect to that role -> STOP + | +- NO -> genuine gap, report to user: + | "Capability gap detected. team-executor cannot generate new role-specs. + | Options: 1. Continue 2. Re-run team-coordinate 3. Manually add role-spec" + +- Continue execution with existing roles +``` + +--- + +### Worker Failure Handling + +1. Reset task -> pending via TaskUpdate +2. Log via team_msg (type: error) +3. Report to user: task reset, will retry on next resume + +### Fast-Advance Failure Recovery + +Detect orphaned tasks (in_progress without active_worker, > 5 minutes) -> reset to pending -> handleSpawnNext. + +### Consensus-Blocked Handling + +``` +Route by severity: + +- HIGH: Create REVISION task (max 1). Already revised -> PAUSE for user + +- MEDIUM: Proceed with warning, log to wisdom/issues.md + +- LOW: Proceed normally as consensus_reached with notes +``` + +## Phase 4: Validation + +| Check | Criteria | +|-------|----------| +| Session state consistent | active_workers matches TaskList in_progress tasks | +| No orphaned tasks | Every in_progress task has an active_worker entry | +| Dynamic roles valid | All task owners exist in session.roles | +| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE | +| Fast-advance tracking | Detect fast-advanced tasks, sync to active_workers | + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Session file not found | Error, suggest re-run team-coordinate | +| Worker callback from unknown role | Log info, scan for other completions | +| All workers still running on resume | Report status, suggest check later | +| Pipeline stall | Check for missing tasks, report to user | +| Fast-advance conflict | Executor reconciles, no duplicate spawns | +| Role-spec file not found | Error, cannot proceed | +| capability_gap | WARN only, cannot generate new role-specs | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-executor-v2/roles/executor/role.md b/.claude/skills/team-executor-v2/roles/executor/role.md new file mode 100644 index 00000000..630dc47a --- /dev/null +++ b/.claude/skills/team-executor-v2/roles/executor/role.md @@ -0,0 +1,171 @@ +# Executor Role + +Orchestrate the team-executor workflow: session validation, state reconciliation, team-worker dispatch, progress monitoring, completion action. The sole built-in role -- all worker roles are loaded from session role-specs and spawned via team-worker agent. + +## Identity + +- **Name**: `executor` | **Tag**: `[executor]` +- **Responsibility**: Validate session -> Reconcile state -> Create team -> Dispatch team-worker agents -> Monitor progress -> Completion action -> Report results + +## Boundaries + +### MUST +- Validate session structure before any execution +- Reconcile session state with TaskList on startup +- Reset in_progress tasks to pending (interrupted tasks) +- Detect fast-advance orphans and reset to pending +- Spawn team-worker agents in background (NOT general-purpose) +- Monitor progress via worker callbacks and route messages +- Maintain session state persistence (team-session.json) +- Handle capability_gap reports with warning only (cannot generate role-specs) +- Execute completion action when pipeline finishes + +### MUST NOT +- Execute task work directly (delegate to workers) +- Modify task output artifacts (workers own their deliverables) +- Call implementation subagents (code-developer, etc.) directly +- Generate new role-specs (use existing session role-specs only) +- Skip session validation +- Override consensus_blocked HIGH without user confirmation +- Spawn workers with `general-purpose` agent (MUST use `team-worker`) + +> **Core principle**: executor is the orchestrator, not the executor. All actual work is delegated to session-defined worker roles via team-worker agents. Unlike team-coordinate coordinator, executor CANNOT generate new role-specs. + +--- + +## Entry Router + +When executor is invoked, first detect the invocation type: + +| Detection | Condition | Handler | +|-----------|-----------|---------| +| Worker callback | Message contains `[role-name]` from session roles | -> handleCallback | +| Status check | Arguments contain "check" or "status" | -> handleCheck | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | +| Capability gap | Message contains "capability_gap" | -> handleAdapt | +| Pipeline complete | All tasks completed, no pending/in_progress | -> handleComplete | +| New execution | None of above | -> Phase 0 | + +For callback/check/resume/adapt/complete: load `commands/monitor.md` and execute the appropriate handler, then STOP. + +--- + +## Phase 0: Session Validation + State Reconciliation + +**Objective**: Validate session structure and reconcile session state with actual task status. + +### Step 1: Session Validation + +Validate session structure (see SKILL.md Session Validation): +- [ ] Directory exists at session path +- [ ] `team-session.json` exists and parses +- [ ] `task-analysis.json` exists and parses +- [ ] `role-specs/` directory has >= 1 .md files +- [ ] All roles in team-session.json#roles have corresponding role-spec .md files +- [ ] Role-spec files have valid YAML frontmatter + Phase 2-4 sections + +If validation fails -> ERROR with specific reason -> STOP + +### Step 2: Load Session State + +Read team-session.json and task-analysis.json. + +### Step 3: Reconcile with TaskList + +Compare TaskList() with session.completed_tasks, bidirectional sync. + +### Step 4: Reset Interrupted Tasks + +Reset any in_progress tasks to pending. + +### Step 5: Detect Fast-Advance Orphans + +In_progress tasks without matching active_worker + created > 5 minutes -> reset to pending. + +### Step 6: Create Missing Tasks (if needed) + +For each task in task-analysis, check if exists in TaskList, create if missing. + +### Step 7: Update Session File + +Write reconciled team-session.json. + +### Step 8: Team Setup + +TeamCreate if team does not exist. + +**Success**: Session validated, state reconciled, team ready -> Phase 1 + +--- + +## Phase 1: Spawn-and-Stop + +**Objective**: Spawn first batch of ready workers as team-worker agents in background, then STOP. + +**Workflow**: +1. Load `commands/monitor.md` +2. Find tasks with: status=pending, blockedBy all resolved, owner assigned +3. For each ready task -> spawn team-worker (see SKILL.md Executor Spawn Template) +4. Output status summary with execution graph +5. STOP + +**Pipeline advancement** driven by three wake sources: +- Worker callback (automatic) -> Entry Router -> handleCallback +- User "check" -> handleCheck (status only) +- User "resume" -> handleResume (advance) + +--- + +## Phase 2: Report + Completion Action + +**Objective**: Completion report, interactive completion choice, and follow-up options. + +**Workflow**: +1. Load session state -> count completed tasks, duration +2. List all deliverables with output paths in `/artifacts/` +3. Include discussion summaries (if inline discuss was used) +4. Summarize wisdom accumulated during execution +5. Output report: + +``` +[executor] ============================================ +[executor] TASK COMPLETE +[executor] +[executor] Deliverables: +[executor] - () +[executor] - () +[executor] +[executor] Pipeline: / tasks +[executor] Roles: +[executor] Duration: +[executor] +[executor] Session: +[executor] ============================================ +``` + +6. **Execute Completion Action** (based on session.completion_action): + +| Mode | Behavior | +|------|----------| +| `interactive` | AskUserQuestion with Archive/Keep/Export options | +| `auto_archive` | Execute Archive & Clean without prompt | +| `auto_keep` | Execute Keep Active without prompt | + +**Interactive handler**: See SKILL.md Completion Action section. + +--- + +## Error Handling + +| Error | Resolution | +|-------|------------| +| Session validation fails | ERROR with specific reason, suggest re-run team-coordinate | +| Task timeout | Log, mark failed, ask user to retry or skip | +| Worker crash | Respawn worker, reassign task | +| Session corruption | Attempt recovery, fallback to manual reconciliation | +| capability_gap reported | handleAdapt: WARN only, cannot generate new role-specs | +| All workers still running on resume | Report status, suggest check later | +| Pipeline stall (no ready, no running) | Check for missing tasks, report to user | +| Fast-advance conflict | Executor reconciles, no duplicate spawns | +| Role-spec file not found | ERROR, cannot proceed without role definition | +| Completion action fails | Default to Keep Active, log warning | diff --git a/.claude/skills/team-executor-v2/specs/session-schema.md b/.claude/skills/team-executor-v2/specs/session-schema.md new file mode 100644 index 00000000..6b7c8180 --- /dev/null +++ b/.claude/skills/team-executor-v2/specs/session-schema.md @@ -0,0 +1,264 @@ +# Session Schema + +Required session structure for team-executor v2. All components MUST exist for valid execution. Updated for role-spec architecture (lightweight Phase 2-4 files instead of full role.md files). + +## Directory Structure + +``` +/ ++-- team-session.json # Session state + dynamic role registry (REQUIRED) ++-- task-analysis.json # Task analysis output: capabilities, dependency graph (REQUIRED) ++-- role-specs/ # Dynamic role-spec definitions (REQUIRED, >= 1 .md file) +| +-- .md # Lightweight: YAML frontmatter + Phase 2-4 only +| +-- .md ++-- artifacts/ # All MD deliverables from workers +| +-- .md ++-- shared-memory.json # Cross-role state store ++-- wisdom/ # Cross-task knowledge +| +-- learnings.md +| +-- decisions.md +| +-- issues.md ++-- explorations/ # Shared explore cache +| +-- cache-index.json +| +-- explore-.json ++-- discussions/ # Inline discuss records +| +-- .md ++-- .msg/ # Team message bus logs +``` + +## Validation Checklist + +team-executor validates the following before execution: + +### Required Components + +| Component | Validation | Error Message | +|-----------|------------|---------------| +| `--session` argument | Must be provided | "Session required. Usage: --session=" | +| Directory | Must exist at path | "Session directory not found: " | +| `team-session.json` | Must exist, parse as JSON, and contain all required fields | "Invalid session: team-session.json missing, corrupt, or missing required fields" | +| `task-analysis.json` | Must exist, parse as JSON, and contain all required fields | "Invalid session: task-analysis.json missing, corrupt, or missing required fields" | +| `role-specs/` directory | Must exist and contain >= 1 .md file | "Invalid session: no role-spec files in role-specs/" | +| Role-spec file mapping | Each role in team-session.json#roles must have .md file | "Role-spec file not found: role-specs/.md" | +| Role-spec structure | Each role-spec must have YAML frontmatter + Phase 2-4 sections | "Invalid role-spec: role-specs/.md missing required section" | + +### Validation Algorithm + +``` +1. Parse --session= from arguments + +- Not provided -> ERROR: "Session required. Usage: --session=" + +2. Check directory exists + +- Not exists -> ERROR: "Session directory not found: " + +3. Check team-session.json + +- Not exists -> ERROR: "Invalid session: team-session.json missing" + +- Parse error -> ERROR: "Invalid session: team-session.json corrupt" + +- Validate required fields: + +- session_id (string) -> missing -> ERROR + +- task_description (string) -> missing -> ERROR + +- status (string: active|paused|completed) -> invalid -> ERROR + +- team_name (string) -> missing -> ERROR + +- roles (array, non-empty) -> missing/empty -> ERROR + +4. Check task-analysis.json + +- Not exists -> ERROR: "Invalid session: task-analysis.json missing" + +- Parse error -> ERROR: "Invalid session: task-analysis.json corrupt" + +- Validate required fields: + +- capabilities (array) -> missing -> ERROR + +- dependency_graph (object) -> missing -> ERROR + +- roles (array, non-empty) -> missing/empty -> ERROR + +5. Check role-specs/ directory + +- Not exists -> ERROR: "Invalid session: role-specs/ directory missing" + +- No .md files -> ERROR: "Invalid session: no role-spec files in role-specs/" + +6. Check role-spec file mapping and structure + +- For each role in team-session.json#roles: + +- Check role-specs/.md exists + +- Not exists -> ERROR: "Role-spec file not found: role-specs/.md" + +- Validate role-spec structure (see Role-Spec Structure Validation) + +7. All checks pass -> proceed to Phase 0 +``` + +--- + +## team-session.json Schema + +```json +{ + "session_id": "TC--", + "task_description": "", + "status": "active | paused | completed", + "team_name": "", + "roles": [ + { + "name": "", + "prefix": "", + "responsibility_type": "", + "inner_loop": false, + "role_spec": "role-specs/.md" + } + ], + "pipeline": { + "dependency_graph": {}, + "tasks_total": 0, + "tasks_completed": 0 + }, + "active_workers": [], + "completed_tasks": [], + "completion_action": "interactive", + "created_at": "" +} +``` + +### Required Fields + +| Field | Type | Description | +|-------|------|-------------| +| `session_id` | string | Unique session identifier | +| `task_description` | string | Original task description from user | +| `status` | string | One of: "active", "paused", "completed" | +| `team_name` | string | Team name for Task tool | +| `roles` | array | List of role definitions | +| `roles[].name` | string | Role name (must match .md filename) | +| `roles[].prefix` | string | Task prefix for this role | +| `roles[].role_spec` | string | Relative path to role-spec file | + +### Optional Fields + +| Field | Type | Description | +|-------|------|-------------| +| `pipeline` | object | Pipeline metadata | +| `active_workers` | array | Currently running workers | +| `completed_tasks` | array | List of completed task IDs | +| `completion_action` | string | Completion mode: interactive, auto_archive, auto_keep | +| `created_at` | string | ISO timestamp | + +--- + +## task-analysis.json Schema + +```json +{ + "capabilities": [ + { + "name": "", + "description": "", + "artifact_type": "" + } + ], + "dependency_graph": { + "": { + "depends_on": [""], + "role": "" + } + }, + "roles": [ + { + "name": "", + "prefix": "", + "responsibility_type": "", + "inner_loop": false, + "role_spec_metadata": { + "subagents": [], + "message_types": { + "success": "_complete", + "error": "error" + } + } + } + ], + "complexity_score": 0 +} +``` + +--- + +## Role-Spec File Schema + +Each role-spec in `role-specs/.md` follows the lightweight format with YAML frontmatter + Phase 2-4 body. + +### Required Structure + +```markdown +--- +role: +prefix: +inner_loop: +message_types: + success: + error: error +--- + +# — Phase 2-4 + +## Phase 2: + + +## Phase 3: + + +## Phase 4: + +``` + +### Role-Spec Structure Validation + +``` +For each role-spec in role-specs/.md: + 1. Read file content + 2. Check for YAML frontmatter (content between --- markers) + +- Not found -> ERROR: "Invalid role-spec: role-specs/.md missing frontmatter" + 3. Parse frontmatter, check required fields: + +- role (string) -> missing -> ERROR + +- prefix (string) -> missing -> ERROR + +- inner_loop (boolean) -> missing -> ERROR + +- message_types (object) -> missing -> ERROR + 4. Check for "## Phase 2" section + +- Not found -> ERROR: "Invalid role-spec: missing Phase 2" + 5. Check for "## Phase 3" section + +- Not found -> ERROR: "Invalid role-spec: missing Phase 3" + 6. Check for "## Phase 4" section + +- Not found -> ERROR: "Invalid role-spec: missing Phase 4" + 7. All checks pass -> role-spec valid +``` + +--- + +## Example Valid Session + +``` +.workflow/.team/TC-auth-feature-2026-02-27/ ++-- team-session.json # Valid JSON with session metadata ++-- task-analysis.json # Valid JSON with dependency graph ++-- role-specs/ +| +-- researcher.md # YAML frontmatter + Phase 2-4 +| +-- developer.md # YAML frontmatter + Phase 2-4 +| +-- tester.md # YAML frontmatter + Phase 2-4 ++-- artifacts/ # (may be empty) ++-- shared-memory.json # Valid JSON (may be {}) ++-- wisdom/ +| +-- learnings.md +| +-- decisions.md +| +-- issues.md ++-- explorations/ +| +-- cache-index.json ++-- discussions/ # (may be empty) ++-- .msg/ # (may be empty) +``` + +--- + +## Recovery from Invalid Sessions + +If session validation fails: + +1. **Missing team-session.json**: Re-run team-coordinate with original task +2. **Missing task-analysis.json**: Re-run team-coordinate with resume +3. **Missing role-spec files**: Re-run team-coordinate with resume +4. **Invalid frontmatter**: Manual fix or re-run team-coordinate +5. **Corrupt JSON**: Manual inspection or re-run team-coordinate + +**team-executor cannot fix invalid sessions** -- it can only report errors and suggest recovery steps.