refactor: team-planex dual-version optimization with v5 architecture

Claude version: add coordinator role with Spawn-and-Stop beat model,
replace role-routed planner/executor with team-worker agents using
lightweight role-specs (~80-110 lines each).

Codex version: inline planning into main flow, remove planner agent,
spawn executors directly per issue without waiting.

Both versions preserve 3 input types (Issue IDs / --text / --plan).
This commit is contained in:
catlog22
2026-02-28 15:31:03 +08:00
parent d14a710797
commit 3788ba1268
11 changed files with 925 additions and 1330 deletions

View File

@@ -0,0 +1,87 @@
# Command: dispatch
## Purpose
Create the initial task chain for team-planex pipeline. Creates PLAN-001 for planner. EXEC-* tasks are NOT pre-created — planner creates them at runtime per issue.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Input type | Phase 1 requirements | Yes |
| Raw input | Phase 1 requirements | Yes |
| Session folder | Phase 2 session init | Yes |
| Execution method | Phase 1 requirements | Yes |
## Phase 3: Task Chain Creation
### Task Creation
Create a single PLAN-001 task for the planner:
```
TaskCreate({
subject: "PLAN-001: Requirement decomposition and solution design",
description: `Decompose requirements into issues and generate solutions.
Input type: <issues|text|plan>
Input: <raw-input>
Session: <session-folder>
Execution method: <agent|codex|gemini>
## Instructions
1. Parse input to get issue list
2. For each issue: call issue-plan-agent → write solution artifact
3. After each solution: create EXEC-* task (owner: executor) with solution_file path
4. After all issues: send all_planned signal
InnerLoop: true`,
activeForm: "Planning requirements"
})
```
### EXEC-* Task Template (for planner reference)
Planner creates EXEC-* tasks at runtime using this template:
```
TaskCreate({
subject: "EXEC-00N: Implement <issue-title>",
description: `Implement solution for issue <issueId>.
Issue ID: <issueId>
Solution file: <session-folder>/artifacts/solutions/<issueId>.json
Session: <session-folder>
Execution method: <agent|codex|gemini>
InnerLoop: true`,
activeForm: "Implementing <issue-title>"
})
```
### Add Command Task Template
When coordinator handles `add` command, create additional PLAN tasks:
```
TaskCreate({
subject: "PLAN-00N: Additional requirement decomposition",
description: `Additional requirements to decompose.
Input type: <issues|text|plan>
Input: <new-input>
Session: <session-folder>
Execution method: <execution-method>
InnerLoop: true`,
activeForm: "Planning additional requirements"
})
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| PLAN-001 created | TaskList shows PLAN-001 |
| Description complete | Contains Input, Session, Execution method |
| No orphans | All tasks have valid owner |

View File

@@ -0,0 +1,163 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. Three wake-up sources: worker callbacks, user `check`, user `resume`.
## 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 |
| WORKER_AGENT | team-worker | All workers are 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 |
## Phase 3: Handler Routing
### Wake-up Source Detection
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[planner]` or `[executor]` tag | handleCallback |
| 2 | Contains "check" or "status" | handleCheck |
| 3 | Contains "resume", "continue", or "next" | handleResume |
| 4 | None of the above (initial spawn) | handleSpawnNext |
---
### Handler: handleCallback
```
Receive callback from [<role>]
+- Match role: planner or executor
+- Progress update (not final)?
| +- YES -> Update session -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- role = planner?
| | | +- Check for new EXEC-* tasks (planner creates them)
| | | +- -> handleSpawnNext (spawn executor for new EXEC-* tasks)
| | +- role = executor?
| | +- Mark issue done
| | +- -> handleSpawnNext (check for more EXEC-* tasks)
| +- NO -> progress message -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process -> handleSpawnNext
+- None completed -> STOP
```
---
### Handler: handleCheck
Read-only status report. No advancement.
```
[coordinator] PlanEx Pipeline Status
[coordinator] Progress: <completed>/<total> (<percent>%)
[coordinator] Task Graph:
PLAN-001: <status-icon> <summary>
EXEC-001: <status-icon> <issue-title>
EXEC-002: <status-icon> <issue-title>
...
done=completed >>>=running o=pending
[coordinator] Active Workers:
> <subject> (<role>) - running <elapsed>
[coordinator] Ready to spawn: <subjects>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
Then STOP.
---
### Handler: handleResume
```
Load active_workers
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- completed -> mark done, log
+- in_progress -> still running
+- other -> worker failure -> reset to pending
After:
+- Some completed -> handleSpawnNext
+- All running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleSpawnNext
```
Collect task states from TaskList()
+- Filter tasks: PLAN-* and EXEC-* prefixes
+- readySubjects: pending + not blocked (no blockedBy or all blockedBy completed)
+- NONE ready + work in progress -> report waiting -> STOP
+- NONE ready + nothing running -> PIPELINE_COMPLETE -> Phase 5
+- HAS ready tasks -> for each:
+- Inner Loop role AND already has active_worker for that role?
| +- YES -> SKIP spawn (existing worker picks up via inner loop)
| +- NO -> spawn below
+- Determine role from task prefix:
| +- PLAN-* -> planner
| +- EXEC-* -> executor
+- Spawn team-worker:
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: .claude/skills/team-planex/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: true
execution_method: <method>`
})
+- Add to session.active_workers
Update session -> output summary -> STOP
```
---
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches in_progress tasks |
| No orphaned tasks | Every in_progress has active_worker |
| Pipeline completeness | All expected EXEC-* tasks accounted for |
## Worker Failure Handling
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-initialization |
| Unknown role callback | Log, scan for other completions |
| All workers running on resume | Report status, suggest check later |
| Pipeline stall (no ready + no running + has pending) | Check blockedBy chains, report |

View File

@@ -0,0 +1,154 @@
# Coordinator Role
Orchestrate the team-planex pipeline: parse input, create team, dispatch tasks, monitor progress via Spawn-and-Stop beats. Uses **team-worker agent** for all worker spawns.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse input -> Create team -> Dispatch PLAN-001 -> Spawn planner -> Monitor callbacks -> Spawn executors -> Report
## Boundaries
### MUST
- Parse user input (Issue IDs / --text / --plan) and determine execution method
- Create team and initialize session directory
- Dispatch tasks via `commands/dispatch.md`
- Monitor progress via `commands/monitor.md` with Spawn-and-Stop pattern
- Maintain session state (team-session.json)
### MUST NOT
- Execute planning or implementation work directly (delegate to workers)
- Modify solution artifacts or code (workers own their deliverables)
- Call implementation subagents (code-developer, etc.) directly
- Skip dependency validation when creating task chains
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file
3. **Commands are inline execution guides** - NOT separate agents
4. **Execute synchronously** - complete the command workflow before proceeding
---
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[planner]` or `[executor]` tag | -> handleCallback (monitor.md) |
| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) |
| Add tasks | Arguments contain "add" | -> handleAdd |
| Interrupted session | Active/paused session exists in `.workflow/.team/PEX-*` | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume: load `commands/monitor.md` and execute the appropriate handler, then STOP.
### handleAdd
1. Parse new input (Issue IDs / `--text` / `--plan`)
2. Get current max PLAN-* sequence from `TaskList`
3. `TaskCreate` new PLAN-00N task (owner: planner)
4. If planner already sent `all_planned` (check team_msg) -> `SendMessage` to planner to re-enter loop
5. STOP
---
## Phase 0: Session Resume Check
1. Scan `.workflow/.team/PEX-*/team-session.json` for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume (Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for selection
**Session Reconciliation**:
1. Audit TaskList -> reconcile session state vs task status
2. Reset in_progress tasks -> pending (they were interrupted)
3. Rebuild team if needed (TeamCreate + spawn needed workers)
4. Kick first executable task -> Phase 4
---
## Phase 1: Input Parsing + Execution Method
1. **Parse arguments**: Extract input type (Issue IDs / --text / --plan) and optional flags (--exec, -y)
2. **Determine execution method** (see SKILL.md Selection Decision Table):
- Explicit `--exec` flag -> use specified method
- `-y` / `--yes` flag -> Auto mode
- No flags -> AskUserQuestion for method choice
3. **Store requirements**: input_type, raw_input, execution_method
---
## Phase 2: Create Team + Initialize Session
1. Generate session ID: `PEX-<slug>-<date>`
2. Create session folder: `.workflow/.team/<session-id>/`
3. Create subdirectories: `artifacts/solutions/`, `wisdom/`
4. Call `TeamCreate` with team name (default: "planex")
5. Initialize wisdom files (learnings.md, decisions.md, conventions.md, issues.md)
6. Write team-session.json:
```
{
session_id: "<session-id>",
input_type: "<issues|text|plan>",
input: "<raw-input>",
execution_method: "<agent|codex|gemini>",
status: "active",
active_workers: [],
started_at: "<ISO timestamp>"
}
```
---
## Phase 3: Create Task Chain
Delegate to `commands/dispatch.md`:
1. Read `roles/coordinator/commands/dispatch.md`
2. Execute its workflow to create PLAN-001 task
3. PLAN-001 contains input info + execution method in description
---
## Phase 4: Spawn-and-Stop
1. Load `commands/monitor.md`
2. Execute `handleSpawnNext` to find ready tasks and spawn planner worker
3. Output status summary
4. **STOP** (idle, wait for worker callback)
**ONE_STEP_PER_INVOCATION**: true — coordinator does one operation per wake-up, then STOPS.
---
## Phase 5: Report + Completion Action
When all tasks are complete (monitor.md detects PIPELINE_COMPLETE):
1. Load session state -> count completed tasks, duration
2. List deliverables with output paths
3. Update session status -> "completed"
4. Execute Completion Action (see SKILL.md)
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Session file not found | Error, suggest re-initialization |
| Unknown worker callback | Log, scan for other completions |
| Pipeline stall | Check missing tasks, report to user |
| Worker crash | Reset task to pending, re-spawn on next beat |
| All workers running on resume | Report status, suggest check later |

View File

@@ -1,356 +0,0 @@
# Executor Role
Load solution -> Route to backend (Agent/Codex/Gemini) based on execution_method -> Test verification -> Commit. Supports multiple CLI execution backends. Execution method is determined before skill invocation (see SKILL.md Execution Method Selection).
## Identity
- **Name**: `executor` | **Tag**: `[executor]`
- **Task Prefix**: `EXEC-*`
- **Responsibility**: Code implementation (solution -> route to backend -> test -> commit)
## Boundaries
### MUST
- Only process `EXEC-*` prefixed tasks
- All output (SendMessage, team_msg, logs) must carry `[executor]` identifier
- Select execution backend based on `execution_method` field in EXEC-* task
- Notify planner after each issue completes
- Continuously poll for new EXEC-* tasks (planner may create new waves anytime)
### MUST NOT
- Create issues (planner responsibility)
- Modify solution or queue (planner responsibility)
- Call issue-plan-agent or issue-queue-agent
- Interact directly with user (AskUserQuestion)
- Create PLAN-* tasks for planner
---
## Toolbox
### Execution Backends
| Backend | Tool | Invocation | Mode |
|---------|------|------------|------|
| `agent` | code-developer subagent | `Task({ subagent_type: "code-developer" })` | Synchronous |
| `codex` | Codex CLI | `ccw cli --tool codex --mode write` | Background |
| `gemini` | Gemini CLI | `ccw cli --tool gemini --mode write` | Background |
### Direct Capabilities
| Tool | Purpose |
|------|---------|
| `Read` | Read solution plan and queue files |
| `Write` | Write implementation artifacts |
| `Edit` | Edit source code |
| `Bash` | Run tests, git operations, CLI calls |
### CLI Capabilities
| CLI Command | Purpose |
|-------------|---------|
| `ccw issue status <id> --json` | Check issue status |
| `ccw issue solution <id> --json` | Load single issue's bound solution (requires issue ID) |
| `ccw issue update <id> --status executing` | Update issue status to executing |
| `ccw issue update <id> --status completed` | Mark issue as completed |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `impl_complete` | executor -> planner | Implementation and tests pass | Single issue implementation complete |
| `impl_failed` | executor -> planner | Implementation failed after retries | Implementation failure |
| `wave_done` | executor -> planner | All EXEC tasks in a wave completed | Entire wave complete |
| `error` | executor -> planner | Blocking error | Execution error |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
**NOTE**: `team` must be **session ID** (e.g., `PEX-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description.
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>, // e.g., "PEX-project-2026-02-27", NOT "planex"
from: "executor",
to: "planner",
type: <message-type>,
summary: "[executor] <task-prefix> complete: <task-subject>",
ref: <artifact-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from executor --to planner --type <message-type> --summary \"[executor] <task-prefix> complete\" --ref <artifact-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `EXEC-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Load Solution & Resolve Executor
**Issue ID Extraction**:
Extract issue ID from task description using pattern `ISS-\d{8}-\d{6}`.
If no issue ID found:
1. Log error via team_msg
2. SendMessage error to planner
3. TaskUpdate completed
4. Return to idle
**Solution Loading (Dual Mode)**:
| Mode | Condition | Action |
|------|-----------|--------|
| File-first | Task description contains `solution_file: <path>` | Read JSON file, extract solution.bound |
| CLI fallback | No solution_file field | Call `ccw issue solution <issueId> --json` |
If no bound solution found:
1. Log error via team_msg
2. SendMessage error to planner
3. TaskUpdate completed
4. Return to idle
**Execution Method Resolution**:
| Condition | Executor |
|-----------|----------|
| `execution_method: Agent` in task description | agent |
| `execution_method: Codex` in task description | codex |
| `execution_method: Gemini` in task description | gemini |
| `execution_method: Auto` + task_count <= 3 | agent |
| `execution_method: Auto` + task_count > 3 | codex |
| Unknown or missing | agent (with warning) |
**Code Review Resolution**:
Extract `code_review` from task description. Values: Skip | Gemini Review | Codex Review | Agent Review. Default: Skip.
**Issue Status Update**:
```
Bash("ccw issue update <issueId> --status executing")
```
### Phase 3: Implementation (Multi-Backend Routing)
Route to execution backend based on resolved executor.
#### Option A: Agent Execution
**When**: executor === 'agent' (simple tasks, task_count <= 3)
**Tool call**:
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Implement solution for <issueId>",
prompt: <execution-prompt>
})
```
Synchronous execution - wait for completion before Phase 4.
#### Option B: Codex CLI Execution
**When**: executor === 'codex' (complex tasks, background execution)
**Tool call**:
```
Bash("ccw cli -p \"<execution-prompt>\" --tool codex --mode write --id planex-<issueId>", { run_in_background: true })
```
**Resume on failure**:
```
ccw cli -p "Continue implementation" --resume planex-<issueId> --tool codex --mode write --id planex-<issueId>-retry
```
STOP after spawn - CLI executes in background, wait for task hook callback.
#### Option C: Gemini CLI Execution
**When**: executor === 'gemini' (analysis-heavy tasks, background execution)
**Tool call**:
```
Bash("ccw cli -p \"<execution-prompt>\" --tool gemini --mode write --id planex-<issueId>", { run_in_background: true })
```
STOP after spawn - CLI executes in background, wait for task hook callback.
### Execution Prompt Template
All backends use unified prompt structure:
```
## Issue
ID: <issueId>
Title: <solution-title>
## Solution Plan
<solution-bound-json>
## Implementation Requirements
1. Follow the solution plan tasks in order
2. Write clean, minimal code following existing patterns
3. Run tests after each significant change
4. Ensure all existing tests still pass
5. Do NOT over-engineer - implement exactly what the solution specifies
## Quality Checklist
- [ ] All solution tasks implemented
- [ ] No TypeScript/linting errors
- [ ] Existing tests pass
- [ ] New tests added where appropriate
- [ ] No security vulnerabilities introduced
## Project Guidelines
@.workflow/specs/*.md
```
### Phase 4: Verify & Commit
**Test Detection**:
| Detection | Method |
|-----------|--------|
| package.json scripts.test | Use `npm test` |
| package.json scripts.test:unit | Use `npm run test:unit` |
| No test script found | Skip verification, proceed to commit |
**Test Verification**:
```
Bash("<testCmd> 2>&1 || echo TEST_FAILED")
```
Check output for `TEST_FAILED` or `FAIL` strings.
**Test Failure Handling**:
| Condition | Action |
|-----------|--------|
| Tests failing | Report impl_failed to planner with test output + resume command |
| Tests passing | Proceed to code review (if configured) |
**Code Review (Optional)**:
| Review Tool | Execution |
|-------------|-----------|
| Gemini Review | `ccw cli -p "<review-prompt>" --tool gemini --mode analysis --id planex-review-<issueId>` (background) |
| Codex Review | `ccw cli --tool codex --mode review --uncommitted` (background, no prompt with target flags) |
| Agent Review | Current agent performs inline review against solution convergence criteria |
**Code Review Prompt**:
```
PURPOSE: Code review for <issueId> implementation against solution plan
TASK: Verify solution convergence criteria | Check test coverage | Analyze code quality | Identify issues
MODE: analysis
CONTEXT: @**/* | Memory: Review planex execution for <issueId>
EXPECTED: Quality assessment with issue identification and recommendations
CONSTRAINTS: Focus on solution adherence and code quality | analysis=READ-ONLY
```
**Issue Completion**:
```
Bash("ccw issue update <issueId> --status completed")
```
### Phase 5: Report + Loop
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
**Success Report**:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>, // e.g., "PEX-project-2026-02-27", NOT "planex"
from: "executor",
to: "planner",
type: "impl_complete",
summary: "[executor] Implementation complete for <issueId> via <executor>, tests passing"
})
SendMessage({
type: "message",
recipient: "planner",
content: `## [executor] Implementation Complete
**Issue**: <issueId>
**Executor**: <executor>
**Solution**: <solution-id>
**Code Review**: <codeReview>
**Status**: All tests passing
**Issue Status**: Updated to resolved`,
summary: "[executor] EXEC complete: <issueId> (<executor>)"
})
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
**Loop Check**:
Query for next `EXEC-*` task with owner=executor, status=pending, blockedBy empty.
| Condition | Action |
|-----------|--------|
| Tasks available | Return to Phase 1 for next task |
| No tasks + planner sent all_planned | Send wave_done and idle |
| No tasks + planner still planning | Idle for more tasks |
**Wave Done Signal**:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>, // e.g., "PEX-project-2026-02-27", NOT "planex"
from: "executor",
to: "planner",
type: "wave_done",
summary: "[executor] All EXEC tasks completed"
})
SendMessage({
type: "message",
recipient: "planner",
content: "## [executor] All Tasks Done\n\nAll EXEC-* tasks have been completed. Pipeline finished.",
summary: "[executor] wave_done: all complete"
})
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No EXEC-* tasks available | Idle, wait for planner to create tasks |
| Solution plan not found | Report error to planner |
| Unknown execution_method | Fallback to `agent` with warning |
| Agent (code-developer) failure | Retry once, then report impl_failed |
| CLI (Codex/Gemini) failure | Provide resume command with fixed ID, report impl_failed |
| CLI timeout | Use fixed ID `planex-{issueId}` for resume |
| Tests failing after implementation | Report impl_failed with test output + resume info |
| Issue status update failure | Log warning, continue with report |
| Dependency not yet complete | Wait - task is blocked by blockedBy |
| All tasks done but planner still planning | Send wave_done, then idle for more |
| Critical issue beyond scope | SendMessage error to planner |

View File

@@ -1,315 +0,0 @@
# Planner Role
Demand decomposition -> Issue creation -> Solution design -> Conflict check -> EXEC task dispatch. Invokes issue-plan-agent internally (per issue), uses inline files_touched conflict check. Dispatches EXEC-* task immediately after each issue's solution is ready. Planner also serves as lead role (no separate coordinator).
## Identity
- **Name**: `planner` | **Tag**: `[planner]`
- **Task Prefix**: `PLAN-*`
- **Responsibility**: Planning lead (requirement -> issues -> solutions -> queue -> dispatch)
## Boundaries
### MUST
- Only process `PLAN-*` prefixed tasks
- All output (SendMessage, team_msg, logs) must carry `[planner]` identifier
- Immediately create `EXEC-*` task after completing each issue's solution and send `issue_ready` signal
- Continue pushing forward without waiting for executor
- Write solution artifacts to `<sessionDir>/artifacts/solutions/{issueId}.json`
### MUST NOT
- Directly write/modify business code (executor responsibility)
- Call code-developer agent
- Run project tests
- git commit code changes
---
## Toolbox
### Subagent Capabilities
| Agent Type | Purpose |
|------------|---------|
| `issue-plan-agent` | Closed-loop planning: ACE exploration + solution generation + binding (single issue granularity) |
### CLI Capabilities
| CLI Command | Purpose |
|-------------|---------|
| `ccw issue create --data '{"title":"..."}' --json` | Create issue from text |
| `ccw issue status <id> --json` | Check issue status |
| `ccw issue solution <id> --json` | Get single issue's solutions (requires issue ID) |
| `ccw issue solutions --status planned --brief` | Batch list all bound solutions (cross-issue) |
| `ccw issue bind <id> <sol-id>` | Bind solution to issue |
### Skill Capabilities
| Skill | Purpose |
|-------|---------|
| `Skill(skill="issue:new", args="--text '...'")` | Create issue from text |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `issue_ready` | planner -> executor | Single issue solution + EXEC task created | Per-issue beat signal |
| `wave_ready` | planner -> executor | All issues in a wave dispatched | Wave summary signal |
| `all_planned` | planner -> executor | All waves planning complete | Final signal |
| `error` | planner -> executor | Blocking error | Planning failure |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
**NOTE**: `team` must be **session ID** (e.g., `PEX-project-2026-02-27`), NOT team name. Extract from `Session:` field in task description.
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>, // e.g., "PEX-project-2026-02-27", NOT "planex"
from: "planner",
to: "executor",
type: <message-type>,
summary: "[planner] <task-prefix> complete: <task-subject>",
ref: <artifact-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from planner --to executor --type <message-type> --summary \"[planner] <task-prefix> complete\" --ref <artifact-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `PLAN-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Input Parsing
Parse task description and arguments to determine input type.
**Input Type Detection**:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Issue IDs | Task description contains `ISS-\d{8}-\d{6}` pattern | Path C: Direct to planning |
| Text input | Arguments contain `--text '...'` | Path A: Create issue first |
| Plan file | Arguments contain `--plan <path>` | Path B: Parse and batch create |
| Execution plan JSON | Plan file is `execution-plan.json` from req-plan | Path D: Wave-aware processing |
| Description text | None of above | Treat task description as requirement text |
**Execution Config Extraction**:
From arguments, extract:
- `execution_method`: Agent | Codex | Gemini | Auto (default: Auto)
- `code_review`: Skip | Gemini Review | Codex Review | Agent Review (default: Skip)
### Phase 3: Issue Processing Pipeline
Execute different processing paths based on input type.
#### Path A: Text Input -> Create Issue
**Workflow**:
1. Use `issue:new` skill to create issue from text
2. Capture created issue ID
3. Add to issue list for planning
**Tool calls**:
```
Skill(skill="issue:new", args="--text '<requirement-text>'")
```
#### Path B: Plan File -> Batch Create Issues
**Workflow**:
1. Read plan file content
2. Parse phases/steps from markdown structure
3. For each phase/step, create an issue
4. Add all issue IDs to list for planning
**Plan Parsing Rules**:
- Match `## Phase N: Title` or `## Step N: Title` or `### N. Title`
- Each match creates one issue with title and description
- Fallback: If no phase structure, entire content becomes single issue
#### Path C: Issue IDs -> Direct Planning
Issue IDs are ready, proceed directly to solution planning.
#### Path D: execution-plan.json -> Wave-Aware Processing
**Workflow**:
1. Parse execution-plan.json with waves array
2. For each wave, process issues sequentially
3. For each issue in wave:
- Call issue-plan-agent to generate solution
- Write solution artifact to `<sessionDir>/artifacts/solutions/{issueId}.json`
- Perform inline conflict check
- Create EXEC-* task with solution_file path
- Send issue_ready signal
4. After each wave completes, send wave_ready signal
5. After all waves, send all_planned signal
**Issue Planning (per issue)**:
```
Task({
subagent_type: "issue-plan-agent",
run_in_background: false,
description: "Plan solution for <issueId>",
prompt: `issue_ids: ["<issueId>"]
project_root: "<projectRoot>"
## Requirements
- Generate solution for this issue
- Auto-bind single solution
- Issues come from req-plan decomposition (tags: req-plan)
- Respect dependencies: <issue_dependencies>`
})
```
**Solution Artifact**:
```
Write({
file_path: "<sessionDir>/artifacts/solutions/<issueId>.json",
content: JSON.stringify({
session_id: <sessionId>,
issue_id: <issueId>,
...solution,
execution_config: { execution_method, code_review },
timestamp: <ISO-timestamp>
}, null, 2)
})
```
**EXEC Task Creation**:
```
TaskCreate({
subject: "EXEC-W<waveNum>-<issueId>: Implement <solution-title>",
description: `## Execution Task
**Wave**: <waveNum>
**Issue**: <issueId>
**solution_file**: <solutionFile>
**execution_method**: <method>
**code_review**: <review>`,
activeForm: "Implementing <issueId>",
owner: "executor"
})
```
#### Wave Processing (Path A/B/C Convergence)
For non-execution-plan inputs, process all issues as a single logical wave:
**Workflow**:
1. For each issue in list:
- Call issue-plan-agent
- Write solution artifact
- Perform inline conflict check
- Create EXEC-* task
- Send issue_ready signal
2. After all issues complete, send wave_ready signal
### Phase 4: Inline Conflict Check + Dispatch
Perform conflict detection using files_touched overlap analysis.
**Conflict Detection Rules**:
| Condition | Action |
|-----------|--------|
| File overlap detected | Add blockedBy dependency to previous task |
| Explicit dependency in solution.bound.dependencies.on_issues | Add blockedBy to referenced task |
| No conflict | No blockedBy, task is immediately executable |
**Inline Conflict Check Algorithm**:
1. Get current solution's files_touched (or affected_files)
2. For each previously dispatched solution:
- Check if any files overlap
- If overlap, add previous execTaskId to blockedBy
3. Check explicit dependencies from solution.bound.dependencies.on_issues
4. Return blockedBy array for TaskUpdate
**Wave Summary Signal** (after all issues in wave):
```
mcp__ccw-tools__team_msg({
operation: "log", team: <session-id>, from: "planner", to: "executor", // team = session ID
type: "wave_ready",
summary: "[planner] Wave <waveNum> fully dispatched: <issueCount> issues"
})
SendMessage({
type: "message", recipient: "executor",
content: "## [planner] Wave <waveNum> Complete\nAll issues dispatched, <count> EXEC tasks created.",
summary: "[planner] wave_ready: wave <waveNum>"
})
```
### Phase 5: Report + Finalize
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
**Final Signal** (all waves complete):
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>, // e.g., "PEX-project-2026-02-27", NOT "planex"
from: "planner",
to: "executor",
type: "all_planned",
summary: "[planner] All <waveCount> waves planned, <issueCount> issues total"
})
SendMessage({
type: "message",
recipient: "executor",
content: `## [planner] All Waves Planned
**Total Waves**: <waveCount>
**Total Issues**: <issueCount>
**Status**: All planning complete, waiting for executor to finish remaining EXEC-* tasks
Pipeline complete when executor sends wave_done confirmation.`,
summary: "[planner] all_planned: <waveCount> waves, <issueCount> issues"
})
TaskUpdate({ taskId: <task-id>, status: "completed" })
```
**Loop Check**: Query for next `PLAN-*` task with owner=planner, status=pending, blockedBy empty. If found, return to Phase 1.
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No PLAN-* tasks available | Idle, wait for orchestrator |
| Issue creation failure | Retry once with simplified text, then report error |
| issue-plan-agent failure | Retry once, then report error and skip to next issue |
| Inline conflict check failure | Skip conflict detection, create EXEC task without blockedBy |
| Plan file not found | Report error with expected path |
| execution-plan.json parse failure | Fallback to plan_file parsing (Path B) |
| execution-plan.json missing waves | Report error, suggest re-running req-plan |
| Empty input (no issues, no text, no plan) | AskUserQuestion for clarification |
| Solution artifact write failure | Log warning, create EXEC task without solution_file (executor fallback) |
| Wave partially failed | Report partial success, continue with successful issues |
| Critical issue beyond scope | SendMessage error to executor |