From 7bcf7f24a3b59a460ab08fcf92bcbca664fd630a Mon Sep 17 00:00:00 2001 From: catlog22 Date: Mon, 17 Nov 2025 22:10:44 +0800 Subject: [PATCH] refactor(workflow): reorganize lite-plan and lite-execute docs for improved clarity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restructure lite-plan.md (844→668 lines, -176) and lite-execute.md (597→569 lines, -28) following agent document patterns. Move Data Structures sections to end as reference, simplify repeated content, improve hierarchical organization. All original content preserved. Key changes: - Data Structures moved to end (from beginning) - Simplified Execution Process to avoid duplication - Improved section hierarchy and flow - Consistent structure across both documents --- .claude/commands/workflow/lite-execute.md | 362 +++--- .claude/commands/workflow/lite-plan.md | 1262 +++++++++------------ 2 files changed, 710 insertions(+), 914 deletions(-) diff --git a/.claude/commands/workflow/lite-execute.md b/.claude/commands/workflow/lite-execute.md index ef1fdad7..a74dfe56 100644 --- a/.claude/commands/workflow/lite-execute.md +++ b/.claude/commands/workflow/lite-execute.md @@ -9,17 +9,15 @@ allowed-tools: TodoWrite(*), Task(*), Bash(*) ## Overview -Flexible task execution command supporting three input modes: in-memory plan (from lite-plan), direct prompt description, or file content (file input is equivalent to prompt). Handles execution orchestration, progress tracking, and optional code review. +Flexible task execution command supporting three input modes: in-memory plan (from lite-plan), direct prompt description, or file content. Handles execution orchestration, progress tracking, and optional code review. -## Core Functionality - -- **Multi-Mode Input**: Three ways to specify what to execute - - `--in-memory`: Use plan from memory (called by lite-plan) - - Prompt description: Direct task execution with simple planning - - File path: Read file content as prompt (equivalent to Mode 2) -- **Execution Orchestration**: Launch Agent or Codex with full context -- **Live Progress Tracking**: Real-time TodoWrite updates at execution call level -- **Optional Code Review**: Post-execution quality analysis with selected tool +**Core capabilities:** +- Multi-mode input (in-memory plan, prompt description, or file path) +- Execution orchestration (Agent or Codex) with full context +- Live progress tracking via TodoWrite at execution call level +- Optional code review with selected tool (Gemini, Agent, or custom) +- Context continuity across multiple executions +- Intelligent format detection (Enhanced Task JSON vs plain text) ## Usage @@ -31,79 +29,49 @@ Flexible task execution command supporting three input modes: in-memory plan (fr --in-memory Use plan from memory (called by lite-plan) # Arguments - Task description string, or path to file containing task description or Enhanced Task JSON (required) + Task description string, or path to file (required) ``` -## Data Structures - -### Input Data (from lite-plan) - -**executionContext** (Mode 1: --in-memory): -- Passed from lite-plan via global variable -- Contains: `planObject`, `explorationContext`, `clarificationContext`, `executionMethod`, `codeReviewTool`, `originalUserInput` - -**Enhanced Task JSON file parsing** (Mode 3: file input): -- **When detected**: File is valid JSON with `meta.workflow === "lite-plan"` (exported by lite-plan) -- **Extracted fields**: `planObject` (from `context.plan`), `explorationContext` (from `context.exploration`), `clarificationContext` (from `context.clarifications`), `originalUserInput` (from `title`) -- **Otherwise**: File content treated as plain text prompt - -### Output Data (produced by lite-execute) - -**executionResult**: -```javascript -{ - executionId: string, // e.g., "[Agent-1]", "[Codex-1]" - status: "completed" | "partial" | "failed", - tasksSummary: string, // Brief description of tasks handled - completionSummary: string, // What was completed - keyOutputs: string, // Files created/modified, key changes - notes: string // Any important context for next execution -} -``` - -Collected after each execution call completes and appended to `previousExecutionResults` array for context continuity in multi-execution scenarios. - ---- - ## Input Modes -#### Mode 1: In-Memory Plan +### Mode 1: In-Memory Plan -**Trigger**: Called by lite-plan after Phase 4 approval +**Trigger**: Called by lite-plan after Phase 4 approval with `--in-memory` flag **Input Source**: `executionContext` global variable set by lite-plan -**Expected Structure**: See [executionContext](#executioncontext) in Data Structures section +**Content**: Complete execution context (see Data Structures section) **Behavior**: -- Skip execution method selection (already set) +- Skip execution method selection (already set by lite-plan) - Directly proceed to execution with full context +- All planning artifacts available (exploration, clarifications, plan) -#### Mode 2: Prompt Description +### Mode 2: Prompt Description **Trigger**: User calls with task description string **Input**: Simple task description (e.g., "Add unit tests for auth module") **Behavior**: -- Store user's prompt as `originalUserInput` +- Store prompt as `originalUserInput` - Create simple execution plan from prompt -- Ask user to select execution method (Agent/Codex/Auto) -- Ask user about code review preference +- AskUserQuestion: Select execution method (Agent/Codex/Auto) +- AskUserQuestion: Select code review tool (Skip/Gemini/Agent/Other) - Proceed to execution with `originalUserInput` included -**AskUserQuestion Call**: +**User Interaction**: ```javascript AskUserQuestion({ questions: [ { - question: "Select execution method for this task:", + question: "Select execution method:", header: "Execution", multiSelect: false, options: [ - { label: "Agent", description: "Execute with @code-developer agent" }, - { label: "Codex", description: "Execute with codex CLI tool" }, - { label: "Auto", description: "Auto-select based on task complexity" } + { label: "Agent", description: "@code-developer agent" }, + { label: "Codex", description: "codex CLI tool" }, + { label: "Auto", description: "Auto-select based on complexity" } ] }, { @@ -111,34 +79,33 @@ AskUserQuestion({ header: "Code Review", multiSelect: false, options: [ - { label: "Skip", description: "No review needed" }, - { label: "Gemini Review", description: "Review with Gemini CLI tool" }, - { label: "Agent Review", description: "Review with current agent" } + { label: "Skip", description: "No review" }, + { label: "Gemini Review", description: "Gemini CLI tool" }, + { label: "Agent Review", description: "Current agent review" } ] } ] }) ``` -#### Mode 3: File Content +### Mode 3: File Content **Trigger**: User calls with file path -**Input**: Path to file containing task description, plan, or Enhanced Task JSON +**Input**: Path to file containing task description or Enhanced Task JSON -**Behavior**: +**Step 1: Read and Detect Format** -**Step 3.1: Read and Detect File Format** ```javascript fileContent = Read(filePath) -// Attempt to parse as JSON +// Attempt JSON parsing try { jsonData = JSON.parse(fileContent) - // Check if it's Enhanced Task JSON from lite-plan + // Check if Enhanced Task JSON from lite-plan if (jsonData.meta?.workflow === "lite-plan") { - // Extract plan data from Enhanced Task JSON + // Extract plan data planObject = { summary: jsonData.context.plan.summary, approach: jsonData.context.plan.approach, @@ -149,9 +116,8 @@ try { } explorationContext = jsonData.context.exploration || null clarificationContext = jsonData.context.clarifications || null - originalUserInput = jsonData.title // Original task description + originalUserInput = jsonData.title - // Set detected format flag isEnhancedTaskJson = true } else { // Valid JSON but not Enhanced Task JSON - treat as plain text @@ -165,7 +131,7 @@ try { } ``` -**Step 3.2: Create Execution Plan** +**Step 2: Create Execution Plan** If `isEnhancedTaskJson === true`: - Use extracted `planObject` directly @@ -173,41 +139,29 @@ If `isEnhancedTaskJson === true`: - User still selects execution method and code review If `isEnhancedTaskJson === false`: -- Create simple execution plan from file content (treated as prompt) -- Same behavior as Mode 2 +- Treat file content as prompt (same behavior as Mode 2) +- Create simple execution plan from content -**Step 3.3: User Interaction** -- Ask user to select execution method (Agent/Codex/Auto) -- Ask user about code review preference +**Step 3: User Interaction** + +- AskUserQuestion: Select execution method (Agent/Codex/Auto) +- AskUserQuestion: Select code review tool - Proceed to execution with full context -**Note**: -- Enhanced Task JSON format from lite-plan is automatically recognized and parsed -- Other file formats (plain text, markdown, etc.) are treated as prompts -- All extracted data stored in `originalUserInput` for execution reference - ## Execution Process ### Workflow Overview ``` -Input Processing +Input Processing → Mode Detection | v -[Mode Detection] - ├─ --in-memory → Load from executionContext variable - ├─ File path → Read and detect format - │ ├─ Enhanced Task JSON (lite-plan export) → Extract plan data - │ └─ Plain text/other → Use as prompt - └─ String → Use as prompt directly +[Mode 1] --in-memory: Load executionContext → Skip selection +[Mode 2] Prompt: Create plan → User selects method + review +[Mode 3] File: Detect format → Extract plan OR treat as prompt → User selects | v -[Execution Method Selection] - ├─ --in-memory: Already set (skip) - └─ Others (file/prompt): AskUserQuestion for method + review - | - v -[Execution & Progress Tracking] +Execution & Progress Tracking ├─ Step 1: Initialize execution tracking ├─ Step 2: Create TodoWrite execution list ├─ Step 3: Launch execution (Agent or Codex) @@ -224,7 +178,7 @@ Execution Complete **Operations**: - Initialize result tracking for multi-execution scenarios -- Set up previousExecutionResults array +- Set up `previousExecutionResults` array for context continuity ```javascript // Initialize result tracking @@ -236,15 +190,14 @@ previousExecutionResults = [] **Operations**: - Create execution tracking from task list - Typically single execution call for all tasks -- May split into multiple calls if task list is very large (>10 tasks) +- Split into multiple calls if task list very large (>10 tasks) +**Execution Call Creation**: ```javascript -// Function to create execution calls from structured task objects function createExecutionCalls(tasks) { - // For structured task objects, create summary from task titles - const taskTitles = tasks.map(t => t.title || t) // Support both old and new format + const taskTitles = tasks.map(t => t.title || t) - // Single execution call for all tasks (most common) + // Single call for ≤10 tasks (most common) if (tasks.length <= 10) { return [{ method: executionMethod === "Codex" ? "Codex" : "Agent", @@ -255,7 +208,7 @@ function createExecutionCalls(tasks) { }] } - // Split into multiple calls for large task sets (>10 tasks) + // Split into multiple calls for >10 tasks const callSize = 5 const calls = [] for (let i = 0; i < tasks.length; i += callSize) { @@ -263,20 +216,20 @@ function createExecutionCalls(tasks) { const batchTitles = batchTasks.map(t => t.title || t) calls.push({ method: executionMethod === "Codex" ? "Codex" : "Agent", - taskSummary: `Tasks ${i + 1}-${Math.min(i + callSize, tasks.length)}: ${batchTitles[0]}${batchTitles.length > 1 ? ', ...' : ''}`, + taskSummary: `Tasks ${i + 1}-${Math.min(i + callSize, tasks.length)}: ${batchTitles[0]}...`, tasks: batchTasks }) } return calls } -// Create execution calls (usually 1-2 calls total) +// Create execution calls with IDs executionCalls = createExecutionCalls(planObject.tasks).map((call, index) => ({ ...call, - id: `[${call.method}-${index+1}]` // Store ID for result collection + id: `[${call.method}-${index+1}]` })) -// Create TodoWrite execution list +// Create TodoWrite list TodoWrite({ todos: executionCalls.map(call => ({ content: `${call.id} (${call.taskSummary})`, @@ -286,20 +239,17 @@ TodoWrite({ }) ``` -**Example Execution List**: -``` -[ ] [Agent-1] (Create AuthService, Add JWT utilities, Implement auth middleware) +**Example Execution Lists**: ``` +Single call (typical): +[ ] [Agent-1] (Create AuthService, Add JWT utilities, Implement middleware) -Or for large task sets (>10 tasks): -``` -[ ] [Agent-1] (Tasks 1-5: Create AuthService, Add JWT utilities, ...) -[ ] [Agent-2] (Tasks 6-10: Create tests, Update documentation, ...) -``` - -Or when only a few tasks: -``` +Few tasks: [ ] [Codex-1] (Create AuthService, Add JWT utilities, and 3 more) + +Large task sets (>10): +[ ] [Agent-1] (Tasks 1-5: Create AuthService, Add JWT utilities, ...) +[ ] [Agent-2] (Tasks 6-10: Create tests, Update docs, ...) ``` ### Step 3: Launch Execution @@ -308,28 +258,24 @@ Or when only a few tasks: **Execution Loop**: ```javascript -// Execute each call in the execution list sequentially for (currentIndex = 0; currentIndex < executionCalls.length; currentIndex++) { const currentCall = executionCalls[currentIndex] - // Update TodoWrite: mark current call as in_progress + // Update TodoWrite: mark current call in_progress // Launch execution with previousExecutionResults context - // After completion, collect result and add to previousExecutionResults - // Update TodoWrite: mark current call as completed + // After completion: collect result, add to previousExecutionResults + // Update TodoWrite: mark current call completed } ``` -Based on execution method selection, launch appropriate execution: +**Option A: Agent Execution** -#### Option A: Agent Execution +When to use: +- `executionMethod = "Agent"` +- `executionMethod = "Auto" AND complexity = "Low"` -**When to use**: -- executionMethod = "Agent" -- executionMethod = "Auto" AND complexity = "Low" - -**Agent Call**: +Agent call format: ```javascript -// Format structured task objects for display function formatTaskForAgent(task, index) { return ` ### Task ${index + 1}: ${task.title} @@ -352,14 +298,13 @@ ${task.acceptance.map((criterion, i) => `${i + 1}. ${criterion}`).join('\n')} Task( subagent_type="code-developer", - description="Implement planned tasks with progress tracking", + description="Implement planned tasks", prompt=` ${originalUserInput ? `## Original User Request\n${originalUserInput}\n\n` : ''} ## Implementation Plan **Summary**: ${planObject.summary} - **Approach**: ${planObject.approach} ## Task Breakdown (${planObject.tasks.length} tasks) @@ -367,9 +312,9 @@ Task( ${previousExecutionResults.length > 0 ? `\n## Previous Execution Results\n${previousExecutionResults.map(result => ` [${result.executionId}] ${result.status} -Tasks handled: ${result.tasksSummary} -Completion status: ${result.completionSummary} -Key outputs: ${result.keyOutputs || 'See git diff for details'} +Tasks: ${result.tasksSummary} +Completion: ${result.completionSummary} +Outputs: ${result.keyOutputs || 'See git diff'} ${result.notes ? `Notes: ${result.notes}` : ''} `).join('\n---\n')}` : ''} @@ -379,28 +324,25 @@ ${result.notes ? `Notes: ${result.notes}` : ''} ${clarificationContext ? `\n## Clarifications\n${JSON.stringify(clarificationContext, null, 2)}` : ''} ## Instructions - - Reference the original user request above to ensure alignment with user intent - - Review previous execution results to understand what's already completed - - Build on previous work and avoid duplication - - Test functionality as you go - - Complete all tasks listed above + - Reference original request to ensure alignment + - Review previous results to understand completed work + - Build on previous work, avoid duplication + - Test functionality as you implement + - Complete all assigned tasks ` ) ``` -**Note**: `originalUserInput` is the user's original prompt (Mode 2), file content (Mode 3 plain text), or task title (Mode 3 Enhanced Task JSON). For Mode 1 (--in-memory), this may be null if not provided by lite-plan. +**Result Collection**: After completion, collect result following `executionResult` structure (see Data Structures section) -**Execution Result Collection**: After agent execution completes, collect result following [executionResult](#executionresult) structure in Data Structures section and append to `previousExecutionResults` array +**Option B: CLI Execution (Codex)** -#### Option B: CLI Execution (Codex) +When to use: +- `executionMethod = "Codex"` +- `executionMethod = "Auto" AND complexity = "Medium" or "High"` -**When to use**: -- executionMethod = "Codex" -- executionMethod = "Auto" AND complexity = "Medium" or "High" - -**Command Format**: +Command format: ```bash -# Format structured task objects for Codex function formatTaskForCodex(task, index) { return ` ${index + 1}. ${task.title} (${task.file}) @@ -421,7 +363,6 @@ ${originalUserInput ? `## Original User Request\n${originalUserInput}\n\n` : ''} ## Implementation Plan TASK: ${planObject.summary} - APPROACH: ${planObject.approach} ### Task Breakdown (${planObject.tasks.length} tasks) @@ -435,7 +376,7 @@ Outputs: ${result.keyOutputs || 'See git diff'} ${result.notes ? `Notes: ${result.notes}` : ''} `).join('\n---\n')} -IMPORTANT: Review previous results above. Build on completed work. Avoid duplication. +IMPORTANT: Review previous results. Build on completed work. Avoid duplication. ` : ''} ### Code Context from Exploration @@ -450,8 +391,8 @@ Constraints: ${explorationContext.constraints || 'None'} ${clarificationContext ? `\n### User Clarifications\n${Object.entries(clarificationContext).map(([q, a]) => `${q}: ${a}`).join('\n')}` : ''} ## Execution Instructions -- Reference the original user request above to ensure alignment with user intent -- Review previous execution results for context continuity +- Reference original request to ensure alignment +- Review previous results for context continuity - Build on previous work, don't duplicate completed tasks - Complete all assigned tasks in single execution - Test functionality as you implement @@ -460,9 +401,7 @@ Complexity: ${planObject.complexity} " --skip-git-repo-check -s danger-full-access ``` -**Note**: `originalUserInput` is the user's original prompt (Mode 2), file content (Mode 3 plain text), or task title (Mode 3 Enhanced Task JSON). For Mode 1 (--in-memory), this may be null if not provided by lite-plan. - -**Execution with Progress Tracking**: +**Execution with tracking**: ```javascript // Launch CLI in foreground (NOT background) bash_result = Bash( @@ -470,83 +409,76 @@ bash_result = Bash( timeout=600000 // 10 minutes ) -// Update TodoWrite when CLI execution call completes +// Update TodoWrite when execution completes ``` -**Execution Result Collection**: After CLI execution completes, analyze output and collect result following [executionResult](#executionresult) structure in Data Structures section +**Result Collection**: After completion, analyze output and collect result following `executionResult` structure ### Step 4: Track Execution Progress -**Real-time TodoWrite Updates**: - -Track at **execution call level** (not individual tasks): +**Real-time TodoWrite Updates** at execution call level: ```javascript -// When execution call starts +// When call starts TodoWrite({ todos: [ - { content: "[Agent-1] (Implement auth service + Create JWT utilities)", status: "in_progress", activeForm: "Executing [Agent-1] (Implement auth service + Create JWT utilities)" }, - { content: "[Agent-2] (Add middleware + Update routes)", status: "pending", activeForm: "Executing [Agent-2] (Add middleware + Update routes)" }, - { content: "[Codex-1] (Add integration tests)", status: "pending", activeForm: "Executing [Codex-1] (Add integration tests)" } + { content: "[Agent-1] (Implement auth + Create JWT utils)", status: "in_progress", activeForm: "..." }, + { content: "[Agent-2] (Add middleware + Update routes)", status: "pending", activeForm: "..." } ] }) -// When execution call completes +// When call completes TodoWrite({ todos: [ - { content: "[Agent-1] (Implement auth service + Create JWT utilities)", status: "completed", activeForm: "Executing [Agent-1] (Implement auth service + Create JWT utilities)" }, - { content: "[Agent-2] (Add middleware + Update routes)", status: "in_progress", activeForm: "Executing [Agent-2] (Add middleware + Update routes)" }, - { content: "[Codex-1] (Add integration tests)", status: "pending", activeForm: "Executing [Codex-1] (Add integration tests)" } + { content: "[Agent-1] (Implement auth + Create JWT utils)", status: "completed", activeForm: "..." }, + { content: "[Agent-2] (Add middleware + Update routes)", status: "in_progress", activeForm: "..." } ] }) ``` **User Visibility**: -- User sees **execution call progress** (not individual task progress) +- User sees execution call progress (not individual task progress) - Current execution highlighted as "in_progress" - Completed executions marked with checkmark -- Pending executions remain unchecked -- Each execution shows **task summary** for context +- Each execution shows task summary for context ### Step 5: Code Review (Optional) -**Skip Condition**: Only run if codeReviewTool ≠ "Skip" +**Skip Condition**: Only run if `codeReviewTool ≠ "Skip"` **Operations**: -- If "Agent Review": Current agent performs direct code review analysis -- If "Gemini Review": Execute gemini CLI with code review analysis prompt -- If custom tool (via "Other"): Execute specified CLI tool (e.g., qwen, codex) -- Review all modified files from execution -- Generate quality assessment and improvement recommendations +- Agent Review: Current agent performs direct review +- Gemini Review: Execute gemini CLI with review prompt +- Custom tool: Execute specified CLI tool (qwen, codex, etc.) -**Command Format**: +**Command Formats**: ```bash -# Agent Review: Direct agent review (no CLI command needed) +# Agent Review: Direct agent review (no CLI) # Uses analysis prompt and TodoWrite tools directly # Gemini Review: gemini -p " PURPOSE: Code review for implemented changes -TASK: • Analyze code quality • Identify potential issues • Suggest improvements +TASK: • Analyze quality • Identify issues • Suggest improvements MODE: analysis -CONTEXT: @**/* | Memory: Review changes from lite-execute execution -EXPECTED: Quality assessment with actionable recommendations +CONTEXT: @**/* | Memory: Review lite-execute changes +EXPECTED: Quality assessment with recommendations RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-review-code-quality.txt) | Focus on recent changes | analysis=READ-ONLY " # Qwen Review (custom tool via "Other"): qwen -p " PURPOSE: Code review for implemented changes -TASK: • Analyze code quality • Identify potential issues • Suggest improvements +TASK: • Analyze quality • Identify issues • Suggest improvements MODE: analysis -CONTEXT: @**/* | Memory: Review changes from lite-execute execution -EXPECTED: Quality assessment with actionable recommendations +CONTEXT: @**/* | Memory: Review lite-execute changes +EXPECTED: Quality assessment with recommendations RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-review-code-quality.txt) | Focus on recent changes | analysis=READ-ONLY " # Codex Review (custom tool via "Other"): -codex --full-auto exec "Review the recent code changes for quality, potential issues, and improvements" --skip-git-repo-check -s danger-full-access +codex --full-auto exec "Review recent code changes for quality, potential issues, and improvements" --skip-git-repo-check -s danger-full-access ``` ## Best Practices @@ -563,12 +495,12 @@ codex --full-auto exec "Review the recent code changes for quality, potential is - Clear visibility of current execution - Simple progress updates -3. **Flexible Execution**: Supports multiple input modes - - In-memory: Seamless integration with lite-plan +3. **Flexible Execution**: Multiple input modes supported + - In-memory: Seamless lite-plan integration - Prompt: Quick standalone execution - File: Intelligent format detection - - Enhanced Task JSON (lite-plan export): Extracts full plan context - - Plain text: Uses as prompt for execution + - Enhanced Task JSON (lite-plan export): Full plan extraction + - Plain text: Uses as prompt ### Task Management @@ -578,19 +510,59 @@ codex --full-auto exec "Review the recent code changes for quality, potential is - Clear completion status 2. **Simple Execution**: Straightforward task handling - - All tasks in single execution call (typical) - - Split only for very large task sets (>10 tasks) + - All tasks in single call (typical) + - Split only for very large task sets (>10) - Agent/Codex determines optimal execution order ## Error Handling | Error | Cause | Resolution | |-------|-------|------------| -| Missing executionContext | --in-memory called without context | Display error: "No execution context found. This mode is only available when called by lite-plan." | -| File not found | File path doesn't exist | Display error: "File not found: {path}. Please check the file path." | -| Empty file | File exists but has no content | Display error: "File is empty: {path}. Please provide task description." | -| Invalid Enhanced Task JSON | JSON parsing succeeds but missing required fields | Display warning: "File appears to be Enhanced Task JSON but missing required fields. Treating as plain text prompt." | -| Malformed JSON | JSON parsing fails | Treat as plain text prompt, no error displayed (expected behavior for non-JSON files) | -| Execution failure | Agent/Codex crashes or errors | Display error details, save partial progress, suggest retry | -| Codex unavailable | Codex tool not installed | Show installation instructions, offer Agent execution | +| Missing executionContext | --in-memory without context | Error: "No execution context found. Only available when called by lite-plan." | +| File not found | File path doesn't exist | Error: "File not found: {path}. Check file path." | +| Empty file | File exists but no content | Error: "File is empty: {path}. Provide task description." | +| Invalid Enhanced Task JSON | JSON missing required fields | Warning: "Missing required fields. Treating as plain text." | +| Malformed JSON | JSON parsing fails | Treat as plain text (expected for non-JSON files) | +| Execution failure | Agent/Codex crashes | Display error, save partial progress, suggest retry | +| Codex unavailable | Codex not installed | Show installation instructions, offer Agent execution | +## Data Structures + +### executionContext (Input - Mode 1) + +Passed from lite-plan via global variable: + +```javascript +{ + planObject: { + summary: string, + approach: string, + tasks: [...], + estimated_time: string, + recommended_execution: string, + complexity: string + }, + explorationContext: {...} | null, + clarificationContext: {...} | null, + executionMethod: "Agent" | "Codex" | "Auto", + codeReviewTool: "Skip" | "Gemini Review" | "Agent Review" | string, + originalUserInput: string +} +``` + +### executionResult (Output) + +Collected after each execution call completes: + +```javascript +{ + executionId: string, // e.g., "[Agent-1]", "[Codex-1]" + status: "completed" | "partial" | "failed", + tasksSummary: string, // Brief description of tasks handled + completionSummary: string, // What was completed + keyOutputs: string, // Files created/modified, key changes + notes: string // Important context for next execution +} +``` + +Appended to `previousExecutionResults` array for context continuity in multi-execution scenarios. diff --git a/.claude/commands/workflow/lite-plan.md b/.claude/commands/workflow/lite-plan.md index 5893e4e8..cc02babd 100644 --- a/.claude/commands/workflow/lite-plan.md +++ b/.claude/commands/workflow/lite-plan.md @@ -11,17 +11,13 @@ allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*) Intelligent lightweight planning command with dynamic workflow adaptation based on task complexity. Focuses on planning phases (exploration, clarification, planning, confirmation) and delegates execution to `/workflow:lite-execute`. -## Core Functionality - -- **Intelligent Task Analysis**: Automatically determines if exploration/planning agents are needed -- **Dynamic Exploration**: Calls cli-explore-agent only when task requires codebase understanding -- **Interactive Clarification**: Asks follow-up questions after exploration to gather missing information -- **Adaptive Planning**: - - Simple tasks: Direct planning by current Claude - - Complex tasks: Delegates to cli-lite-planning-agent for detailed breakdown -- **Two-Step Confirmation**: First display complete plan as text, then collect three-dimensional input (task approval + execution method + code review tool) -- **Execution Dispatch**: Stores execution context in memory and calls `/workflow:lite-execute --in-memory` for actual implementation - +**Core capabilities:** +- Intelligent task analysis with automatic exploration detection +- Dynamic code exploration (cli-explore-agent) when codebase understanding needed +- Interactive clarification after exploration to gather missing information +- Adaptive planning strategy (direct Claude vs cli-lite-planning-agent) based on complexity +- Two-step confirmation: plan display → multi-dimensional input collection +- Execution dispatch with complete context handoff to lite-execute ## Usage @@ -30,17 +26,532 @@ Intelligent lightweight planning command with dynamic workflow adaptation based /workflow:lite-plan [FLAGS] # Flags --e, --explore Force code exploration phase (overrides auto-detection logic) +-e, --explore Force code exploration phase (overrides auto-detection) # Arguments Task description or path to .md file (required) ``` +### Input Requirements +- **Task description**: String or path to .md file (required) + - Should be specific and concrete + - Can include context about existing code or requirements + - Examples: + - "Implement user authentication with JWT tokens" + - "Refactor logging module for better performance" + - "Add unit tests for authentication service" +- **Flags** (optional): + - `-e` or `--explore`: Force exploration when: + - Task appears simple but requires codebase context + - Auto-detection might miss integration points + - Comprehensive code understanding needed before planning + +## Execution Process + +### Workflow Overview + +``` +User Input → Task Analysis & Exploration Decision (Phase 1) + ↓ + Clarification (Phase 2, optional) + ↓ + Complexity Assessment & Planning (Phase 3) + ↓ + Task Confirmation & Execution Selection (Phase 4) + ↓ + Dispatch to Execution (Phase 5) + ↓ + Planning Complete (lite-execute continues) +``` + +### Phase Summary + +**Phase 1: Task Analysis & Exploration Decision** (10-60 seconds) +- Analyze task to determine exploration needs +- Decision logic: `--explore` flag OR requires codebase context +- If needed: Launch cli-explore-agent for code analysis +- Output: `explorationContext` with relevant files, patterns, constraints + +**Phase 2: Clarification** (30-60 seconds, optional) +- Skip if no ambiguities found in Phase 1 +- Use exploration findings to generate targeted questions +- AskUserQuestion based on `clarification_needs` from exploration +- Output: `clarificationContext` with user responses + +**Phase 3: Complexity Assessment & Planning** (20-60 seconds) +- Assess complexity (Low/Medium/High) from multiple factors +- Strategy selection: + - Low: Direct planning by current Claude (fast, 20-30s) + - Medium/High: Delegate to cli-lite-planning-agent (detailed, 40-60s) +- Output: `planObject` with tasks, time estimates, recommendations + +**Phase 4: Task Confirmation & Execution Selection** (user interaction) +- Step 1: Display complete plan as text to user +- Step 2: Collect four inputs via AskUserQuestion: + 1. Confirm plan (Allow/Modify/Cancel + supplements via "Other") + 2. Execution method (Agent/Codex/Auto) + 3. Code review tool (Skip/Gemini/Agent + custom via "Other") + 4. Export JSON (Yes/No for Enhanced Task JSON export) + +**Phase 5: Dispatch to Execution** (<1 second) +- Export Enhanced Task JSON (optional, if user selected "Yes") +- Store `executionContext` in memory with full plan + context +- Call `/workflow:lite-execute --in-memory` +- Execution tracking delegated to lite-execute + +## Detailed Phase Execution + +### Phase 1: Task Analysis & Exploration Decision + +**Decision Logic**: +```javascript +needsExploration = ( + flags.includes('--explore') || flags.includes('-e') || // Force if flag present + ( + task.mentions_specific_files || + task.requires_codebase_context || + task.needs_architecture_understanding || + task.modifies_existing_code + ) +) +``` + +**Decision Criteria**: + +| Task Type | Needs Exploration | Reason | +|-----------|-------------------|--------| +| Any task with `-e`/`--explore` flag | **Yes (forced)** | **Flag overrides auto-detection** | +| "Implement new feature X" | Maybe | Depends on integration needs | +| "Refactor module Y" | Yes | Needs current implementation understanding | +| "Add tests for Z" | Yes | Needs code structure understanding | +| "Create standalone utility" | No | Self-contained, no existing context | +| "Update documentation" | No | Doesn't require code exploration | +| "Fix bug in function F" | Yes | Needs implementation understanding | + +**Exploration Execution** (if needed): +```javascript +Task( + subagent_type="cli-explore-agent", + description="Analyze codebase for task context", + prompt=` + Task: ${task_description} + + Analyze and return structured information: + 1. Project Structure: Architecture and module organization + 2. Relevant Files: Files to be affected (with paths) + 3. Current Patterns: Code patterns, conventions, styles + 4. Dependencies: External/internal module dependencies + 5. Integration Points: Task connections with existing code + 6. Architecture Constraints: Technical limitations/requirements + 7. Clarification Needs: Ambiguities requiring user input + + Time Limit: 60 seconds + Output Format: JSON-like structured object + ` +) +``` + +**Output**: `explorationContext` (see Data Structures section) + +**Progress Tracking**: +- Mark Phase 1 completed +- If `clarification_needs.length > 0`: Mark Phase 2 in_progress +- Else: Skip to Phase 3 + +--- + +### Phase 2: Clarification (Optional) + +**Skip Condition**: Only run if `needsClarification = true` from Phase 1 + +**Operations**: +- Review `explorationContext.clarification_needs` +- Generate AskUserQuestion from exploration findings +- Focus on ambiguities affecting implementation approach + +**Question Generation**: +```javascript +AskUserQuestion({ + questions: explorationContext.clarification_needs.map(need => ({ + question: `${need.context}\n\n${need.question}`, + header: "Clarification", + multiSelect: false, + options: need.options.map(opt => ({ + label: opt, + description: `Use ${opt} approach` + })) + })) +}) +``` + +**Output**: `clarificationContext` in format `{ question_id: selected_answer }` + +**Progress Tracking**: +- Mark Phase 2 completed +- Mark Phase 3 in_progress + +--- + +### Phase 3: Complexity Assessment & Planning + +**Complexity Assessment**: +```javascript +complexityScore = { + file_count: exploration.files_to_modify.length, + integration_points: exploration.dependencies.length, + architecture_changes: exploration.requires_architecture_change, + technology_stack: exploration.unfamiliar_technologies.length, + task_scope: (task.estimated_steps > 5), + cross_cutting_concerns: exploration.affects_multiple_modules +} + +// Calculate complexity +if (complexityScore < 3) complexity = "Low" +else if (complexityScore < 6) complexity = "Medium" +else complexity = "High" +``` + +**Complexity Levels**: + +| Level | Characteristics | Planning Strategy | +|-------|----------------|-------------------| +| Low | 1-2 files, simple changes, clear requirements | Direct planning (current Claude) | +| Medium | 3-5 files, moderate integration, some ambiguity | cli-lite-planning-agent | +| High | 6+ files, complex architecture, high uncertainty | cli-lite-planning-agent with detailed analysis | + +**Option A: Direct Planning (Low Complexity)** + +Current Claude generates plan directly: +- Summary: 2-3 sentence overview +- Approach: High-level implementation strategy +- Task Breakdown: 3-5 specific, actionable tasks with file paths +- Estimated Time: Total implementation time +- Recommended Execution: "Agent" + +**Option B: Agent-Based Planning (Medium/High Complexity)** + +Delegate to cli-lite-planning-agent: +```javascript +Task( + subagent_type="cli-lite-planning-agent", + description="Generate detailed implementation plan", + prompt=` + ## Task Description + ${task_description} + + ## Exploration Context + ${JSON.stringify(explorationContext, null, 2) || "No exploration performed"} + + ## User Clarifications + ${JSON.stringify(clarificationContext, null, 2) || "None provided"} + + ## Complexity Level + ${complexity} + + ## Your Task + 1. Execute CLI planning using Gemini (Qwen fallback) + 2. Parse CLI output and extract structured plan + 3. Enhance tasks with file paths and pattern references + 4. Generate planObject with: + - Summary (2-3 sentences) + - Approach (high-level strategy) + - Tasks (3-10 actionable steps) + - Estimated time (with breakdown) + - Recommended execution (Agent for Low, Codex for Medium/High) + 5. Return planObject (no file writes) + + ## Quality Requirements + Each task MUST include: + - Action verb (Create/Update/Add/Implement/Refactor) + - Specific file path + - Detailed changes + - Pattern reference from exploration + + Format: "{Action} in {file_path}: {details} following {pattern}" + ` +) +``` + +**Output**: `planObject` (see Data Structures section) + +**Progress Tracking**: +- Mark Phase 3 completed +- Mark Phase 4 in_progress + +**Expected Duration**: +- Low: 20-30 seconds (direct) +- Medium/High: 40-60 seconds (agent-based) + +--- + +### Phase 4: Task Confirmation & Execution Selection + +**Two-Step Confirmation Process** + +**Step 4.1: Display Plan Summary** + +Output complete plan as regular text: + +``` +## Implementation Plan + +**Summary**: ${planObject.summary} + +**Approach**: ${planObject.approach} + +**Task Breakdown** (${planObject.tasks.length} tasks): +${planObject.tasks.map((task, i) => ` +${i+1}. **${task.title}** (${task.file}) + - What: ${task.description} + - How: ${task.implementation.length} steps + - Reference: ${task.reference.pattern} + - Verification: ${task.acceptance.length} criteria +`).join('')} + +**Complexity**: ${planObject.complexity} +**Estimated Time**: ${planObject.estimated_time} +**Recommended Execution**: ${planObject.recommended_execution} +``` + +**Step 4.2: Collect User Confirmation** + +Four questions via single AskUserQuestion call: + +```javascript +AskUserQuestion({ + questions: [ + { + question: `**Plan Summary**: ${planObject.summary} + +**Tasks**: ${planObject.tasks.length} | **Complexity**: ${planObject.complexity} | **Time**: ${planObject.estimated_time} + +Confirm plan? (Multi-select: can supplement via "Other")`, + header: "Confirm Plan", + multiSelect: true, + options: [ + { label: "Allow", description: "Proceed as-is" }, + { label: "Modify", description: "Adjust before execution" }, + { label: "Cancel", description: "Abort workflow" } + ] + }, + { + question: "Select execution method:", + header: "Execution", + multiSelect: false, + options: [ + { label: "Agent", description: "@code-developer agent" }, + { label: "Codex", description: "codex CLI tool" }, + { label: "Auto", description: `Auto: ${planObject.complexity === 'Low' ? 'Agent' : 'Codex'}` } + ] + }, + { + question: "Enable code review after execution?\n\n(Custom tools via \"Other\": qwen, codex, etc.)", + header: "Code Review", + multiSelect: false, + options: [ + { label: "Gemini Review", description: "Gemini CLI (gemini-2.5-pro)" }, + { label: "Agent Review", description: "@code-reviewer agent" }, + { label: "Skip", description: "No review" } + ] + }, + { + question: "Export plan to Enhanced Task JSON file?\n\nAllows reuse with lite-execute later.", + header: "Export JSON", + multiSelect: false, + options: [ + { label: "Yes", description: "Export to JSON (recommended for complex tasks)" }, + { label: "No", description: "Keep in-memory only" } + ] + } + ] +}) +``` + +**Decision Flow**: +``` +Task Confirmation (Multi-select): + ├─ Allow (+ supplements) → Execution Method Selection + ├─ Modify (+ supplements) → Re-run Phase 3 + └─ Cancel → Exit + +Execution Method (Single-select): + ├─ Agent → Launch @code-developer + ├─ Codex → Execute with codex CLI + └─ Auto → Low complexity: Agent | Medium/High: Codex + +Code Review (after execution): + ├─ Skip → No review + ├─ Gemini Review → gemini CLI analysis + ├─ Agent Review → Current Claude review + └─ Other → Custom tool (e.g., qwen, codex) + +Export JSON: + ├─ Yes → Export to .workflow/lite-plans/plan-{timestamp}.json + └─ No → In-memory only +``` + +**Progress Tracking**: +- Mark Phase 4 completed +- Mark Phase 5 in_progress + +--- + +### Phase 5: Dispatch to Execution + +**Step 5.1: Export Enhanced Task JSON (Optional)** + +Only execute if `userSelection.export_task_json === "Yes"`: + +```javascript +if (userSelection.export_task_json === "Yes") { + const timestamp = new Date().toISOString().replace(/[:.]/g, '-') + const taskId = `LP-${timestamp}` + const filename = `.workflow/lite-plans/${taskId}.json` + + const enhancedTaskJson = { + id: taskId, + title: original_task_description, + status: "pending", + + meta: { + type: "planning", + created_at: new Date().toISOString(), + complexity: planObject.complexity, + estimated_time: planObject.estimated_time, + recommended_execution: planObject.recommended_execution, + workflow: "lite-plan" + }, + + context: { + requirements: [original_task_description], + plan: { + summary: planObject.summary, + approach: planObject.approach, + tasks: planObject.tasks + }, + exploration: explorationContext || null, + clarifications: clarificationContext || null, + focus_paths: explorationContext?.relevant_files || [], + acceptance: planObject.tasks.flatMap(t => t.acceptance) + } + } + + Write(filename, JSON.stringify(enhancedTaskJson, null, 2)) + console.log(`Enhanced Task JSON exported to: ${filename}`) + console.log(`Reuse with: /workflow:lite-execute ${filename}`) +} +``` + +**Step 5.2: Store Execution Context** + +```javascript +executionContext = { + planObject: planObject, + explorationContext: explorationContext || null, + clarificationContext: clarificationContext || null, + executionMethod: userSelection.execution_method, + codeReviewTool: userSelection.code_review_tool, + originalUserInput: original_task_description +} +``` + +**Step 5.3: Call lite-execute** + +```javascript +SlashCommand(command="/workflow:lite-execute --in-memory") +``` + +**Execution Handoff**: +- lite-execute reads `executionContext` variable +- All execution logic handled by lite-execute +- lite-plan completes after successful handoff + +**Progress Tracking**: +- Mark Phase 5 completed +- Execution tracking delegated to lite-execute + +## Best Practices + +### Workflow Intelligence + +1. **Dynamic Adaptation**: Workflow adjusts based on task characteristics + - Smart exploration: Only when codebase context needed + - Adaptive planning: Simple → direct, complex → specialized agent + - Context-aware clarification: Only when truly needed + - Reduces unnecessary steps while maintaining thoroughness + +2. **Flag-Based Control**: Use `-e`/`--explore` to force exploration when: + - Task appears simple but requires codebase context + - Auto-detection might miss subtle integration points + - Comprehensive code understanding needed + +3. **Progressive Clarification**: Information gathered at right time + - Phase 1: Explore codebase (current state) + - Phase 2: Ask questions (based on findings) + - Phase 3: Plan with complete context + - Avoids premature assumptions, reduces rework + +4. **Complexity-Aware Planning**: Strategy matches task complexity + - Low (1-2 files): Direct planning (fast, 20-30s) + - Medium (3-5 files): CLI planning (detailed, 40-50s) + - High (6+ files): CLI planning with risk analysis (thorough, 50-60s) + +5. **Two-Step Confirmation**: Clear separation between plan and control + - Step 1: Display plan as readable text (not in question) + - Step 2: Collect multi-dimensional input + - Plan confirmation (multi-select with supplements) + - Execution method selection + - Code review tool selection (custom via "Other") + - JSON export option + - Allows plan refinement without re-selecting execution method + +### Task Management + +1. **Phase-Based Organization**: 5 distinct phases with clear transitions + - Phase 1: Analysis & Exploration (automatic) + - Phase 2: Clarification (conditional, interactive) + - Phase 3: Planning (automatic, adaptive) + - Phase 4: Confirmation (interactive, multi-dimensional) + - Phase 5: Execution Dispatch (automatic) + +2. **Flexible Task Counts**: Adapts to complexity + - Low: 3-5 tasks (focused) + - Medium: 5-7 tasks (detailed) + - High: 7-10 tasks (comprehensive) + +3. **No File Artifacts During Planning**: + - All planning stays in memory + - Optional Enhanced Task JSON export (user choice) + - Faster workflow, cleaner workspace + - Plan context passed directly to execution + +### Planning Standards + +1. **Context-Rich Planning**: Plans include all relevant context + - Exploration findings (structure, patterns, constraints) + - User clarifications (requirements, preferences, decisions) + - Complexity assessment (risks, dependencies, estimates) + - Execution recommendations (Direct vs CLI, specific tool) + +2. **Modification Support**: Iterative refinement + - User can request modifications in Phase 4 + - Feedback incorporated into re-planning + - No restart from scratch + - Collaborative planning workflow + +## Error Handling + +| Error | Cause | Resolution | +|-------|-------|------------| +| Phase 1 Exploration Failure | cli-explore-agent unavailable/timeout | Skip exploration, set `explorationContext = null`, continue with task description only | +| Phase 2 Clarification Timeout | User no response > 5 minutes | Use exploration findings as-is, proceed to Phase 3 with warning | +| Phase 3 Planning Agent Failure | cli-lite-planning-agent unavailable/timeout | Fallback to direct planning by current Claude | +| Phase 3 Planning Timeout | Planning > 90 seconds | Generate simplified plan, mark as "Quick Plan", continue | +| Phase 4 Confirmation Timeout | User no response > 5 minutes | Save context to temp var, display resume instructions, exit gracefully | +| Phase 4 Modification Loop | User requests modify > 3 times | Suggest breaking task into smaller pieces or using `/workflow:plan` | ## Data Structures -All workflow phases use these standardized data structures: - ### explorationContext Exploration findings from cli-explore-agent (Phase 1): @@ -73,20 +584,20 @@ Implementation plan from Phase 3: approach: string, // High-level implementation strategy tasks: [ // 3-10 structured task objects { - title: string, // Task title (e.g., "Create AuthService") + title: string, // Task title file: string, // Target file path - action: string, // Action type: Create|Update|Implement|Refactor|Add|Delete + action: string, // Create|Update|Implement|Refactor|Add|Delete description: string, // What to implement (1-2 sentences) - implementation: string[], // Step-by-step how to do it (3-7 steps) + implementation: string[], // Step-by-step how-to (3-7 steps) reference: { // What to reference - pattern: string, // Pattern name (e.g., "UserService pattern") + pattern: string, // Pattern name files: string[], // Reference file paths - examples: string // Specific guidance on what to copy/follow + examples: string // Specific guidance }, acceptance: string[] // Verification criteria (2-4 items) } ], - estimated_time: string, // Total implementation time estimate + estimated_time: string, // Total implementation time recommended_execution: string, // "Agent" (Low) or "Codex" (Medium/High) complexity: string // "Low" | "Medium" | "High" } @@ -98,29 +609,15 @@ Context passed to lite-execute via --in-memory (Phase 5): ```javascript { - planObject: { // Complete planObject structure (see above) + planObject: { // Complete planObject (see above) summary: string, approach: string, - tasks: [ // Array of structured task objects (7 fields each) - { - title: string, - file: string, - action: string, - description: string, - implementation: string[], - reference: { - pattern: string, - files: string[], - examples: string - }, - acceptance: string[] - } - ], + tasks: [...], estimated_time: string, recommended_execution: string, complexity: string }, - explorationContext: {...} | null, // See explorationContext structure above + explorationContext: {...} | null, // See explorationContext above clarificationContext: {...} | null, // User responses from Phase 2 executionMethod: "Agent" | "Codex" | "Auto", codeReviewTool: "Skip" | "Gemini Review" | "Agent Review" | string, @@ -130,7 +627,7 @@ Context passed to lite-execute via --in-memory (Phase 5): ### Enhanced Task JSON Export -When user selects "Export JSON", lite-plan exports an enhanced structure aligned with Enhanced Task JSON Schema: +When user selects "Export JSON", lite-plan exports this structure: ```json { @@ -151,693 +648,20 @@ When user selects "Export JSON", lite-plan exports an enhanced structure aligned "requirements": ["Original task description"], "plan": { "summary": "2-3 sentence overview", - "approach": "High-level implementation strategy", - "tasks": [ - { - "title": "Task 1 title", - "file": "src/path/to/file.ts", - "action": "Create|Update|Implement|...", - "description": "What to implement", - "implementation": ["Step 1", "Step 2", "..."], - "reference": { - "pattern": "Pattern name", - "files": ["ref/file1.ts", "ref/file2.ts"], - "examples": "Specific guidance" - }, - "acceptance": ["Criterion 1", "Criterion 2", "..."] - } - ] + "approach": "High-level strategy", + "tasks": [/* Array of task objects */] }, - "exploration": { - "project_structure": "...", - "relevant_files": ["file1.ts", "file2.ts"], - "patterns": "...", - "dependencies": "...", - "integration_points": "...", - "constraints": "..." - } | null, - "clarifications": { - "question1": "answer1", - "question2": "answer2" - } | null, + "exploration": {/* explorationContext */} | null, + "clarifications": {/* clarificationContext */} | null, "focus_paths": ["src/auth", "tests/auth"], - "acceptance": ["Task completion criteria from plan.tasks"] + "acceptance": ["Criteria from plan.tasks"] } } ``` -**Schema Alignment Notes**: +**Schema Notes**: - Aligns with Enhanced Task JSON Schema (6-field structure) -- `context_package_path` omitted (lite-plan doesn't use context packages) -- `flow_control` omitted (execution handled by lite-execute) +- `context_package_path` omitted (not used by lite-plan) +- `flow_control` omitted (handled by lite-execute) - `focus_paths` derived from `exploration.relevant_files` - `acceptance` derived from `plan.tasks` - ---- - -## Execution Process - -### Workflow Overview - -``` -User Input ("/workflow:lite-plan \"task\"") - | - v -[Phase 1] Task Analysis & Exploration Decision (10-20 seconds) - -> Analyze task description - -> Decision: Need exploration? (Yes/No) - -> If Yes: Launch cli-explore-agent - -> Output: explorationContext (if performed) - | - v -[Phase 2] Clarification (Optional, user interaction) - -> If exploration revealed ambiguities or missing info - -> AskUserQuestion: Gather clarifications - -> Update task context with user responses - -> If no clarification needed: Skip to Phase 3 - | - v -[Phase 3] Complexity Assessment & Planning (20-60 seconds) - -> Assess task complexity (Low/Medium/High) - -> Decision: Planning strategy - - Low: Direct planning (current Claude) - - Medium/High: Delegate to cli-lite-planning-agent - -> Output: planObject - | - v -[Phase 4] Task Confirmation & Execution Selection (User interaction) - -> Step 4.1: Output complete plan as text to user - -> Step 4.2: AskUserQuestion with four dimensions - 1. Confirm task: Allow/Modify/Cancel (multi-select, can supplement via Other) - 2. Execution method: Agent/Codex/Auto (single-select, auto: simple→agent, complex→codex) - 3. Code review: Skip/Gemini/Agent/Other (single-select, can specify custom tool via Other) - 4. Export JSON: Yes/No (single-select, export enhanced task JSON) - -> Process selections and proceed to Phase 5 - -> If cancel: Exit - | - v -[Phase 5] Dispatch to Execution - -> Export enhanced task JSON (optional, if user selected "Yes") - -> Store executionContext in memory - -> Call /workflow:lite-execute --in-memory - -> Execution delegated to lite-execute command - | - v -Planning Complete (Execution continues in lite-execute) -``` - -### Task Management Pattern - -- lite-plan focuses on planning phases (1-4) with TodoWrite tracking -- Phase 5 stores execution context and dispatches to lite-execute -- Execution tracking (TodoWrite updates, progress monitoring) handled by lite-execute -- Optional enhanced task JSON export aligned with Enhanced Task JSON Schema -- Execution artifacts (code changes, test results) managed by lite-execute - -## Detailed Phase Execution - -### Phase 1: Task Analysis & Exploration Decision - -**Operations**: -- Analyze task description to determine if code exploration is needed -- Decision logic: - ```javascript - needsExploration = ( - flags.includes('--explore') || flags.includes('-e') || // Force exploration if flag present - ( - task.mentions_specific_files || - task.requires_codebase_context || - task.needs_architecture_understanding || - task.modifies_existing_code - ) - ) - ``` - -**Decision Criteria**: - -| Task Type | Needs Exploration | Reason | -|-----------|-------------------|--------| -| Any task with `-e` or `--explore` flag | **Yes (forced)** | **Flag overrides auto-detection logic** | -| "Implement new feature X" | Maybe | Depends on integration with existing code | -| "Refactor module Y" | Yes | Needs understanding of current implementation | -| "Add tests for Z" | Yes | Needs to understand code structure | -| "Create new standalone utility" | No | Self-contained, no existing code context | -| "Update documentation" | No | Doesn't require code exploration | -| "Fix bug in function F" | Yes | Needs to understand implementation | - -**If Exploration Needed**: -- Launch cli-explore-agent with task-specific focus -- Agent call format: - ```javascript - Task( - subagent_type="cli-explore-agent", - description="Analyze codebase for task context", - prompt=` - Task: ${task_description} - - Analyze and return the following information in structured format: - 1. Project Structure: Overall architecture and module organization - 2. Relevant Files: List of files that will be affected by this task (with paths) - 3. Current Implementation Patterns: Existing code patterns, conventions, and styles - 4. Dependencies: External dependencies and internal module dependencies - 5. Integration Points: Where this task connects with existing code - 6. Architecture Constraints: Technical limitations or requirements - 7. Clarification Needs: Ambiguities or missing information requiring user input - - Time Limit: 60 seconds - - Output Format: Return a JSON-like structured object with the above fields populated. - Include specific file paths, pattern examples, and clear questions for clarifications. - ` - ) - ``` - -**Expected Return Structure**: See [explorationContext](#explorationcontext) in Data Structures section - -**Output Processing**: -- Store exploration findings in `explorationContext` -- Extract `clarification_needs` array from exploration results -- Set `needsClarification = (clarification_needs.length > 0)` -- Use clarification_needs to generate Phase 2 questions - -**Progress Tracking**: -- Mark Phase 1 as completed -- If needsClarification: Mark Phase 2 as in_progress -- Else: Skip to Phase 3 - -**Expected Duration**: 10-20 seconds (analysis) + 30-60 seconds (exploration if needed) - ---- - -### Phase 2: Clarification (Optional) - -**Skip Condition**: Only run if Phase 1 set `needsClarification = true` - -**Operations**: -- Review `explorationContext.clarification_needs` from Phase 1 -- Generate AskUserQuestion based on exploration findings -- Focus on ambiguities that affect implementation approach - -**AskUserQuestion Call** (simplified reference): -```javascript -// Use clarification_needs from exploration to build questions -AskUserQuestion({ - questions: explorationContext.clarification_needs.map(need => ({ - question: `${need.context}\n\n${need.question}`, - header: "Clarification", - multiSelect: false, - options: need.options.map(opt => ({ - label: opt, - description: `Use ${opt} approach` - })) - })) -}) -``` - -**Output Processing**: -- Collect user responses and store in `clarificationContext` -- Format: `{ question_id: selected_answer, ... }` -- This context will be passed to Phase 3 planning - -**Progress Tracking**: -- Mark Phase 2 as completed -- Mark Phase 3 as in_progress - -**Expected Duration**: User-dependent (typically 30-60 seconds) - ---- - -### Phase 3: Complexity Assessment & Planning - -**Operations**: -- Assess task complexity based on multiple factors -- Select appropriate planning strategy -- Generate task breakdown using selected method - -**Complexity Assessment Factors**: -```javascript -complexityScore = { - file_count: exploration.files_to_modify.length, - integration_points: exploration.dependencies.length, - architecture_changes: exploration.requires_architecture_change, - technology_stack: exploration.unfamiliar_technologies.length, - task_scope: (task.estimated_steps > 5), - cross_cutting_concerns: exploration.affects_multiple_modules -} - -// Calculate complexity -if (complexityScore < 3) complexity = "Low" -else if (complexityScore < 6) complexity = "Medium" -else complexity = "High" -``` - -**Complexity Levels**: - -| Level | Characteristics | Planning Strategy | -|-------|----------------|-------------------| -| Low | 1-2 files, simple changes, clear requirements | Direct planning (current Claude) | -| Medium | 3-5 files, moderate integration, some ambiguity | Delegate to cli-lite-planning-agent | -| High | 6+ files, complex architecture, high uncertainty | Delegate to cli-lite-planning-agent with detailed analysis | - -**Planning Execution**: - -**Option A: Direct Planning (Low Complexity)** - -Current Claude generates plan directly following these guidelines: -- **Summary**: 2-3 sentence overview of the implementation -- **Approach**: High-level implementation strategy -- **Task Breakdown**: 3-5 specific, actionable tasks with file paths -- **Estimated Time**: Total implementation time estimate -- **Recommended Execution**: "Agent" (for Low complexity tasks) - -**Option B: Agent-Based Planning (Medium/High Complexity)** - -Delegate to cli-lite-planning-agent with detailed requirements: -```javascript -Task( - subagent_type="cli-lite-planning-agent", - description="Generate detailed implementation plan", - prompt=` - ## Task Description - ${task_description} - - ## Exploration Context - ${JSON.stringify(explorationContext, null, 2) || "No exploration performed"} - - ## User Clarifications - ${JSON.stringify(clarificationContext, null, 2) || "None provided"} - - ## Complexity Level - ${complexity} - - ## Your Task - 1. Execute CLI planning analysis using Gemini (Qwen as fallback) - 2. Parse CLI output and extract structured plan - 3. Enhance tasks to be actionable with file paths and pattern references - 4. Generate planObject with: - - Summary (2-3 sentences) - - Approach (high-level strategy) - - Tasks (3-10 actionable steps with file paths) - - Estimated time (with breakdown if available) - - Recommended execution method (Agent for Low, Codex for Medium/High) - 5. Return planObject (no file writes) - - ## Quality Requirements - Each task MUST include: - - Action verb (Create, Update, Add, Implement, Refactor) - - Specific file path - - Detailed changes - - Pattern reference from exploration context - - Format: "{Action} in {file_path}: {specific_details} following {pattern}" - ` -) -``` - -**Expected Return Structure (Both Options)**: See [planObject](#planobject) in Data Structures section - -**Progress Tracking**: -- Mark Phase 3 as completed -- Mark Phase 4 as in_progress - -**Expected Duration**: -- Low complexity: 20-30 seconds (direct) -- Medium/High complexity: 40-60 seconds (agent-based) - ---- - -### Phase 4: Task Confirmation & Execution Selection - -**User Interaction Flow**: Two-step confirmation process - -**Step 4.1: Display Plan Summary** - -First, output the complete plan to the user as regular text: - -``` -## Implementation Plan - -**Summary**: ${planObject.summary} - -**Approach**: ${planObject.approach} - -**Task Breakdown** (${planObject.tasks.length} tasks): -${planObject.tasks.map((task, i) => ` -${i+1}. **${task.title}** (${task.file}) - - What: ${task.description} - - How: ${task.implementation.length} steps - - Reference: ${task.reference.pattern} - - Verification: ${task.acceptance.length} criteria -`).join('')} - -**Complexity**: ${planObject.complexity} -**Estimated Time**: ${planObject.estimated_time} -**Recommended Execution**: ${planObject.recommended_execution} -``` - -**Step 4.2: Collect User Confirmation** - -After displaying the plan, collect four inputs via AskUserQuestion: - -**Operations**: -- Collect four inputs: - 1. Task confirmation (multi-select: Allow/Modify/Cancel + optional supplements via "Other") - 2. Execution method (single-select: Agent/Codex/Auto) - - Agent: Execute with @code-developer - - Codex: Execute with codex CLI tool - - Auto: Simple tasks (Low complexity) → Agent, Complex tasks (Medium/High) → Codex - 3. Code review tool (single-select: Skip/Gemini/Agent + custom tools via "Other") - - Gemini Review: Use gemini CLI for code analysis - - Agent Review: Use @code-reviewer agent - - Other: Specify custom tool (e.g., "qwen", "codex") via text input - 4. Task JSON output (single-select: Yes/No) - - Yes: Export plan to task JSON file for reuse or documentation - - No: Keep plan in-memory only -- Support plan supplements and custom tool specification via "Other" input - -**Four Questions in Single AskUserQuestion Call**: -- Question 1: Task confirmation (multi-select: Allow/Modify/Cancel) -- Question 2: Execution method selection (single-select: Agent/Codex/Auto) -- Question 3: Code review tool selection (single-select: Skip/Gemini/Agent, custom via "Other") -- Question 4: Task JSON output (single-select: Yes/No) - -**AskUserQuestion Call**: -```javascript -AskUserQuestion({ - questions: [ - { - question: `**Plan Summary**: ${planObject.summary} - -**Tasks**: ${planObject.tasks.length} tasks | **Complexity**: ${planObject.complexity} | **Estimated Time**: ${planObject.estimated_time} - -Confirm this plan? (Multi-select enabled - you can select multiple options and add supplements via "Other")`, - header: "Confirm Plan", - multiSelect: true, - options: [ - { label: "Allow", description: "Proceed with plan as-is" }, - { label: "Modify", description: "Adjust plan before execution" }, - { label: "Cancel", description: "Abort workflow" } - ] - }, - { - question: `Select execution method:`, - header: "Execution", - multiSelect: false, - options: [ - { label: "Agent", description: "Execute with @code-developer agent" }, - { label: "Codex", description: "Execute with codex CLI tool" }, - { label: "Auto", description: `Auto-select: ${planObject.complexity === 'Low' ? 'Agent (Low complexity)' : 'Codex (Medium/High complexity)'}` } - ] - }, - { - question: `Enable code review after execution? - -(You can specify other tools like "qwen" or "codex" via "Other" option)`, - header: "Code Review", - multiSelect: false, - options: [ - { label: "Gemini Review", description: "Review with Gemini CLI tool (gemini-2.5-pro)" }, - { label: "Agent Review", description: "Review with @code-reviewer agent" }, - { label: "Skip", description: "No review needed" } - ] - }, - { - question: `Export plan to task JSON file? - -This allows you to reuse the plan or use it with lite-execute later.`, - header: "Export JSON", - multiSelect: false, - options: [ - { label: "Yes", description: "Export plan to JSON file (recommended for complex tasks)" }, - { label: "No", description: "Keep plan in-memory only" } - ] - } - ] -}) -``` - -**Decision Flow**: -``` -Task Confirmation (Multi-select): - ├─ Allow (+ optional supplements in Other) → Proceed to Execution Method Selection - ├─ Modify (+ optional supplements in Other) → Re-run Phase 3 with modifications - └─ Cancel → Exit (no execution) - -Execution Method Selection (Single-select): - ├─ Agent → Launch @code-developer agent - ├─ Codex → Execute with codex CLI tool - └─ Auto → Automatic selection: - ├─ If complexity = Low → Launch @code-developer agent - └─ If complexity = Medium/High → Execute with codex CLI tool - -Code Review Selection (after execution): - ├─ Skip → Skip review, workflow complete - ├─ Gemini Review → Run gemini code analysis (gemini-2.5-pro) - ├─ Agent Review → Current Claude agent review - └─ Other → Specify custom tool (e.g., "qwen", "codex") via text input - -Task JSON Export: - ├─ Yes → Export plan to JSON file before execution - │ Format: .workflow/lite-plans/plan-{timestamp}.json - │ Contains: planObject + explorationContext + clarificationContext - └─ No → Keep plan in-memory only, no file export -``` - -**Progress Tracking**: -- Mark Phase 4 as completed -- Mark Phase 5 as in_progress - -**Expected Duration**: User-dependent (1-3 minutes typical) - ---- - -### Phase 5: Dispatch to Execution - -**Operations**: -- Export plan to task JSON file (if user selected "Yes") -- Store execution context in memory variable -- Call lite-execute command with --in-memory flag -- Execution tracking delegated to lite-execute - -**Step 5.1: Export Task JSON (Optional)** - -**Skip Condition**: Only run if user selected "Yes" for Task JSON Export in Phase 4 - -**Operations**: -- Create `.workflow/lite-plans/` directory if not exists -- Generate timestamp-based filename -- Export enhanced task JSON aligned with Enhanced Task JSON Schema - -```javascript -// Only execute if userSelection.export_task_json === "Yes" -if (userSelection.export_task_json === "Yes") { - const timestamp = new Date().toISOString().replace(/[:.]/g, '-') - const taskId = `LP-${timestamp}` - const filename = `.workflow/lite-plans/${taskId}.json` - - const enhancedTaskJson = { - id: taskId, - title: original_task_description, - status: "pending", - - meta: { - type: "planning", - created_at: new Date().toISOString(), - complexity: planObject.complexity, - estimated_time: planObject.estimated_time, - recommended_execution: planObject.recommended_execution, - workflow: "lite-plan" - }, - - context: { - requirements: [original_task_description], - plan: { - summary: planObject.summary, - approach: planObject.approach, - tasks: planObject.tasks // Array of structured task objects - }, - exploration: explorationContext || null, - clarifications: clarificationContext || null, - focus_paths: explorationContext?.relevant_files || [], - acceptance: planObject.tasks.flatMap(t => t.acceptance) // Collect all acceptance criteria from tasks - } - } - - Write(filename, JSON.stringify(enhancedTaskJson, null, 2)) - - // Display export confirmation to user - console.log(`Enhanced task JSON exported to: ${filename}`) - console.log(`You can reuse this plan with: /workflow:lite-execute ${filename}`) -} -``` - -**Export File Format**: See [Enhanced Task JSON Export](#enhanced-task-json-export) in Data Structures section - -**Step 5.2: Store Execution Context** - -Create execution context variable with all necessary information: - -```javascript -// Create execution context for lite-execute -executionContext = { - planObject: planObject, // From Phase 3 - explorationContext: explorationContext || null, // From Phase 1 - clarificationContext: clarificationContext || null, // From Phase 2 - executionMethod: userSelection.execution_method, // From Phase 4 - codeReviewTool: userSelection.code_review_tool, // From Phase 4 - originalUserInput: original_task_description // Original user input -} -``` - -**Context Structure**: See [executionContext](#executioncontext) in Data Structures section - -**Step 5.3: Call lite-execute** - -Dispatch execution to lite-execute command: -```javascript -SlashCommand(command="/workflow:lite-execute --in-memory") -``` - -**Execution Handoff**: -- lite-execute reads executionContext variable -- All execution logic (TodoWrite tracking, Agent/Codex calls, code review) handled by lite-execute -- lite-plan completes after successful handoff - -**Progress Tracking**: -- Mark Phase 5 as completed -- Execution tracking handed over to lite-execute -- User sees execution progress from lite-execute TodoWrite updates - -**Expected Duration**: < 1 second (dispatch only, actual execution in lite-execute) - ---- - -## Best Practices - -### Workflow Intelligence - -1. **Dynamic Adaptation**: Workflow automatically adjusts based on task characteristics - - Smart exploration: Only runs when task requires codebase context - - Adaptive planning: Simple tasks get direct planning, complex tasks use specialized agent - - Context-aware clarification: Only asks questions when truly needed - - Reduces unnecessary steps while maintaining thoroughness - - **Flag-Based Control**: - - Use `-e` or `--explore` to force exploration when: - - Task appears simple but you know it requires codebase context - - Auto-detection might miss subtle integration points - - You want comprehensive code understanding before planning - -2. **Progressive Clarification**: Gather information at the right time - - Phase 1: Explore codebase to understand current state - - Phase 2: Ask clarifying questions based on exploration findings - - Phase 3: Plan with complete context (task + exploration + clarifications) - - Avoids premature assumptions and reduces rework - -3. **Complexity-Aware Planning**: Planning strategy matches task complexity - - Low complexity (1-2 files): Direct planning by current Claude (fast, 20-30s) - - Medium complexity (3-5 files): CLI planning agent (detailed, 40-50s) - - High complexity (6+ files): CLI planning agent with risk analysis (thorough, 50-60s) - - Balances speed and thoroughness appropriately - -4. **Two-Step Confirmation Process**: Clear plan presentation followed by comprehensive control - - **Step 1**: Display complete plan as readable text output (not embedded in question) - - Shows summary, approach, tasks, dependencies, risks, complexity, time estimate - - Clear separation between plan content and user interaction - - **Step 2**: Collect three-dimensional input via AskUserQuestion - - First dimension: Confirm/Modify/Cancel plan (multi-select with supplement via "Other") - - Second dimension: Execution method selection (Agent/Codex/Auto) - - Third dimension: Code review tool selection (Skip/Gemini/Agent, custom via "Other") - - Allows plan refinement without re-selecting execution method - - Supports iterative planning with user feedback - - Auto mode intelligently selects execution method based on complexity - - Custom code review tools (qwen, codex, etc.) can be specified via "Other" option - -### Task Management - -1. **Live Progress Tracking**: TodoWrite provides real-time execution call visibility - - Execution calls ([Agent-1], [Codex-1], etc.) created before execution starts - - Updated in real-time as execution calls progress - - User sees current execution call being worked on (e.g., "[Agent-1] (Task A + Task B)") - - Each execution call shows task summary for context - - Clear completion status at call level (not individual task level) - -2. **Phase-Based Organization**: 5 distinct phases with clear transitions - - Phase 1: Task Analysis & Exploration (automatic) - - Phase 2: Clarification (conditional, interactive) - - Phase 3: Planning (automatic, adaptive) - - Phase 4: Confirmation (interactive, two-dimensional) - - Phase 5: Execution & Tracking (automatic with live updates) - -3. **Flexible Task Counts**: Task breakdown adapts to complexity - - Low complexity: 3-5 tasks (focused) - - Medium complexity: 5-7 tasks (detailed) - - High complexity: 7-10 tasks (comprehensive) - - Avoids artificial constraints while maintaining focus - -4. **Dependency Tracking**: Medium/High complexity tasks include dependencies - - Explicit task ordering when sequence matters - - Parallel execution hints when tasks are independent - - Risk flagging for complex interactions - - Helps agent/CLI execute correctly - -### Planning Standards - -1. **Context-Rich Planning**: Plans include all relevant context - - Exploration findings (code structure, patterns, constraints) - - User clarifications (requirements, preferences, decisions) - - Complexity assessment (risks, dependencies, time estimates) - - Execution recommendations (Direct vs CLI, specific tool) - -2. **Modification Support**: Plans can be iteratively refined - - User can request plan modifications in Phase 4 - - Feedback incorporated into re-planning - - No need to restart from scratch - - Supports collaborative planning workflow - -3. **No File Artifacts**: All planning stays in memory - - Faster workflow without I/O overhead - - Cleaner workspace - - Plan context passed directly to execution - - Reduces complexity and maintenance - -## Error Handling - -### Common Errors - -| Error | Cause | Resolution | -|-------|-------|------------| -| Phase 1 Exploration Failure | cli-explore-agent unavailable or timeout | Skip exploration, set `explorationContext = null`, log warning, continue to Phase 2/3 with task description only | -| Phase 2 Clarification Timeout | User no response > 5 minutes | Use exploration findings as-is without clarification, proceed to Phase 3 with warning | -| Phase 3 Planning Agent Failure | cli-lite-planning-agent unavailable or timeout | Fallback to direct planning by current Claude (simplified plan), continue to Phase 4 | -| Phase 3 Planning Timeout | Planning takes > 90 seconds | Generate simplified direct plan, mark as "Quick Plan", continue to Phase 4 with reduced detail | -| Phase 4 Confirmation Timeout | User no response > 5 minutes | Save plan context to temporary var, display resume instructions, exit gracefully | -| Phase 4 Modification Loop | User requests modify > 3 times | Suggest breaking task into smaller pieces or using /workflow:plan for comprehensive planning | - -## Input/Output - -### Input Requirements -- Task description: String or path to .md file (required) - - Should be specific and concrete - - Can include context about existing code or requirements - - Examples: - - "Implement user authentication with JWT tokens" - - "Refactor logging module for better performance" - - "Add unit tests for authentication service" -- Flags (optional): - - `-e` or `--explore`: Force code exploration phase (overrides auto-detection) - -### Output Format - -**In-Memory Plan Object**: See [planObject](#planobject) in Data Structures section - -**Optional Enhanced Task JSON Export**: See [Enhanced Task JSON Export](#enhanced-task-json-export) in Data Structures section (when user selects "Export JSON") - -**Execution Context**: See [executionContext](#executioncontext) in Data Structures section (passed to lite-execute) - -**Execution Result**: -- Immediate dispatch to lite-execute with executionContext -- Optional enhanced task JSON file export aligned with Enhanced Task JSON Schema -- No other file artifacts generated during planning phase -- Execution starts immediately in lite-execute after context handoff -- Tool/agent handles implementation and any necessary file operations -