feat(cli): add support for custom execution IDs and multi-turn conversations

- Introduced `--id <id>` option in CLI for custom execution IDs.
- Enhanced CLI command handling to support multi-turn conversations.
- Updated execution and conversation detail retrieval to accommodate new structure.
- Implemented merging of multiple conversations with tracking of source IDs.
- Improved history management to save and load conversation records.
- Added styles for displaying multi-turn conversation details in the dashboard.
- Refactored existing execution detail functions for backward compatibility.
This commit is contained in:
catlog22
2025-12-13 14:03:24 +08:00
parent 23e15e479e
commit c780544792
14 changed files with 1483 additions and 640 deletions

View File

@@ -476,7 +476,7 @@ Detailed plan: ${executionContext.session.artifacts.plan}`)
ccw cli exec "${buildCLIPrompt(batch)}" --tool codex --mode auto
```
**Execution with tracking**:
**Execution with fixed IDs** (predictable ID pattern):
```javascript
// Launch CLI in foreground (NOT background)
// Timeout based on complexity: Low=40min, Medium=60min, High=100min
@@ -486,15 +486,48 @@ const timeoutByComplexity = {
"High": 6000000 // 100 minutes
}
// Generate fixed execution ID: ${sessionId}-${groupId}
// This enables predictable ID lookup without relying on resume context chains
const sessionId = executionContext?.session?.id || 'standalone'
const fixedExecutionId = `${sessionId}-${batch.groupId}` // e.g., "implement-auth-2025-12-13-P1"
// Check if resuming from previous failed execution
const previousCliId = batch.resumeFromCliId || null
// Build command with fixed ID (and optional resume for continuation)
const cli_command = previousCliId
? `ccw cli exec "${buildCLIPrompt(batch)}" --tool codex --mode auto --id ${fixedExecutionId} --resume ${previousCliId}`
: `ccw cli exec "${buildCLIPrompt(batch)}" --tool codex --mode auto --id ${fixedExecutionId}`
bash_result = Bash(
command=cli_command,
timeout=timeoutByComplexity[planObject.complexity] || 3600000
)
// Execution ID is now predictable: ${fixedExecutionId}
// Can also extract from output: "ID: implement-auth-2025-12-13-P1"
const cliExecutionId = fixedExecutionId
// Update TodoWrite when execution completes
```
**Result Collection**: After completion, analyze output and collect result following `executionResult` structure
**Resume on Failure** (with fixed ID):
```javascript
// If execution failed or timed out, offer resume option
if (bash_result.status === 'failed' || bash_result.status === 'timeout') {
console.log(`
⚠️ Execution incomplete. Resume available:
Fixed ID: ${fixedExecutionId}
Lookup: ccw cli detail ${fixedExecutionId}
Resume: ccw cli exec "Continue tasks" --resume ${fixedExecutionId} --tool codex --mode auto --id ${fixedExecutionId}-retry
`)
// Store for potential retry in same session
batch.resumeFromCliId = fixedExecutionId
}
```
**Result Collection**: After completion, analyze output and collect result following `executionResult` structure (include `cliExecutionId` for resume capability)
### Step 4: Progress Tracking
@@ -552,6 +585,21 @@ ccw cli exec "[Shared Prompt Template with artifacts]" --tool qwen
ccw cli exec "[Verify plan acceptance criteria at ${plan.json}]" --tool codex --mode auto
```
**Multi-Round Review with Fixed IDs**:
```javascript
// Generate fixed review ID
const reviewId = `${sessionId}-review`
// First review pass with fixed ID
const reviewResult = Bash(`ccw cli exec "[Review prompt]" --tool gemini --id ${reviewId}`)
// If issues found, continue review dialog with fixed ID chain
if (hasUnresolvedIssues(reviewResult)) {
// Resume with follow-up questions
Bash(`ccw cli exec "Clarify the security concerns you mentioned" --resume ${reviewId} --tool gemini --id ${reviewId}-followup`)
}
```
**Implementation Note**: Replace `[Shared Prompt Template with artifacts]` placeholder with actual template content, substituting:
- `@{plan.json}``@${executionContext.session.artifacts.plan}`
- `[@{exploration.json}]` → exploration files from artifacts (if exists)
@@ -623,8 +671,10 @@ console.log(`✓ Development index: [${category}] ${entry.title}`)
| Empty file | File exists but no content | Error: "File is empty: {path}. Provide task description." |
| Invalid Enhanced Task JSON | JSON missing required fields | Warning: "Missing required fields. Treating as plain text." |
| Malformed JSON | JSON parsing fails | Treat as plain text (expected for non-JSON files) |
| Execution failure | Agent/Codex crashes | Display error, save partial progress, suggest retry |
| Execution failure | Agent/Codex crashes | Display error, use fixed ID `${sessionId}-${groupId}` for resume: `ccw cli exec "Continue" --resume <fixed-id> --id <fixed-id>-retry` |
| 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
@@ -679,8 +729,20 @@ Collected after each execution call completes:
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
notes: string, // Important context for next execution
fixedCliId: string | null // Fixed CLI execution ID (e.g., "implement-auth-2025-12-13-P1")
}
```
Appended to `previousExecutionResults` array for context continuity in multi-execution scenarios.
**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 exec "Continue from where we left off" --resume ${fixedCliId} --tool codex --mode auto --id ${fixedCliId}-retry
```

View File

@@ -54,6 +54,14 @@ Phase 3: Fix Planning (NO CODE EXECUTION - planning only)
+- Decision (based on Phase 1 severity):
|- Low/Medium -> Load schema: cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json -> Direct Claude planning (following schema) -> fix-plan.json -> MUST proceed to Phase 4
+- High/Critical -> cli-lite-planning-agent -> fix-plan.json -> MUST proceed to Phase 4
+- CLI Execution ID Assignment (MANDATORY for all tasks):
|- Generate cli_execution_id for each task (format: {sessionId}-{task.id})
+- Compute cli_execution strategy based on depends_on:
|- No deps -> strategy: "new"
|- 1 dep + sequential -> strategy: "resume", resume_from: parent.cli_execution_id
|- 1 dep + parallel children -> strategy: "fork", resume_from: parent.cli_execution_id
|- N deps -> strategy: "merge", merge_from: [parent1.cli_execution_id, ...]
+- N deps + creates branch -> strategy: "merge_fork", merge_from: [...], new ID
Phase 4: Confirmation & Selection
|- Display fix-plan summary (tasks, severity, estimated time)
@@ -381,7 +389,7 @@ const fixPlan = {
summary: "...",
root_cause: "...",
strategy: "immediate_patch|comprehensive_fix|refactor",
tasks: [...], // Each task: { id, title, scope, ..., depends_on, complexity }
tasks: [...], // Each task: { id, title, scope, ..., depends_on, cli_execution_id, cli_execution }
estimated_time: "...",
recommended_execution: "Agent",
severity: severity,
@@ -389,10 +397,66 @@ const fixPlan = {
_metadata: { timestamp: getUtc8ISOString(), source: "direct-planning", planning_mode: "direct" }
}
// Step 3: Write fix-plan to session folder
// Step 3: ⚠️ MANDATORY - Assign CLI Execution IDs and strategies
assignCliExecutionIds(fixPlan.tasks, sessionId)
// Step 4: Write fix-plan to session folder
Write(`${sessionFolder}/fix-plan.json`, JSON.stringify(fixPlan, null, 2))
// Step 4: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
// Step 5: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
```
**CLI Execution ID Assignment Function** (MANDATORY for ALL planning modes):
```javascript
function assignCliExecutionIds(tasks, sessionId) {
// Build dependency graph
const taskMap = new Map(tasks.map(t => [t.id, t]))
const childCount = new Map() // Track how many tasks depend on each task
tasks.forEach(task => {
(task.depends_on || []).forEach(depId => {
childCount.set(depId, (childCount.get(depId) || 0) + 1)
})
})
tasks.forEach(task => {
// Assign unique CLI execution ID
task.cli_execution_id = `${sessionId}-${task.id}`
const deps = task.depends_on || []
if (deps.length === 0) {
// No dependencies: new conversation
task.cli_execution = { strategy: "new" }
} else if (deps.length === 1) {
const parent = taskMap.get(deps[0])
const parentChildCount = childCount.get(deps[0]) || 0
if (parentChildCount === 1) {
// Single child: resume (continue same conversation)
task.cli_execution = {
strategy: "resume",
resume_from: parent.cli_execution_id
}
} else {
// Multiple children: fork (create new branch)
task.cli_execution = {
strategy: "fork",
resume_from: parent.cli_execution_id
}
}
} else {
// Multiple dependencies: merge
const mergeFrom = deps.map(depId => taskMap.get(depId).cli_execution_id)
task.cli_execution = {
strategy: "merge_fork", // Merge always creates new ID
merge_from: mergeFrom
}
}
})
return tasks
}
```
**High/Critical Severity** - Invoke cli-lite-planning-agent:
@@ -407,6 +471,15 @@ Generate fix plan and write fix-plan.json.
## Output Schema Reference
Execute: cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json (get schema reference before generating plan)
## CLI Execution ID Requirements (MANDATORY)
After generating tasks, you MUST assign CLI execution IDs and strategies:
1. Each task needs cli_execution_id: {sessionId}-{task.id}
2. Compute cli_execution.strategy based on depends_on:
- No deps → { strategy: "new" }
- 1 dep (single child) → { strategy: "resume", resume_from: parent.cli_execution_id }
- 1 dep (multiple children) → { strategy: "fork", resume_from: parent.cli_execution_id }
- N deps → { strategy: "merge_fork", merge_from: [parent1.cli_execution_id, ...] }
## Bug Description
${bug_description}

