feat: add exploration and plan JSON schemas for task context and planning

This commit is contained in:
catlog22
2025-11-24 21:57:19 +08:00
parent 481a716c09
commit 19acaea0f9
3 changed files with 377 additions and 534 deletions

View File

@@ -21,7 +21,6 @@ Intelligent lightweight planning command with dynamic workflow adaptation based
## Usage ## Usage
### Command Syntax
```bash ```bash
/workflow:lite-plan [FLAGS] <TASK_DESCRIPTION> /workflow:lite-plan [FLAGS] <TASK_DESCRIPTION>
@@ -32,24 +31,8 @@ Intelligent lightweight planning command with dynamic workflow adaptation based
<task-description> Task description or path to .md file (required) <task-description> Task description or path to .md file (required)
``` ```
### Input Requirements
- **Task description**: String or path to .md file (required)
- Should be specific and concrete
- Can include context about existing code or requirements
- Examples:
- "Implement user authentication with JWT tokens"
- "Refactor logging module for better performance"
- "Add unit tests for authentication service"
- **Flags** (optional):
- `-e` or `--explore`: Force exploration when:
- Task appears simple but requires codebase context
- Auto-detection might miss integration points
- Comprehensive code understanding needed before planning
## Execution Process ## Execution Process
### Workflow Overview
``` ```
User Input → Task Analysis & Exploration Decision (Phase 1) User Input → Task Analysis & Exploration Decision (Phase 1)
@@ -60,147 +43,99 @@ User Input → Task Analysis & Exploration Decision (Phase 1)
Task Confirmation & Execution Selection (Phase 4) Task Confirmation & Execution Selection (Phase 4)
Dispatch to Execution (Phase 5) Dispatch to Execution (Phase 5)
Planning Complete (lite-execute continues)
``` ```
### Phase Summary ## Implementation
**Phase 1: Task Analysis & Exploration Decision** (10-60 seconds)
- Analyze task to determine exploration needs
- Decision logic: `--explore` flag OR requires codebase context
- If needed: Launch cli-explore-agent for code analysis
- Output: `explorationContext` with relevant files, patterns, constraints
**Phase 2: Clarification** (30-60 seconds, optional)
- Skip if no ambiguities found in Phase 1
- Use exploration findings to generate targeted questions
- AskUserQuestion based on `clarification_needs` from exploration
- Output: `clarificationContext` with user responses
**Phase 3: Complexity Assessment & Planning** (20-60 seconds)
- Assess complexity (Low/Medium/High) from multiple factors
- Strategy selection:
- Low: Direct planning by current Claude (fast, 20-30s)
- Medium/High: Delegate to cli-lite-planning-agent (detailed, 40-60s)
- Output: `planObject` with tasks, time estimates, recommendations
**Phase 4: Task Confirmation & Execution Selection** (user interaction)
- Step 1: Display complete plan as text to user
- Step 2: Collect four inputs via AskUserQuestion:
1. Confirm plan (Allow/Modify/Cancel + supplements via "Other")
2. Execution method (Agent/Codex/Auto)
3. Code review tool (Skip/Gemini/Agent + custom via "Other")
4. Export JSON (Yes/No for Enhanced Task JSON export)
**Phase 5: Dispatch to Execution** (<1 second)
- Export Enhanced Task JSON (optional, if user selected "Yes")
- Store `executionContext` in memory with full plan + context
- Call `/workflow:lite-execute --in-memory`
- Execution tracking delegated to lite-execute
## Detailed Phase Execution
### Phase 1: Task Analysis & Exploration Decision ### Phase 1: Task Analysis & Exploration Decision
**Session Setup**:
```javascript
const taskSlug = task_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40)
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const shortTimestamp = timestamp.substring(0, 19).replace('T', '-')
const sessionId = `${taskSlug}-${shortTimestamp}`
const sessionFolder = `.workflow/.lite-plan/${sessionId}`
bash(`mkdir -p ${sessionFolder}`)
```
**Decision Logic**: **Decision Logic**:
```javascript ```javascript
needsExploration = ( needsExploration = (
flags.includes('--explore') || flags.includes('-e') || // Force if flag present flags.includes('--explore') || flags.includes('-e') ||
( task.mentions_specific_files ||
task.mentions_specific_files || task.requires_codebase_context ||
task.requires_codebase_context || task.needs_architecture_understanding ||
task.needs_architecture_understanding || task.modifies_existing_code
task.modifies_existing_code
)
) )
``` ```
**Decision Criteria**: **If exploration needed** - Invoke cli-explore-agent:
| Task Type | Needs Exploration | Reason |
|-----------|-------------------|--------|
| Any task with `-e`/`--explore` flag | **Yes (forced)** | **Flag overrides auto-detection** |
| "Implement new feature X" | Maybe | Depends on integration needs |
| "Refactor module Y" | Yes | Needs current implementation understanding |
| "Add tests for Z" | Yes | Needs code structure understanding |
| "Create standalone utility" | No | Self-contained, no existing context |
| "Update documentation" | No | Doesn't require code exploration |
| "Fix bug in function F" | Yes | Needs implementation understanding |
**Exploration Execution** (if needed):
```javascript ```javascript
// Generate session identifiers for artifact storage
const taskSlug = task_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40)
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const shortTimestamp = timestamp.substring(0, 19).replace('T', '-') // YYYY-MM-DD-HH-mm-ss
const sessionId = `${taskSlug}-${shortTimestamp}`
const sessionFolder = `.workflow/.lite-plan/${sessionId}`
Task( Task(
subagent_type="cli-explore-agent", subagent_type="cli-explore-agent",
description="Analyze codebase for task context", description="Analyze codebase for task context",
prompt=` prompt=`
Task: ${task_description} Analyze codebase for task context and generate exploration.json.
Analyze and return structured information: ## Output Schema Reference
1. Project Structure: Architecture and module organization ~/.claude/workflows/cli-templates/schemas/explore-json-schema.json
2. Relevant Files: Files to be affected (with paths)
3. Current Patterns: Code patterns, conventions, styles
4. Dependencies: External/internal module dependencies
5. Integration Points: Task connections with existing code
6. Architecture Constraints: Technical limitations/requirements
7. Clarification Needs: Ambiguities requiring user input
Time Limit: 60 seconds ## Task Description
Output Format: JSON-like structured object ${task_description}
`
## Requirements
Generate exploration.json with:
- project_structure: Architecture and module organization
- relevant_files: File paths to be affected
- patterns: Code patterns, conventions, styles
- dependencies: External/internal module dependencies
- integration_points: Task connections with existing code
- constraints: Technical limitations/requirements
- clarification_needs: Ambiguities requiring user input
- _metadata: timestamp, task_description, source
## Execution
1. Structural scan: get_modules_by_depth.sh, find, rg
2. Semantic analysis: Gemini for patterns/architecture
3. Write JSON: Write('${sessionFolder}/exploration.json', jsonContent)
4. Return brief completion summary
Time Limit: 60 seconds
`
) )
// Save exploration results for CLI/agent access in lite-execute
const explorationFile = `${sessionFolder}/exploration.json`
Write(explorationFile, JSON.stringify(explorationContext, null, 2))
``` ```
**Output**: `explorationContext` (in-memory, see Data Structures section) **Output**: `${sessionFolder}/exploration.json` (if exploration performed)
**Artifact**: Saved to `{sessionFolder}/exploration.json` for CLI/agent use
**Progress Tracking**:
- Mark Phase 1 completed
- If `clarification_needs.length > 0`: Mark Phase 2 in_progress
- Else: Skip to Phase 3
--- ---
### Phase 2: Clarification (Optional) ### Phase 2: Clarification (Optional)
**Skip Condition**: Only run if `needsClarification = true` from Phase 1 **Skip if**: No exploration or `clarification_needs` is empty
**Operations**: **If clarification needed**:
- Review `explorationContext.clarification_needs`
- Generate AskUserQuestion from exploration findings
- Focus on ambiguities affecting implementation approach
**Question Generation**:
```javascript ```javascript
AskUserQuestion({ const exploration = JSON.parse(Read(`${sessionFolder}/exploration.json`))
questions: explorationContext.clarification_needs.map(need => ({
question: `${need.context}\n\n${need.question}`, if (exploration.clarification_needs?.length > 0) {
header: "Clarification", AskUserQuestion({
multiSelect: false, questions: exploration.clarification_needs.map(need => ({
options: need.options.map(opt => ({ question: `${need.context}\n\n${need.question}`,
label: opt, header: "Clarification",
description: `Use ${opt} approach` multiSelect: false,
options: need.options.map(opt => ({
label: opt,
description: `Use ${opt} approach`
}))
})) }))
})) })
}) }
``` ```
**Output**: `clarificationContext` in format `{ question_id: selected_answer }` **Output**: `clarificationContext` (in-memory)
**Progress Tracking**:
- Mark Phase 2 completed
- Mark Phase 3 in_progress
--- ---
@@ -209,149 +144,96 @@ AskUserQuestion({
**Complexity Assessment**: **Complexity Assessment**:
```javascript ```javascript
complexityScore = { complexityScore = {
file_count: exploration.files_to_modify.length, file_count: exploration?.relevant_files?.length || 0,
integration_points: exploration.dependencies.length, integration_points: exploration?.dependencies?.length || 0,
architecture_changes: exploration.requires_architecture_change, architecture_changes: exploration?.constraints?.includes('architecture'),
technology_stack: exploration.unfamiliar_technologies.length, task_scope: estimated_steps > 5
task_scope: (task.estimated_steps > 5),
cross_cutting_concerns: exploration.affects_multiple_modules
} }
// Calculate complexity // Low: score < 3, Medium: 3-5, High: > 5
if (complexityScore < 3) complexity = "Low"
else if (complexityScore < 6) complexity = "Medium"
else complexity = "High"
``` ```
**Complexity Levels**: **Low Complexity** - Direct planning by Claude:
- Generate plan directly, write to `${sessionFolder}/plan.json`
- No agent invocation
| Level | Characteristics | Planning Strategy | **Medium/High Complexity** - Invoke cli-lite-planning-agent:
|-------|----------------|-------------------|
| Low | 1-2 files, simple changes, clear requirements | Direct planning (current Claude) |
| Medium | 3-5 files, moderate integration, some ambiguity | cli-lite-planning-agent |
| High | 6+ files, complex architecture, high uncertainty | cli-lite-planning-agent with detailed analysis |
**Option A: Direct Planning (Low Complexity)**
Current Claude generates plan directly:
- Summary: 2-3 sentence overview
- Approach: High-level implementation strategy
- Task Breakdown: 3-5 specific, actionable tasks with file paths
- Estimated Time: Total implementation time
- Recommended Execution: "Agent"
```javascript
// Save planning results to session folder (same as Option B)
const planFile = `${sessionFolder}/plan.json`
Write(planFile, JSON.stringify(planObject, null, 2))
```
**Artifact**: Saved to `{sessionFolder}/plan.json` for CLI/agent use
**Option B: Agent-Based Planning (Medium/High Complexity)**
Delegate to cli-lite-planning-agent:
```javascript ```javascript
Task( Task(
subagent_type="cli-lite-planning-agent", subagent_type="cli-lite-planning-agent",
description="Generate detailed implementation plan", description="Generate detailed implementation plan",
prompt=` prompt=`
## Task Description Generate implementation plan and write plan.json.
${task_description}
## Exploration Context ## Output Schema Reference
${JSON.stringify(explorationContext, null, 2) || "No exploration performed"} ~/.claude/workflows/cli-templates/schemas/plan-json-schema.json
## User Clarifications ## Task Description
${JSON.stringify(clarificationContext, null, 2) || "None provided"} ${task_description}
## Complexity Level ## Exploration Context
${complexity} ${sessionFolder}/exploration.json (if exists)
## Your Task ## User Clarifications
1. Execute CLI planning using Gemini (Qwen fallback) ${JSON.stringify(clarificationContext) || "None"}
2. Parse CLI output and extract structured plan
3. Enhance tasks with file paths and pattern references
4. Generate planObject with:
- Summary (2-3 sentences)
- Approach (high-level strategy)
- Tasks (3-10 actionable steps)
- Estimated time (with breakdown)
- Recommended execution (Agent for Low, Codex for Medium/High)
5. Return planObject (no file writes)
## Quality Requirements ## Complexity Level
Each task MUST include: ${complexity}
- Action verb (Create/Update/Add/Implement/Refactor)
- Specific file path
- Detailed changes
- Pattern reference from exploration
Format: "{Action} in {file_path}: {details} following {pattern}" ## Requirements
` Generate plan.json with:
- summary: 2-3 sentence overview
- approach: High-level implementation strategy
- tasks: 3-10 structured tasks with:
- title, file, action, description
- implementation (3-7 steps)
- reference (pattern, files, examples)
- acceptance (2-4 criteria)
- estimated_time, recommended_execution, complexity
- _metadata: timestamp, source, planning_mode
## Execution
1. Execute CLI planning using Gemini (Qwen fallback)
2. Parse output and structure plan
3. Write JSON: Write('${sessionFolder}/plan.json', jsonContent)
4. Return brief completion summary
`
) )
// Save planning results to session folder
const planFile = `${sessionFolder}/plan.json`
Write(planFile, JSON.stringify(planObject, null, 2))
``` ```
**Output**: `planObject` (see Data Structures section) **Output**: `${sessionFolder}/plan.json`
**Artifact**: Saved to `{sessionFolder}/plan.json` for CLI/agent use
**Progress Tracking**:
- Mark Phase 3 completed
- Mark Phase 4 in_progress
**Expected Duration**:
- Low: 20-30 seconds (direct)
- Medium/High: 40-60 seconds (agent-based)
--- ---
### Phase 4: Task Confirmation & Execution Selection ### Phase 4: Task Confirmation & Execution Selection
**Two-Step Confirmation Process** **Step 4.1: Display Plan**
```javascript
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
**Step 4.1: Display Plan Summary** console.log(`
Output complete plan as regular text:
```
## Implementation Plan ## Implementation Plan
**Summary**: ${planObject.summary} **Summary**: ${plan.summary}
**Approach**: ${plan.approach}
**Approach**: ${planObject.approach} **Tasks** (${plan.tasks.length}):
${plan.tasks.map((t, i) => `${i+1}. ${t.title} (${t.file})`).join('\n')}
**Task Breakdown** (${planObject.tasks.length} tasks): **Complexity**: ${plan.complexity}
${planObject.tasks.map((task, i) => ` **Estimated Time**: ${plan.estimated_time}
${i+1}. **${task.title}** (${task.file}) **Recommended**: ${plan.recommended_execution}
- What: ${task.description} `)
- How: ${task.implementation.length} steps
- Reference: ${task.reference.pattern}
- Verification: ${task.acceptance.length} criteria
`).join('')}
**Complexity**: ${planObject.complexity}
**Estimated Time**: ${planObject.estimated_time}
**Recommended Execution**: ${planObject.recommended_execution}
``` ```
**Step 4.2: Collect User Confirmation** **Step 4.2: Collect Confirmation**
Three questions via single AskUserQuestion call:
```javascript ```javascript
AskUserQuestion({ AskUserQuestion({
questions: [ questions: [
{ {
question: `**Plan Summary**: ${planObject.summary} question: `Confirm plan? (${plan.tasks.length} tasks, ${plan.complexity})`,
header: "Confirm",
**Tasks**: ${planObject.tasks.length} | **Complexity**: ${planObject.complexity} | **Time**: ${planObject.estimated_time}
Confirm plan? (Multi-select: can supplement via "Other")`,
header: "Confirm Plan",
multiSelect: true, multiSelect: true,
options: [ options: [
{ label: "Allow", description: "Proceed as-is" }, { label: "Allow", description: "Proceed as-is" },
@@ -360,22 +242,22 @@ Confirm plan? (Multi-select: can supplement via "Other")`,
] ]
}, },
{ {
question: "Select execution method:", question: "Execution method:",
header: "Execution", header: "Execution",
multiSelect: false, multiSelect: false,
options: [ options: [
{ label: "Agent", description: "@code-developer agent" }, { label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" }, { label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: `Auto: ${planObject.complexity === 'Low' ? 'Agent' : 'Codex'}` } { label: "Auto", description: `Auto: ${plan.complexity === 'Low' ? 'Agent' : 'Codex'}` }
] ]
}, },
{ {
question: "Enable code review after execution?\n\n(Custom tools via \"Other\": qwen, codex, etc.)", question: "Code review after execution?",
header: "Code Review", header: "Review",
multiSelect: false, multiSelect: false,
options: [ options: [
{ label: "Gemini Review", description: "Gemini CLI (gemini-2.5-pro)" }, { label: "Gemini Review", description: "Gemini CLI" },
{ label: "Agent Review", description: "@code-reviewer agent" }, { label: "Agent Review", description: "@code-reviewer" },
{ label: "Skip", description: "No review" } { label: "Skip", description: "No review" }
] ]
} }
@@ -383,351 +265,95 @@ Confirm plan? (Multi-select: can supplement via "Other")`,
}) })
``` ```
**Decision Flow**:
```
Task Confirmation (Multi-select):
├─ Allow (+ supplements) → Execution Method Selection
├─ Modify (+ supplements) → Re-run Phase 3
└─ Cancel → Exit
Execution Method (Single-select):
├─ Agent → Launch @code-developer
├─ Codex → Execute with codex CLI
└─ Auto → Low complexity: Agent | Medium/High: Codex
Code Review (after execution):
├─ Skip → No review
├─ Gemini Review → gemini CLI analysis
├─ Agent Review → Current Claude review
└─ Other → Custom tool (e.g., qwen, codex)
```
**Progress Tracking**:
- Mark Phase 4 completed
- Mark Phase 5 in_progress
--- ---
### Phase 5: Dispatch to Execution ### Phase 5: Dispatch to Execution
**Step 5.1: Export Enhanced Task JSON** **Step 5.1: Generate task.json** (by command, not agent)
Always export Enhanced Task JSON to session folder:
```javascript ```javascript
const taskId = `LP-${shortTimestamp}` const taskId = `LP-${shortTimestamp}`
const filename = `${sessionFolder}/task.json` const exploration = file_exists(`${sessionFolder}/exploration.json`)
? JSON.parse(Read(`${sessionFolder}/exploration.json`))
: null
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
const enhancedTaskJson = { const taskJson = {
id: taskId, id: taskId,
title: original_task_description, title: task_description,
status: "pending", status: "pending",
meta: { meta: {
type: "planning", type: "planning",
created_at: new Date().toISOString(), created_at: new Date().toISOString(),
complexity: planObject.complexity, complexity: plan.complexity,
estimated_time: planObject.estimated_time, estimated_time: plan.estimated_time,
recommended_execution: planObject.recommended_execution, recommended_execution: plan.recommended_execution,
workflow: "lite-plan", workflow: "lite-plan",
session_id: sessionId, session_id: sessionId,
session_folder: sessionFolder session_folder: sessionFolder
}, },
context: { context: {
requirements: [original_task_description], requirements: [task_description],
plan: { plan: {
summary: planObject.summary, summary: plan.summary,
approach: planObject.approach, approach: plan.approach,
tasks: planObject.tasks tasks: plan.tasks
}, },
exploration: explorationContext || null, exploration: exploration,
clarifications: clarificationContext || null, clarifications: clarificationContext || null,
focus_paths: explorationContext?.relevant_files || [], focus_paths: exploration?.relevant_files || [],
acceptance: planObject.tasks.flatMap(t => t.acceptance) acceptance: plan.tasks.flatMap(t => t.acceptance)
} }
} }
Write(filename, JSON.stringify(enhancedTaskJson, null, 2)) Write(`${sessionFolder}/task.json`, JSON.stringify(taskJson, null, 2))
console.log(`Enhanced Task JSON exported to: ${filename}`)
console.log(`Session folder: ${sessionFolder}`)
console.log(`Reuse with: /workflow:lite-execute ${filename}`)
``` ```
**Step 5.2: Store Execution Context** **Step 5.2: Store executionContext**
```javascript ```javascript
executionContext = { executionContext = {
planObject: planObject, planObject: plan,
explorationContext: explorationContext || null, explorationContext: exploration,
clarificationContext: clarificationContext || null, clarificationContext: clarificationContext || null,
executionMethod: userSelection.execution_method, executionMethod: userSelection.execution_method,
codeReviewTool: userSelection.code_review_tool, codeReviewTool: userSelection.code_review_tool,
originalUserInput: original_task_description, originalUserInput: task_description,
// Session artifacts location
session: { session: {
id: sessionId, id: sessionId,
folder: sessionFolder, folder: sessionFolder,
artifacts: { artifacts: {
exploration: explorationContext ? `${sessionFolder}/exploration.json` : null, exploration: exploration ? `${sessionFolder}/exploration.json` : null,
plan: `${sessionFolder}/plan.json`, plan: `${sessionFolder}/plan.json`,
task: `${sessionFolder}/task.json` // Always exported task: `${sessionFolder}/task.json`
} }
} }
} }
``` ```
**Step 5.3: Call lite-execute** **Step 5.3: Dispatch**
```javascript ```javascript
SlashCommand(command="/workflow:lite-execute --in-memory") SlashCommand(command="/workflow:lite-execute --in-memory")
``` ```
**Execution Handoff**: ## Session Folder Structure
- lite-execute reads `executionContext` variable from memory
- `executionContext.session.artifacts` contains file paths to saved planning artifacts:
- `exploration` - exploration.json (if exploration performed)
- `plan` - plan.json (always exists)
- `task` - task.json (if user selected export)
- All execution logic handled by lite-execute
- lite-plan completes after successful handoff
**Progress Tracking**: ```
- Mark Phase 5 completed .workflow/.lite-plan/{task-slug}-{timestamp}/
- Execution tracking delegated to lite-execute ├── exploration.json # If exploration performed (by cli-explore-agent)
├── plan.json # Always created (by agent or direct planning)
## Best Practices └── task.json # Always created (by command)
```
### Workflow Intelligence
1. **Dynamic Adaptation**: Workflow adjusts based on task characteristics
- Smart exploration: Only when codebase context needed
- Adaptive planning: Simple → direct, complex → specialized agent
- Context-aware clarification: Only when truly needed
- Reduces unnecessary steps while maintaining thoroughness
2. **Flag-Based Control**: Use `-e`/`--explore` to force exploration when:
- Task appears simple but requires codebase context
- Auto-detection might miss subtle integration points
- Comprehensive code understanding needed
3. **Progressive Clarification**: Information gathered at right time
- Phase 1: Explore codebase (current state)
- Phase 2: Ask questions (based on findings)
- Phase 3: Plan with complete context
- Avoids premature assumptions, reduces rework
4. **Complexity-Aware Planning**: Strategy matches task complexity
- Low (1-2 files): Direct planning (fast, 20-30s)
- Medium (3-5 files): CLI planning (detailed, 40-50s)
- High (6+ files): CLI planning with risk analysis (thorough, 50-60s)
5. **Two-Step Confirmation**: Clear separation between plan and control
- Step 1: Display plan as readable text (not in question)
- Step 2: Collect multi-dimensional input
- Plan confirmation (multi-select with supplements)
- Execution method selection
- Code review tool selection (custom via "Other")
- Enhanced Task JSON always exported to session folder
- Allows plan refinement without re-selecting execution method
### Task Management
1. **Phase-Based Organization**: 5 distinct phases with clear transitions
- Phase 1: Analysis & Exploration (automatic)
- Phase 2: Clarification (conditional, interactive)
- Phase 3: Planning (automatic, adaptive)
- Phase 4: Confirmation (interactive, multi-dimensional)
- Phase 5: Execution Dispatch (automatic)
2. **Flexible Task Counts**: Adapts to complexity
- Low: 3-5 tasks (focused)
- Medium: 5-7 tasks (detailed)
- High: 7-10 tasks (comprehensive)
3. **Session Artifact Management**:
- All planning artifacts saved to dedicated session folder
- Enhanced Task JSON always exported for reusability
- Plan context passed to execution via memory and files
- Clean organization with session-based folder structure
### Planning Standards
1. **Context-Rich Planning**: Plans include all relevant context
- Exploration findings (structure, patterns, constraints)
- User clarifications (requirements, preferences, decisions)
- Complexity assessment (risks, dependencies, estimates)
- Execution recommendations (Direct vs CLI, specific tool)
2. **Modification Support**: Iterative refinement
- User can request modifications in Phase 4
- Feedback incorporated into re-planning
- No restart from scratch
- Collaborative planning workflow
## Error Handling ## Error Handling
| Error | Cause | Resolution | | Error | Resolution |
|-------|-------|------------| |-------|------------|
| Phase 1 Exploration Failure | cli-explore-agent unavailable/timeout | Skip exploration, set `explorationContext = null`, continue with task description only | | Exploration agent failure | Skip exploration, continue with task description only |
| Phase 2 Clarification Timeout | User no response > 5 minutes | Use exploration findings as-is, proceed to Phase 3 with warning | | Planning agent failure | Fallback to direct planning by Claude |
| Phase 3 Planning Agent Failure | cli-lite-planning-agent unavailable/timeout | Fallback to direct planning by current Claude | | Clarification timeout | Use exploration findings as-is |
| Phase 3 Planning Timeout | Planning > 90 seconds | Generate simplified plan, mark as "Quick Plan", continue | | Confirmation timeout | Save context, display resume instructions |
| Phase 4 Confirmation Timeout | User no response > 5 minutes | Save context to temp var, display resume instructions, exit gracefully | | Modify loop > 3 times | Suggest breaking task or using /workflow:plan |
| Phase 4 Modification Loop | User requests modify > 3 times | Suggest breaking task into smaller pieces or using `/workflow:plan` |
## Session Folder Structure
Each lite-plan execution creates a dedicated session folder to organize all artifacts:
```
.workflow/.lite-plan/{task-slug}-{short-timestamp}/
├── exploration.json # Exploration results (if exploration performed)
├── plan.json # Planning results (always created)
└── task.json # Enhanced Task JSON (always created)
```
**Folder Naming Convention**:
- `{task-slug}`: First 40 characters of task description, lowercased, non-alphanumeric replaced with `-`
- `{short-timestamp}`: YYYY-MM-DD-HH-mm-ss format
- Example: `.workflow/.lite-plan/implement-user-auth-jwt-2025-01-15-14-30-45/`
**File Contents**:
- `exploration.json`: Complete explorationContext object (if exploration performed, see Data Structures)
- `plan.json`: Complete planObject (always created, see Data Structures)
- `task.json`: Enhanced Task JSON with all context (always created, see Data Structures)
**Access Patterns**:
- **lite-plan**: Creates folder and writes all artifacts during execution, passes paths via `executionContext.session.artifacts`
- **lite-execute**: Reads artifact paths from `executionContext.session.artifacts` (see lite-execute.md for usage details)
- **User**: Can inspect artifacts for debugging or reference
- **Reuse**: Pass `task.json` path to `/workflow:lite-execute {path}` for re-execution
## Data Structures
### explorationContext
Exploration findings from cli-explore-agent (Phase 1):
```javascript
{
project_structure: string, // Overall architecture description
relevant_files: string[], // File paths to be modified/referenced
patterns: string, // Existing patterns and conventions
dependencies: string, // Dependencies and integration points
integration_points: string, // Where this connects with existing code
constraints: string, // Technical constraints
clarification_needs: [ // Questions requiring user input
{
question: string,
context: string,
options: string[]
}
]
}
```
### planObject
Implementation plan from Phase 3:
```javascript
{
summary: string, // 2-3 sentence overview
approach: string, // High-level implementation strategy
tasks: [ // 3-10 structured task objects
{
title: string, // Task title
file: string, // Target file path
action: string, // Create|Update|Implement|Refactor|Add|Delete
description: string, // What to implement (1-2 sentences)
implementation: string[], // Step-by-step how-to (3-7 steps)
reference: { // What to reference
pattern: string, // Pattern name
files: string[], // Reference file paths
examples: string // Specific guidance
},
acceptance: string[] // Verification criteria (2-4 items)
}
],
estimated_time: string, // Total implementation time
recommended_execution: string, // "Agent" (Low) or "Codex" (Medium/High)
complexity: string // "Low" | "Medium" | "High"
}
```
### executionContext
Context passed to lite-execute via --in-memory (Phase 5):
```javascript
{
planObject: { // Complete planObject (see above)
summary: string,
approach: string,
tasks: [...],
estimated_time: string,
recommended_execution: string,
complexity: string
},
explorationContext: {...} | null, // See explorationContext above
clarificationContext: {...} | null, // User responses from Phase 2
executionMethod: "Agent" | "Codex" | "Auto",
codeReviewTool: "Skip" | "Gemini Review" | "Agent Review" | string,
originalUserInput: string, // User's original task description
// Session artifacts location (for lite-execute to access saved files)
session: {
id: string, // Session identifier: {taskSlug}-{shortTimestamp}
folder: string, // Session folder path: .workflow/.lite-plan/{session-id}
artifacts: {
exploration: string | null, // exploration.json path (if exploration performed)
plan: string, // plan.json path (always present)
task: string // task.json path (always exported)
}
}
}
```
### Enhanced Task JSON Export
When user selects "Export JSON", lite-plan exports this structure:
```json
{
"id": "LP-{timestamp}",
"title": "Original task description",
"status": "pending",
"meta": {
"type": "planning",
"created_at": "ISO timestamp",
"complexity": "Low|Medium|High",
"estimated_time": "X minutes",
"recommended_execution": "Agent|Codex",
"workflow": "lite-plan"
},
"context": {
"requirements": ["Original task description"],
"plan": {
"summary": "2-3 sentence overview",
"approach": "High-level strategy",
"tasks": [/* Array of task objects */]
},
"exploration": {/* explorationContext */} | null,
"clarifications": {/* clarificationContext */} | null,
"focus_paths": ["src/auth", "tests/auth"],
"acceptance": ["Criteria from plan.tasks"]
}
}
```
**Schema Notes**:
- Aligns with Enhanced Task JSON Schema (6-field structure)
- `context_package_path` omitted (not used by lite-plan)
- `flow_control` omitted (handled by lite-execute)
- `focus_paths` derived from `exploration.relevant_files`
- `acceptance` derived from `plan.tasks`

View File

@@ -0,0 +1,90 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Exploration Context Schema",
"description": "Code exploration results from cli-explore-agent for task context gathering",
"type": "object",
"required": [
"project_structure",
"relevant_files",
"patterns",
"dependencies",
"integration_points",
"constraints",
"clarification_needs",
"_metadata"
],
"properties": {
"project_structure": {
"type": "string",
"description": "Overall architecture description: module organization, layer structure, component relationships"
},
"relevant_files": {
"type": "array",
"items": {"type": "string"},
"description": "File paths to be modified or referenced for the task"
},
"patterns": {
"type": "string",
"description": "Existing code patterns, conventions, and styles found in the codebase"
},
"dependencies": {
"type": "string",
"description": "External and internal module dependencies relevant to the task"
},
"integration_points": {
"type": "string",
"description": "Where this task connects with existing code: APIs, hooks, events, shared state"
},
"constraints": {
"type": "string",
"description": "Technical constraints and limitations affecting implementation"
},
"clarification_needs": {
"type": "array",
"items": {
"type": "object",
"required": ["question", "context", "options"],
"properties": {
"question": {
"type": "string",
"description": "The clarification question to ask user"
},
"context": {
"type": "string",
"description": "Background context explaining why this clarification is needed"
},
"options": {
"type": "array",
"items": {"type": "string"},
"description": "Available options for user to choose from (2-4 options)"
}
}
},
"description": "Ambiguities requiring user input before planning"
},
"_metadata": {
"type": "object",
"required": ["timestamp", "task_description", "source"],
"properties": {
"timestamp": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp of exploration"
},
"task_description": {
"type": "string",
"description": "Original task description that triggered exploration"
},
"source": {
"type": "string",
"const": "cli-explore-agent",
"description": "Agent that performed exploration"
},
"duration_seconds": {
"type": "integer",
"description": "Exploration duration in seconds"
}
}
}
}
}

View File

@@ -0,0 +1,127 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Plan Object Schema",
"description": "Implementation plan from cli-lite-planning-agent or direct planning",
"type": "object",
"required": [
"summary",
"approach",
"tasks",
"estimated_time",
"recommended_execution",
"complexity",
"_metadata"
],
"properties": {
"summary": {
"type": "string",
"description": "2-3 sentence overview of the implementation plan"
},
"approach": {
"type": "string",
"description": "High-level implementation strategy and methodology"
},
"tasks": {
"type": "array",
"minItems": 3,
"maxItems": 10,
"items": {
"type": "object",
"required": ["title", "file", "action", "description", "implementation", "reference", "acceptance"],
"properties": {
"title": {
"type": "string",
"description": "Task title (action verb + target)"
},
"file": {
"type": "string",
"description": "Target file path for this task"
},
"action": {
"type": "string",
"enum": ["Create", "Update", "Implement", "Refactor", "Add", "Delete", "Configure", "Test"],
"description": "Primary action type"
},
"description": {
"type": "string",
"description": "What to implement (1-2 sentences)"
},
"implementation": {
"type": "array",
"items": {"type": "string"},
"minItems": 3,
"maxItems": 7,
"description": "Step-by-step implementation guide"
},
"reference": {
"type": "object",
"required": ["pattern", "files", "examples"],
"properties": {
"pattern": {
"type": "string",
"description": "Pattern name to follow"
},
"files": {
"type": "array",
"items": {"type": "string"},
"description": "Reference file paths to study"
},
"examples": {
"type": "string",
"description": "Specific guidance or example references"
}
},
"description": "Reference materials for implementation"
},
"acceptance": {
"type": "array",
"items": {"type": "string"},
"minItems": 2,
"maxItems": 4,
"description": "Verification criteria for task completion"
}
}
},
"description": "Structured task breakdown (3-10 tasks)"
},
"estimated_time": {
"type": "string",
"description": "Total estimated implementation time (e.g., '30 minutes', '2 hours')"
},
"recommended_execution": {
"type": "string",
"enum": ["Agent", "Codex"],
"description": "Recommended execution method based on complexity"
},
"complexity": {
"type": "string",
"enum": ["Low", "Medium", "High"],
"description": "Task complexity level"
},
"_metadata": {
"type": "object",
"required": ["timestamp", "source", "planning_mode"],
"properties": {
"timestamp": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp of planning"
},
"source": {
"type": "string",
"enum": ["cli-lite-planning-agent", "direct-planning"],
"description": "Planning source"
},
"planning_mode": {
"type": "string",
"enum": ["direct", "agent-based"],
"description": "Planning execution mode"
},
"duration_seconds": {
"type": "integer",
"description": "Planning duration in seconds"
}
}
}
}
}