Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking. Triggers on "workflow-execute".
Orchestrates autonomous workflow execution through systematic task discovery, agent coordination, and progress tracking. Executes entire workflow without user interruption (except initial session selection if multiple active sessions exist), providing complete context to agents and ensuring proper flow control execution with comprehensive TodoWrite tracking.
Resume Mode: When called with --resume-session flag, skips discovery phase and directly enters TodoWrite generation and agent execution for the specified session.
# Interactive mode (with confirmations)
/workflow-execute
/workflow-execute --resume-session="WFS-auth"
# Auto mode (skip confirmations, use defaults)
/workflow-execute --yes
/workflow-execute -y
/workflow-execute -y --resume-session="WFS-auth"
# With auto-commit (commit after each task completion)
/workflow-execute --with-commit
/workflow-execute -y --with-commit
/workflow-execute -y --with-commit --resume-session="WFS-auth"
When --yes or -y flag is used:
/workflow:session:complete --yes)When --with-commit flag is used:
Flag Parsing:
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)
const withCommit = $ARGUMENTS.includes('--with-commit')
Lazy Loading: Task JSONs read on-demand during execution, not upfront. TODO_LIST.md + IMPL_PLAN.md provide metadata for planning.
Loading Strategy:
Complete entire workflow autonomously without user interruption, using TodoWrite for comprehensive progress tracking. Execute all discovered pending tasks until workflow completion or blocking dependency. User-choice completion: When all tasks finished, ask user to choose review or complete. ONE AGENT = ONE TASK JSON: Each agent instance executes exactly one task JSON file - never batch multiple tasks into single agent execution.
Normal Mode:
Phase 1: Discovery
├─ Count active sessions
└─ Decision:
├─ count=0 → ERROR: No active sessions
├─ count=1 → Auto-select session → Phase 2
└─ count>1 → AskUserQuestion (max 4 options) → Phase 2
Phase 2: Planning Document Validation
├─ Check IMPL_PLAN.md exists
├─ Check TODO_LIST.md exists
└─ Validate .task/ contains IMPL-*.json files
Phase 3: TodoWrite Generation
├─ Update session status to "active" (Step 0)
├─ Parse TODO_LIST.md for task statuses
├─ Generate TodoWrite for entire workflow
└─ Prepare session context paths
Phase 4: Execution Strategy & Task Execution
├─ Step 4A: Parse execution strategy from IMPL_PLAN.md
└─ Step 4B: Execute tasks with lazy loading
└─ Loop:
├─ Get next in_progress task from TodoWrite
├─ Lazy load task JSON
├─ Launch agent with task context
├─ Mark task completed (update IMPL-*.json status)
│ # Quick fix: Update task status for ccw dashboard
│ # TS=$(date -Iseconds) && jq --arg ts "$TS" '.status="completed" | .status_history=(.status_history // [])+[{"from":"in_progress","to":"completed","changed_at":$ts}]' IMPL-X.json > tmp.json && mv tmp.json IMPL-X.json
├─ [with-commit] Commit changes based on summary (minimal principle)
│ # Read summary from .summaries/IMPL-X-summary.md
│ # Extract changed files from summary's "Files Modified" section
│ # Generate commit message: "feat/fix/refactor: {task-title} - {summary}"
│ # git add <changed-files> && git commit -m "<commit-message>"
└─ Advance to next task
Phase 5: Completion
├─ Update task statuses in JSON files
├─ Generate summaries
└─ AskUserQuestion: Choose next step
├─ "Enter Review" → Phase 6
└─ "Complete Session" → /workflow:session:complete
Phase 6: Post-Implementation Review (Optional)
└─ Ref: phases/06-review.md
├─ Select review type (quality/security/architecture/action-items)
├─ CLI-assisted analysis (Gemini/Qwen)
├─ Generate REVIEW-{type}.md report
└─ Post-review: another review or complete session
Resume Mode (--resume-session):
├─ Skip Phase 1 & Phase 2
└─ Entry Point: Phase 3 (TodoWrite Generation)
├─ Update session status to "active" (if not already)
└─ Continue: Phase 4 → Phase 5 → [Phase 6]
Applies to: Normal mode only (skipped in resume mode)
Purpose: Find and select active workflow session with user confirmation when multiple sessions exist
Process:
bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null | wc -l)
Case A: No Sessions (count = 0)
ERROR: No active workflow sessions found
Run /workflow-plan "task description" to create a session
Case B: Single Session (count = 1)
bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null | head -1 | xargs basename)
Auto-select and continue to Phase 2.
Case C: Multiple Sessions (count > 1)
List sessions with metadata and prompt user selection:
bash(for dir in .workflow/active/WFS-*/; do [ -d "$dir" ] || continue; session=$(basename "$dir"); project=$(jq -r '.project // "Unknown"' "${dir}workflow-session.json" 2>/dev/null || echo "Unknown"); total=$(grep -c '^\- \[' "${dir}TODO_LIST.md" 2>/dev/null || echo 0); completed=$(grep -c '^\- \[x\]' "${dir}TODO_LIST.md" 2>/dev/null || echo 0); if [ "$total" -gt 0 ]; then progress=$((completed * 100 / total)); else progress=0; fi; echo "$session | $project | $completed/$total tasks ($progress%)"; done)
Parse --yes flag:
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)
Conditional Selection:
if (autoYes) {
// Auto mode: Select first session (most recent)
const firstSession = sessions[0]
console.log(`[--yes] Auto-selecting session: ${firstSession.id}`)
selectedSessionId = firstSession.id
// Continue to Phase 2
} else {
// Interactive mode: Use AskUserQuestion to present formatted options (max 4 options shown)
// If more than 4 sessions, show most recent 4 with "Other" option for manual input
const sessions = getActiveSessions() // sorted by last modified
const displaySessions = sessions.slice(0, 4)
AskUserQuestion({
questions: [{
question: "Multiple active sessions detected. Select one:",
header: "Session",
multiSelect: false,
options: displaySessions.map(s => ({
label: s.id,
description: `${s.project} | ${s.progress}`
}))
// Note: User can select "Other" to manually enter session ID
}]
})
}
Input Validation:
Parse user input (supports: number "1", full ID "WFS-auth-system", or partial "auth"), validate selection, and continue to Phase 2.
bash(cat .workflow/active/${sessionId}/workflow-session.json)
Output: Store session metadata in memory DO NOT read task JSONs yet - defer until execution phase (lazy loading)
Resume Mode: This entire phase is skipped when --resume-session="session-id" flag is provided.
Applies to: Normal mode only (skipped in resume mode)
Purpose: Validate planning artifacts exist before execution
Process:
.task/ contains at least one IMPL-*.json fileKey Optimization: Only existence checks here. Actual file reading happens in later phases.
Resume Mode: This phase is skipped when --resume-session flag is provided. Resume mode entry point is Phase 3.
Applies to: Both normal and resume modes (resume mode entry point)
Step 0: Update Session Status to Active Before generating TodoWrite, update session status from "planning" to "active":
# Update session status (idempotent - safe to run if already active)
jq '.status = "active" | .execution_started_at = (.execution_started_at // now | todate)' \
.workflow/active/${sessionId}/workflow-session.json > tmp.json && \
mv tmp.json .workflow/active/${sessionId}/workflow-session.json
This ensures the dashboard shows the session as "ACTIVE" during execution.
Process:
Resume Mode Behavior:
.workflow/active/{session-id}/Applies to: Both normal and resume modes
Step 4A: Parse Execution Strategy (plan.json preferred, IMPL_PLAN.md fallback)
Prefer plan.json (structured) over IMPL_PLAN.md (human-readable) for execution strategy:
recommended_execution, complexity, task_ids[], shared_contextExtract:
If neither has execution strategy, use intelligent fallback (analyze task structure).
Step 4B: Execute Tasks with Lazy Loading
Key Optimization: Read task JSON only when needed for execution
Execution Loop Pattern:
while (TODO_LIST.md has pending tasks) {
next_task_id = getTodoWriteInProgressTask()
task_json = Read(.workflow/active/{session}/.task/{next_task_id}.json) // Lazy load
executeTaskWithAgent(task_json)
updateTodoListMarkCompleted(next_task_id)
advanceTodoWriteToNextTask()
}
Execution Process per Task:
in_progress task ID.task/{task-id}.json for current task ONLY--with-commit flag enabled, commit changes based on summary
.summaries/{task-id}-summary.mdmeta.type (feature→feat, bugfix→fix, refactor→refactor)git add <files> && git commit -m "<message>"Note: TODO_LIST.md updates are handled by agents (e.g., code-developer.md), not by the orchestrator.
Applies to: Both normal and resume modes
Process:
.summaries/// Parse --yes flag
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)
if (autoYes) {
// Auto mode: Complete session automatically
console.log(`[--yes] Auto-selecting: Complete Session`)
Skill(skill="workflow:session:complete", args="--yes")
} else {
// Interactive mode: Ask user
AskUserQuestion({
questions: [{
question: "All tasks completed. What would you like to do next?",
header: "Next Step",
multiSelect: false,
options: [
{
label: "Enter Review",
description: "Run specialized review (security/architecture/quality/action-items)"
},
{
label: "Complete Session",
description: "Archive session and update manifest"
}
]
}]
})
}
Based on user selection:
Ref: phases/06-review.md/workflow:session:completeAuto-sync: 执行 /workflow:session:sync -y "{summary}" 更新 specs/*.md + project-tech。
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 /issue:new "{summary} - {dimension}"
IMPL_PLAN-Driven Execution (Recommended):
Intelligent Fallback (When IMPL_PLAN lacks execution details):
meta.execution_group in task JSONsdepends_on relationshipsWhen: IMPL_PLAN specifies "Sequential" OR no clear parallelization guidance
Pattern: Execute tasks one by one in TODO_LIST order
TodoWrite: ONE task marked as in_progress at a time
When: IMPL_PLAN specifies "Parallel" with clear parallelization opportunities
Pattern: Execute independent task groups concurrently by launching multiple agent instances
TodoWrite: MULTIPLE tasks (in same batch) marked as in_progress simultaneously
Agent Instantiation: Launch one agent instance per task (respects ONE AGENT = ONE TASK JSON rule)
When: IMPL_PLAN specifies "Phased" with phase breakdown Pattern: Execute tasks in phases, respect phase boundaries TodoWrite: Within each phase, follow Sequential or Parallel rules
When: IMPL_PLAN lacks execution strategy details Pattern: Analyze task structure and apply smart defaults TodoWrite: Follow Sequential or Parallel rules based on analysis
pending + dependencies_met → executable
completed → skip
blocked → skip until dependencies clear
Rule 1: Initial Creation
Rule 2: In-Progress Task Count (Execution-Model-Dependent)
in_progress at a timein_progress simultaneously[execution_group: group-id] for parallel tasksRule 3: Status Updates
Rule 4: Workflow Completion Check
completed, prompt user to choose review or complete sessionExample 1: Sequential Execution
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
status: "in_progress", // ONE task in progress
activeForm: "Executing IMPL-1.1: Design auth schema"
},
{
content: "Execute IMPL-1.2: Implement auth logic [code-developer] [FLOW_CONTROL]",
status: "pending",
activeForm: "Executing IMPL-1.2: Implement auth logic"
}
]
});
Example 2: Parallel Batch Execution
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Build Auth API [code-developer] [execution_group: parallel-auth-api]",
status: "in_progress", // Batch task 1
activeForm: "Executing IMPL-1.1: Build Auth API"
},
{
content: "Execute IMPL-1.2: Build User UI [code-developer] [execution_group: parallel-ui-comp]",
status: "in_progress", // Batch task 2 (running concurrently)
activeForm: "Executing IMPL-1.2: Build User UI"
},
{
content: "Execute IMPL-1.3: Setup Database [code-developer] [execution_group: parallel-db-schema]",
status: "in_progress", // Batch task 3 (running concurrently)
activeForm: "Executing IMPL-1.3: Setup Database"
},
{
content: "Execute IMPL-2.1: Integration Tests [test-fix-agent] [depends_on: IMPL-1.1, IMPL-1.2, IMPL-1.3]",
status: "pending", // Next batch (waits for current batch completion)
activeForm: "Executing IMPL-2.1: Integration Tests"
}
]
});
[FLOW_CONTROL] marker indicates task JSON contains pre_analysis steps for context preparation.
Note: Orchestrator does NOT execute flow control steps - Agent interprets and executes them autonomously.
Path-Based Invocation: Pass paths and trigger markers, let agent parse task JSON autonomously.
Agent(subagent_type="{meta.agent}",
run_in_background=false,
prompt="Implement task {task.id}: {task.title}
[FLOW_CONTROL]
**Input**:
- Task JSON: {session.task_json_path}
- Context Package: {session.context_package_path}
**Output Location**:
- Workflow: {session.workflow_dir}
- TODO List: {session.todo_list_path}
- Summaries: {session.summaries_dir}
**Execution**: Read task JSON → Execute pre_analysis → Check execution_config.method → (CLI: handoff to CLI tool | Agent: direct implementation) → Update TODO_LIST.md → Generate summary",
description="Implement: {task.id}")
Key Markers:
Implement keyword: Triggers tech stack detection and guidelines loading[FLOW_CONTROL]: Triggers pre_analysis executionWhy Path-Based: Agent (code-developer.md) autonomously:
Embedding task content in prompt creates duplication and conflicts with agent's parsing logic.
meta.agent specified → Use specified agent
meta.agent missing → Infer from meta.type:
- "feature" → @code-developer
- "test-gen" → @code-developer
- "test-fix" → @test-fix-agent
- "review" → @universal-executor
- "docs" → @doc-generator
| Phase | Document | Purpose |
|---|---|---|
| 6 | phases/06-review.md | Post-implementation specialized review (security/architecture/quality/action-items) |
.workflow/active/WFS-[topic-slug]/
├── workflow-session.json # Session state and metadata
├── plan.json # Structured plan overview (machine-readable)
├── IMPL_PLAN.md # Planning document and requirements (human-readable)
├── TODO_LIST.md # Progress tracking (updated by agents)
├── .task/ # Task definitions (JSON only)
│ ├── IMPL-1.json # Main task definitions
│ └── IMPL-1.1.json # Subtask definitions
├── .summaries/ # Task completion summaries
│ ├── IMPL-1-summary.md # Task completion details
│ └── IMPL-1.1-summary.md # Subtask completion details
└── .process/ # Planning artifacts
├── context-package.json # Smart context package
└── ANALYSIS_RESULTS.md # Planning analysis results
| Error Type | Cause | Recovery Strategy | Max Attempts |
|---|---|---|---|
| Discovery Errors | |||
| No active session | No sessions in .workflow/active/ | Create or resume session: /workflow-plan "project" | N/A |
| Multiple sessions | Multiple sessions in .workflow/active/ | Prompt user selection | N/A |
| Corrupted session | Invalid JSON files | Recreate session structure or validate files | N/A |
| Execution Errors | |||
| Agent failure | Agent crash/timeout | Retry with simplified context | 2 |
| Flow control error | Command failure | Skip optional, fail critical | 1 per step |
| Context loading error | Missing dependencies | Reload from JSON, use defaults | 3 |
| JSON file corruption | File system issues | Restore from backup/recreate | 1 |
Behavior: After each agent task completes, automatically commit changes based on summary document.
Minimal Principle: Only commit files modified by the completed task.
Commit Message Format: {type}: {task-title} - {summary}
Type Mapping (from meta.type):
feature → feat | bugfix → fix | refactor → refactortest-gen → test | docs → docs | review → choreImplementation:
# 1. Read summary from .summaries/{task-id}-summary.md
# 2. Extract files from "Files Modified" section
# 3. Commit: git add <files> && git commit -m "{type}: {title} - {summary}"
Error Handling: Skip commit on no changes/missing summary, log errors, continue workflow.
Prerequisite Skills:
workflow-plan skill - Generate implementation plan and task JSONsCalled During Execution:
/workflow:session:complete - Archive session after all tasks completereview-cycle skill - Post-implementation reviewFollow-up Skills:
/issue:new - Create follow-up issues (test/enhance/refactor/doc)