--- name: ccw description: Main workflow orchestrator - analyze intent, select workflow, execute command chain in main process argument-hint: "\"task description\"" allowed-tools: SlashCommand(*), TodoWrite(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*) --- # CCW Command - Main Workflow Orchestrator Main process orchestrator: intent analysis → workflow selection → command chain execution. ## Execution Model **Synchronous (Main Process)**: Commands execute via SlashCommand in main process, blocking until complete. ``` User Input → Analyze Intent → Select Workflow → [Confirm] → Execute Chain ↓ SlashCommand (blocking) ↓ Update TodoWrite ↓ Next Command... ``` **vs ccw-coordinator**: External CLI execution with background tasks and hook callbacks. ## 5-Phase Workflow ### Phase 1: Analyze Intent ```javascript function analyzeIntent(input) { return { goal: extractGoal(input), scope: extractScope(input), constraints: extractConstraints(input), task_type: detectTaskType(input), // bugfix|feature|tdd|review|exploration|... complexity: assessComplexity(input), // low|medium|high clarity_score: calculateClarity(input) // 0-3 (>=2 = clear) }; } // Task type detection (priority order) function detectTaskType(text) { const patterns = { 'bugfix-hotfix': /urgent|production|critical/ && /fix|bug/, 'bugfix': /fix|bug|error|crash|fail|debug/, 'issue-batch': /issues?|batch/ && /fix|resolve/, 'exploration': /uncertain|explore|research|what if/, 'multi-perspective': /multi-perspective|compare|cross-verify/, 'quick-task': /quick|simple|small/ && /feature|function/, 'ui-design': /ui|design|component|style/, 'tdd': /tdd|test-driven|test first/, 'test-fix': /test fail|fix test|failing test/, 'review': /review|code review/, 'documentation': /docs|documentation|readme/ }; for (const [type, pattern] of Object.entries(patterns)) { if (pattern.test(text)) return type; } return 'feature'; } ``` **Output**: `Type: [task_type] | Goal: [goal] | Complexity: [complexity] | Clarity: [clarity_score]/3` --- ### Phase 1.5: Requirement Clarification (if clarity_score < 2) ```javascript async function clarifyRequirements(analysis) { if (analysis.clarity_score >= 2) return analysis; const questions = generateClarificationQuestions(analysis); // Goal, Scope, Constraints const answers = await AskUserQuestion({ questions }); return updateAnalysis(analysis, answers); } ``` **Questions**: Goal (Create/Fix/Optimize/Analyze), Scope (Single file/Module/Cross-module/System), Constraints (Backward compat/Skip tests/Urgent hotfix) --- ### Phase 2: Select Workflow & Build Command Chain ```javascript function selectWorkflow(analysis) { const levelMap = { 'bugfix-hotfix': { level: 2, flow: 'bugfix.hotfix' }, 'bugfix': { level: 2, flow: 'bugfix.standard' }, 'issue-batch': { level: 'Issue', flow: 'issue' }, 'exploration': { level: 4, flow: 'full' }, 'quick-task': { level: 1, flow: 'lite-lite-lite' }, 'ui-design': { level: analysis.complexity === 'high' ? 4 : 3, flow: 'ui' }, 'tdd': { level: 3, flow: 'tdd' }, 'test-fix': { level: 3, flow: 'test-fix-gen' }, 'review': { level: 3, flow: 'review-fix' }, 'documentation': { level: 2, flow: 'docs' }, 'feature': { level: analysis.complexity === 'high' ? 3 : 2, flow: analysis.complexity === 'high' ? 'coupled' : 'rapid' } }; const selected = levelMap[analysis.task_type] || levelMap['feature']; return buildCommandChain(selected, analysis); } // Build command chain (port-based matching) function buildCommandChain(workflow, analysis) { const chains = { // Level 1 - Rapid 'lite-lite-lite': [ { cmd: '/workflow:lite-lite-lite', args: `"${analysis.goal}"` } ], // Level 2 - Lightweight 'rapid': [ { cmd: '/workflow:lite-plan', args: `"${analysis.goal}"` }, { cmd: '/workflow:lite-execute', args: '--in-memory' }, ...(analysis.constraints?.includes('skip-tests') ? [] : [ { cmd: '/workflow:test-cycle-execute', args: '' } ]) ], 'bugfix.standard': [ { cmd: '/workflow:lite-fix', args: `"${analysis.goal}"` }, ...(analysis.constraints?.includes('skip-tests') ? [] : [ { cmd: '/workflow:test-cycle-execute', args: '' } ]) ], 'bugfix.hotfix': [ { cmd: '/workflow:lite-fix', args: `--hotfix "${analysis.goal}"` } ], 'multi-cli-plan': [ { cmd: '/workflow:multi-cli-plan', args: `"${analysis.goal}"` }, { cmd: '/workflow:lite-execute', args: '--in-memory' }, ...(analysis.constraints?.includes('skip-tests') ? [] : [ { cmd: '/workflow:test-cycle-execute', args: '' } ]) ], 'docs': [ { cmd: '/workflow:lite-plan', args: `"${analysis.goal}"` }, { cmd: '/workflow:lite-execute', args: '--in-memory' } ], // Level 3 - Standard 'coupled': [ { cmd: '/workflow:plan', args: `"${analysis.goal}"` }, { cmd: '/workflow:plan-verify', args: '' }, { cmd: '/workflow:execute', args: '' }, { cmd: '/workflow:review-session-cycle', args: '' }, ...(analysis.constraints?.includes('skip-tests') ? [] : [ { cmd: '/workflow:test-cycle-execute', args: '' } ]) ], 'tdd': [ { cmd: '/workflow:tdd-plan', args: `"${analysis.goal}"` }, { cmd: '/workflow:execute', args: '' }, { cmd: '/workflow:tdd-verify', args: '' } ], 'test-fix-gen': [ { cmd: '/workflow:test-fix-gen', args: `"${analysis.goal}"` }, { cmd: '/workflow:test-cycle-execute', args: '' } ], 'review-fix': [ { cmd: '/workflow:review', args: '' }, { cmd: '/workflow:review-fix', args: '' }, { cmd: '/workflow:test-cycle-execute', args: '' } ], 'ui': [ { cmd: '/workflow:ui-design:explore-auto', args: `"${analysis.goal}"` }, { cmd: '/workflow:plan', args: '' }, { cmd: '/workflow:execute', args: '' } ], // Level 4 - Brainstorm 'full': [ { cmd: '/workflow:brainstorm:auto-parallel', args: `"${analysis.goal}"` }, { cmd: '/workflow:plan', args: '' }, { cmd: '/workflow:plan-verify', args: '' }, { cmd: '/workflow:execute', args: '' }, { cmd: '/workflow:test-cycle-execute', args: '' } ], // Issue Workflow 'issue': [ { cmd: '/issue:discover', args: '' }, { cmd: '/issue:plan', args: '--all-pending' }, { cmd: '/issue:queue', args: '' }, { cmd: '/issue:execute', args: '' } ] }; return chains[workflow.flow] || chains['rapid']; } ``` **Output**: `Level [X] - [flow] | Pipeline: [...] | Commands: [1. /cmd1 2. /cmd2 ...]` --- ### Phase 3: User Confirmation ```javascript async function getUserConfirmation(chain) { const response = await AskUserQuestion({ questions: [{ question: "Execute this command chain?", header: "Confirm", options: [ { label: "Confirm", description: "Start" }, { label: "Adjust", description: "Modify" }, { label: "Cancel", description: "Abort" } ] }] }); if (response.error === "Cancel") throw new Error("Cancelled"); if (response.error === "Adjust") return await adjustChain(chain); return chain; } ``` --- ### Phase 4: Setup TODO Tracking ```javascript function setupTodoTracking(chain, workflow) { const todos = chain.map((step, i) => ({ content: `CCW:${workflow}: [${i + 1}/${chain.length}] ${step.cmd}`, status: i === 0 ? 'in_progress' : 'pending', activeForm: `Executing ${step.cmd}` })); TodoWrite({ todos }); } ``` **Output**: `-> CCW:rapid: [1/3] /workflow:lite-plan | CCW:rapid: [2/3] /workflow:lite-execute | ...` --- ### Phase 5: Execute Command Chain ```javascript async function executeCommandChain(chain, workflow) { let previousResult = null; for (let i = 0; i < chain.length; i++) { try { const fullCommand = assembleCommand(chain[i], previousResult); const result = await SlashCommand({ command: fullCommand }); previousResult = { ...result, success: true }; updateTodoStatus(i, chain.length, workflow, 'completed'); } catch (error) { const action = await handleError(chain[i], error, i); if (action === 'retry') { i--; // Retry } else if (action === 'abort') { return { success: false, error: error.message }; } // 'skip' - continue } } return { success: true, completed: chain.length }; } // Assemble full command with session/plan parameters function assembleCommand(step, previousResult) { let command = step.cmd; if (step.args) { command += ` ${step.args}`; } else if (previousResult?.session_id) { command += ` --session="${previousResult.session_id}"`; } return command; } // Update TODO: mark current as complete, next as in-progress function updateTodoStatus(index, total, workflow, status) { const todos = getAllCurrentTodos(); const updated = todos.map(todo => { if (todo.content.startsWith(`CCW:${workflow}:`)) { const stepNum = extractStepIndex(todo.content); if (stepNum === index + 1) return { ...todo, status }; if (stepNum === index + 2 && status === 'completed') return { ...todo, status: 'in_progress' }; } return todo; }); TodoWrite({ todos: updated }); } // Error handling: Retry/Skip/Abort async function handleError(step, error, index) { const response = await AskUserQuestion({ questions: [{ question: `${step.cmd} failed: ${error.message}`, header: "Error", options: [ { label: "Retry", description: "Re-execute" }, { label: "Skip", description: "Continue next" }, { label: "Abort", description: "Stop" } ] }] }); return { Retry: 'retry', Skip: 'skip', Abort: 'abort' }[response.Error] || 'abort'; } ``` --- ## Execution Flow Summary ``` User Input | Phase 1: Analyze Intent |-- Extract: goal, scope, constraints, task_type, complexity, clarity +-- If clarity < 2 -> Phase 1.5: Clarify Requirements | Phase 2: Select Workflow & Build Chain |-- Map task_type -> Level (1/2/3/4/Issue) |-- Select flow based on complexity +-- Build command chain (port-based) | Phase 3: User Confirmation (optional) |-- Show pipeline visualization +-- Allow adjustment | Phase 4: Setup TODO Tracking +-- Create todos with CCW prefix | Phase 5: Execute Command Chain |-- For each command: | |-- Assemble full command | |-- Execute via SlashCommand | |-- Update TODO status | +-- Handle errors (retry/skip/abort) +-- Return workflow result ``` --- ## Pipeline Examples | Input | Type | Level | Commands | |-------|------|-------|----------| | "Add API endpoint" | feature (low) | 2 | lite-plan → lite-execute → test-cycle-execute | | "Fix login timeout" | bugfix | 2 | lite-fix → test-cycle-execute | | "OAuth2 system" | feature (high) | 3 | plan → plan-verify → execute → review-session-cycle → test-cycle-execute | | "Implement with TDD" | tdd | 3 | tdd-plan → execute → tdd-verify | | "Uncertain: real-time arch" | exploration | 4 | brainstorm:auto-parallel → plan → plan-verify → execute → test-cycle-execute | --- ## Key Design Principles 1. **Main Process Execution** - Use SlashCommand in main process, no external CLI 2. **Intent-Driven** - Auto-select workflow based on task intent 3. **Port-Based Chaining** - Build command chain using port matching 4. **Progressive Clarification** - Low clarity triggers clarification phase 5. **TODO Tracking** - Use CCW prefix to isolate workflow todos 6. **Error Resilient** - Support retry/skip/abort error handling 7. **User Control** - Optional user confirmation at each phase --- ## State Management **TodoWrite-Based Tracking**: All execution state tracked via TodoWrite with `CCW:` prefix. ```javascript // Initial state todos = [ { content: "CCW:rapid: [1/3] /workflow:lite-plan", status: "in_progress" }, { content: "CCW:rapid: [2/3] /workflow:lite-execute", status: "pending" }, { content: "CCW:rapid: [3/3] /workflow:test-cycle-execute", status: "pending" } ]; // After command 1 completes todos = [ { content: "CCW:rapid: [1/3] /workflow:lite-plan", status: "completed" }, { content: "CCW:rapid: [2/3] /workflow:lite-execute", status: "in_progress" }, { content: "CCW:rapid: [3/3] /workflow:test-cycle-execute", status: "pending" } ]; ``` **vs ccw-coordinator**: Extensive state.json with task_id, status transitions, hook callbacks. --- ## Type Comparison: ccw vs ccw-coordinator | Aspect | ccw | ccw-coordinator | |--------|-----|-----------------| | **Type** | Main process (SlashCommand) | External CLI (ccw cli + hook callbacks) | | **Execution** | Synchronous blocking | Async background with hook completion | | **Workflow** | Auto intent-based selection | Manual chain building | | **Intent Analysis** | 5-phase clarity check | 3-phase requirement analysis | | **State** | TodoWrite only (in-memory) | state.json + checkpoint/resume | | **Error Handling** | Retry/skip/abort (interactive) | Retry/skip/abort (via AskUser) | | **Use Case** | Auto workflow for any task | Manual orchestration, large chains | --- ## Usage ```bash # Auto-select workflow ccw "Add user authentication" # Complex requirement (triggers clarification) ccw "Optimize system performance" # Bug fix ccw "Fix memory leak in WebSocket handler" # TDD development ccw "Implement user registration with TDD" # Exploratory task ccw "Uncertain about architecture for real-time notifications" ```