diff --git a/.codex/skills/workflow-lite-plan-execute/SKILL.md b/.codex/skills/workflow-lite-plan-execute/SKILL.md index 7c2b3ffd..af8d0774 100644 --- a/.codex/skills/workflow-lite-plan-execute/SKILL.md +++ b/.codex/skills/workflow-lite-plan-execute/SKILL.md @@ -1,19 +1,20 @@ --- name: workflow-lite-plan-execute -description: Lightweight planning + execution workflow. Exploration -> Clarification -> Planning -> Confirmation -> Execution (via lite-execute). -allowed-tools: spawn_agent, wait, send_input, close_agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context +description: Lightweight planning + execution workflow. Serial CLI exploration → Search verification → Clarification → Planning → Unified JSONL output → Execution via unified-execute. +allowed-tools: AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context --- # Planning Workflow -Lite Plan produces an implementation plan and an `executionContext`, then hands off to Lite Execute for task execution. +Lite Plan produces a unified JSONL (`tasks.jsonl`) implementation plan via serial CLI exploration and direct planning, then hands off to unified-execute-with-file for task execution. ## Key Design Principles -1. **Shared Execution**: Lite Plan produces `executionContext` consumed by Phase 2 (Lite Execute) -2. **Progressive Phase Loading**: Only load phase docs when about to execute -3. **Auto-Continue**: After the plan is confirmed ("Allow"), automatically load execution phase -4. **Default Auto Mode**: When `--yes`, skip confirmations and auto-approve the plan +1. **Serial Execution**: All phases execute serially inline, no agent delegation +2. **CLI Exploration**: Multi-angle codebase exploration via `ccw cli` calls (default gemini, fallback claude) +3. **Search Verification**: Verify CLI findings with ACE search / Grep / Glob before incorporating +4. **Unified JSONL Output**: Produces `tasks.jsonl` compatible with `collaborative-plan-with-file` and `unified-execute-with-file` +5. **Progressive Phase Loading**: Only load phase docs when about to execute ## Auto Mode @@ -42,14 +43,14 @@ $workflow-lite-plan-execute -e "Refactor payment module" $workflow-lite-plan-execute "docs/todo.md" ``` -> **Implementation sketch**: 编排器内部使用 `Skill(skill="workflow-lite-plan-execute", args="...")` 接口调用,此为伪代码示意,非命令行语法。 +> **Implementation sketch**: 编排器内部使用 `$workflow-lite-plan-execute "..."` 接口调用,此为伪代码示意,非命令行语法。 ## Phase Reference Documents (Read On Demand) | Phase | Document | Purpose | |-------|----------|---------| -| 1 | `phases/01-lite-plan.md` | Lightweight planning with exploration, clarification, plan generation, and confirmation | -| 2 | `phases/02-lite-execute.md` | Shared execution engine: task grouping, batch execution, optional code review | +| 1 | `phases/01-lite-plan.md` | Serial CLI exploration, clarification, plan generation → tasks.jsonl | +| 2 | `phases/02-lite-execute.md` | Handoff to unified-execute-with-file for task execution | ## Orchestrator Logic @@ -71,47 +72,76 @@ function extractTaskDescription(args) { const taskDescription = extractTaskDescription($ARGUMENTS) -// Phase 1: Lite Plan +// Phase 1: Lite Plan → tasks.jsonl Read('phases/01-lite-plan.md') // Execute planning phase... // Gate: only continue when confirmed (or --yes) -if (executionContext?.userSelection?.confirmation !== 'Allow' && !autoYes) { +if (planResult?.userSelection?.confirmation !== 'Allow' && !autoYes) { // Stop: user cancelled or requested modifications return } -// Phase 2: Lite Execute +// Phase 2: Handoff to unified-execute-with-file Read('phases/02-lite-execute.md') -// Execute execution phase with executionContext from Phase 1 +// Invoke unified-execute-with-file with tasks.jsonl path ``` -## executionContext Contract (High Level) +## Output Contract -`executionContext` is the only contract between Phase 1 and Phase 2. +Phase 1 produces `tasks.jsonl` (unified JSONL format) — compatible with `collaborative-plan-with-file` and consumable by `unified-execute-with-file`. + +**Output Directory**: `{projectRoot}/.workflow/.lite-plan/{session-id}/` + +``` +{projectRoot}/.workflow/.lite-plan/{session-id}/ +├── exploration-{angle1}.md # Per-angle CLI exploration results +├── exploration-{angle2}.md # (1-4 files based on complexity) +├── explorations-manifest.json # Exploration index +├── exploration-notes.md # Synthesized exploration notes +├── requirement-analysis.json # Complexity assessment +├── tasks.jsonl # ⭐ Unified JSONL (collaborative-plan-with-file compatible) +└── plan.md # Human-readable summary +``` + +**Unified JSONL Task Format** (one task per line): -Required (minimum) fields: ```javascript { - projectRoot: string, // 项目根目录绝对路径 (git rev-parse --show-toplevel || pwd) - planObject: { summary, approach, tasks, complexity, estimated_time, recommended_execution }, - originalUserInput: string, - executionMethod: "Agent" | "Codex" | "Auto", - codeReviewTool: "Skip" | "Gemini Review" | "Codex Review" | "Agent Review" | string, - userSelection: { confirmation: "Allow" | "Modify" | "Cancel" } + id: "TASK-001", + title: string, + description: string, + type: "feature|fix|refactor|enhancement|testing|infrastructure", + priority: "high|medium|low", + effort: "small|medium|large", + scope: string, + depends_on: ["TASK-xxx"], + convergence: { + criteria: string[], // Testable conditions + verification: string, // Executable command or manual steps + definition_of_done: string // Business language + }, + files: [{ + path: string, + action: "modify|create|delete", + changes: string[], + conflict_risk: "low|medium|high" + }], + source: { + tool: "workflow-lite-plan-execute", + session_id: string, + original_id: string + } } ``` -Recommended fields: -- `explorationsContext`, `clarificationContext`, `executorAssignments`, and `session` (artifacts folder + paths) - ## TodoWrite Pattern Initialization: ```json [ {"content": "Lite Plan - Planning", "status": "in_progress", "activeForm": "Planning"}, - {"content": "Execution (Phase 2)", "status": "pending", "activeForm": "Executing tasks"} + {"content": "Execution (unified-execute)", "status": "pending", "activeForm": "Executing tasks"} ] ``` @@ -119,28 +149,30 @@ After planning completes: ```json [ {"content": "Lite Plan - Planning", "status": "completed", "activeForm": "Planning"}, - {"content": "Execution (Phase 2)", "status": "in_progress", "activeForm": "Executing tasks"} + {"content": "Execution (unified-execute)", "status": "in_progress", "activeForm": "Executing tasks"} ] ``` ## Core Rules -1. **Planning phase NEVER modifies project code** - it may write planning artifacts, but all implementation is delegated to Phase 2 -2. **Phase 2 runs only after confirmation** - execute only when confirmation is "Allow" (or `--yes` auto mode) -3. **executionContext is the contract** between planning and execution phases -4. **Progressive loading**: Read phase doc only when about to execute -5. **File-path detection**: Treat input as a file path only if the path exists; do not infer from file extensions -6. **Explicit lifecycle**: Always `close_agent` after `wait` completes +1. **Planning phase NEVER modifies project code** — it may write planning artifacts, but all implementation is delegated to unified-execute +2. **All phases serial, no agent delegation** — everything runs inline, no spawn_agent +3. **CLI exploration with search verification** — CLI calls produce findings, ACE/Grep/Glob verify them +4. **tasks.jsonl is the output contract** — unified JSONL format passed to unified-execute-with-file +5. **Progressive loading**: Read phase doc only when about to execute +6. **File-path detection**: Treat input as a file path only if the path exists; do not infer from file extensions ## Error Handling | Error | Resolution | |-------|------------| +| CLI exploration failure | Skip angle, continue with remaining; fallback gemini → claude | | Planning phase failure | Display error, offer retry | -| executionContext missing | Error: planning phase did not produce context | +| tasks.jsonl missing | Error: planning phase did not produce output | | Phase file not found | Error with file path for debugging | ## Related Skills +- Collaborative planning: `../collaborative-plan-with-file/SKILL.md` +- Unified execution: `../unified-execute-with-file/SKILL.md` - Full planning workflow: `../workflow-plan-execute/SKILL.md` -- Brainstorming: `../workflow-brainstorm-auto-parallel/SKILL.md` diff --git a/.codex/skills/workflow-lite-plan-execute/phases/01-lite-plan.md b/.codex/skills/workflow-lite-plan-execute/phases/01-lite-plan.md index 6fa18bc2..0dadca65 100644 --- a/.codex/skills/workflow-lite-plan-execute/phases/01-lite-plan.md +++ b/.codex/skills/workflow-lite-plan-execute/phases/01-lite-plan.md @@ -2,15 +2,15 @@ ## Overview -Intelligent lightweight planning command with dynamic workflow adaptation based on task complexity. Focuses on planning phases (exploration, clarification, planning, confirmation) and delegates execution to Phase 2: Lite Execute (phases/02-lite-execute.md). +Serial lightweight planning with CLI-powered exploration and search verification. Produces unified JSONL (`tasks.jsonl`) compatible with `collaborative-plan-with-file` output format, consumable by `unified-execute-with-file`. **Core capabilities:** - Intelligent task analysis with automatic exploration detection -- Dynamic code exploration (cli-explore-agent) when codebase understanding needed +- Serial CLI exploration (ccw cli, default gemini / fallback claude) per angle +- Search verification after each CLI exploration (ACE search, Grep, Glob) - Interactive clarification after exploration to gather missing information -- Adaptive planning: Low complexity → Direct Claude; Medium/High → cli-lite-planning-agent -- Two-step confirmation: plan display → multi-dimensional input collection -- Execution handoff with complete context to lite-execute +- Direct planning by Claude (all complexity levels, no agent delegation) +- Unified JSONL output (`tasks.jsonl`) with convergence criteria ## Parameters @@ -24,28 +24,20 @@ Intelligent lightweight planning command with dynamic workflow adaptation based | Artifact | Description | |----------|-------------| -| `exploration-{angle}.json` | Per-angle exploration results (1-4 files based on complexity) | +| `exploration-{angle}.md` | Per-angle CLI exploration results (verified) | | `explorations-manifest.json` | Index of all exploration files | -| `exploration-notes.md` | Full exploration log (consumed by Plan phase, 6 sections) | -| `exploration-notes-refined.md` | Refined exploration log (consumed by Execute phase, task-relevant only) | -| `planning-context.md` | Evidence paths + synthesized understanding | -| `plan.json` | Structured implementation plan (plan-json-schema.json) | +| `exploration-notes.md` | Synthesized exploration notes (all angles combined) | +| `requirement-analysis.json` | Complexity assessment and session metadata | +| `tasks.jsonl` | ⭐ Unified JSONL (collaborative-plan-with-file compatible) | +| `plan.md` | Human-readable summary with execution command | -**Output Directory**: `{projectRoot}/.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/` - -**Agent Usage**: -- Low complexity → Direct Claude planning (no agent) -- Medium/High complexity → `cli-lite-planning-agent` generates `plan.json` - -**Schema Reference**: `~/.ccw/workflows/cli-templates/schemas/plan-json-schema.json` +**Output Directory**: `{projectRoot}/.workflow/.lite-plan/{session-id}/` ## Auto Mode Defaults When `--yes` or `-y` flag is used: - **Clarification Questions**: Skipped (no clarification phase) - **Plan Confirmation**: Auto-selected "Allow" -- **Execution Method**: Auto-selected "Auto" -- **Code Review**: Auto-selected "Skip" **Flag Parsing**: ```javascript @@ -60,38 +52,33 @@ Phase 1: Task Analysis & Exploration ├─ Parse input (description or .md file) ├─ Intelligent complexity assessment (Low/Medium/High) ├─ Exploration decision (auto-detect or --explore flag) - ├─ Context protection: If file reading ≥50k chars → force cli-explore-agent └─ Decision: - ├─ needsExploration=true → Launch parallel cli-explore-agents (1-4 based on complexity) + ├─ needsExploration=true → Serial CLI exploration (1-4 angles) + │ └─ For each angle: CLI call → Search verification → Save results └─ needsExploration=false → Skip to Phase 2/3 Phase 2: Clarification (optional, multi-round) - ├─ Aggregate clarification_needs from all exploration angles + ├─ Extract clarification needs from exploration results ├─ Deduplicate similar questions - └─ Decision: - ├─ Has clarifications → ASK_USER (max 4 questions per round, multiple rounds allowed) - └─ No clarifications → Skip to Phase 3 + └─ ASK_USER (max 4 questions per round, multiple rounds) -Phase 3: Planning (NO CODE EXECUTION - planning only) - └─ Decision (based on Phase 1 complexity): - ├─ Low → Load schema: cat ~/.ccw/workflows/cli-templates/schemas/plan-json-schema.json → Direct Claude planning (following schema) → plan.json - └─ Medium/High → cli-lite-planning-agent → plan.json (agent internally executes quality check) +Phase 3: Planning → tasks.jsonl (NO CODE EXECUTION) + ├─ Load exploration notes + clarifications + project context + ├─ Direct Claude planning (following unified JSONL schema) + ├─ Generate tasks.jsonl (one task per line) + └─ Generate plan.md (human-readable summary) -Phase 4: Confirmation & Selection - ├─ Display plan summary (tasks, complexity, estimated time) - └─ ASK_USER: - ├─ Confirm: Allow / Modify / Cancel - ├─ Execution: Agent / Codex / Auto - └─ Review: Gemini / Agent / Skip +Phase 4: Confirmation + ├─ Display plan summary (tasks, complexity, dependencies) + └─ ASK_USER: Allow / Modify / Cancel -Phase 5: Execute - ├─ Build executionContext (plan + explorations + clarifications + selections) - └─ → Hand off to Phase 2: Lite Execute (phases/02-lite-execute.md) --in-memory +Phase 5: Handoff + └─ → unified-execute-with-file with tasks.jsonl ``` ## Implementation -### Phase 1: Intelligent Multi-Angle Exploration +### Phase 1: Serial CLI Exploration with Search Verification #### Session Setup (MANDATORY) @@ -129,7 +116,7 @@ Exploration is needed when **ANY** of these conditions are met: If none apply → skip to Phase 2 (Clarification) or Phase 3 (Planning). -**⚠️ Context Protection**: If file reading would exceed ≥50k chars → force exploration (delegate to cli-explore-agent). +**⚠️ Context Protection**: If file reading would exceed ≥50k chars → force CLI exploration to delegate context gathering. #### Complexity Assessment @@ -156,140 +143,128 @@ Angles are assigned based on task type keyword matching, then sliced by complexi **Angle count by complexity**: Low → 1, Medium → 3, High → 4 -**Planning strategy**: Low → "Direct Claude Planning", Medium/High → "cli-lite-planning-agent" +Display exploration plan summary (complexity, selected angles) before starting. -Display exploration plan summary (complexity, selected angles, planning strategy) before launching agents. +#### Serial CLI Exploration Loop -#### Launch Parallel Explorations +For each selected exploration angle, execute the following three steps **serially**: -**⚠️ CRITICAL — SYNCHRONOUS EXECUTION**: Exploration results are REQUIRED before planning. Use `spawn_agent` + `wait` pattern. +##### Step A: CLI Exploration Call -**Orchestration Flow**: +Execute `ccw cli` to explore codebase from the specific angle: -``` -1. Spawn agents - └─ For each selected angle → create cli-explore-agent with Agent Prompt (below) - -2. Batch wait - └─ Wait for ALL agents (timeout: 10 minutes) - -3. Handle timeout - └─ If partial timeout → log warning, continue with completed results - -4. Collect results - └─ For each completed agent → store exploration data keyed by angle - -5. Close agents - └─ Close ALL exploration agents after collection +```bash +ccw cli -p "PURPOSE: Explore codebase from {angle} perspective for task planning context; success = actionable findings with file:line references verified against actual code +TASK: • Analyze project structure relevant to {angle} • Identify files and modules related to {angle} • Discover existing patterns and conventions for {angle} • Find integration points and dependencies (with file:line locations) • Identify constraints and risks from {angle} viewpoint • List questions needing user clarification +MODE: analysis +CONTEXT: @**/* | Memory: Task: {task_description} +EXPECTED: Structured analysis with sections: 1) Project structure overview 2) Relevant files with relevance assessment (high/medium/low) 3) Existing patterns (with code examples) 4) Dependencies 5) Integration points (file:line) 6) Constraints 7) Clarification questions +CONSTRAINTS: Focus on {angle} perspective | Analysis only | Include file:line references" --tool gemini --mode analysis --rule analysis-analyze-code-patterns ``` -**Agent Prompt Template** (per angle): +**CLI Tool Selection**: +- Default: `--tool gemini` (gemini-2.5-flash) +- Fallback: `--tool claude` (if gemini fails or is unavailable) + +**Execution Mode**: `Bash({ command: "ccw cli ...", run_in_background: true })` → Wait for completion + +##### Step B: Search Verification + +After CLI exploration returns, verify key findings inline using search tools: ``` -## TASK ASSIGNMENT +For each key finding from CLI result: +├─ Files mentioned → Glob to verify existence, Read to verify content +├─ Patterns mentioned → Grep to verify pattern presence in codebase +├─ Integration points → mcp__ace-tool__search_context to verify context accuracy +└─ Dependencies → Grep to verify import/export relationships -### MANDATORY FIRST STEPS (Agent Execute) -1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first) -2. Read: {projectRoot}/.workflow/project-tech.json -3. Read: {projectRoot}/.workflow/project-guidelines.json +Verification rules: +├─ File exists? → Mark as ✅ verified +├─ File not found? → Mark as ⚠️ unverified, note in output +├─ Pattern confirmed? → Include with code reference +└─ Pattern not found? → Exclude or mark as uncertain +``` + +**Verification Checklist**: +- [ ] All mentioned files verified to exist +- [ ] Patterns described match actual code +- [ ] Integration points confirmed at correct file:line locations +- [ ] Dependencies are accurate (imports/exports verified) + +##### Step C: Save Verified Exploration Results + +Save verified exploration results as Markdown: + +```markdown +# Exploration: {angle} + +**Task**: {task_description} +**Timestamp**: {ISO timestamp} +**CLI Tool**: gemini / claude --- -## Task Objective -Execute **{angle}** exploration for task planning context. Analyze codebase from this specific angle to discover relevant structure, patterns, and constraints. +## Findings -## Output Location +### Project Structure +{verified structure relevant to this angle} -**Session Folder**: {sessionFolder} -**Output File**: {sessionFolder}/exploration-{angle}.json +### Relevant Files -## Assigned Context -- **Exploration Angle**: {angle} -- **Task Description**: {task_description} -- **Exploration Index**: {index} of {total} +| File | Relevance | Rationale | Verified | +|------|-----------|-----------|----------| +| `src/auth/login.ts` | high | Core authentication logic | ✅ | +| `src/middleware/auth.ts` | medium | Auth middleware chain | ✅ | -## MANDATORY STEPS (Execute by Agent) -**You (cli-explore-agent) MUST execute these steps in order:** -1. Run: ccw tool exec get_modules_by_depth '{}' (project structure) -2. Run: rg -l "{keyword_from_task}" --type ts (locate relevant files) -3. Execute: cat ~/.ccw/workflows/cli-templates/schemas/explore-json-schema.json (get output schema reference) -4. Read: {projectRoot}/.workflow/project-tech.json (technology stack and architecture context) -5. Read: {projectRoot}/.workflow/project-guidelines.json (user-defined constraints and conventions) +### Patterns +{verified patterns with actual code examples from codebase} -## Exploration Strategy ({angle} focus) +### Integration Points +{verified integration points with file:line references} -**Step 1: Structural Scan** (Bash) -- get_modules_by_depth.sh → identify modules related to {angle} -- find/rg → locate files relevant to {angle} aspect -- Analyze imports/dependencies from {angle} perspective +### Dependencies +{verified dependency relationships} -**Step 2: Semantic Analysis** (Gemini CLI) -- How does existing code handle {angle} concerns? -- What patterns are used for {angle}? -- Where would new code integrate from {angle} viewpoint? +### Constraints +{angle-specific constraints discovered} -**Step 3: Write Output** -- Consolidate {angle} findings into JSON -- Identify {angle}-specific clarification needs - -## Expected Output - -**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 3, follow schema exactly - -**Required Fields** (all {angle} focused): -- project_structure: Modules/architecture relevant to {angle} -- relevant_files: Files affected from {angle} perspective - **IMPORTANT**: Use object format with relevance scores for synthesis: - `[{path: "src/file.ts", relevance: 0.85, rationale: "Core {angle} logic"}]` - Scores: 0.7+ high priority, 0.5-0.7 medium, <0.5 low -- patterns: {angle}-related patterns to follow -- dependencies: Dependencies relevant to {angle} -- integration_points: Where to integrate from {angle} viewpoint (include file:line locations) -- constraints: {angle}-specific limitations/conventions -- clarification_needs: {angle}-related ambiguities (options array + recommended index) -- _metadata.exploration_angle: "{angle}" - -## Success Criteria -- [ ] Schema obtained via cat explore-json-schema.json -- [ ] get_modules_by_depth.sh executed -- [ ] At least 3 relevant files identified with {angle} rationale -- [ ] Patterns are actionable (code examples, not generic advice) -- [ ] Integration points include file:line locations -- [ ] Constraints are project-specific to {angle} -- [ ] JSON output follows schema exactly -- [ ] clarification_needs includes options + recommended - -## Execution -**Write**: `{sessionFolder}/exploration-{angle}.json` -**Return**: 2-3 sentence summary of {angle} findings +### Clarification Needs +{questions that need user input, with suggested options} ``` -#### Auto-discover & Manifest Generation +**Write**: `{sessionFolder}/exploration-{angle}.md` -After explorations complete: +#### Manifest Generation -1. **Discover** — Find all `exploration-*.json` files in session folder -2. **Read metadata** — Extract `_metadata.exploration_angle` and `_metadata.exploration_index` from each file -3. **Build manifest** — Create `explorations-manifest.json` containing: - - `session_id`, `task_description`, `timestamp`, `complexity`, `exploration_count` - - `explorations[]`: array of `{ angle, file, path, index }` per exploration -4. **Write** — Save manifest to `{sessionFolder}/explorations-manifest.json` -5. **Display** — Summary of generated files and explored angles +After all angle explorations complete: -**Output**: -- `{sessionFolder}/exploration-{angle1}.json` -- `{sessionFolder}/exploration-{angle2}.json` -- ... (1-4 files based on complexity) -- `{sessionFolder}/explorations-manifest.json` +1. **Build manifest** — Create `explorations-manifest.json`: + ```javascript + { + session_id: sessionId, + task_description: taskDescription, + timestamp: getUtc8ISOString(), + complexity: complexity, + exploration_count: selectedAngles.length, + explorations: selectedAngles.map((angle, i) => ({ + angle: angle, + file: `exploration-${angle}.md`, + path: `${sessionFolder}/exploration-${angle}.md`, + index: i + })) + } + ``` +2. **Write** — Save to `{sessionFolder}/explorations-manifest.json` #### Generate Exploration Notes -Auto-generated after exploration completes. +Synthesize all exploration Markdown files into a unified notes document. **Steps**: -1. **Load** all exploration JSON files via manifest -2. **Extract core files** — Filter `relevant_files` with relevance ≥ 0.7, sort by relevance descending, deduplicate by path +1. **Load** all exploration Markdown files via manifest +2. **Extract core files** — Collect all "Relevant Files" tables, deduplicate by path, sort by relevance 3. **Build exploration notes** — 6-part Markdown document (structure below) 4. **Write** to `{sessionFolder}/exploration-notes.md` @@ -306,45 +281,39 @@ Auto-generated after exploration completes. ## Part 1: Multi-Angle Exploration Summary Per angle: Key Files (priority sorted), Code Patterns, Integration Points, Dependencies, Constraints -## Part 2: File Deep-Dive Summary -Top 10 core files: read content, find cross-references via rg, format structural details +## Part 2: Core Files Index +Top 10 files across all angles, with cross-references and structural details -## Part 3: Architecture Reasoning Chains -Synthesized from exploration findings and task description +## Part 3: Architecture Reasoning +Synthesized architectural insights from all angles -## Part 4: Potential Risks and Mitigations +## Part 4: Risks and Mitigations Derived from explorations and core file analysis ## Part 5: Clarification Questions Summary -Aggregated from all exploration angles +Aggregated from all exploration angles, deduplicated -## Part 6: Execution Recommendations Checklist -Generated from task description, explorations, and core files - ---- - -## Appendix: Key Code Location Index +## Part 6: Key Code Location Index | Component | File Path | Key Lines | Purpose | +|-----------|-----------|-----------|---------| ``` -**Output**: `{sessionFolder}/exploration-notes.md` (full version, consumed by Plan phase) - --- ### Phase 2: Clarification (Optional, Multi-Round) -**Skip Conditions**: No exploration performed OR `clarification_needs` empty across all explorations +**Skip Conditions**: No exploration performed OR clarification needs empty across all explorations **⚠️ CRITICAL**: ASK_USER limits max 4 questions per call. **MUST execute multiple rounds** to exhaust all clarification needs — do NOT stop at round 1. **Flow**: ``` -1. Load manifest + all exploration files +1. Load all exploration Markdown files -2. Aggregate clarification_needs - └─ For each exploration → collect needs, tag each with source_angle +2. Extract clarification needs + └─ For each exploration → collect "Clarification Needs" section items 3. Deduplicate └─ Intelligent merge: identify similar intent across angles @@ -357,7 +326,6 @@ Generated from task description, explorations, and core files ├─ Batch size: 4 questions per round ├─ Per round: display "Round N/M", present via ASK_USER │ └─ Each question: [source_angle] question + context - │ Options with recommended marked ★ ├─ Store responses in clarificationContext after each round └─ Repeat until all questions exhausted ``` @@ -366,256 +334,216 @@ Generated from task description, explorations, and core files --- -### Phase 3: Planning +### Phase 3: Planning → tasks.jsonl -**IMPORTANT**: Phase 3 is **planning only** — NO code execution. All execution happens in Phase 5 via lite-execute. +**IMPORTANT**: Phase 3 is **planning only** — NO code execution. All implementation happens via unified-execute-with-file. -#### Executor Assignment Rules +#### Step 3.1: Gather Planning Context -Applied after plan generation. Priority (high → low): +1. **Read** all exploration Markdown files and `exploration-notes.md` +2. **Read** `{projectRoot}/.workflow/project-tech.json` (if exists) +3. **Read** `{projectRoot}/.workflow/project-guidelines.json` (if exists) +4. **Collect** clarificationContext (if any) -1. **User explicit** — If task description specifies tool (e.g., "用 gemini 分析...") → use that executor -2. **Default** → agent +#### Step 3.2: Generate requirement-analysis.json -Result: `executorAssignments` map — `{ taskId: { executor: 'gemini'|'codex'|'agent', reason: string } }` +```javascript +Write(`${sessionFolder}/requirement-analysis.json`, JSON.stringify({ + session_id: sessionId, + original_requirement: taskDescription, + complexity: complexity, + exploration_angles: selectedAngles, + total_explorations: selectedAngles.length, + timestamp: getUtc8ISOString() +}, null, 2)) +``` -#### Low Complexity — Direct Planning by Claude +#### Step 3.3: Generate tasks.jsonl -1. **Read schema** — `cat ~/.ccw/workflows/cli-templates/schemas/plan-json-schema.json` -2. **Read ALL exploration files** (⚠️ MANDATORY) — Load manifest, read each exploration JSON, review findings -3. **Generate plan** following schema — Claude directly generates plan incorporating exploration insights +Direct Claude planning — synthesize exploration findings and clarifications into unified JSONL tasks: + +**Task Grouping Rules**: +1. **Group by feature**: All changes for one feature = one task (even if 3-5 files) +2. **Group by context**: Tasks with similar context or related functional changes can be grouped +3. **Minimize task count**: Simple, related tasks grouped together (target 2-7 tasks) +4. **Substantial tasks**: Each task should represent meaningful work +5. **True dependencies only**: Only use depends_on when Task B cannot start without Task A's output +6. **Prefer parallel**: Most tasks should be independent (no depends_on) + +**Unified JSONL Task Format** (one JSON object per line): -**plan.json structure** (Low complexity): ```javascript { - summary: "...", - approach: "...", - tasks: [...], // Each: { id, title, scope, ..., depends_on, execution_group, complexity } - estimated_time: "...", - recommended_execution: "Agent", - complexity: "Low", - _metadata: { timestamp, source: "direct-planning", planning_mode: "direct" } + id: "TASK-001", // Padded 3-digit ID + title: "...", + description: "...", // Scope/goal + implementation approach + type: "feature", // feature|infrastructure|enhancement|fix|refactor|testing + priority: "medium", // high|medium|low + effort: "medium", // small|medium|large + scope: "...", // Brief scope description + depends_on: [], // TASK-xxx references (empty if independent) + convergence: { + criteria: [ // Testable conditions (2-5 items) + "File src/auth/login.ts exports authenticateUser function", + "Unit test covers both success and failure paths" + ], + verification: "npm test -- --grep auth", // Executable command or manual steps + definition_of_done: "Users can log in with JWT tokens and receive refresh tokens" + }, + files: [ // Files to modify (from exploration findings) + { + path: "src/auth/login.ts", + action: "modify", // modify|create|delete + changes: ["Add JWT token generation", "Add refresh token logic"], + conflict_risk: "low" // low|medium|high + } + ], + source: { + tool: "workflow-lite-plan-execute", + session_id: sessionId, + original_id: "TASK-001" + } } ``` -4. **Write** `{sessionFolder}/plan.json` -5. **Continue** to Phase 4 (Confirmation) — DO NOT execute code here - -#### Medium/High Complexity — Invoke cli-lite-planning-agent - -**Orchestration**: - -``` -1. Spawn planning agent → with Agent Prompt (below) -2. Wait for completion → timeout: 15 minutes -3. Close agent → after completion +**Write tasks.jsonl**: +```javascript +const jsonlContent = tasks.map(t => JSON.stringify(t)).join('\n') +Write(`${sessionFolder}/tasks.jsonl`, jsonlContent) ``` -**Agent Prompt Template**: +#### Step 3.4: Generate plan.md +Create human-readable summary: + +```javascript +const planMd = `# Lite Plan + +**Session**: ${sessionId} +**Requirement**: ${taskDescription} +**Created**: ${getUtc8ISOString()} +**Complexity**: ${complexity} +**Exploration Angles**: ${selectedAngles.join(', ')} + +## 需求理解 + +${requirementUnderstanding} + +## 任务概览 + +| # | ID | Title | Type | Priority | Effort | Dependencies | +|---|-----|-------|------|----------|--------|--------------| +${tasks.map((t, i) => `| ${i+1} | ${t.id} | ${t.title} | ${t.type} | ${t.priority} | ${t.effort} | ${t.depends_on.join(', ') || '-'} |`).join('\n')} + +## 任务详情 + +${tasks.map(t => `### ${t.id}: ${t.title} +- **范围**: ${t.scope} +- **修改文件**: ${t.files.map(f => \`\\\`${f.path}\\\` (${f.action})\`).join(', ')} +- **收敛标准**: +${t.convergence.criteria.map(c => \` - ${c}\`).join('\n')} +- **验证方式**: ${t.convergence.verification} +- **完成定义**: ${t.convergence.definition_of_done} +`).join('\n')} + +## 执行 + +\`\`\`bash +$unified-execute-with-file PLAN="${sessionFolder}/tasks.jsonl" +\`\`\` + +**Session artifacts**: \`${sessionFolder}/\` +` +Write(`${sessionFolder}/plan.md`, planMd) ``` -## TASK ASSIGNMENT - -### MANDATORY FIRST STEPS (Agent Execute) -1. **Read role definition**: ~/.codex/agents/cli-lite-planning-agent.md (MUST read first) -2. Read: {projectRoot}/.workflow/project-tech.json -3. Read: {projectRoot}/.workflow/project-guidelines.json --- -Generate implementation plan and write plan.json. - -## Output Location - -**Session Folder**: {sessionFolder} -**Output Files**: -- {sessionFolder}/planning-context.md (evidence + understanding) -- {sessionFolder}/plan.json (implementation plan) -- {sessionFolder}/exploration-notes-refined.md (refined exploration notes for Execute phase) - -## Output Schema Reference -Execute: cat ~/.ccw/workflows/cli-templates/schemas/plan-json-schema.json (get schema reference before generating plan) - -## Project Context (MANDATORY - Read Both Files) -1. Read: {projectRoot}/.workflow/project-tech.json (technology stack, architecture, key components) -2. Read: {projectRoot}/.workflow/project-guidelines.json (user-defined constraints and conventions) - -**CRITICAL**: All generated tasks MUST comply with constraints in project-guidelines.json - -## Task Description -{task_description} - -## Multi-Angle Exploration Context - -{For each exploration: -### Exploration: {angle} ({file}) -Path: {path} - -Read this file for detailed {angle} analysis. -} - -Total explorations: {count} -Angles covered: {angles} - -Manifest: {sessionFolder}/explorations-manifest.json - -## User Clarifications -{clarificationContext or "None"} - -## Complexity Level -{complexity} - -## Requirements -Generate plan.json following the schema obtained above. Key constraints: -- tasks: 2-7 structured tasks (**group by feature/module, NOT by file**) -- _metadata.exploration_angles: {angles} - -## Task Grouping Rules -1. **Group by feature**: All changes for one feature = one task (even if 3-5 files) -2. **Group by context**: Tasks with similar context or related functional changes can be grouped together -3. **Minimize agent count**: Simple, unrelated tasks can also be grouped to reduce agent execution overhead -4. **Avoid file-per-task**: Do NOT create separate tasks for each file -5. **Substantial tasks**: Each task should represent 15-60 minutes of work -6. **True dependencies only**: Only use depends_on when Task B cannot start without Task A's output -7. **Prefer parallel**: Most tasks should be independent (no depends_on) - -## Execution -1. Read schema file (cat command above) -2. Execute CLI planning using Gemini (Qwen fallback) -3. Read ALL exploration files for comprehensive context -4. Synthesize findings and generate plan following schema -5. **Write**: `{sessionFolder}/planning-context.md` (evidence paths + understanding) -6. **Write**: `{sessionFolder}/plan.json` -7. Execute Phase 5 (Plan Quality Check) and Phase 6 (Refine Exploration Notes) per agent role definition -8. **Write**: `{sessionFolder}/exploration-notes-refined.md` (Phase 6 output) -9. Return brief completion summary -``` - -**Output**: `{sessionFolder}/plan.json` + `{sessionFolder}/exploration-notes-refined.md` - -> **Note**: `exploration-notes-refined.md` is generated by cli-lite-planning-agent (Phase 6) as part of its execution flow. See `~/.codex/agents/cli-lite-planning-agent.md` Phase 6 for structure and generation logic. - ---- - -### Phase 4: Task Confirmation & Execution Selection +### Phase 4: Task Confirmation #### Step 4.1: Display Plan -Read `{sessionFolder}/plan.json` and display summary: +Read `{sessionFolder}/tasks.jsonl` and display summary: -- **Summary**: plan.summary -- **Approach**: plan.approach -- **Tasks**: numbered list with title and file -- **Complexity**: plan.complexity -- **Estimated Time**: plan.estimated_time -- **Recommended**: plan.recommended_execution +- **Summary**: Overall approach (from requirement understanding) +- **Tasks**: Numbered list with ID, title, type, effort +- **Complexity**: Assessment result +- **Total tasks**: Count +- **Dependencies**: Graph overview #### Step 4.2: Collect Confirmation **Route by mode**: ``` -├─ --yes mode → Auto-confirm with defaults: -│ ├─ Confirmation: "Allow" -│ ├─ Execution: "Auto" -│ └─ Review: "Skip" +├─ --yes mode → Auto-confirm: +│ └─ Confirmation: "Allow" │ -└─ Interactive mode → ASK_USER with 3 questions: +└─ Interactive mode → ASK_USER: + └─ Confirm plan? ({N} tasks, {complexity}) + ├─ Allow (proceed as-is) + ├─ Modify (adjust before execution) + └─ Cancel (abort workflow) ``` -**Interactive Questions**: +**Output**: `userSelection` — `{ confirmation: "Allow" | "Modify" | "Cancel" }` -| Question | Options | Default | -|----------|---------|---------| -| Confirm plan? ({N} tasks, {complexity}) | Allow (proceed as-is), Modify (adjust before execution), Cancel (abort workflow) | Allow | -| Execution method | Agent (@code-developer), Codex (codex CLI), Auto (Low→Agent, else→Codex) | Auto | -| Code review after execution? | Gemini Review, Codex Review (git-aware), Agent Review, Skip | Skip | - -**Output**: `userSelection` — `{ confirmation, executionMethod, codeReviewTool }` +**Modify Loop**: If "Modify" selected, display current tasks.jsonl content, accept user edits (max 3 rounds), regenerate plan.md, re-confirm. --- ### Phase 5: Handoff to Execution -**CRITICAL**: lite-plan NEVER executes code directly. ALL execution MUST go through lite-execute. +**CRITICAL**: lite-plan NEVER executes code directly. ALL execution goes through unified-execute-with-file. -#### Step 5.1: Build executionContext - -Assemble the complete execution context from all planning phase outputs: - -```javascript -{ - planObject: plan, // From plan.json - explorationsContext: { [angle]: explorationData }, // From exploration JSONs - explorationAngles: ["angle1", "angle2", ...], // From manifest - explorationManifest: manifest, // Full manifest object - clarificationContext: { [question]: answer } | null, - userSelection: { confirmation, executionMethod, codeReviewTool }, - executionMethod: userSelection.executionMethod, // Global default; may be overridden by executorAssignments - codeReviewTool: userSelection.codeReviewTool, - originalUserInput: task_description, - - // Task-level executor assignments (priority over global executionMethod) - executorAssignments: { [taskId]: { executor, reason } }, - - session: { - id: sessionId, - folder: sessionFolder, - artifacts: { - explorations: [{ angle, path }], // Per-angle exploration paths - explorations_manifest: "{sessionFolder}/explorations-manifest.json", - exploration_log: "{sessionFolder}/exploration-notes.md", // Full version (Plan consumption) - exploration_log_refined: "{sessionFolder}/exploration-notes-refined.md", // Refined version (Execute consumption) - plan: "{sessionFolder}/plan.json" - } - } -} -``` - -#### Step 5.2: Execute - -→ Hand off to Phase 2: Lite Execute (`phases/02-lite-execute.md`) with `--in-memory` flag +→ Hand off to Phase 2: `phases/02-lite-execute.md` which invokes `unified-execute-with-file` ## Session Folder Structure ``` -{projectRoot}/.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/ -├── exploration-{angle1}.json # Exploration angle 1 -├── exploration-{angle2}.json # Exploration angle 2 -├── exploration-{angle3}.json # Exploration angle 3 (if applicable) -├── exploration-{angle4}.json # Exploration angle 4 (if applicable) -├── explorations-manifest.json # Exploration index -├── exploration-notes.md # Full exploration notes (Plan phase consumption) -├── exploration-notes-refined.md # Refined exploration notes (Execute phase consumption) -└── plan.json # Implementation plan +{projectRoot}/.workflow/.lite-plan/{session-id}/ +├── exploration-{angle1}.md # CLI exploration angle 1 +├── exploration-{angle2}.md # CLI exploration angle 2 +├── exploration-{angle3}.md # (if applicable) +├── exploration-{angle4}.md # (if applicable) +├── explorations-manifest.json # Exploration index +├── exploration-notes.md # Synthesized exploration notes +├── requirement-analysis.json # Complexity assessment +├── tasks.jsonl # ⭐ Unified JSONL output +└── plan.md # Human-readable summary ``` **Example**: ``` -{projectRoot}/.workflow/.lite-plan/implement-jwt-refresh-2025-11-25-14-30-25/ -├── exploration-architecture.json -├── exploration-auth-patterns.json -├── exploration-security.json +{projectRoot}/.workflow/.lite-plan/implement-jwt-refresh-2025-11-25/ +├── exploration-patterns.md +├── exploration-integration-points.md +├── exploration-testing.md ├── explorations-manifest.json -└── plan.json +├── exploration-notes.md +├── requirement-analysis.json +├── tasks.jsonl +└── plan.md ``` ## Error Handling | Error | Resolution | |-------|------------| -| Exploration agent failure | Skip exploration, continue with task description only | -| Planning agent failure | Fallback to direct planning by Claude | +| CLI exploration failure | Skip angle, continue with remaining; fallback gemini → claude | +| CLI tool unavailable | Try fallback tool; if all fail, proceed without exploration | +| Search verification failure | Note unverified findings, continue with caution marker | +| Planning failure | Display error, offer retry | | Clarification timeout | Use exploration findings as-is | -| Confirmation timeout | Save context, display resume instructions | -| Modify loop > 3 times | Suggest breaking task or using full planning workflow (workflow-plan-execute/SKILL.md) | +| Confirmation timeout | Save artifacts, display resume instructions | +| Modify loop > 3 times | Suggest using full planning workflow (workflow-plan-execute/SKILL.md) | --- ## Post-Phase Update After Phase 1 (Lite Plan) completes: -- **Output Created**: `executionContext` with plan.json, explorations, clarifications, user selections +- **Output Created**: `tasks.jsonl` + `plan.md` + exploration artifacts in session folder - **Session Artifacts**: All files in `{projectRoot}/.workflow/.lite-plan/{session-id}/` -- **Next Action**: Auto-continue to [Phase 2: Lite Execute](02-lite-execute.md) with --in-memory -- **TodoWrite**: Mark "Lite Plan - Planning" as completed, start "Execution (Phase 2)" +- **Next Action**: Auto-continue to [Phase 2: Execution Handoff](02-lite-execute.md) +- **TodoWrite**: Mark "Lite Plan - Planning" as completed, start "Execution (unified-execute)" diff --git a/.codex/skills/workflow-lite-plan-execute/phases/02-lite-execute.md b/.codex/skills/workflow-lite-plan-execute/phases/02-lite-execute.md index f4a09670..2f5d3336 100644 --- a/.codex/skills/workflow-lite-plan-execute/phases/02-lite-execute.md +++ b/.codex/skills/workflow-lite-plan-execute/phases/02-lite-execute.md @@ -1,518 +1,636 @@ -# Phase 2: Lite Execute +# Phase 2: Execution ## Overview -Flexible task execution phase supporting three input modes: in-memory plan (from planning phases), direct prompt description, or file content. Handles execution orchestration, progress tracking, and optional code review. +消费 Phase 1 产出的统一 JSONL (`tasks.jsonl`),串行执行任务并进行收敛验证,通过 `execution.md` + `execution-events.md` 跟踪进度。 -**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) +**Core workflow**: Load JSONL → Validate → Pre-Execution Analysis → Execute → Verify Convergence → Track Progress -## Parameters +**Key features**: +- **Single format**: 只消费统一 JSONL (`tasks.jsonl`) +- **Convergence-driven**: 每个任务执行后验证收敛标准 +- **Serial execution**: 按拓扑序串行执行,依赖跟踪 +- **Dual progress tracking**: `execution.md` (概览) + `execution-events.md` (事件流) +- **Auto-commit**: 可选的每任务 conventional commits +- **Dry-run mode**: 模拟执行,不做实际修改 -- `--in-memory`: Use plan from memory (called by planning phases) -- ``: Task description string, or path to file (required) +## Invocation -## Input Modes +```javascript +$unified-execute-with-file PLAN="${sessionFolder}/tasks.jsonl" -### Mode 1: In-Memory Plan - -**Trigger**: Called by planning phase after confirmation with `--in-memory` flag - -**Input Source**: `executionContext` global variable set by planning phase - -**Content**: Complete execution context (see Data Structures section) - -**Behavior**: -- Skip execution method selection (already set by planning phase) -- Directly proceed to execution with full context -- All planning artifacts available (exploration, clarifications, plan) - -### 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 prompt as `originalUserInput` -- Execute `git rev-parse --show-toplevel` to determine `projectRoot` -- Create simple execution plan from prompt -- ASK_USER: Select execution method (Agent/Codex/Auto) -- ASK_USER: Select code review tool (Skip/Gemini/Agent/Other) -- Proceed to execution with `originalUserInput` included - -**User Interaction**: - -``` -Route by mode: -├─ --yes mode → Auto-confirm with defaults: -│ ├─ Execution method: Auto -│ └─ Code review: Skip -│ -└─ Interactive mode → ASK_USER with 2 questions: - ├─ Execution method: Agent (@code-developer) / Codex (codex CLI) / Auto (complexity-based) - └─ Code review: Skip / Gemini Review / Codex Review (git-aware) / Agent Review +// With options +$unified-execute-with-file PLAN="${sessionFolder}/tasks.jsonl" --auto-commit +$unified-execute-with-file PLAN="${sessionFolder}/tasks.jsonl" --dry-run ``` -### Mode 3: File Content - -**Trigger**: User calls with file path - -**Input**: Path to file containing task description or plan.json - -**Format Detection**: +## Output Structure ``` -1. Execute git rev-parse --show-toplevel to determine projectRoot -2. Read file content -3. Attempt JSON parsing - ├─ Valid JSON with summary + approach + tasks fields → plan.json format - │ ├─ Use parsed data as planObject - │ └─ Set originalUserInput = summary - └─ Not valid JSON or missing required fields → plain text format - └─ Set originalUserInput = file content (same as Mode 2) -3. User selects execution method + code review (same as Mode 2) +${projectRoot}/.workflow/.execution/EXEC-{slug}-{date}-{random}/ +├── execution.md # Plan overview + task table + summary statistics +└── execution-events.md # Unified event log (single source of truth) ``` -## Execution Process +Additionally, the source `tasks.jsonl` is updated in-place with `_execution` states. -``` -Input Parsing: - └─ Decision (mode detection): - ├─ --in-memory flag → Mode 1: Load executionContext → Skip user selection - ├─ Existing file path (path exists) → Mode 3: Read file → Detect format - │ ├─ Valid plan.json → Use planObject → User selects method + review - │ └─ Not plan.json → Treat as prompt → User selects method + review - └─ Otherwise → Mode 2: Prompt description → User selects method + review +--- -Execution: - ├─ Step 1: Initialize result tracking (previousExecutionResults = []) - ├─ Step 2: Task grouping & batch creation - │ ├─ Extract explicit depends_on (no file/keyword inference) - │ ├─ Group: independent tasks → single parallel batch (maximize utilization) - │ ├─ Group: dependent tasks → sequential phases (respect dependencies) - │ └─ Create TodoWrite list for batches - ├─ Step 3: Launch execution - │ ├─ Phase 1: All independent tasks (single batch, concurrent) - │ └─ Phase 2+: Dependent tasks by dependency order - ├─ Step 4: Track progress (TodoWrite updates per batch) - └─ Step 5: Code review (if codeReviewTool ≠ "Skip") +## Session Initialization -Output: - └─ Execution complete with results in previousExecutionResults[] +```javascript +const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() +const projectRoot = Bash(`git rev-parse --show-toplevel 2>/dev/null || pwd`).trim() + +// Parse arguments +const autoCommit = $ARGUMENTS.includes('--auto-commit') +const dryRun = $ARGUMENTS.includes('--dry-run') +const planMatch = $ARGUMENTS.match(/PLAN="([^"]+)"/) || $ARGUMENTS.match(/PLAN=(\S+)/) +let planPath = planMatch ? planMatch[1] : null + +// Auto-detect if no PLAN specified +if (!planPath) { + // Search in order (most recent first): + // .workflow/.lite-plan/*/tasks.jsonl + // .workflow/.req-plan/*/tasks.jsonl + // .workflow/.planning/*/tasks.jsonl + // .workflow/.analysis/*/tasks.jsonl + // .workflow/.brainstorm/*/tasks.jsonl +} + +// Resolve path +planPath = path.isAbsolute(planPath) ? planPath : `${projectRoot}/${planPath}` + +// Generate session ID +const slug = path.basename(path.dirname(planPath)).toLowerCase().substring(0, 30) +const dateStr = getUtc8ISOString().substring(0, 10) +const random = Math.random().toString(36).substring(2, 9) +const sessionId = `EXEC-${slug}-${dateStr}-${random}` +const sessionFolder = `${projectRoot}/.workflow/.execution/${sessionId}` + +Bash(`mkdir -p ${sessionFolder}`) ``` -## Detailed Execution Steps +--- -### Step 1: Initialize Execution Tracking +## Phase 1: Load & Validate -**Operations**: -- Initialize `previousExecutionResults` array for context continuity -- **In-Memory Mode**: Echo execution strategy from planning phase for transparency - - Display: Method, Review tool, Task count, Complexity, Executor assignments (if present) +**Objective**: Parse unified JSONL, validate schema and dependencies, build execution order. -### Step 2: Task Grouping & Batch Creation +### Step 1.1: Parse Unified JSONL -**Dependency Analysis**: Use **explicit** `depends_on` from plan.json only — no inference from file paths or keywords. +```javascript +const content = Read(planPath) +const tasks = content.split('\n') + .filter(line => line.trim()) + .map((line, i) => { + try { return JSON.parse(line) } + catch (e) { throw new Error(`Line ${i + 1}: Invalid JSON — ${e.message}`) } + }) -``` -1. Build task ID → index mapping - -2. For each task: - └─ Resolve depends_on IDs to task indices - └─ Filter: only valid IDs that reference earlier tasks - -3. Group into execution batches: - ├─ Phase 1: All tasks with NO dependencies → single parallel batch - │ └─ Mark as processed - └─ Phase 2+: Iterative dependency resolution - ├─ Find tasks whose ALL dependencies are satisfied (processed) - ├─ Group ready tasks as batch (parallel within batch if multiple) - ├─ Mark as processed - ├─ Repeat until no tasks remain - └─ Safety: If no ready tasks found → circular dependency warning → force remaining - -4. Assign batch IDs: - ├─ Parallel batches: P1, P2, P3... - └─ Sequential batches: S1, S2, S3... - -5. Create TodoWrite list with batch indicators: - ├─ ⚡ for parallel batches (concurrent) - └─ → for sequential batches (one-by-one) +if (tasks.length === 0) throw new Error('No tasks found in JSONL file') ``` -### Step 3: Launch Execution +### Step 1.2: Validate Schema -#### Executor Resolution +```javascript +const errors = [] +tasks.forEach((task, i) => { + // Required fields + if (!task.id) errors.push(`Task ${i + 1}: missing 'id'`) + if (!task.title) errors.push(`Task ${i + 1}: missing 'title'`) + if (!task.description) errors.push(`Task ${i + 1}: missing 'description'`) + if (!Array.isArray(task.depends_on)) errors.push(`${task.id}: missing 'depends_on' array`) -Task-level executor assignment takes priority over global execution method: + // Convergence required + if (!task.convergence) { + errors.push(`${task.id}: missing 'convergence'`) + } else { + if (!task.convergence.criteria?.length) errors.push(`${task.id}: empty convergence.criteria`) + if (!task.convergence.verification) errors.push(`${task.id}: missing convergence.verification`) + if (!task.convergence.definition_of_done) errors.push(`${task.id}: missing convergence.definition_of_done`) + } +}) -``` -Resolution order (per task): -├─ 1. executorAssignments[task.id] → use assigned executor (gemini/codex/agent) -└─ 2. Fallback to global executionMethod: - ├─ "Agent" → agent - ├─ "Codex" → codex - └─ "Auto" → Low complexity → agent; Medium/High → codex +if (errors.length) { + // Report errors, stop execution +} ``` -#### Execution Flow +### Step 1.3: Build Execution Order -``` -1. Separate batches into parallel and sequential groups +```javascript +// 1. Validate dependency references +const taskIds = new Set(tasks.map(t => t.id)) +tasks.forEach(task => { + task.depends_on.forEach(dep => { + if (!taskIds.has(dep)) errors.push(`${task.id}: depends on unknown task '${dep}'`) + }) +}) -2. Phase 1 — Launch all parallel batches concurrently: - ├─ Update TodoWrite: all parallel → in_progress - ├─ Execute all parallel batches simultaneously (single message, multiple tool calls) - ├─ Collect results → append to previousExecutionResults - └─ Update TodoWrite: all parallel → completed +// 2. Detect cycles (DFS) +function detectCycles(tasks) { + const graph = new Map(tasks.map(t => [t.id, t.depends_on || []])) + const visited = new Set(), inStack = new Set(), cycles = [] + function dfs(node, path) { + if (inStack.has(node)) { cycles.push([...path, node].join(' → ')); return } + if (visited.has(node)) return + visited.add(node); inStack.add(node) + ;(graph.get(node) || []).forEach(dep => dfs(dep, [...path, node])) + inStack.delete(node) + } + tasks.forEach(t => { if (!visited.has(t.id)) dfs(t.id, []) }) + return cycles +} +const cycles = detectCycles(tasks) +if (cycles.length) errors.push(`Circular dependencies: ${cycles.join('; ')}`) -3. Phase 2+ — Execute sequential batches in order: - ├─ For each sequential batch: - │ ├─ Update TodoWrite: current batch → in_progress - │ ├─ Execute batch - │ ├─ Collect result → append to previousExecutionResults - │ └─ Update TodoWrite: current batch → completed - └─ Continue until all batches completed +// 3. Topological sort +function topoSort(tasks) { + const inDegree = new Map(tasks.map(t => [t.id, 0])) + tasks.forEach(t => t.depends_on.forEach(dep => { + inDegree.set(t.id, (inDegree.get(t.id) || 0) + 1) + })) + const queue = tasks.filter(t => inDegree.get(t.id) === 0).map(t => t.id) + const order = [] + while (queue.length) { + const id = queue.shift() + order.push(id) + tasks.forEach(t => { + if (t.depends_on.includes(id)) { + inDegree.set(t.id, inDegree.get(t.id) - 1) + if (inDegree.get(t.id) === 0) queue.push(t.id) + } + }) + } + return order +} +const executionOrder = topoSort(tasks) ``` -### Unified Task Prompt Builder +### Step 1.4: Initialize Execution Artifacts -Each task is formatted as a **self-contained checklist**. The executor only needs to know what THIS task requires. Same template for Agent and CLI. +```javascript +// execution.md +const executionMd = `# Execution Overview -**Prompt Structure** (assembled from batch tasks): +## Session Info +- **Session ID**: ${sessionId} +- **Plan Source**: ${planPath} +- **Started**: ${getUtc8ISOString()} +- **Total Tasks**: ${tasks.length} +- **Mode**: ${dryRun ? 'Dry-run (no changes)' : 'Direct inline execution'} +- **Auto-Commit**: ${autoCommit ? 'Enabled' : 'Disabled'} +## Task Overview + +| # | ID | Title | Type | Priority | Effort | Dependencies | Status | +|---|-----|-------|------|----------|--------|--------------|--------| +${tasks.map((t, i) => `| ${i+1} | ${t.id} | ${t.title} | ${t.type || '-'} | ${t.priority || '-'} | ${t.effort || '-'} | ${t.depends_on.join(', ') || '-'} | pending |`).join('\n')} + +## Pre-Execution Analysis +> Populated in Phase 2 + +## Execution Timeline +> Updated as tasks complete + +## Execution Summary +> Updated after all tasks complete +` +Write(`${sessionFolder}/execution.md`, executionMd) + +// execution-events.md +Write(`${sessionFolder}/execution-events.md`, `# Execution Events + +**Session**: ${sessionId} +**Started**: ${getUtc8ISOString()} +**Source**: ${planPath} + +--- + +`) ``` -## Goal -{originalUserInput} -## Tasks -(For each task in batch, separated by ---) +--- -### {task.title} -**Scope**: {task.scope} | **Action**: {task.action} +## Phase 2: Pre-Execution Analysis -#### Modification Points -- **{file}** → `{target}`: {change} +**Objective**: Validate feasibility and identify issues before execution. -#### Why this approach (Medium/High only) -{rationale.chosen_approach} -Key factors: {decision_factors} -Tradeoffs: {tradeoffs} +### Step 2.1: Analyze File Conflicts -#### How to do it -{description} -{implementation steps} +```javascript +const fileTaskMap = new Map() // file → [taskIds] +tasks.forEach(task => { + (task.files || []).forEach(f => { + const key = f.path + if (!fileTaskMap.has(key)) fileTaskMap.set(key, []) + fileTaskMap.get(key).push(task.id) + }) +}) -#### Code skeleton (High only) -Interfaces: {interfaces} -Functions: {key_functions} -Classes: {classes} +const conflicts = [] +fileTaskMap.forEach((taskIds, file) => { + if (taskIds.length > 1) { + conflicts.push({ file, tasks: taskIds, resolution: 'Execute in dependency order' }) + } +}) -#### Reference -- Pattern: {pattern} -- Files: {files} -- Notes: {examples} +// Check file existence +const missingFiles = [] +tasks.forEach(task => { + (task.files || []).forEach(f => { + if (f.action !== 'create' && !file_exists(f.path)) { + missingFiles.push({ file: f.path, task: task.id }) + } + }) +}) +``` -#### Risk mitigations (High only) -- {risk.description} → **{risk.mitigation}** +### Step 2.2: Append to execution.md -#### Done when -- [ ] {acceptance criteria} -Success metrics: {verification.success_metrics} +```javascript +// Replace "Pre-Execution Analysis" section with: +// - File Conflicts (list or "No conflicts") +// - Missing Files (list or "All files exist") +// - Dependency Validation (errors or "No issues") +// - Execution Order (numbered list) +``` -## Context -(Assembled from available sources, reference only) +### Step 2.3: User Confirmation -### Exploration Notes (Refined) -**Read first**: {exploration_log_refined path} -Contains: file index, task-relevant context, code reference, execution notes -**IMPORTANT**: Use to avoid re-exploring already analyzed files +```javascript +if (!dryRun) { + AskUserQuestion({ + questions: [{ + question: `Execute ${tasks.length} tasks?\n\n${conflicts.length ? `⚠ ${conflicts.length} file conflicts\n` : ''}Execution order:\n${executionOrder.map((id, i) => ` ${i+1}. ${id}: ${tasks.find(t => t.id === id).title}`).join('\n')}`, + header: "Confirm", + multiSelect: false, + options: [ + { label: "Execute", description: "Start serial execution" }, + { label: "Dry Run", description: "Simulate without changes" }, + { label: "Cancel", description: "Abort execution" } + ] + }] + }) +} +``` -### Previous Work -{previousExecutionResults summaries} +--- -### Clarifications -{clarificationContext entries} +## Phase 3: Serial Execution + Convergence Verification -### Data Flow -{planObject.data_flow.diagram} +**Objective**: Execute tasks sequentially, verify convergence after each task, track all state. +**Execution Model**: Direct inline execution — main process reads, edits, writes files directly. No CLI delegation. + +### Step 3.1: Execution Loop + +```javascript +const completedTasks = new Set() +const failedTasks = new Set() +const skippedTasks = new Set() + +for (const taskId of executionOrder) { + const task = tasks.find(t => t.id === taskId) + const startTime = getUtc8ISOString() + + // 1. Check dependencies + const unmetDeps = task.depends_on.filter(dep => !completedTasks.has(dep)) + if (unmetDeps.length) { + appendToEvents(task, 'BLOCKED', `Unmet dependencies: ${unmetDeps.join(', ')}`) + skippedTasks.add(task.id) + task._execution = { status: 'skipped', executed_at: startTime, + result: { success: false, error: `Blocked by: ${unmetDeps.join(', ')}` } } + continue + } + + // 2. Record START event + appendToEvents(`## ${getUtc8ISOString()} — ${task.id}: ${task.title} + +**Type**: ${task.type || '-'} | **Priority**: ${task.priority || '-'} | **Effort**: ${task.effort || '-'} +**Status**: ⏳ IN PROGRESS +**Files**: ${(task.files || []).map(f => f.path).join(', ') || 'To be determined'} +**Description**: ${task.description} +**Convergence Criteria**: +${task.convergence.criteria.map(c => `- [ ] ${c}`).join('\n')} + +### Execution Log +`) + + if (dryRun) { + // Simulate: mark as completed without changes + appendToEvents(`\n**Status**: ⏭ DRY RUN (no changes)\n\n---\n`) + task._execution = { status: 'completed', executed_at: startTime, + result: { success: true, summary: 'Dry run — no changes made' } } + completedTasks.add(task.id) + continue + } + + // 3. Execute task directly + // - Read each file in task.files (if specified) + // - Analyze what changes satisfy task.description + task.convergence.criteria + // - If task.files has detailed changes, use them as guidance + // - Apply changes using Edit (preferred) or Write (for new files) + // - Use Grep/Glob/mcp__ace-tool for discovery if needed + // - Use Bash for build/test commands + + // 4. Verify convergence + const convergenceResults = verifyConvergence(task) + + const endTime = getUtc8ISOString() + const filesModified = getModifiedFiles() + + if (convergenceResults.allPassed) { + // 5a. Record SUCCESS + appendToEvents(` +**Status**: ✅ COMPLETED +**Duration**: ${calculateDuration(startTime, endTime)} +**Files Modified**: ${filesModified.join(', ')} + +#### Changes Summary +${changeSummary} + +#### Convergence Verification +${task.convergence.criteria.map((c, i) => `- [${convergenceResults.verified[i] ? 'x' : ' '}] ${c}`).join('\n')} +- **Verification**: ${convergenceResults.verificationOutput} +- **Definition of Done**: ${task.convergence.definition_of_done} + +--- +`) + task._execution = { + status: 'completed', executed_at: endTime, + result: { + success: true, + files_modified: filesModified, + summary: changeSummary, + convergence_verified: convergenceResults.verified + } + } + completedTasks.add(task.id) + } else { + // 5b. Record FAILURE + handleTaskFailure(task, convergenceResults, startTime, endTime) + } + + // 6. Auto-commit if enabled + if (autoCommit && task._execution.status === 'completed') { + autoCommitTask(task, filesModified) + } +} +``` + +### Step 3.2: Convergence Verification + +```javascript +function verifyConvergence(task) { + const results = { + verified: [], // boolean[] per criterion + verificationOutput: '', // output of verification command + allPassed: true + } + + // 1. Check each criterion + // For each criterion in task.convergence.criteria: + // - If it references a testable condition, check it + // - If it's manual, mark as verified based on changes made + // - Record true/false per criterion + task.convergence.criteria.forEach(criterion => { + const passed = evaluateCriterion(criterion, task) + results.verified.push(passed) + if (!passed) results.allPassed = false + }) + + // 2. Run verification command (if executable) + const verification = task.convergence.verification + if (isExecutableCommand(verification)) { + try { + const output = Bash(verification, { timeout: 120000 }) + results.verificationOutput = `${verification} → PASS` + } catch (e) { + results.verificationOutput = `${verification} → FAIL: ${e.message}` + results.allPassed = false + } + } else { + results.verificationOutput = `Manual: ${verification}` + } + + return results +} + +function isExecutableCommand(verification) { + // Detect executable patterns: npm, npx, jest, tsc, curl, pytest, go test, etc. + return /^(npm|npx|jest|tsc|eslint|pytest|go\s+test|cargo\s+test|curl|make)/.test(verification.trim()) +} +``` + +### Step 3.3: Failure Handling + +```javascript +function handleTaskFailure(task, convergenceResults, startTime, endTime) { + appendToEvents(` +**Status**: ❌ FAILED +**Duration**: ${calculateDuration(startTime, endTime)} +**Error**: Convergence verification failed + +#### Failed Criteria +${task.convergence.criteria.map((c, i) => `- [${convergenceResults.verified[i] ? 'x' : ' '}] ${c}`).join('\n')} +- **Verification**: ${convergenceResults.verificationOutput} + +--- +`) + + task._execution = { + status: 'failed', executed_at: endTime, + result: { + success: false, + error: 'Convergence verification failed', + convergence_verified: convergenceResults.verified + } + } + failedTasks.add(task.id) + + // Ask user + AskUserQuestion({ + questions: [{ + question: `Task ${task.id} failed convergence verification. How to proceed?`, + header: "Failure", + multiSelect: false, + options: [ + { label: "Skip & Continue", description: "Skip this task, continue with next" }, + { label: "Retry", description: "Retry this task" }, + { label: "Accept", description: "Mark as completed despite failure" }, + { label: "Abort", description: "Stop execution, keep progress" } + ] + }] + }) +} +``` + +### Step 3.4: Auto-Commit + +```javascript +function autoCommitTask(task, filesModified) { + Bash(`git add ${filesModified.join(' ')}`) + + const commitType = { + fix: 'fix', refactor: 'refactor', feature: 'feat', + enhancement: 'feat', testing: 'test', infrastructure: 'chore' + }[task.type] || 'chore' + + const scope = inferScope(filesModified) + + Bash(`git commit -m "$(cat <<'EOF' +${commitType}(${scope}): ${task.title} + +Task: ${task.id} +Source: ${path.basename(planPath)} +EOF +)"`) + + appendToEvents(`**Commit**: \`${commitType}(${scope}): ${task.title}\`\n`) +} +``` + +--- + +## Phase 4: Completion + +**Objective**: Finalize all artifacts, write back execution state, offer follow-up actions. + +### Step 4.1: Finalize execution.md + +Append summary statistics to execution.md: + +```javascript +const summary = ` +## Execution Summary + +- **Completed**: ${getUtc8ISOString()} +- **Total Tasks**: ${tasks.length} +- **Succeeded**: ${completedTasks.size} +- **Failed**: ${failedTasks.size} +- **Skipped**: ${skippedTasks.size} +- **Success Rate**: ${Math.round(completedTasks.size / tasks.length * 100)}% + +### Task Results + +| ID | Title | Status | Convergence | Files Modified | +|----|-------|--------|-------------|----------------| +${tasks.map(t => { + const ex = t._execution || {} + const convergenceStatus = ex.result?.convergence_verified + ? `${ex.result.convergence_verified.filter(v => v).length}/${ex.result.convergence_verified.length}` + : '-' + return `| ${t.id} | ${t.title} | ${ex.status || 'pending'} | ${convergenceStatus} | ${(ex.result?.files_modified || []).join(', ') || '-'} |` +}).join('\n')} + +${failedTasks.size > 0 ? `### Failed Tasks + +${[...failedTasks].map(id => { + const t = tasks.find(t => t.id === id) + return `- **${t.id}**: ${t.title} — ${t._execution?.result?.error || 'Unknown'}` +}).join('\n')} +` : ''} ### Artifacts -Plan: {plan path} - -### Project Guidelines -@{projectRoot}/.workflow/project-guidelines.json - -Complete each task according to its "Done when" checklist. +- **Plan Source**: ${planPath} +- **Execution Overview**: ${sessionFolder}/execution.md +- **Execution Events**: ${sessionFolder}/execution-events.md +` +// Append to execution.md ``` -#### Option A: Agent Execution +### Step 4.2: Finalize execution-events.md -**When to use**: `getTaskExecutor(task) === "agent"`, or global `executionMethod = "Agent"`, or `Auto AND complexity = Low` +```javascript +appendToEvents(` +--- -**Execution Flow**: +# Session Summary -``` -1. Spawn code-developer agent with prompt: - ├─ MANDATORY FIRST STEPS: - │ ├─ Read: ~/.codex/agents/code-developer.md - │ ├─ Read: {projectRoot}/.workflow/project-tech.json - │ ├─ Read: {projectRoot}/.workflow/project-guidelines.json - │ └─ Read: {exploration_log_refined} (execution-relevant context) - └─ Body: {buildExecutionPrompt(batch)} - -2. Wait for completion (timeout: 10 minutes) - -3. Close agent after collection - -4. Collect result → executionResult structure +- **Session**: ${sessionId} +- **Completed**: ${getUtc8ISOString()} +- **Tasks**: ${completedTasks.size} completed, ${failedTasks.size} failed, ${skippedTasks.size} skipped +- **Total Events**: ${completedTasks.size + failedTasks.size + skippedTasks.size} +`) ``` -#### Option B: CLI Execution (Codex) +### Step 4.3: Write Back tasks.jsonl with _execution -**When to use**: `getTaskExecutor(task) === "codex"`, or global `executionMethod = "Codex"`, or `Auto AND complexity = Medium/High` +Update the source JSONL file with execution states: -**Execution**: - -```bash -ccw cli -p "{buildExecutionPrompt(batch)}" --tool codex --mode write --id {sessionId}-{groupId} +```javascript +const updatedJsonl = tasks.map(task => JSON.stringify(task)).join('\n') +Write(planPath, updatedJsonl) +// Each task now has _execution: { status, executed_at, result } ``` -**Fixed ID Pattern**: `{sessionId}-{groupId}` (e.g., `implement-auth-2025-12-13-P1`) - -**Execution Mode**: Background (`run_in_background=true`) → Stop output → Wait for task hook callback - -**Resume on Failure**: - -``` -If status = failed or timeout: -├─ Display: Fixed ID, lookup command, resume command -├─ Lookup: ccw cli detail {fixedExecutionId} -└─ Resume: ccw cli -p "Continue tasks" --resume {fixedExecutionId} --tool codex --mode write --id {fixedExecutionId}-retry -``` - -#### Option C: CLI Execution (Gemini) - -**When to use**: `getTaskExecutor(task) === "gemini"` (analysis tasks) - -```bash -ccw cli -p "{buildExecutionPrompt(batch)}" --tool gemini --mode analysis --id {sessionId}-{groupId} -``` - -### Step 4: Progress Tracking - -Progress tracked at **batch level** (not individual task level). - -| Icon | Meaning | -|------|---------| -| ⚡ | Parallel batch (concurrent execution) | -| → | Sequential batch (one-by-one execution) | - -### Step 5: Code Review (Optional) - -**Skip Condition**: Only run if `codeReviewTool ≠ "Skip"` - -**Review Focus**: Verify implementation against plan acceptance criteria and verification requirements. - -**Review Criteria**: -- **Acceptance Criteria**: Verify each criterion from plan.tasks[].acceptance -- **Verification Checklist** (Medium/High): Check unit_tests, integration_tests, success_metrics from plan.tasks[].verification -- **Code Quality**: Analyze quality, identify issues, suggest improvements -- **Plan Alignment**: Validate implementation matches planned approach and risk mitigations - -**Shared Review Prompt Template**: - -``` -PURPOSE: Code review for implemented changes against plan acceptance criteria and verification requirements -TASK: • Verify plan acceptance criteria fulfillment • Check verification requirements (unit tests, success metrics) • Analyze code quality • Identify issues • Suggest improvements • Validate plan adherence and risk mitigations -MODE: analysis -CONTEXT: @**/* @{plan.json} [@{exploration.json}] | Memory: Review lite-execute changes against plan requirements including verification checklist -EXPECTED: Quality assessment with: - - Acceptance criteria verification (all tasks) - - Verification checklist validation (Medium/High: unit_tests, integration_tests, success_metrics) - - Issue identification - - Recommendations - Explicitly check each acceptance criterion and verification item from plan.json tasks. -CONSTRAINTS: Focus on plan acceptance criteria, verification requirements, and plan adherence | analysis=READ-ONLY -``` - -**Tool-Specific Execution**: - -| Tool | Command | Notes | -|------|---------|-------| -| Agent Review | Direct review by current agent | Read plan.json, apply review criteria, report findings | -| Gemini Review | `ccw cli -p "[review prompt]" --tool gemini --mode analysis` | Recommended | -| Qwen Review | `ccw cli -p "[review prompt]" --tool qwen --mode analysis` | Alternative | -| Codex Review (A) | `ccw cli -p "[review prompt]" --tool codex --mode review` | Complex reviews with focus areas | -| Codex Review (B) | `ccw cli --tool codex --mode review --uncommitted` | Quick review, no custom prompt | - -> **IMPORTANT**: `-p` prompt and target flags (`--uncommitted`/`--base`/`--commit`) are **mutually exclusive** for codex review. - -**Multi-Round Review**: Generate fixed review ID (`{sessionId}-review`). If issues found, resume with follow-up: - -```bash -ccw cli -p "Clarify the security concerns" --resume {reviewId} --tool gemini --mode analysis --id {reviewId}-followup -``` - -**Implementation Note**: Replace `[review prompt]` placeholder with actual Shared Review Prompt Template content, substituting: -- `@{plan.json}` → `@{executionContext.session.artifacts.plan}` -- `[@{exploration.json}]` → exploration files from artifacts (if exists) - -### Step 6: Update Development Index - -**Trigger**: After all executions complete (regardless of code review) - -**Skip Condition**: Skip if `{projectRoot}/.workflow/project-tech.json` does not exist - -**Operations**: - -``` -1. Read {projectRoot}/.workflow/project-tech.json - └─ If not found → silent skip - -2. Initialize development_index if missing - └─ Categories: feature, enhancement, bugfix, refactor, docs - -3. Detect category from task keywords: - ├─ fix/bug/error/issue/crash → bugfix - ├─ refactor/cleanup/reorganize → refactor - ├─ doc/readme/comment → docs - ├─ add/new/create/implement → feature - └─ (default) → enhancement - -4. Detect sub_feature from task file paths - └─ Extract parent directory names, return most frequent - -5. Create entry: - ├─ title: plan summary (max 60 chars) - ├─ sub_feature: detected from file paths - ├─ date: current date (YYYY-MM-DD) - ├─ description: plan approach (max 100 chars) - ├─ status: "completed" if all results completed, else "partial" - └─ session_id: from executionContext - -6. Append entry to development_index[category] -7. Update statistics.last_updated timestamp -8. Write updated project-tech.json -``` - -## Best Practices - -**Input Modes**: In-memory (planning phase), prompt (standalone), file (JSON/text) -**Task Grouping**: Based on explicit depends_on only; independent tasks run in single parallel batch -**Execution**: All independent tasks launch concurrently via single Claude message with multiple tool calls - -## Error Handling - -| Error | Cause | Resolution | -|-------|-------|------------| -| Missing executionContext | --in-memory without context | Error: "No execution context found. Only available when called by planning phase." | -| 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, use fixed ID `{sessionId}-{groupId}` for resume | -| Execution timeout | CLI exceeded timeout | Use fixed ID for resume with extended timeout | -| Codex unavailable | Codex not installed | Show installation instructions, offer Agent execution | -| Fixed ID not found | Custom ID lookup failed | Check `ccw cli history`, verify date directories | - -## Data Structures - -### executionContext (Input - Mode 1) - -Passed from planning phase via global variable: +**_execution State** (added to each task): ```javascript { - projectRoot: string, // 项目根目录绝对路径 (git rev-parse --show-toplevel || pwd) - planObject: { - summary: string, - approach: string, - tasks: [...], - estimated_time: string, - recommended_execution: string, - complexity: string - }, - explorationsContext: {...} | null, // Multi-angle explorations - explorationAngles: string[], // List of exploration angles - explorationManifest: {...} | null, // Exploration manifest - clarificationContext: {...} | null, - executionMethod: "Agent" | "Codex" | "Auto", // Global default - codeReviewTool: "Skip" | "Gemini Review" | "Agent Review" | string, - originalUserInput: string, - - // Task-level executor assignments (priority over executionMethod) - executorAssignments: { - [taskId]: { executor: "gemini" | "codex" | "agent", reason: string } - }, - - // Session artifacts location (saved by planning phase) - session: { - id: string, // Session identifier: {taskSlug}-{shortTimestamp} - folder: string, // Session folder path: {projectRoot}/.workflow/.lite-plan/{session-id} - artifacts: { - explorations: [{angle, path}], // exploration-{angle}.json paths - explorations_manifest: string, // explorations-manifest.json path - exploration_log: string, // exploration-notes.md (full version, Plan consumption) - exploration_log_refined: string, // exploration-notes-refined.md (refined version, Execute consumption) - plan: string // plan.json path (always present) + // ... original task fields ... + _execution: { + status: "completed" | "failed" | "skipped", + executed_at: "ISO timestamp", + result: { + success: boolean, + files_modified: string[], // list of modified file paths + summary: string, // change description + convergence_verified: boolean[], // per criterion + error: string // if failed } } } ``` -**Artifact Usage**: -- **exploration_log**: Full exploration notes, for Plan phase reference, contains 6 sections -- **exploration_log_refined**: Refined exploration notes, for Execute phase consumption, task-relevant content only -- Pass artifact paths to CLI tools and agents for enhanced context -- See execution options above for usage examples - -### executionResult (Output) - -Collected after each execution call completes: +### Step 4.4: Post-Completion Options ```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 - fixedCliId: string | null // Fixed CLI execution ID (e.g., "implement-auth-2025-12-13-P1") -} +AskUserQuestion({ + questions: [{ + question: `Execution complete: ${completedTasks.size}/${tasks.length} succeeded (${Math.round(completedTasks.size / tasks.length * 100)}%).\nNext step:`, + header: "Post-Execute", + multiSelect: false, + options: [ + { label: "Retry Failed", description: `Re-execute ${failedTasks.size} failed tasks` }, + { label: "View Events", description: "Display execution-events.md" }, + { label: "Create Issue", description: "Create issue from failed tasks" }, + { label: "Done", description: "End workflow" } + ] + }] +}) ``` -Appended to `previousExecutionResults` array for context continuity in multi-execution scenarios. - -## Post-Completion Expansion - -After completion, ask user whether to expand as issue (test/enhance/refactor/doc). Selected items create new issues accordingly. - -**Fixed ID Pattern**: `{sessionId}-{groupId}` enables predictable lookup without auto-generated timestamps. - -**Resume Usage**: If `status` is "partial" or "failed", use `fixedCliId` to resume: - -```bash -# Lookup previous execution -ccw cli detail {fixedCliId} - -# Resume with new fixed ID for retry -ccw cli -p "Continue from where we left off" --resume {fixedCliId} --tool codex --mode write --id {fixedCliId}-retry -``` +| Selection | Action | +|-----------|--------| +| Retry Failed | Filter tasks with `_execution.status === 'failed'`, re-execute, append `[RETRY]` events | +| View Events | Display execution-events.md content | +| Create Issue | `$issue:new` from failed task details | +| Done | Display artifact paths, end workflow | --- -## Post-Phase Update +## Error Handling & Recovery -After Phase 2 (Lite Execute) completes: -- **Output Created**: Executed tasks, optional code review results, updated development index -- **Execution Results**: `previousExecutionResults[]` with status per batch -- **Next Action**: Workflow complete. Optionally expand to issue (test/enhance/refactor/doc) -- **TodoWrite**: Mark all execution batches as completed +| Situation | Action | Recovery | +|-----------|--------|----------| +| JSONL file not found | Report error with path | Check path, verify planning phase output | +| Invalid JSON line | Report line number and error | Fix JSONL file manually | +| Missing convergence | Report validation error | Add convergence fields to tasks | +| Circular dependency | Stop, report cycle path | Fix dependencies in JSONL | +| Task execution fails | Record in events, ask user | Retry, skip, accept, or abort | +| Convergence verification fails | Mark task failed, ask user | Fix code and retry, or accept | +| Verification command timeout | Mark as unverified | Manual verification needed | +| File conflict during execution | Document in events | Resolve in dependency order | +| All tasks fail | Report, suggest plan review | Re-analyze or manual intervention | + +--- + +## Post-Completion + +After execution completes, the workflow is finished. + +- **TodoWrite**: Mark "Execution (unified-execute)" as completed +- **Summary**: Display execution statistics (succeeded/failed/skipped counts) +- **Artifacts**: Point user to execution.md and execution-events.md paths