View File

@@ -54,6 +54,14 @@ Phase 3: Planning (NO CODE EXECUTION - planning only)
└─ Decision (based on Phase 1 complexity):
├─ Low → Load schema: cat ~/.claude/workflows/cli-templates/schemas/plan-json-schema.json → Direct Claude planning (following schema) → plan.json → MUST proceed to Phase 4
└─ Medium/High → cli-lite-planning-agent → plan.json → MUST proceed to Phase 4
└─ CLI Execution ID Assignment (MANDATORY for all tasks):
├─ Generate cli_execution_id for each task (format: {sessionId}-T{N})
└─ Compute cli_execution strategy based on depends_on:
├─ No deps → strategy: "new"
├─ 1 dep + sequential → strategy: "resume", resume_from: parent.cli_execution_id
├─ 1 dep + parallel children → strategy: "fork", resume_from: parent.cli_execution_id
├─ N deps → strategy: "merge", merge_from: [parent1.cli_execution_id, ...]
└─ N deps + creates branch → strategy: "merge_fork", merge_from: [...], new ID
Phase 4: Confirmation & Selection
├─ Display plan summary (tasks, complexity, estimated time)
@@ -373,17 +381,73 @@ manifest.explorations.forEach(exp => {
const plan = {
summary: "...",
approach: "...",
tasks: [...], // Each task: { id, title, scope, ..., depends_on, execution_group, complexity }
tasks: [...], // Each task: { id, title, scope, ..., depends_on, cli_execution_id, cli_execution }
estimated_time: "...",
recommended_execution: "Agent",
complexity: "Low",
_metadata: { timestamp: getUtc8ISOString(), source: "direct-planning", planning_mode: "direct" }
}
// Step 4: Write plan to session folder
// Step 4: ⚠️ MANDATORY - Assign CLI Execution IDs and strategies
assignCliExecutionIds(plan.tasks, sessionId)
// Step 5: Write plan to session folder
Write(`${sessionFolder}/plan.json`, JSON.stringify(plan, null, 2))
// Step 5: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
// Step 6: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here
```
**CLI Execution ID Assignment Function** (MANDATORY for ALL planning modes):
```javascript
function assignCliExecutionIds(tasks, sessionId) {
// Build dependency graph
const taskMap = new Map(tasks.map(t => [t.id, t]))
const childCount = new Map() // Track how many tasks depend on each task
tasks.forEach(task => {
(task.depends_on || []).forEach(depId => {
childCount.set(depId, (childCount.get(depId) || 0) + 1)
})
})
tasks.forEach(task => {
// Assign unique CLI execution ID
task.cli_execution_id = `${sessionId}-${task.id}`
const deps = task.depends_on || []
if (deps.length === 0) {
// No dependencies: new conversation
task.cli_execution = { strategy: "new" }
} else if (deps.length === 1) {
const parent = taskMap.get(deps[0])
const parentChildCount = childCount.get(deps[0]) || 0
if (parentChildCount === 1) {
// Single child: resume (continue same conversation)
task.cli_execution = {
strategy: "resume",
resume_from: parent.cli_execution_id
}
} else {
// Multiple children: fork (create new branch)
task.cli_execution = {
strategy: "fork",
resume_from: parent.cli_execution_id
}
}
} else {
// Multiple dependencies: merge
const mergeFrom = deps.map(depId => taskMap.get(depId).cli_execution_id)
task.cli_execution = {
strategy: "merge_fork", // Merge always creates new ID
merge_from: mergeFrom
}
}
})
return tasks
}
```
**Medium/High Complexity** - Invoke cli-lite-planning-agent:
@@ -398,6 +462,15 @@ Generate implementation plan and write plan.json.
## Output Schema Reference
Execute: cat ~/.claude/workflows/cli-templates/schemas/plan-json-schema.json (get schema reference before generating plan)
## CLI Execution ID Requirements (MANDATORY)
After generating tasks, you MUST assign CLI execution IDs and strategies:
1. Each task needs cli_execution_id: {sessionId}-{task.id}
2. Compute cli_execution.strategy based on depends_on:
- No deps → { strategy: "new" }
- 1 dep (single child) → { strategy: "resume", resume_from: parent.cli_execution_id }
- 1 dep (multiple children) → { strategy: "fork", resume_from: parent.cli_execution_id }
- N deps → { strategy: "merge_fork", merge_from: [parent1.cli_execution_id, ...] }
## Task Description
${task_description}

View File

@@ -28,6 +28,12 @@ Input Parsing:
├─ Parse flags: --session
└─ Validation: session_id REQUIRED
Phase 0: User Configuration (Interactive)
├─ Question 1: Supplementary materials/guidelines?
├─ Question 2: Execution method preference (Agent/CLI/Hybrid)
├─ Question 3: CLI tool preference (if CLI selected)
└─ Store: userConfig for agent prompt
Phase 1: Context Preparation & Module Detection (Command)
├─ Assemble session paths (metadata, context package, output dirs)
├─ Provide metadata (session_id, execution_mode, mcp_capabilities)
@@ -57,6 +63,82 @@ Phase 3: Integration (+1 Coordinator, Multi-Module Only)
## Document Generation Lifecycle
### Phase 0: User Configuration (Interactive)
**Purpose**: Collect user preferences before task generation to ensure generated tasks match execution expectations.
**User Questions**:
```javascript
AskUserQuestion({
questions: [
{
question: "Do you have supplementary materials or guidelines to include?",
header: "Materials",
multiSelect: false,
options: [
{ label: "No additional materials", description: "Use existing context only" },
{ label: "Provide file paths", description: "I'll specify paths to include" },
{ label: "Provide inline content", description: "I'll paste content directly" }
]
},
{
question: "Select execution method for generated tasks:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent (Recommended)", description: "Claude agent executes tasks directly" },
{ label: "Hybrid", description: "Agent orchestrates, calls CLI for complex steps" },
{ label: "CLI Only", description: "All execution via CLI tools (codex/gemini/qwen)" }
]
},
{
question: "If using CLI, which tool do you prefer?",
header: "CLI Tool",
multiSelect: false,
options: [
{ label: "Codex (Recommended)", description: "Best for implementation tasks" },
{ label: "Gemini", description: "Best for analysis and large context" },
{ label: "Qwen", description: "Alternative analysis tool" },
{ label: "Auto", description: "Let agent decide per-task" }
]
}
]
})
```
**Handle Materials Response**:
```javascript
if (userConfig.materials === "Provide file paths") {
// Follow-up question for file paths
const pathsResponse = AskUserQuestion({
questions: [{
question: "Enter file paths to include (comma-separated or one per line):",
header: "Paths",
multiSelect: false,
options: [
{ label: "Enter paths", description: "Provide paths in text input" }
]
}]
})
userConfig.supplementaryPaths = parseUserPaths(pathsResponse)
}
```
**Build userConfig**:
```javascript
const userConfig = {
supplementaryMaterials: {
type: "none|paths|inline",
content: [...], // Parsed paths or inline content
},
executionMethod: "agent|hybrid|cli",
preferredCliTool: "codex|gemini|qwen|auto",
enableResume: true // Always enable resume for CLI executions
}
```
**Pass to Agent**: Include `userConfig` in agent prompt for Phase 2A/2B.
### Phase 1: Context Preparation & Module Detection (Command Responsibility)
**Command prepares session paths, metadata, and detects module structure.**
@@ -159,10 +241,21 @@ Output:
Session ID: {session-id}
MCP Capabilities: {exa_code, exa_web, code_index}
## USER CONFIGURATION (from Phase 0)
Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli
Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto
Supplementary Materials: ${userConfig.supplementaryMaterials}
## CLI TOOL SELECTION
Determine CLI tool usage per-step based on user's task description:
- If user specifies "use Codex/Gemini/Qwen for X" → Add command field to relevant steps
- Default: Agent execution (no command field) unless user explicitly requests CLI
Based on userConfig.executionMethod:
- "agent": No command field in implementation_approach steps
- "hybrid": Add command field to complex steps only (agent handles simple steps)
- "cli": Add command field to ALL implementation_approach steps
CLI Resume Support (MANDATORY for all CLI commands):
- Use --resume parameter to continue from previous task execution
- Read previous task's cliExecutionId from session state
- Format: ccw cli exec "[prompt]" --resume ${previousCliId} --tool ${tool} --mode auto
## EXPLORATION CONTEXT (from context-package.exploration_results)
- Load exploration_results from context-package.json
@@ -186,6 +279,7 @@ Determine CLI tool usage per-step based on user's task description:
- Artifacts integration from context package
- **focus_paths enhanced with exploration critical_files**
- Flow control with pre_analysis steps (include exploration integration_points analysis)
- **CLI Execution IDs and strategies (MANDATORY)**
2. Implementation Plan (IMPL_PLAN.md)
- Context analysis and artifact references
@@ -197,6 +291,27 @@ Determine CLI tool usage per-step based on user's task description:
- Links to task JSONs and summaries
- Matches task JSON hierarchy
## CLI EXECUTION ID REQUIREMENTS (MANDATORY)
Each task JSON MUST include:
- **cli_execution_id**: Unique ID for CLI execution (format: `{session_id}-{task_id}`)
- **cli_execution**: Strategy object based on depends_on:
- No deps → `{ "strategy": "new" }`
- 1 dep (single child) → `{ "strategy": "resume", "resume_from": "parent-cli-id" }`
- 1 dep (multiple children) → `{ "strategy": "fork", "resume_from": "parent-cli-id" }`
- N deps → `{ "strategy": "merge_fork", "merge_from": ["id1", "id2", ...] }`
**CLI Execution Strategy Rules**:
1. **new**: Task has no dependencies - starts fresh CLI conversation
2. **resume**: Task has 1 parent AND that parent has only this child - continues same conversation
3. **fork**: Task has 1 parent BUT parent has multiple children - creates new branch with parent context
4. **merge_fork**: Task has multiple parents - merges all parent contexts into new conversation
**Execution Command Patterns**:
- new: `ccw cli exec "[prompt]" --tool [tool] --id [cli_execution_id]`
- resume: `ccw cli exec "[prompt]" --resume [resume_from] --tool [tool]`
- fork: `ccw cli exec "[prompt]" --resume [resume_from] --id [cli_execution_id] --tool [tool]`
- merge_fork: `ccw cli exec "[prompt]" --resume [merge_from.join(',')] --id [cli_execution_id] --tool [tool]`
## QUALITY STANDARDS
Hard Constraints:
- Task count <= 18 (hard limit - request re-scope if exceeded)