refactor: rewrite workflow-lite-plan-execute to serial CLI exploration with unified JSONL output

- Remove agent delegation (spawn_agent/wait/send_input/close_agent), all phases serial inline
- Replace parallel agent exploration with serial ccw cli calls (gemini/claude)
- Add search verification after each CLI exploration (ACE/Grep/Glob)
- Change output from plan.json/executionContext to tasks.jsonl (unified JSONL)
- Output format now compatible with collaborative-plan-with-file
- Replace custom execution engine with unified-execute-with-file delegation
- Copy full execution spec inline (no external references)
- Use $ prefix for codex skill invocations
This commit is contained in:
catlog22
2026-02-09 14:59:16 +08:00
parent 752d98ba5a
commit ef7382ecf5
3 changed files with 900 additions and 822 deletions

View File

@@ -1,19 +1,20 @@
--- ---
name: workflow-lite-plan-execute name: workflow-lite-plan-execute
description: Lightweight planning + execution workflow. Exploration -> Clarification -> Planning -> Confirmation -> Execution (via lite-execute). description: Lightweight planning + execution workflow. Serial CLI exploration → Search verification → Clarification Planning → Unified JSONL output → Execution via unified-execute.
allowed-tools: spawn_agent, wait, send_input, close_agent, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context allowed-tools: AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context
--- ---
# Planning Workflow # 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 ## Key Design Principles
1. **Shared Execution**: Lite Plan produces `executionContext` consumed by Phase 2 (Lite Execute) 1. **Serial Execution**: All phases execute serially inline, no agent delegation
2. **Progressive Phase Loading**: Only load phase docs when about to execute 2. **CLI Exploration**: Multi-angle codebase exploration via `ccw cli` calls (default gemini, fallback claude)
3. **Auto-Continue**: After the plan is confirmed ("Allow"), automatically load execution phase 3. **Search Verification**: Verify CLI findings with ACE search / Grep / Glob before incorporating
4. **Default Auto Mode**: When `--yes`, skip confirmations and auto-approve the plan 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 ## Auto Mode
@@ -42,14 +43,14 @@ $workflow-lite-plan-execute -e "Refactor payment module"
$workflow-lite-plan-execute "docs/todo.md" $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 Reference Documents (Read On Demand)
| Phase | Document | Purpose | | Phase | Document | Purpose |
|-------|----------|---------| |-------|----------|---------|
| 1 | `phases/01-lite-plan.md` | Lightweight planning with exploration, clarification, plan generation, and confirmation | | 1 | `phases/01-lite-plan.md` | Serial CLI exploration, clarification, plan generation → tasks.jsonl |
| 2 | `phases/02-lite-execute.md` | Shared execution engine: task grouping, batch execution, optional code review | | 2 | `phases/02-lite-execute.md` | Handoff to unified-execute-with-file for task execution |
## Orchestrator Logic ## Orchestrator Logic
@@ -71,47 +72,76 @@ function extractTaskDescription(args) {
const taskDescription = extractTaskDescription($ARGUMENTS) const taskDescription = extractTaskDescription($ARGUMENTS)
// Phase 1: Lite Plan // Phase 1: Lite Plan → tasks.jsonl
Read('phases/01-lite-plan.md') Read('phases/01-lite-plan.md')
// Execute planning phase... // Execute planning phase...
// Gate: only continue when confirmed (or --yes) // 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 // Stop: user cancelled or requested modifications
return return
} }
// Phase 2: Lite Execute // Phase 2: Handoff to unified-execute-with-file
Read('phases/02-lite-execute.md') 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 ```javascript
{ {
projectRoot: string, // 项目根目录绝对路径 (git rev-parse --show-toplevel || pwd) id: "TASK-001",
planObject: { summary, approach, tasks, complexity, estimated_time, recommended_execution }, title: string,
originalUserInput: string, description: string,
executionMethod: "Agent" | "Codex" | "Auto", type: "feature|fix|refactor|enhancement|testing|infrastructure",
codeReviewTool: "Skip" | "Gemini Review" | "Codex Review" | "Agent Review" | string, priority: "high|medium|low",
userSelection: { confirmation: "Allow" | "Modify" | "Cancel" } 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 ## TodoWrite Pattern
Initialization: Initialization:
```json ```json
[ [
{"content": "Lite Plan - Planning", "status": "in_progress", "activeForm": "Planning"}, {"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 ```json
[ [
{"content": "Lite Plan - Planning", "status": "completed", "activeForm": "Planning"}, {"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 ## Core Rules
1. **Planning phase NEVER modifies project code** - it may write planning artifacts, but all implementation is delegated to Phase 2 1. **Planning phase NEVER modifies project code** it may write planning artifacts, but all implementation is delegated to unified-execute
2. **Phase 2 runs only after confirmation** - execute only when confirmation is "Allow" (or `--yes` auto mode) 2. **All phases serial, no agent delegation** everything runs inline, no spawn_agent
3. **executionContext is the contract** between planning and execution phases 3. **CLI exploration with search verification** — CLI calls produce findings, ACE/Grep/Glob verify them
4. **Progressive loading**: Read phase doc only when about to execute 4. **tasks.jsonl is the output contract** — unified JSONL format passed to unified-execute-with-file
5. **File-path detection**: Treat input as a file path only if the path exists; do not infer from file extensions 5. **Progressive loading**: Read phase doc only when about to execute
6. **Explicit lifecycle**: Always `close_agent` after `wait` completes 6. **File-path detection**: Treat input as a file path only if the path exists; do not infer from file extensions
## Error Handling ## Error Handling
| Error | Resolution | | Error | Resolution |
|-------|------------| |-------|------------|
| CLI exploration failure | Skip angle, continue with remaining; fallback gemini → claude |
| Planning phase failure | Display error, offer retry | | 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 | | Phase file not found | Error with file path for debugging |
## Related Skills ## 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` - Full planning workflow: `../workflow-plan-execute/SKILL.md`
- Brainstorming: `../workflow-brainstorm-auto-parallel/SKILL.md`

View File

@@ -2,15 +2,15 @@
## Overview ## 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:** **Core capabilities:**
- Intelligent task analysis with automatic exploration detection - 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 - Interactive clarification after exploration to gather missing information
- Adaptive planning: Low complexity → Direct Claude; Medium/High → cli-lite-planning-agent - Direct planning by Claude (all complexity levels, no agent delegation)
- Two-step confirmation: plan display → multi-dimensional input collection - Unified JSONL output (`tasks.jsonl`) with convergence criteria
- Execution handoff with complete context to lite-execute
## Parameters ## Parameters
@@ -24,28 +24,20 @@ Intelligent lightweight planning command with dynamic workflow adaptation based
| Artifact | Description | | 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 | | `explorations-manifest.json` | Index of all exploration files |
| `exploration-notes.md` | Full exploration log (consumed by Plan phase, 6 sections) | | `exploration-notes.md` | Synthesized exploration notes (all angles combined) |
| `exploration-notes-refined.md` | Refined exploration log (consumed by Execute phase, task-relevant only) | | `requirement-analysis.json` | Complexity assessment and session metadata |
| `planning-context.md` | Evidence paths + synthesized understanding | | `tasks.jsonl` | ⭐ Unified JSONL (collaborative-plan-with-file compatible) |
| `plan.json` | Structured implementation plan (plan-json-schema.json) | | `plan.md` | Human-readable summary with execution command |
**Output Directory**: `{projectRoot}/.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/` **Output Directory**: `{projectRoot}/.workflow/.lite-plan/{session-id}/`
**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`
## Auto Mode Defaults ## Auto Mode Defaults
When `--yes` or `-y` flag is used: When `--yes` or `-y` flag is used:
- **Clarification Questions**: Skipped (no clarification phase) - **Clarification Questions**: Skipped (no clarification phase)
- **Plan Confirmation**: Auto-selected "Allow" - **Plan Confirmation**: Auto-selected "Allow"
- **Execution Method**: Auto-selected "Auto"
- **Code Review**: Auto-selected "Skip"
**Flag Parsing**: **Flag Parsing**:
```javascript ```javascript
@@ -60,38 +52,33 @@ Phase 1: Task Analysis & Exploration
├─ Parse input (description or .md file) ├─ Parse input (description or .md file)
├─ Intelligent complexity assessment (Low/Medium/High) ├─ Intelligent complexity assessment (Low/Medium/High)
├─ Exploration decision (auto-detect or --explore flag) ├─ Exploration decision (auto-detect or --explore flag)
├─ Context protection: If file reading ≥50k chars → force cli-explore-agent
└─ Decision: └─ 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 └─ needsExploration=false → Skip to Phase 2/3
Phase 2: Clarification (optional, multi-round) Phase 2: Clarification (optional, multi-round)
├─ Aggregate clarification_needs from all exploration angles ├─ Extract clarification needs from exploration results
├─ Deduplicate similar questions ├─ Deduplicate similar questions
└─ Decision: └─ ASK_USER (max 4 questions per round, multiple rounds)
├─ Has clarifications → ASK_USER (max 4 questions per round, multiple rounds allowed)
└─ No clarifications → Skip to Phase 3
Phase 3: Planning (NO CODE EXECUTION - planning only) Phase 3: Planning → tasks.jsonl (NO CODE EXECUTION)
Decision (based on Phase 1 complexity): Load exploration notes + clarifications + project context
├─ Low → Load schema: cat ~/.ccw/workflows/cli-templates/schemas/plan-json-schema.json → Direct Claude planning (following schema) → plan.json ├─ Direct Claude planning (following unified JSONL schema)
└─ Medium/High → cli-lite-planning-agent → plan.json (agent internally executes quality check) ├─ Generate tasks.jsonl (one task per line)
└─ Generate plan.md (human-readable summary)
Phase 4: Confirmation & Selection Phase 4: Confirmation
├─ Display plan summary (tasks, complexity, estimated time) ├─ Display plan summary (tasks, complexity, dependencies)
└─ ASK_USER: └─ ASK_USER: Allow / Modify / Cancel
├─ Confirm: Allow / Modify / Cancel
├─ Execution: Agent / Codex / Auto
└─ Review: Gemini / Agent / Skip
Phase 5: Execute Phase 5: Handoff
Build executionContext (plan + explorations + clarifications + selections) → unified-execute-with-file with tasks.jsonl
└─ → Hand off to Phase 2: Lite Execute (phases/02-lite-execute.md) --in-memory
``` ```
## Implementation ## Implementation
### Phase 1: Intelligent Multi-Angle Exploration ### Phase 1: Serial CLI Exploration with Search Verification
#### Session Setup (MANDATORY) #### 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). 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 #### 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 **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:
``` ```bash
1. Spawn agents ccw cli -p "PURPOSE: Explore codebase from {angle} perspective for task planning context; success = actionable findings with file:line references verified against actual code
└─ For each selected angle → create cli-explore-agent with Agent Prompt (below) 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
2. Batch wait CONTEXT: @**/* | Memory: Task: {task_description}
└─ Wait for ALL agents (timeout: 10 minutes) 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
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
``` ```
**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) Verification rules:
1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first) ├─ File exists? → Mark as ✅ verified
2. Read: {projectRoot}/.workflow/project-tech.json ├─ File not found? → Mark as ⚠️ unverified, note in output
3. Read: {projectRoot}/.workflow/project-guidelines.json ├─ 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 ## Findings
Execute **{angle}** exploration for task planning context. Analyze codebase from this specific angle to discover relevant structure, patterns, and constraints.
## Output Location ### Project Structure
{verified structure relevant to this angle}
**Session Folder**: {sessionFolder} ### Relevant Files
**Output File**: {sessionFolder}/exploration-{angle}.json
## Assigned Context | File | Relevance | Rationale | Verified |
- **Exploration Angle**: {angle} |------|-----------|-----------|----------|
- **Task Description**: {task_description} | `src/auth/login.ts` | high | Core authentication logic | ✅ |
- **Exploration Index**: {index} of {total} | `src/middleware/auth.ts` | medium | Auth middleware chain | ✅ |
## MANDATORY STEPS (Execute by Agent) ### Patterns
**You (cli-explore-agent) MUST execute these steps in order:** {verified patterns with actual code examples from codebase}
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)
## Exploration Strategy ({angle} focus) ### Integration Points
{verified integration points with file:line references}
**Step 1: Structural Scan** (Bash) ### Dependencies
- get_modules_by_depth.sh → identify modules related to {angle} {verified dependency relationships}
- find/rg → locate files relevant to {angle} aspect
- Analyze imports/dependencies from {angle} perspective
**Step 2: Semantic Analysis** (Gemini CLI) ### Constraints
- How does existing code handle {angle} concerns? {angle-specific constraints discovered}
- What patterns are used for {angle}?
- Where would new code integrate from {angle} viewpoint?
**Step 3: Write Output** ### Clarification Needs
- Consolidate {angle} findings into JSON {questions that need user input, with suggested options}
- 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
``` ```
#### Auto-discover & Manifest Generation **Write**: `{sessionFolder}/exploration-{angle}.md`
After explorations complete: #### Manifest Generation
1. **Discover** — Find all `exploration-*.json` files in session folder After all angle explorations complete:
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
**Output**: 1. **Build manifest** — Create `explorations-manifest.json`:
- `{sessionFolder}/exploration-{angle1}.json` ```javascript
- `{sessionFolder}/exploration-{angle2}.json` {
- ... (1-4 files based on complexity) session_id: sessionId,
- `{sessionFolder}/explorations-manifest.json` 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 #### Generate Exploration Notes
Auto-generated after exploration completes. Synthesize all exploration Markdown files into a unified notes document.
**Steps**: **Steps**:
1. **Load** all exploration JSON files via manifest 1. **Load** all exploration Markdown files via manifest
2. **Extract core files**Filter `relevant_files` with relevance ≥ 0.7, sort by relevance descending, deduplicate by path 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) 3. **Build exploration notes** — 6-part Markdown document (structure below)
4. **Write** to `{sessionFolder}/exploration-notes.md` 4. **Write** to `{sessionFolder}/exploration-notes.md`
@@ -306,45 +281,39 @@ Auto-generated after exploration completes.
## Part 1: Multi-Angle Exploration Summary ## Part 1: Multi-Angle Exploration Summary
Per angle: Key Files (priority sorted), Code Patterns, Integration Points, Dependencies, Constraints Per angle: Key Files (priority sorted), Code Patterns, Integration Points, Dependencies, Constraints
## Part 2: File Deep-Dive Summary ## Part 2: Core Files Index
Top 10 core files: read content, find cross-references via rg, format structural details Top 10 files across all angles, with cross-references and structural details
## Part 3: Architecture Reasoning Chains ## Part 3: Architecture Reasoning
Synthesized from exploration findings and task description Synthesized architectural insights from all angles
## Part 4: Potential Risks and Mitigations ## Part 4: Risks and Mitigations
Derived from explorations and core file analysis Derived from explorations and core file analysis
## Part 5: Clarification Questions Summary ## Part 5: Clarification Questions Summary
Aggregated from all exploration angles Aggregated from all exploration angles, deduplicated
## Part 6: Execution Recommendations Checklist ## Part 6: Key Code Location Index
Generated from task description, explorations, and core files
---
## Appendix: Key Code Location Index
| Component | File Path | Key Lines | Purpose | | Component | File Path | Key Lines | Purpose |
|-----------|-----------|-----------|---------|
``` ```
**Output**: `{sessionFolder}/exploration-notes.md` (full version, consumed by Plan phase)
--- ---
### Phase 2: Clarification (Optional, Multi-Round) ### 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. **⚠️ 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**: **Flow**:
``` ```
1. Load manifest + all exploration files 1. Load all exploration Markdown files
2. Aggregate clarification_needs 2. Extract clarification needs
└─ For each exploration → collect needs, tag each with source_angle └─ For each exploration → collect "Clarification Needs" section items
3. Deduplicate 3. Deduplicate
└─ Intelligent merge: identify similar intent across angles └─ 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 ├─ Batch size: 4 questions per round
├─ Per round: display "Round N/M", present via ASK_USER ├─ Per round: display "Round N/M", present via ASK_USER
│ └─ Each question: [source_angle] question + context │ └─ Each question: [source_angle] question + context
│ Options with recommended marked ★
├─ Store responses in clarificationContext after each round ├─ Store responses in clarificationContext after each round
└─ Repeat until all questions exhausted └─ 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 #### Step 3.2: Generate requirement-analysis.json
2. **Default** → agent
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` Direct Claude planning — synthesize exploration findings and clarifications into unified JSONL tasks:
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 **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 ```javascript
{ {
summary: "...", id: "TASK-001", // Padded 3-digit ID
approach: "...", title: "...",
tasks: [...], // Each: { id, title, scope, ..., depends_on, execution_group, complexity } description: "...", // Scope/goal + implementation approach
estimated_time: "...", type: "feature", // feature|infrastructure|enhancement|fix|refactor|testing
recommended_execution: "Agent", priority: "medium", // high|medium|low
complexity: "Low", effort: "medium", // small|medium|large
_metadata: { timestamp, source: "direct-planning", planning_mode: "direct" } 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` **Write tasks.jsonl**:
5. **Continue** to Phase 4 (Confirmation) — DO NOT execute code here ```javascript
const jsonlContent = tasks.map(t => JSON.stringify(t)).join('\n')
#### Medium/High Complexity — Invoke cli-lite-planning-agent Write(`${sessionFolder}/tasks.jsonl`, jsonlContent)
**Orchestration**:
```
1. Spawn planning agent → with Agent Prompt (below)
2. Wait for completion → timeout: 15 minutes
3. Close agent → after completion
``` ```
**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. ### Phase 4: Task Confirmation
## 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
#### Step 4.1: Display Plan #### Step 4.1: Display Plan
Read `{sessionFolder}/plan.json` and display summary: Read `{sessionFolder}/tasks.jsonl` and display summary:
- **Summary**: plan.summary - **Summary**: Overall approach (from requirement understanding)
- **Approach**: plan.approach - **Tasks**: Numbered list with ID, title, type, effort
- **Tasks**: numbered list with title and file - **Complexity**: Assessment result
- **Complexity**: plan.complexity - **Total tasks**: Count
- **Estimated Time**: plan.estimated_time - **Dependencies**: Graph overview
- **Recommended**: plan.recommended_execution
#### Step 4.2: Collect Confirmation #### Step 4.2: Collect Confirmation
**Route by mode**: **Route by mode**:
``` ```
├─ --yes mode → Auto-confirm with defaults: ├─ --yes mode → Auto-confirm:
─ Confirmation: "Allow" ─ Confirmation: "Allow"
│ ├─ Execution: "Auto"
│ └─ Review: "Skip"
└─ 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 | **Modify Loop**: If "Modify" selected, display current tasks.jsonl content, accept user edits (max 3 rounds), regenerate plan.md, re-confirm.
|----------|---------|---------|
| 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 }`
--- ---
### Phase 5: Handoff to Execution ### 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 → Hand off to Phase 2: `phases/02-lite-execute.md` which invokes `unified-execute-with-file`
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
## Session Folder Structure ## Session Folder Structure
``` ```
{projectRoot}/.workflow/.lite-plan/{task-slug}-{YYYY-MM-DD}/ {projectRoot}/.workflow/.lite-plan/{session-id}/
├── exploration-{angle1}.json # Exploration angle 1 ├── exploration-{angle1}.md # CLI exploration angle 1
├── exploration-{angle2}.json # Exploration angle 2 ├── exploration-{angle2}.md # CLI exploration angle 2
├── exploration-{angle3}.json # Exploration angle 3 (if applicable) ├── exploration-{angle3}.md # (if applicable)
├── exploration-{angle4}.json # Exploration angle 4 (if applicable) ├── exploration-{angle4}.md # (if applicable)
├── explorations-manifest.json # Exploration index ├── explorations-manifest.json # Exploration index
├── exploration-notes.md # Full exploration notes (Plan phase consumption) ├── exploration-notes.md # Synthesized exploration notes
├── exploration-notes-refined.md # Refined exploration notes (Execute phase consumption) ├── requirement-analysis.json # Complexity assessment
── plan.json # Implementation plan ── tasks.jsonl # ⭐ Unified JSONL output
└── plan.md # Human-readable summary
``` ```
**Example**: **Example**:
``` ```
{projectRoot}/.workflow/.lite-plan/implement-jwt-refresh-2025-11-25-14-30-25/ {projectRoot}/.workflow/.lite-plan/implement-jwt-refresh-2025-11-25/
├── exploration-architecture.json ├── exploration-patterns.md
├── exploration-auth-patterns.json ├── exploration-integration-points.md
├── exploration-security.json ├── exploration-testing.md
├── explorations-manifest.json ├── explorations-manifest.json
── plan.json ── exploration-notes.md
├── requirement-analysis.json
├── tasks.jsonl
└── plan.md
``` ```
## Error Handling ## Error Handling
| Error | Resolution | | Error | Resolution |
|-------|------------| |-------|------------|
| Exploration agent failure | Skip exploration, continue with task description only | | CLI exploration failure | Skip angle, continue with remaining; fallback gemini → claude |
| Planning agent failure | Fallback to direct planning by 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 | | Clarification timeout | Use exploration findings as-is |
| Confirmation timeout | Save context, display resume instructions | | Confirmation timeout | Save artifacts, display resume instructions |
| Modify loop > 3 times | Suggest breaking task or using full planning workflow (workflow-plan-execute/SKILL.md) | | Modify loop > 3 times | Suggest using full planning workflow (workflow-plan-execute/SKILL.md) |
--- ---
## Post-Phase Update ## Post-Phase Update
After Phase 1 (Lite Plan) completes: 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}/` - **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 - **Next Action**: Auto-continue to [Phase 2: Execution Handoff](02-lite-execute.md)
- **TodoWrite**: Mark "Lite Plan - Planning" as completed, start "Execution (Phase 2)" - **TodoWrite**: Mark "Lite Plan - Planning" as completed, start "Execution (unified-execute)"