feat: add team-coordinate-v2 and team-executor-v2 with team-worker agent architecture

v2 upgrades using the unified team-worker agent pattern:
- Replace general-purpose + Skill spawn with team-worker agent
- Use lightweight role-spec files (~80 lines, Phase 2-4 only) instead of full role.md (~250 lines)
- Add interactive completion action (Archive/Keep/Export) via handleComplete handler
- Remove shared infrastructure from SKILL.md (now in team-worker agent)

team-coordinate-v2 (8 files):
- SKILL.md: coordinator-only, team-worker spawn template
- specs/role-spec-template.md: lightweight Phase 2-4 template
- roles/coordinator/: updated for role-spec generation
- subagents/: discuss + explore (unchanged)

team-executor-v2 (4 files):
- SKILL.md: executor-only, team-worker spawn
- specs/session-schema.md: validates role-specs (not roles/)
- roles/executor/: updated for team-worker spawn + handleComplete
This commit is contained in:
catlog22
2026-02-27 20:47:03 +08:00
parent 61f929005c
commit 5b54f38aa3
12 changed files with 2497 additions and 0 deletions

View File

@@ -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 | `<session>/roles/<role>.md` (full role.md) | `<session>/role-specs/<role>.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=<path>" [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>`: Path to team-coordinate session folder (REQUIRED)
### Validation Steps
1. **Check `--session` provided**:
- If missing -> **ERROR**: "Session required. Usage: --session=<path-to-TC-folder>"
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=<session-folder>")`
**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) | `<session>/role-specs/<role-name>.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 <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
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=<path>')" |
| 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 |

View File

@@ -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 | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Role registry | session.roles[] | Yes |
**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name`. Role-spec paths are in `session.roles[].role_spec`.
## Phase 3: Handler Routing
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from session roles | handleCallback |
| 2 | Contains "capability_gap" | handleAdapt |
| 3 | Contains "check" or "status" | handleCheck |
| 4 | Contains "resume", "continue", or "next" | handleResume |
| 5 | Pipeline detected as complete | handleComplete |
| 6 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Verify completion, update state, auto-advance.
```
Receive callback from [<role>]
+- Find matching active worker by role (from session.roles)
+- Is this a progress update (not final)?
| +- 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: <completed>/<total> (<percent>%)
[executor] Execution Graph:
<visual representation with status icons>
done=completed >>>=running o=pending .=not created
[executor] Active Workers:
> <subject> (<role>) - running <elapsed>
[executor] Ready to spawn: <subjects>
[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=<session-id>)
+- 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 <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
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 [<role>]
+- 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 |

View File

@@ -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 `<session>/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] - <artifact-1.md> (<producer role>)
[executor] - <artifact-2.md> (<producer role>)
[executor]
[executor] Pipeline: <completed>/<total> tasks
[executor] Roles: <role-list>
[executor] Duration: <elapsed>
[executor]
[executor] Session: <session-folder>
[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 |

View File

@@ -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
```
<session-folder>/
+-- 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)
| +-- <role-1>.md # Lightweight: YAML frontmatter + Phase 2-4 only
| +-- <role-2>.md
+-- artifacts/ # All MD deliverables from workers
| +-- <artifact>.md
+-- shared-memory.json # Cross-role state store
+-- wisdom/ # Cross-task knowledge
| +-- learnings.md
| +-- decisions.md
| +-- issues.md
+-- explorations/ # Shared explore cache
| +-- cache-index.json
| +-- explore-<angle>.json
+-- discussions/ # Inline discuss records
| +-- <round>.md
+-- .msg/ # Team message bus logs
```
## Validation Checklist
team-executor validates the following before execution:
### Required Components
| Component | Validation | Error Message |
|-----------|------------|---------------|
| `--session` argument | Must be provided | "Session required. Usage: --session=<path-to-TC-folder>" |
| Directory | Must exist at path | "Session directory not found: <path>" |
| `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/<role>.md" |
| Role-spec structure | Each role-spec must have YAML frontmatter + Phase 2-4 sections | "Invalid role-spec: role-specs/<role>.md missing required section" |
### Validation Algorithm
```
1. Parse --session=<path> from arguments
+- Not provided -> ERROR: "Session required. Usage: --session=<path-to-TC-folder>"
2. Check directory exists
+- Not exists -> ERROR: "Session directory not found: <path>"
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/<role.name>.md exists
+- Not exists -> ERROR: "Role-spec file not found: role-specs/<role.name>.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-<slug>-<date>",
"task_description": "<original user input>",
"status": "active | paused | completed",
"team_name": "<team-name>",
"roles": [
{
"name": "<role-name>",
"prefix": "<PREFIX>",
"responsibility_type": "<type>",
"inner_loop": false,
"role_spec": "role-specs/<role-name>.md"
}
],
"pipeline": {
"dependency_graph": {},
"tasks_total": 0,
"tasks_completed": 0
},
"active_workers": [],
"completed_tasks": [],
"completion_action": "interactive",
"created_at": "<timestamp>"
}
```
### 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": "<capability-name>",
"description": "<description>",
"artifact_type": "<type>"
}
],
"dependency_graph": {
"<task-id>": {
"depends_on": ["<dependency-task-id>"],
"role": "<role-name>"
}
},
"roles": [
{
"name": "<role-name>",
"prefix": "<PREFIX>",
"responsibility_type": "<type>",
"inner_loop": false,
"role_spec_metadata": {
"subagents": [],
"message_types": {
"success": "<prefix>_complete",
"error": "error"
}
}
}
],
"complexity_score": 0
}
```
---
## Role-Spec File Schema
Each role-spec in `role-specs/<role-name>.md` follows the lightweight format with YAML frontmatter + Phase 2-4 body.
### Required Structure
```markdown
---
role: <name>
prefix: <PREFIX>
inner_loop: <true|false>
message_types:
success: <type>
error: error
---
# <Role Name> — Phase 2-4
## Phase 2: <Name>
<domain-specific context loading>
## Phase 3: <Name>
<domain-specific execution>
## Phase 4: <Name>
<domain-specific validation>
```
### Role-Spec Structure Validation
```
For each role-spec in role-specs/<role>.md:
1. Read file content
2. Check for YAML frontmatter (content between --- markers)
+- Not found -> ERROR: "Invalid role-spec: role-specs/<role>.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.