mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-11 02:33:51 +08:00
feat(execution): add Phase 4: Execution with agent orchestration, lazy loading, and auto-commit features
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
# Phase 1: Session Discovery
|
||||
|
||||
Discover existing sessions or start new workflow session with intelligent session management and conflict detection.
|
||||
|
||||
## Objective
|
||||
|
||||
- Ensure project-level state exists (first-time initialization)
|
||||
- Create or discover workflow session for the planning workflow
|
||||
- Generate unique session ID (WFS-xxx format)
|
||||
- Initialize session directory structure
|
||||
|
||||
## Step 0: Initialize Project State (First-time Only)
|
||||
|
||||
**Executed before all modes** - Ensures project-level state files exist by calling `workflow:init`.
|
||||
|
||||
### Check and Initialize
|
||||
```bash
|
||||
# Check if project state exists (both files required)
|
||||
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
|
||||
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
|
||||
```
|
||||
|
||||
**If either NOT_FOUND**, delegate to `workflow:init`:
|
||||
```javascript
|
||||
// Codex: Execute workflow:init command for intelligent project analysis
|
||||
codex workflow:init
|
||||
|
||||
// Wait for init completion
|
||||
// project-tech.json and project-guidelines.json will be created
|
||||
```
|
||||
|
||||
**Output**:
|
||||
- If BOTH_EXIST: `PROJECT_STATE: initialized`
|
||||
- If NOT_FOUND: Calls `workflow:init` → creates:
|
||||
- `.workflow/project-tech.json` with full technical analysis
|
||||
- `.workflow/project-guidelines.json` with empty scaffold
|
||||
|
||||
**Note**: `workflow:init` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1.1: Execute Session Start
|
||||
|
||||
```javascript
|
||||
// Codex: Execute session start command
|
||||
codex workflow:session:start --auto "[structured-task-description]"
|
||||
```
|
||||
|
||||
**Task Description Structure**:
|
||||
```
|
||||
GOAL: [Clear, concise objective]
|
||||
SCOPE: [What's included/excluded]
|
||||
CONTEXT: [Relevant background or constraints]
|
||||
```
|
||||
|
||||
**Example**:
|
||||
```
|
||||
GOAL: Build JWT-based authentication system
|
||||
SCOPE: User registration, login, token validation
|
||||
CONTEXT: Existing user database schema, REST API endpoints
|
||||
```
|
||||
|
||||
### Step 1.2: Parse Output
|
||||
|
||||
- Extract: `SESSION_ID: WFS-[id]` (store as `sessionId`)
|
||||
|
||||
### Step 1.3: Validate
|
||||
|
||||
- Session ID successfully extracted
|
||||
- Session directory `.workflow/active/[sessionId]/` exists
|
||||
|
||||
**Note**: Session directory contains `workflow-session.json` (metadata). Do NOT look for `manifest.json` here - it only exists in `.workflow/archives/` for archived sessions.
|
||||
|
||||
### Step 1.4: Initialize Planning Notes
|
||||
|
||||
Create `planning-notes.md` with N+1 context support:
|
||||
|
||||
```javascript
|
||||
const planningNotesPath = `.workflow/active/${sessionId}/planning-notes.md`
|
||||
const userGoal = structuredDescription.goal
|
||||
const userConstraints = structuredDescription.context || "None specified"
|
||||
|
||||
Write(planningNotesPath, `# Planning Notes
|
||||
|
||||
**Session**: ${sessionId}
|
||||
**Created**: ${new Date().toISOString()}
|
||||
|
||||
## User Intent (Phase 1)
|
||||
|
||||
- **GOAL**: ${userGoal}
|
||||
- **KEY_CONSTRAINTS**: ${userConstraints}
|
||||
|
||||
---
|
||||
|
||||
## Context Findings (Phase 2)
|
||||
(To be filled by context-gather)
|
||||
|
||||
## Conflict Decisions (Phase 2)
|
||||
(To be filled if conflicts detected)
|
||||
|
||||
## Consolidated Constraints (Phase 3 Input)
|
||||
1. ${userConstraints}
|
||||
|
||||
---
|
||||
|
||||
## Task Generation (Phase 3)
|
||||
(To be filled by action-planning-agent)
|
||||
|
||||
## N+1 Context
|
||||
### Decisions
|
||||
| Decision | Rationale | Revisit? |
|
||||
|----------|-----------|----------|
|
||||
|
||||
### Deferred
|
||||
- [ ] (For N+1)
|
||||
`)
|
||||
```
|
||||
|
||||
## Session Types
|
||||
|
||||
The `--type` parameter classifies sessions for CCW dashboard organization:
|
||||
|
||||
| Type | Description | Default For |
|
||||
|------|-------------|-------------|
|
||||
| `workflow` | Standard implementation (default) | `workflow:plan` |
|
||||
| `review` | Code review sessions | `workflow:review-module-cycle` |
|
||||
| `tdd` | TDD-based development | `workflow:tdd-plan` |
|
||||
| `test` | Test generation/fix sessions | `workflow:test-fix-gen` |
|
||||
| `docs` | Documentation sessions | `memory:docs` |
|
||||
|
||||
**Validation**: If `--type` is provided with invalid value, return error:
|
||||
```
|
||||
ERROR: Invalid session type. Valid types: workflow, review, tdd, test, docs
|
||||
```
|
||||
|
||||
## Mode 1: Discovery Mode (Default)
|
||||
|
||||
### Usage
|
||||
```bash
|
||||
workflow:session:start
|
||||
```
|
||||
|
||||
### Step 1: List Active Sessions
|
||||
```bash
|
||||
bash(ls -1 .workflow/active/ 2>/dev/null | head -5)
|
||||
```
|
||||
|
||||
### Step 2: Display Session Metadata
|
||||
```bash
|
||||
bash(cat .workflow/active/WFS-promptmaster-platform/workflow-session.json)
|
||||
```
|
||||
|
||||
### Step 4: User Decision
|
||||
Present session information and wait for user to select or create session.
|
||||
|
||||
**Output**: `SESSION_ID: WFS-[user-selected-id]`
|
||||
|
||||
## Mode 2: Auto Mode (Intelligent)
|
||||
|
||||
### Usage
|
||||
```bash
|
||||
workflow:session:start --auto "task description"
|
||||
```
|
||||
|
||||
### Step 1: Check Active Sessions Count
|
||||
```bash
|
||||
bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null | wc -l)
|
||||
```
|
||||
|
||||
### Step 2a: No Active Sessions → Create New
|
||||
```bash
|
||||
# Generate session slug
|
||||
bash(echo "implement OAuth2 auth" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)
|
||||
|
||||
# Create directory structure
|
||||
bash(mkdir -p .workflow/active/WFS-implement-oauth2-auth/.process)
|
||||
bash(mkdir -p .workflow/active/WFS-implement-oauth2-auth/.task)
|
||||
bash(mkdir -p .workflow/active/WFS-implement-oauth2-auth/.summaries)
|
||||
|
||||
# Create metadata (include type field, default to "workflow" if not specified)
|
||||
bash(echo '{"session_id":"WFS-implement-oauth2-auth","project":"implement OAuth2 auth","status":"planning","type":"workflow","created_at":"2024-12-04T08:00:00Z"}' > .workflow/active/WFS-implement-oauth2-auth/workflow-session.json)
|
||||
```
|
||||
|
||||
**Output**: `SESSION_ID: WFS-implement-oauth2-auth`
|
||||
|
||||
### Step 2b: Single Active Session → Check Relevance
|
||||
```bash
|
||||
# Extract session ID
|
||||
bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null | head -1 | xargs basename)
|
||||
|
||||
# Read project name from metadata
|
||||
bash(cat .workflow/active/WFS-promptmaster-platform/workflow-session.json | grep -o '"project":"[^"]*"' | cut -d'"' -f4)
|
||||
|
||||
# Check keyword match (manual comparison)
|
||||
# If task contains project keywords → Reuse session
|
||||
# If task unrelated → Create new session (use Step 2a)
|
||||
```
|
||||
|
||||
**Output (reuse)**: `SESSION_ID: WFS-promptmaster-platform`
|
||||
**Output (new)**: `SESSION_ID: WFS-[new-slug]`
|
||||
|
||||
### Step 2c: Multiple Active Sessions → Use First
|
||||
```bash
|
||||
# Get first active session
|
||||
bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null | head -1 | xargs basename)
|
||||
|
||||
# Output warning and session ID
|
||||
# WARNING: Multiple active sessions detected
|
||||
# SESSION_ID: WFS-first-session
|
||||
```
|
||||
|
||||
## Mode 3: Force New Mode
|
||||
|
||||
### Usage
|
||||
```bash
|
||||
workflow:session:start --new "task description"
|
||||
```
|
||||
|
||||
### Step 1: Generate Unique Session Slug
|
||||
```bash
|
||||
# Convert to slug
|
||||
bash(echo "fix login bug" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)
|
||||
|
||||
# Check if exists, add counter if needed
|
||||
bash(ls .workflow/active/WFS-fix-login-bug 2>/dev/null && echo "WFS-fix-login-bug-2" || echo "WFS-fix-login-bug")
|
||||
```
|
||||
|
||||
### Step 2: Create Session Structure
|
||||
```bash
|
||||
bash(mkdir -p .workflow/active/WFS-fix-login-bug/.process)
|
||||
bash(mkdir -p .workflow/active/WFS-fix-login-bug/.task)
|
||||
bash(mkdir -p .workflow/active/WFS-fix-login-bug/.summaries)
|
||||
```
|
||||
|
||||
### Step 3: Create Metadata
|
||||
```bash
|
||||
# Include type field from --type parameter (default: "workflow")
|
||||
bash(echo '{"session_id":"WFS-fix-login-bug","project":"fix login bug","status":"planning","type":"workflow","created_at":"2024-12-04T08:00:00Z"}' > .workflow/active/WFS-fix-login-bug/workflow-session.json)
|
||||
```
|
||||
|
||||
**Output**: `SESSION_ID: WFS-fix-login-bug`
|
||||
|
||||
## Execution Guideline
|
||||
|
||||
- **Non-interrupting**: When called from other commands, this command completes and returns control to the caller without interrupting subsequent tasks.
|
||||
|
||||
## Session ID Format
|
||||
|
||||
- Pattern: `WFS-[lowercase-slug]`
|
||||
- Characters: `a-z`, `0-9`, `-` only
|
||||
- Max length: 50 characters
|
||||
- Uniqueness: Add numeric suffix if collision (`WFS-auth-2`, `WFS-auth-3`)
|
||||
|
||||
## Output Format Specification
|
||||
|
||||
### Success
|
||||
```
|
||||
SESSION_ID: WFS-session-slug
|
||||
```
|
||||
|
||||
### Error
|
||||
```
|
||||
ERROR: --auto mode requires task description
|
||||
ERROR: Failed to create session directory
|
||||
```
|
||||
|
||||
### Analysis (Auto Mode)
|
||||
```
|
||||
ANALYSIS: Task relevance = high
|
||||
DECISION: Reusing existing session
|
||||
SESSION_ID: WFS-promptmaster-platform
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
- **Variable**: `sessionId` (e.g., `WFS-implement-oauth2-auth`)
|
||||
- **File**: `.workflow/active/{sessionId}/planning-notes.md`
|
||||
- **TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress
|
||||
|
||||
## Next Phase
|
||||
|
||||
Return to orchestrator showing Phase 1 results, then auto-continue to [Phase 2: Context Gathering](02-context-gathering.md).
|
||||
@@ -0,0 +1,928 @@
|
||||
# Phase 2: Context Gathering & Conflict Resolution
|
||||
|
||||
Intelligently collect project context using context-search-agent based on task description, packages into standardized JSON. When conflicts are detected, resolve them inline before packaging.
|
||||
|
||||
## Objective
|
||||
|
||||
- Check for existing valid context-package before executing
|
||||
- Assess task complexity and launch parallel exploration agents (with conflict detection)
|
||||
- Detect and resolve conflicts inline (conditional, when conflict indicators found)
|
||||
- Invoke context-search-agent to analyze codebase
|
||||
- Generate standardized `context-package.json` with prioritized context
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
- **Agent Delegation**: Delegate all discovery to `context-search-agent` for autonomous execution
|
||||
- **Detection-First**: Check for existing context-package before executing
|
||||
- **Conflict-Aware Exploration**: Explore agents detect conflict indicators during exploration
|
||||
- **Inline Resolution**: Conflicts resolved as sub-step within this phase, not a separate phase
|
||||
- **Conditional Trigger**: Conflict resolution only executes when exploration results contain conflict indicators
|
||||
- **Plan Mode**: Full comprehensive analysis (vs lightweight brainstorm mode)
|
||||
- **Standardized Output**: Generate `.workflow/active/{session}/.process/context-package.json`
|
||||
- **Explicit Lifecycle**: Manage subagent creation, waiting, and cleanup
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Input Parsing:
|
||||
├─ Parse flags: --session
|
||||
└─ Parse: task_description (required)
|
||||
|
||||
Step 1: Context-Package Detection
|
||||
└─ Decision (existing package):
|
||||
├─ Valid package exists → Return existing (skip execution)
|
||||
└─ No valid package → Continue to Step 2
|
||||
|
||||
Step 2: Complexity Assessment & Parallel Explore (conflict-aware)
|
||||
├─ Analyze task_description → classify Low/Medium/High
|
||||
├─ Select exploration angles (1-4 based on complexity)
|
||||
├─ Launch N cli-explore-agents in parallel (spawn_agent)
|
||||
│ └─ Each outputs: exploration-{angle}.json (includes conflict_indicators)
|
||||
├─ Wait for all agents (batch wait)
|
||||
├─ Close all agents
|
||||
└─ Generate explorations-manifest.json
|
||||
|
||||
Step 3: Inline Conflict Resolution (conditional)
|
||||
├─ 3.1 Aggregate conflict_indicators from all explorations
|
||||
├─ 3.2 Decision: No significant conflicts → Skip to Step 4
|
||||
├─ 3.3 Spawn conflict-analysis agent (cli-execution-agent)
|
||||
│ └─ Gemini/Qwen CLI analysis → conflict strategies
|
||||
├─ 3.4 Iterative user clarification (send_input loop, max 10 rounds)
|
||||
│ ├─ Display conflict + strategy ONE BY ONE
|
||||
│ ├─ AskUserQuestion for user selection
|
||||
│ └─ send_input → agent re-analysis → confirm uniqueness
|
||||
├─ 3.5 Generate conflict-resolution.json
|
||||
└─ 3.6 Close conflict agent
|
||||
|
||||
Step 4: Invoke Context-Search Agent (enhanced)
|
||||
├─ Receives exploration results + resolved conflicts (if any)
|
||||
└─ Generates context-package.json with exploration_results + conflict status
|
||||
|
||||
Step 5: Output Verification (enhanced)
|
||||
└─ Verify context-package.json contains exploration_results + conflict resolution
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Step 1: Context-Package Detection
|
||||
|
||||
**Execute First** - Check if valid package already exists:
|
||||
|
||||
```javascript
|
||||
const contextPackagePath = `.workflow/${session_id}/.process/context-package.json`;
|
||||
|
||||
if (file_exists(contextPackagePath)) {
|
||||
const existing = Read(contextPackagePath);
|
||||
|
||||
// Validate package belongs to current session
|
||||
if (existing?.metadata?.session_id === session_id) {
|
||||
console.log("Valid context-package found for session:", session_id);
|
||||
console.log("Stats:", existing.statistics);
|
||||
console.log("Conflict Risk:", existing.conflict_detection.risk_level);
|
||||
return existing; // Skip execution, return existing
|
||||
} else {
|
||||
console.warn("Invalid session_id in existing package, re-generating...");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Complexity Assessment & Parallel Explore
|
||||
|
||||
**Only execute if Step 1 finds no valid package**
|
||||
|
||||
```javascript
|
||||
// 2.1 Complexity Assessment
|
||||
function analyzeTaskComplexity(taskDescription) {
|
||||
const text = taskDescription.toLowerCase();
|
||||
if (/architect|refactor|restructure|modular|cross-module/.test(text)) return 'High';
|
||||
if (/multiple|several|integrate|migrate|extend/.test(text)) return 'Medium';
|
||||
return 'Low';
|
||||
}
|
||||
|
||||
const ANGLE_PRESETS = {
|
||||
architecture: ['architecture', 'dependencies', 'modularity', 'integration-points'],
|
||||
security: ['security', 'auth-patterns', 'dataflow', 'validation'],
|
||||
performance: ['performance', 'bottlenecks', 'caching', 'data-access'],
|
||||
bugfix: ['error-handling', 'dataflow', 'state-management', 'edge-cases'],
|
||||
feature: ['patterns', 'integration-points', 'testing', 'dependencies'],
|
||||
refactor: ['architecture', 'patterns', 'dependencies', 'testing']
|
||||
};
|
||||
|
||||
function selectAngles(taskDescription, complexity) {
|
||||
const text = taskDescription.toLowerCase();
|
||||
let preset = 'feature';
|
||||
if (/refactor|architect|restructure/.test(text)) preset = 'architecture';
|
||||
else if (/security|auth|permission/.test(text)) preset = 'security';
|
||||
else if (/performance|slow|optimi/.test(text)) preset = 'performance';
|
||||
else if (/fix|bug|error|issue/.test(text)) preset = 'bugfix';
|
||||
|
||||
const count = complexity === 'High' ? 4 : (complexity === 'Medium' ? 3 : 1);
|
||||
return ANGLE_PRESETS[preset].slice(0, count);
|
||||
}
|
||||
|
||||
const complexity = analyzeTaskComplexity(task_description);
|
||||
const selectedAngles = selectAngles(task_description, complexity);
|
||||
const sessionFolder = `.workflow/active/${session_id}/.process`;
|
||||
|
||||
// 2.2 Launch Parallel Explore Agents (with conflict detection)
|
||||
const explorationAgents = [];
|
||||
|
||||
// Spawn all agents in parallel
|
||||
selectedAngles.forEach((angle, index) => {
|
||||
const agentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## Task Objective
|
||||
Execute **${angle}** exploration for task planning context. Analyze codebase from this specific angle to discover relevant structure, patterns, and constraints.
|
||||
|
||||
**CONFLICT DETECTION**: Additionally detect conflict indicators including module overlaps, breaking changes, incompatible patterns, and scenario boundary ambiguities.
|
||||
|
||||
## Assigned Context
|
||||
- **Exploration Angle**: ${angle}
|
||||
- **Task Description**: ${task_description}
|
||||
- **Session ID**: ${session_id}
|
||||
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
|
||||
- **Output File**: ${sessionFolder}/exploration-${angle}.json
|
||||
|
||||
## MANDATORY FIRST STEPS (Execute by Agent)
|
||||
**You (cli-explore-agent) MUST execute these steps in order:**
|
||||
1. Run: ccw tool exec get_modules_by_depth '{}' (project structure)
|
||||
2. Run: rg -l "{keyword_from_task}" --type ts (locate relevant files)
|
||||
3. Execute: cat ~/.claude/workflows/cli-templates/schemas/explore-json-schema.json (get output schema reference)
|
||||
|
||||
## Exploration Strategy (${angle} focus)
|
||||
|
||||
**Step 1: Structural Scan** (Bash)
|
||||
- get_modules_by_depth.sh → identify modules related to ${angle}
|
||||
- find/rg → locate files relevant to ${angle} aspect
|
||||
- Analyze imports/dependencies from ${angle} perspective
|
||||
|
||||
**Step 2: Semantic Analysis** (Gemini CLI)
|
||||
- How does existing code handle ${angle} concerns?
|
||||
- What patterns are used for ${angle}?
|
||||
- Where would new code integrate from ${angle} viewpoint?
|
||||
- **Detect conflict indicators**: module overlaps, breaking changes, incompatible patterns
|
||||
|
||||
**Step 3: Write Output**
|
||||
- Consolidate ${angle} findings into JSON
|
||||
- Identify ${angle}-specific clarification needs
|
||||
- **Include conflict_indicators array** with detected conflicts
|
||||
|
||||
## Expected Output
|
||||
|
||||
**File**: ${sessionFolder}/exploration-${angle}.json
|
||||
|
||||
**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)
|
||||
- **conflict_indicators**: Array of detected conflicts from ${angle} perspective
|
||||
\`[{type: "ModuleOverlap|BreakingChange|PatternConflict", severity: "high|medium|low", description: "...", affected_files: [...]}]\`
|
||||
- _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}
|
||||
- [ ] conflict_indicators populated (empty array if none detected)
|
||||
- [ ] JSON output follows schema exactly
|
||||
- [ ] clarification_needs includes options + recommended
|
||||
|
||||
## Output
|
||||
Write: ${sessionFolder}/exploration-${angle}.json
|
||||
Return: 2-3 sentence summary of ${angle} findings + conflict indicators count
|
||||
`
|
||||
});
|
||||
|
||||
explorationAgents.push(agentId);
|
||||
});
|
||||
|
||||
// 2.3 Batch wait for all exploration agents
|
||||
const explorationResults = wait({
|
||||
ids: explorationAgents,
|
||||
timeout_ms: 600000 // 10 minutes
|
||||
});
|
||||
|
||||
// Check for timeouts
|
||||
if (explorationResults.timed_out) {
|
||||
console.log('Some exploration agents timed out - continuing with completed results');
|
||||
}
|
||||
|
||||
// 2.4 Close all exploration agents
|
||||
explorationAgents.forEach(agentId => {
|
||||
close_agent({ id: agentId });
|
||||
});
|
||||
|
||||
// 2.5 Generate Manifest after all complete
|
||||
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`).split('\n').filter(f => f.trim());
|
||||
const explorationManifest = {
|
||||
session_id,
|
||||
task_description,
|
||||
timestamp: new Date().toISOString(),
|
||||
complexity,
|
||||
exploration_count: selectedAngles.length,
|
||||
angles_explored: selectedAngles,
|
||||
explorations: explorationFiles.map(file => {
|
||||
const data = JSON.parse(Read(file));
|
||||
return { angle: data._metadata.exploration_angle, file: file.split('/').pop(), path: file, index: data._metadata.exploration_index };
|
||||
})
|
||||
};
|
||||
Write(`${sessionFolder}/explorations-manifest.json`, JSON.stringify(explorationManifest, null, 2));
|
||||
```
|
||||
|
||||
### Step 3: Inline Conflict Resolution
|
||||
|
||||
**Conditional execution** - Only runs when exploration results contain significant conflict indicators.
|
||||
|
||||
#### 3.1 Aggregate Conflict Indicators
|
||||
|
||||
```javascript
|
||||
// Aggregate conflict_indicators from all explorations
|
||||
const allConflictIndicators = [];
|
||||
explorationFiles.forEach(file => {
|
||||
const data = JSON.parse(Read(file));
|
||||
if (data.conflict_indicators?.length > 0) {
|
||||
allConflictIndicators.push(...data.conflict_indicators.map(ci => ({
|
||||
...ci,
|
||||
source_angle: data._metadata.exploration_angle
|
||||
})));
|
||||
}
|
||||
});
|
||||
|
||||
const hasSignificantConflicts = allConflictIndicators.some(ci => ci.severity === 'high') ||
|
||||
allConflictIndicators.filter(ci => ci.severity === 'medium').length >= 2;
|
||||
```
|
||||
|
||||
#### 3.2 Decision Gate
|
||||
|
||||
```javascript
|
||||
if (!hasSignificantConflicts) {
|
||||
console.log(`No significant conflicts detected (${allConflictIndicators.length} low indicators). Skipping conflict resolution.`);
|
||||
// Skip to Step 4
|
||||
} else {
|
||||
console.log(`Significant conflicts detected: ${allConflictIndicators.length} indicators. Launching conflict analysis...`);
|
||||
// Continue to 3.3
|
||||
}
|
||||
```
|
||||
|
||||
#### 3.3 Spawn Conflict-Analysis Agent
|
||||
|
||||
```javascript
|
||||
const conflictAgentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/cli-execution-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## Context
|
||||
- Session: ${session_id}
|
||||
- Conflict Indicators: ${JSON.stringify(allConflictIndicators)}
|
||||
- Files: ${existing_files_list}
|
||||
|
||||
## Exploration Context (from exploration results)
|
||||
- Exploration Count: ${explorationManifest.exploration_count}
|
||||
- Angles Analyzed: ${JSON.stringify(explorationManifest.angles_explored)}
|
||||
- Pre-identified Conflict Indicators: ${JSON.stringify(allConflictIndicators)}
|
||||
- Critical Files: ${JSON.stringify(explorationFiles.flatMap(f => JSON.parse(Read(f)).relevant_files?.filter(rf => rf.relevance >= 0.7).map(rf => rf.path) || []))}
|
||||
|
||||
## Analysis Steps
|
||||
|
||||
### 0. Load Output Schema (MANDATORY)
|
||||
Execute: cat ~/.claude/workflows/cli-templates/schemas/conflict-resolution-schema.json
|
||||
|
||||
### 1. Load Context
|
||||
- Read existing files from conflict indicators
|
||||
- Load exploration results and use aggregated insights for enhanced analysis
|
||||
|
||||
### 2. Execute CLI Analysis (Enhanced with Exploration + Scenario Uniqueness)
|
||||
|
||||
Primary (Gemini):
|
||||
ccw cli -p "
|
||||
PURPOSE: Detect conflicts between plan and codebase, using exploration insights
|
||||
TASK:
|
||||
• **Review pre-identified conflict_indicators from exploration results**
|
||||
• Compare architectures (use exploration key_patterns)
|
||||
• Identify breaking API changes
|
||||
• Detect data model incompatibilities
|
||||
• Assess dependency conflicts
|
||||
• **Analyze module scenario uniqueness**
|
||||
- Cross-validate with exploration critical_files
|
||||
- Generate clarification questions for boundary definition
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*.ts @**/*.js @**/*.tsx @**/*.jsx @.workflow/active/${session_id}/**/*
|
||||
EXPECTED: Conflict list with severity ratings, including:
|
||||
- Validation of exploration conflict_indicators
|
||||
- ModuleOverlap conflicts with overlap_analysis
|
||||
- Targeted clarification questions
|
||||
CONSTRAINTS: Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
|
||||
" --tool gemini --mode analysis --rule analysis-code-patterns --cd ${project_root}
|
||||
|
||||
Fallback: Qwen (same prompt) → Claude (manual analysis)
|
||||
|
||||
### 3. Generate Strategies (2-4 per conflict)
|
||||
|
||||
Template per conflict:
|
||||
- Severity: Critical/High/Medium
|
||||
- Category: Architecture/API/Data/Dependency/ModuleOverlap
|
||||
- Affected files + impact
|
||||
- **For ModuleOverlap**: Include overlap_analysis with existing modules and scenarios
|
||||
- Options with pros/cons, effort, risk
|
||||
- **For ModuleOverlap strategies**: Add clarification_needed questions for boundary definition
|
||||
- Recommended strategy + rationale
|
||||
|
||||
### 4. Return Structured Conflict Data
|
||||
|
||||
**Schema Reference**: Execute \`cat ~/.claude/workflows/cli-templates/schemas/conflict-resolution-schema.json\` to get full schema
|
||||
|
||||
Return JSON following the schema above. Key requirements:
|
||||
- Minimum 2 strategies per conflict, max 4
|
||||
- All text in Chinese for user-facing fields (brief, name, pros, cons, modification_suggestions)
|
||||
- modifications.old_content: 20-100 chars for unique Edit tool matching
|
||||
- modifications.new_content: preserves markdown formatting
|
||||
- modification_suggestions: 2-5 actionable suggestions for custom handling
|
||||
|
||||
### 5. Planning Notes Record (REQUIRED)
|
||||
After analysis complete, append a brief execution record to planning-notes.md:
|
||||
|
||||
**File**: .workflow/active/${session_id}/planning-notes.md
|
||||
**Location**: Under "## Conflict Decisions (Phase 2)" section
|
||||
**Format**:
|
||||
\`\`\`
|
||||
### [Conflict-Resolution Agent] YYYY-MM-DD
|
||||
- **Note**: [brief summary of conflict types, resolution strategies, key decisions]
|
||||
\`\`\`
|
||||
`
|
||||
});
|
||||
|
||||
// Wait for initial analysis
|
||||
const analysisResult = wait({
|
||||
ids: [conflictAgentId],
|
||||
timeout_ms: 600000 // 10 minutes
|
||||
});
|
||||
|
||||
// Parse conflicts from result
|
||||
const conflicts = parseConflictsFromResult(analysisResult);
|
||||
```
|
||||
|
||||
#### Conflict Categories
|
||||
|
||||
| Category | Description |
|
||||
|----------|-------------|
|
||||
| **Architecture** | Incompatible design patterns, module structure changes, pattern migration |
|
||||
| **API** | Breaking contract changes, signature modifications, public interface impacts |
|
||||
| **Data Model** | Schema modifications, type breaking changes, data migration needs |
|
||||
| **Dependency** | Version incompatibilities, setup conflicts, breaking updates |
|
||||
| **ModuleOverlap** | Functional overlap, scenario boundary ambiguity, duplicate responsibility |
|
||||
|
||||
#### 3.4 Iterative User Clarification
|
||||
|
||||
```javascript
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
const resolvedConflicts = [];
|
||||
const customConflicts = [];
|
||||
|
||||
FOR each conflict:
|
||||
round = 0, clarified = false, userClarifications = []
|
||||
|
||||
WHILE (!clarified && round++ < 10):
|
||||
// 1. Display conflict info (text output for context)
|
||||
displayConflictSummary(conflict) // id, brief, severity, overlap_analysis if ModuleOverlap
|
||||
|
||||
// 2. Strategy selection
|
||||
if (autoYes) {
|
||||
console.log(`[--yes] Auto-selecting recommended strategy`)
|
||||
selectedStrategy = conflict.strategies[conflict.recommended || 0]
|
||||
clarified = true // Skip clarification loop
|
||||
} else {
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: formatStrategiesForDisplay(conflict.strategies),
|
||||
header: "策略选择",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
...conflict.strategies.map((s, i) => ({
|
||||
label: `${s.name}${i === conflict.recommended ? ' (推荐)' : ''}`,
|
||||
description: `${s.complexity}复杂度 | ${s.risk}风险${s.clarification_needed?.length ? ' | 需澄清' : ''}`
|
||||
})),
|
||||
{ label: "自定义修改", description: `建议: ${conflict.modification_suggestions?.slice(0,2).join('; ')}` }
|
||||
]
|
||||
}]
|
||||
})
|
||||
|
||||
// 3. Handle selection
|
||||
if (userChoice === "自定义修改") {
|
||||
customConflicts.push({ id, brief, category, suggestions, overlap_analysis })
|
||||
break
|
||||
}
|
||||
|
||||
selectedStrategy = findStrategyByName(userChoice)
|
||||
}
|
||||
|
||||
// 4. Clarification (if needed) - using send_input for agent re-analysis
|
||||
if (!autoYes && selectedStrategy.clarification_needed?.length > 0) {
|
||||
for (batch of chunk(selectedStrategy.clarification_needed, 4)) {
|
||||
AskUserQuestion({
|
||||
questions: batch.map((q, i) => ({
|
||||
question: q, header: `澄清${i+1}`, multiSelect: false,
|
||||
options: [{ label: "详细说明", description: "提供答案" }]
|
||||
}))
|
||||
})
|
||||
userClarifications.push(...collectAnswers(batch))
|
||||
}
|
||||
|
||||
// 5. Agent re-analysis via send_input (key: agent stays active)
|
||||
send_input({
|
||||
id: conflictAgentId,
|
||||
message: `
|
||||
## CLARIFICATION ANSWERS
|
||||
Conflict: ${conflict.id}
|
||||
Strategy: ${selectedStrategy.name}
|
||||
User Clarifications: ${JSON.stringify(userClarifications)}
|
||||
|
||||
## REQUEST
|
||||
Based on the clarifications above, update the strategy assessment.
|
||||
Output: { uniqueness_confirmed: boolean, rationale: string, updated_strategy: {...}, remaining_questions: [...] }
|
||||
`
|
||||
});
|
||||
|
||||
// Wait for re-analysis result
|
||||
const reanalysisResult = wait({
|
||||
ids: [conflictAgentId],
|
||||
timeout_ms: 300000 // 5 minutes
|
||||
});
|
||||
|
||||
const parsedResult = parseReanalysisResult(reanalysisResult);
|
||||
|
||||
if (parsedResult.uniqueness_confirmed) {
|
||||
selectedStrategy = { ...parsedResult.updated_strategy, clarifications: userClarifications }
|
||||
clarified = true
|
||||
} else {
|
||||
selectedStrategy.clarification_needed = parsedResult.remaining_questions
|
||||
}
|
||||
} else {
|
||||
clarified = true
|
||||
}
|
||||
|
||||
if (clarified) resolvedConflicts.push({ conflict, strategy: selectedStrategy })
|
||||
END WHILE
|
||||
END FOR
|
||||
|
||||
selectedStrategies = resolvedConflicts.map(r => ({
|
||||
conflict_id: r.conflict.id, strategy: r.strategy, clarifications: r.strategy.clarifications || []
|
||||
}))
|
||||
```
|
||||
|
||||
**Key Points**:
|
||||
- AskUserQuestion: max 4 questions/call, batch if more
|
||||
- Strategy options: 2-4 strategies + "自定义修改"
|
||||
- Clarification loop via send_input: max 10 rounds, agent determines uniqueness_confirmed
|
||||
- Agent stays active throughout interaction (no close_agent until Step 3.6)
|
||||
- Custom conflicts: record overlap_analysis for subsequent manual handling
|
||||
|
||||
#### 3.5 Generate conflict-resolution.json
|
||||
|
||||
```javascript
|
||||
// Apply modifications from resolved strategies
|
||||
const modifications = [];
|
||||
selectedStrategies.forEach(item => {
|
||||
if (item.strategy && item.strategy.modifications) {
|
||||
modifications.push(...item.strategy.modifications.map(mod => ({
|
||||
...mod,
|
||||
conflict_id: item.conflict_id,
|
||||
clarifications: item.clarifications
|
||||
})));
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nApplying ${modifications.length} modifications...`);
|
||||
|
||||
const appliedModifications = [];
|
||||
const failedModifications = [];
|
||||
const fallbackConstraints = [];
|
||||
|
||||
modifications.forEach((mod, idx) => {
|
||||
try {
|
||||
console.log(`[${idx + 1}/${modifications.length}] Modifying ${mod.file}...`);
|
||||
|
||||
if (!file_exists(mod.file)) {
|
||||
console.log(` File not found, recording as constraint`);
|
||||
fallbackConstraints.push({
|
||||
source: "conflict-resolution",
|
||||
conflict_id: mod.conflict_id,
|
||||
target_file: mod.file,
|
||||
section: mod.section,
|
||||
change_type: mod.change_type,
|
||||
content: mod.new_content,
|
||||
rationale: mod.rationale
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (mod.change_type === "update") {
|
||||
Edit({ file_path: mod.file, old_string: mod.old_content, new_string: mod.new_content });
|
||||
} else if (mod.change_type === "add") {
|
||||
const fileContent = Read(mod.file);
|
||||
const updated = insertContentAfterSection(fileContent, mod.section, mod.new_content);
|
||||
Write(mod.file, updated);
|
||||
} else if (mod.change_type === "remove") {
|
||||
Edit({ file_path: mod.file, old_string: mod.old_content, new_string: "" });
|
||||
}
|
||||
|
||||
appliedModifications.push(mod);
|
||||
} catch (error) {
|
||||
failedModifications.push({ ...mod, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Generate conflict-resolution.json
|
||||
const resolutionOutput = {
|
||||
session_id: sessionId,
|
||||
resolved_at: new Date().toISOString(),
|
||||
summary: {
|
||||
total_conflicts: conflicts.length,
|
||||
resolved_with_strategy: selectedStrategies.length,
|
||||
custom_handling: customConflicts.length,
|
||||
fallback_constraints: fallbackConstraints.length
|
||||
},
|
||||
resolved_conflicts: selectedStrategies.map(s => ({
|
||||
conflict_id: s.conflict_id,
|
||||
strategy_name: s.strategy.name,
|
||||
strategy_approach: s.strategy.approach,
|
||||
clarifications: s.clarifications || [],
|
||||
modifications_applied: s.strategy.modifications?.filter(m =>
|
||||
appliedModifications.some(am => am.conflict_id === s.conflict_id)
|
||||
) || []
|
||||
})),
|
||||
custom_conflicts: customConflicts.map(c => ({
|
||||
id: c.id, brief: c.brief, category: c.category,
|
||||
suggestions: c.suggestions, overlap_analysis: c.overlap_analysis || null
|
||||
})),
|
||||
planning_constraints: fallbackConstraints,
|
||||
failed_modifications: failedModifications
|
||||
};
|
||||
|
||||
const resolutionPath = `.workflow/active/${sessionId}/.process/conflict-resolution.json`;
|
||||
Write(resolutionPath, JSON.stringify(resolutionOutput, null, 2));
|
||||
|
||||
// Output custom conflict summary (if any)
|
||||
if (customConflicts.length > 0) {
|
||||
customConflicts.forEach(conflict => {
|
||||
console.log(`[${conflict.category}] ${conflict.id}: ${conflict.brief}`);
|
||||
if (conflict.category === 'ModuleOverlap' && conflict.overlap_analysis) {
|
||||
console.log(` New module: ${conflict.overlap_analysis.new_module.name}`);
|
||||
conflict.overlap_analysis.existing_modules.forEach(mod => {
|
||||
console.log(` Overlaps: ${mod.name} (${mod.file})`);
|
||||
});
|
||||
}
|
||||
conflict.suggestions.forEach(s => console.log(` - ${s}`));
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### 3.6 Close Conflict Agent
|
||||
|
||||
```javascript
|
||||
close_agent({ id: conflictAgentId });
|
||||
```
|
||||
|
||||
### Step 4: Invoke Context-Search Agent
|
||||
|
||||
**Execute after Step 2 (and Step 3 if triggered)**
|
||||
|
||||
```javascript
|
||||
// Load user intent from planning-notes.md (from Phase 1)
|
||||
const planningNotesPath = `.workflow/active/${session_id}/planning-notes.md`;
|
||||
let userIntent = { goal: task_description, key_constraints: "None specified" };
|
||||
|
||||
if (file_exists(planningNotesPath)) {
|
||||
const notesContent = Read(planningNotesPath);
|
||||
const goalMatch = notesContent.match(/\*\*GOAL\*\*:\s*(.+)/);
|
||||
const constraintsMatch = notesContent.match(/\*\*KEY_CONSTRAINTS\*\*:\s*(.+)/);
|
||||
if (goalMatch) userIntent.goal = goalMatch[1].trim();
|
||||
if (constraintsMatch) userIntent.key_constraints = constraintsMatch[1].trim();
|
||||
}
|
||||
|
||||
// Prepare conflict resolution context for agent
|
||||
const conflictContext = hasSignificantConflicts
|
||||
? `Conflict Resolution: ${resolutionPath} (${selectedStrategies.length} resolved, ${customConflicts.length} custom)`
|
||||
: `Conflict Resolution: None needed (no significant conflicts detected)`;
|
||||
|
||||
// Spawn context-search-agent
|
||||
const contextAgentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/context-search-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## Execution Mode
|
||||
**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution with priority sorting
|
||||
|
||||
## Session Information
|
||||
- **Session ID**: ${session_id}
|
||||
- **Task Description**: ${task_description}
|
||||
- **Output Path**: .workflow/${session_id}/.process/context-package.json
|
||||
|
||||
## User Intent (from Phase 1 - Planning Notes)
|
||||
**GOAL**: ${userIntent.goal}
|
||||
**KEY_CONSTRAINTS**: ${userIntent.key_constraints}
|
||||
|
||||
This is the PRIMARY context source - all subsequent analysis must align with user intent.
|
||||
|
||||
## Exploration Input (from Step 2)
|
||||
- **Manifest**: ${sessionFolder}/explorations-manifest.json
|
||||
- **Exploration Count**: ${explorationManifest.exploration_count}
|
||||
- **Angles**: ${explorationManifest.angles_explored.join(', ')}
|
||||
- **Complexity**: ${complexity}
|
||||
|
||||
## Conflict Resolution Input (from Step 3)
|
||||
- **${conflictContext}**
|
||||
${hasSignificantConflicts ? `- **Resolution File**: ${resolutionPath}
|
||||
- **Resolved Conflicts**: ${selectedStrategies.length}
|
||||
- **Custom Conflicts**: ${customConflicts.length}
|
||||
- **Planning Constraints**: ${fallbackConstraints.length}` : ''}
|
||||
|
||||
## Mission
|
||||
Execute complete context-search-agent workflow for implementation planning:
|
||||
|
||||
### Phase 1: Initialization & Pre-Analysis
|
||||
1. **Project State Loading**:
|
||||
- Read and parse \`.workflow/project-tech.json\`. Use its \`overview\` section as the foundational \`project_context\`. This is your primary source for architecture, tech stack, and key components.
|
||||
- Read and parse \`.workflow/project-guidelines.json\`. Load \`conventions\`, \`constraints\`, and \`learnings\` into a \`project_guidelines\` section.
|
||||
- If files don't exist, proceed with fresh analysis.
|
||||
2. **Detection**: Check for existing context-package (early exit if valid)
|
||||
3. **Foundation**: Initialize CodexLens, get project structure, load docs
|
||||
4. **Analysis**: Extract keywords, determine scope, classify complexity based on task description and project state
|
||||
|
||||
### Phase 2: Multi-Source Context Discovery
|
||||
Execute all discovery tracks (WITH USER INTENT INTEGRATION):
|
||||
- **Track -1**: User Intent & Priority Foundation (EXECUTE FIRST)
|
||||
- Load user intent (GOAL, KEY_CONSTRAINTS) from session input
|
||||
- Map user requirements to codebase entities (files, modules, patterns)
|
||||
- Establish baseline priority scores based on user goal alignment
|
||||
- Output: user_intent_mapping.json with preliminary priority scores
|
||||
|
||||
- **Track 0**: Exploration Synthesis (load ${sessionFolder}/explorations-manifest.json, prioritize critical_files, deduplicate patterns/integration_points)
|
||||
- **Track 1**: Historical archive analysis (query manifest.json for lessons learned)
|
||||
- **Track 2**: Reference documentation (CLAUDE.md, architecture docs)
|
||||
- **Track 3**: Web examples (use Exa MCP for unfamiliar tech/APIs)
|
||||
- **Track 4**: Codebase analysis (5-layer discovery: files, content, patterns, deps, config/tests)
|
||||
|
||||
### Phase 3: Synthesis, Assessment & Packaging
|
||||
1. Apply relevance scoring and build dependency graph
|
||||
2. **Synthesize 5-source data** (including Track -1): Merge findings from all sources
|
||||
- Priority order: User Intent > Archive > Docs > Exploration > Code > Web
|
||||
- **Prioritize the context from \`project-tech.json\`** for architecture and tech stack unless code analysis reveals it's outdated
|
||||
3. **Context Priority Sorting**:
|
||||
a. Combine scores from Track -1 (user intent alignment) + relevance scores + exploration critical_files
|
||||
b. Classify files into priority tiers:
|
||||
- **Critical** (score >= 0.85): Directly mentioned in user goal OR exploration critical_files
|
||||
- **High** (0.70-0.84): Key dependencies, patterns required for goal
|
||||
- **Medium** (0.50-0.69): Supporting files, indirect dependencies
|
||||
- **Low** (< 0.50): Contextual awareness only
|
||||
c. Generate dependency_order: Based on dependency graph + user goal sequence
|
||||
d. Document sorting_rationale: Explain prioritization logic
|
||||
|
||||
4. **Populate \`project_context\`**: Directly use the \`overview\` from \`project-tech.json\` to fill the \`project_context\` section. Include description, technology_stack, architecture, and key_components.
|
||||
5. **Populate \`project_guidelines\`**: Load conventions, constraints, and learnings from \`project-guidelines.json\` into a dedicated section.
|
||||
6. Integrate brainstorm artifacts (if .brainstorming/ exists, read content)
|
||||
7. Perform conflict detection with risk assessment
|
||||
8. **Inject conflict resolution results** (if conflict-resolution.json exists) into conflict_detection
|
||||
9. **Generate prioritized_context section**:
|
||||
\`\`\`json
|
||||
{
|
||||
"prioritized_context": {
|
||||
"user_intent": {
|
||||
"goal": "...",
|
||||
"scope": "...",
|
||||
"key_constraints": ["..."]
|
||||
},
|
||||
"priority_tiers": {
|
||||
"critical": [{ "path": "...", "relevance": 0.95, "rationale": "..." }],
|
||||
"high": [...],
|
||||
"medium": [...],
|
||||
"low": [...]
|
||||
},
|
||||
"dependency_order": ["module1", "module2", "module3"],
|
||||
"sorting_rationale": "Based on user goal alignment (Track -1), exploration critical files, and dependency graph analysis"
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
10. Generate and validate context-package.json with prioritized_context field
|
||||
|
||||
## Output Requirements
|
||||
Complete context-package.json with:
|
||||
- **metadata**: task_description, keywords, complexity, tech_stack, session_id
|
||||
- **project_context**: description, technology_stack, architecture, key_components (sourced from \`project-tech.json\`)
|
||||
- **project_guidelines**: {conventions, constraints, quality_rules, learnings} (sourced from \`project-guidelines.json\`)
|
||||
- **assets**: {documentation[], source_code[], config[], tests[]} with relevance scores
|
||||
- **dependencies**: {internal[], external[]} with dependency graph
|
||||
- **brainstorm_artifacts**: {guidance_specification, role_analyses[], synthesis_output} with content
|
||||
- **conflict_detection**: {risk_level, risk_factors, affected_modules[], mitigation_strategy, historical_conflicts[], resolution_file (if exists)}
|
||||
- **exploration_results**: {manifest_path, exploration_count, angles, explorations[], aggregated_insights} (from Track 0)
|
||||
- **prioritized_context**: {user_intent, priority_tiers{critical, high, medium, low}, dependency_order[], sorting_rationale}
|
||||
|
||||
## Quality Validation
|
||||
Before completion verify:
|
||||
- [ ] Valid JSON format with all required fields
|
||||
- [ ] File relevance accuracy >80%
|
||||
- [ ] Dependency graph complete (max 2 transitive levels)
|
||||
- [ ] Conflict risk level calculated correctly
|
||||
- [ ] No sensitive data exposed
|
||||
- [ ] Total files <=50 (prioritize high-relevance)
|
||||
|
||||
## Planning Notes Record (REQUIRED)
|
||||
After completing context-package.json, append a brief execution record to planning-notes.md:
|
||||
|
||||
**File**: .workflow/active/${session_id}/planning-notes.md
|
||||
**Location**: Under "## Context Findings (Phase 2)" section
|
||||
**Format**:
|
||||
\`\`\`
|
||||
### [Context-Search Agent] YYYY-MM-DD
|
||||
- **Note**: [brief summary of key findings]
|
||||
\`\`\`
|
||||
|
||||
Execute autonomously following agent documentation.
|
||||
Report completion with statistics.
|
||||
`
|
||||
});
|
||||
|
||||
// Wait for context agent to complete
|
||||
const contextResult = wait({
|
||||
ids: [contextAgentId],
|
||||
timeout_ms: 900000 // 15 minutes
|
||||
});
|
||||
|
||||
// Close context agent
|
||||
close_agent({ id: contextAgentId });
|
||||
```
|
||||
|
||||
### Step 5: Output Verification
|
||||
|
||||
After agent completes, verify output:
|
||||
|
||||
```javascript
|
||||
// Verify file was created
|
||||
const outputPath = `.workflow/${session_id}/.process/context-package.json`;
|
||||
if (!file_exists(outputPath)) {
|
||||
throw new Error("Agent failed to generate context-package.json");
|
||||
}
|
||||
|
||||
// Verify exploration_results included
|
||||
const pkg = JSON.parse(Read(outputPath));
|
||||
if (pkg.exploration_results?.exploration_count > 0) {
|
||||
console.log(`Exploration results aggregated: ${pkg.exploration_results.exploration_count} angles`);
|
||||
}
|
||||
|
||||
// Verify conflict resolution status
|
||||
if (hasSignificantConflicts) {
|
||||
const resolutionFileRef = pkg.conflict_detection?.resolution_file;
|
||||
if (resolutionFileRef) {
|
||||
console.log(`Conflict resolution integrated: ${resolutionFileRef}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Parameter Reference
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `--session` | string | Yes | Workflow session ID (e.g., WFS-user-auth) |
|
||||
| `task_description` | string | Yes | Detailed task description for context extraction |
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Auto-select recommended strategy for each conflict in Step 3, skip clarification questions.
|
||||
|
||||
## Post-Phase Update
|
||||
|
||||
After context-gather completes, update planning-notes.md:
|
||||
|
||||
```javascript
|
||||
const contextPackage = JSON.parse(Read(contextPath))
|
||||
const conflictRisk = contextPackage.conflict_detection?.risk_level || 'low'
|
||||
const criticalFiles = (contextPackage.exploration_results?.aggregated_insights?.critical_files || [])
|
||||
.slice(0, 5).map(f => f.path)
|
||||
const archPatterns = contextPackage.project_context?.architecture_patterns || []
|
||||
const constraints = contextPackage.exploration_results?.aggregated_insights?.constraints || []
|
||||
|
||||
// Update Phase 2 section
|
||||
Edit(planningNotesPath, {
|
||||
old: '## Context Findings (Phase 2)\n(To be filled by context-gather)',
|
||||
new: `## Context Findings (Phase 2)
|
||||
|
||||
- **CRITICAL_FILES**: ${criticalFiles.join(', ') || 'None identified'}
|
||||
- **ARCHITECTURE**: ${archPatterns.join(', ') || 'Not detected'}
|
||||
- **CONFLICT_RISK**: ${conflictRisk}
|
||||
- **CONSTRAINTS**: ${constraints.length > 0 ? constraints.join('; ') : 'None'}`
|
||||
})
|
||||
|
||||
// If conflicts were resolved inline, update conflict decisions section
|
||||
if (hasSignificantConflicts && file_exists(resolutionPath)) {
|
||||
const conflictRes = JSON.parse(Read(resolutionPath))
|
||||
const resolved = conflictRes.resolved_conflicts || []
|
||||
const planningConstraints = conflictRes.planning_constraints || []
|
||||
|
||||
Edit(planningNotesPath, {
|
||||
old: '## Conflict Decisions (Phase 2)\n(To be filled if conflicts detected)',
|
||||
new: `## Conflict Decisions (Phase 2)
|
||||
|
||||
- **RESOLVED**: ${resolved.map(r => `${r.conflict_id} → ${r.strategy_name}`).join('; ') || 'None'}
|
||||
- **CUSTOM_HANDLING**: ${conflictRes.custom_conflicts?.map(c => c.id).join(', ') || 'None'}
|
||||
- **CONSTRAINTS**: ${planningConstraints.map(c => c.content).join('; ') || 'None'}`
|
||||
})
|
||||
|
||||
// Append conflict constraints to consolidated list
|
||||
if (planningConstraints.length > 0) {
|
||||
Edit(planningNotesPath, {
|
||||
old: '## Consolidated Constraints (Phase 3 Input)',
|
||||
new: `## Consolidated Constraints (Phase 3 Input)
|
||||
${planningConstraints.map((c, i) => `${constraintCount + i + 1}. [Conflict] ${c.content}`).join('\n')}`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Append Phase 2 constraints to consolidated list
|
||||
Edit(planningNotesPath, {
|
||||
old: '## Consolidated Constraints (Phase 3 Input)',
|
||||
new: `## Consolidated Constraints (Phase 3 Input)
|
||||
${constraints.map((c, i) => `${i + 2}. [Context] ${c}`).join('\n')}`
|
||||
})
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Recovery Strategy
|
||||
```
|
||||
1. Pre-check: Verify exploration results before conflict analysis
|
||||
2. Monitor: Track agents via wait with timeout
|
||||
3. Validate: Parse agent JSON output
|
||||
4. Recover:
|
||||
- Agent failure → check logs + report error
|
||||
- Invalid JSON → retry once with Claude fallback
|
||||
- CLI failure → fallback to Claude analysis
|
||||
- Edit tool failure → report affected files + rollback option
|
||||
- User cancels → mark as "unresolved", continue to Step 4
|
||||
5. Degrade: If conflict analysis fails, skip and continue with context packaging
|
||||
6. Cleanup: Always close_agent even on error path
|
||||
```
|
||||
|
||||
### Rollback Handling
|
||||
```
|
||||
If Edit tool fails mid-application:
|
||||
1. Log all successfully applied modifications
|
||||
2. Output rollback option via text interaction
|
||||
3. If rollback selected: restore files from git or backups
|
||||
4. If continue: mark partial resolution in context-package.json
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- **Detection-first**: Always check for existing package before invoking agent
|
||||
- **User intent integration**: Load user intent from planning-notes.md (Phase 1 output)
|
||||
- **Conflict-aware exploration**: Explore agents detect conflict indicators during their work
|
||||
- **Inline conflict resolution**: Conflicts resolved within this phase when significant indicators found
|
||||
- **Output**: Generates `context-package.json` with `prioritized_context` field + optional `conflict-resolution.json`
|
||||
- **Plan-specific**: Use this for implementation planning; brainstorm mode uses direct agent call
|
||||
- **Explicit Lifecycle**: Always close_agent after wait to free resources
|
||||
- **Batch Wait**: Use single wait call for multiple parallel agents for efficiency
|
||||
|
||||
## Output
|
||||
|
||||
- **Variable**: `contextPath` (e.g., `.workflow/active/WFS-xxx/.process/context-package.json`)
|
||||
- **Variable**: `conflictRisk` (none/low/medium/high/resolved)
|
||||
- **File**: Updated `planning-notes.md` with context findings + conflict decisions (if applicable)
|
||||
- **File**: Optional `conflict-resolution.json` (when conflicts resolved inline)
|
||||
|
||||
## Next Phase
|
||||
|
||||
Return to orchestrator, then auto-continue to [Phase 3: Task Generation](03-task-generation.md).
|
||||
756
.codex/skills/workflow-plan-execute/phases/03-task-generation.md
Normal file
756
.codex/skills/workflow-plan-execute/phases/03-task-generation.md
Normal file
@@ -0,0 +1,756 @@
|
||||
# Phase 3: Task Generation
|
||||
|
||||
Generate implementation plan documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) using action-planning-agent - produces planning artifacts, does NOT execute code implementation.
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Skip user questions, use defaults (no materials, Agent executor, Codex CLI tool).
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
- **Planning Only**: Generate planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) - does NOT implement code
|
||||
- **Agent-Driven Document Generation**: Delegate plan generation to action-planning-agent
|
||||
- **NO Redundant Context Sorting**: Context priority sorting is ALREADY completed in context-gather Phase 2
|
||||
- Use `context-package.json.prioritized_context` directly
|
||||
- DO NOT re-sort files or re-compute priorities
|
||||
- `priority_tiers` and `dependency_order` are pre-computed and ready-to-use
|
||||
- **N+1 Parallel Planning**: Auto-detect multi-module projects, enable parallel planning (2+1 or 3+1 mode)
|
||||
- **Progressive Loading**: Load context incrementally (Core → Selective → On-Demand) due to analysis.md file size
|
||||
- **Memory-First**: Reuse loaded documents from conversation memory
|
||||
- **Smart Selection**: Load synthesis_output OR guidance + relevant role analyses, NOT all role analyses
|
||||
- **MCP-Enhanced**: Use MCP tools for advanced code analysis and research
|
||||
- **Path Clarity**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root (e.g., `./src/module`)
|
||||
- **Explicit Lifecycle**: Manage subagent lifecycle with spawn_agent → wait → close_agent
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
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)
|
||||
├─ Auto-detect modules from context-package + directory structure
|
||||
└─ Decision:
|
||||
├─ modules.length == 1 → Single Agent Mode (Phase 2A)
|
||||
└─ modules.length >= 2 → Parallel Mode (Phase 2B + Phase 3)
|
||||
|
||||
Phase 2A: Single Agent Planning (Original Flow)
|
||||
├─ Spawn action-planning-agent
|
||||
├─ Wait for completion
|
||||
├─ Close agent
|
||||
├─ Outputs: Task JSONs, IMPL_PLAN.md, TODO_LIST.md
|
||||
└─ Lifecycle: spawn_agent → wait → close_agent
|
||||
|
||||
Phase 2B: N Parallel Planning (Multi-Module)
|
||||
├─ Spawn N action-planning-agents simultaneously (one per module)
|
||||
├─ Wait for all agents (batch wait)
|
||||
├─ Close all agents
|
||||
├─ Each generates module-scoped tasks (IMPL-{prefix}{seq}.json)
|
||||
├─ Task ID format: IMPL-A1, IMPL-A2... / IMPL-B1, IMPL-B2...
|
||||
└─ Each module limited to ≤9 tasks
|
||||
|
||||
Phase 3: Integration (+1 Coordinator, Multi-Module Only)
|
||||
├─ Spawn coordinator agent
|
||||
├─ Wait for completion
|
||||
├─ Close agent
|
||||
├─ Collect all module task JSONs
|
||||
├─ Resolve cross-module dependencies (CROSS::{module}::{pattern} → actual ID)
|
||||
├─ Generate unified IMPL_PLAN.md (grouped by module)
|
||||
└─ Generate TODO_LIST.md (hierarchical: module → tasks)
|
||||
```
|
||||
|
||||
## Document Generation Lifecycle
|
||||
|
||||
### Phase 0: User Configuration (Interactive)
|
||||
|
||||
**Purpose**: Collect user preferences before task generation to ensure generated tasks match execution expectations.
|
||||
|
||||
**Auto Mode Check**:
|
||||
```javascript
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
|
||||
if (autoYes) {
|
||||
console.log(`[--yes] Using defaults: No materials, Agent executor, Codex CLI`)
|
||||
userConfig = {
|
||||
supplementaryMaterials: { type: "none", content: [] },
|
||||
executionMethod: "agent",
|
||||
preferredCliTool: "codex",
|
||||
enableResume: true
|
||||
}
|
||||
// Skip to Phase 1
|
||||
}
|
||||
```
|
||||
|
||||
**User Questions** (skipped if autoYes):
|
||||
```javascript
|
||||
if (!autoYes) 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** (skipped if autoYes):
|
||||
```javascript
|
||||
if (!autoYes && 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, detects module structure. Context priority sorting is NOT performed here - it's already completed in context-gather Phase 2.**
|
||||
|
||||
**Session Path Structure**:
|
||||
```
|
||||
.workflow/active/WFS-{session-id}/
|
||||
├── workflow-session.json # Session metadata
|
||||
├── planning-notes.md # Consolidated planning notes
|
||||
├── .process/
|
||||
│ └── context-package.json # Context package with artifact catalog
|
||||
├── .task/ # Output: Task JSON files
|
||||
│ ├── IMPL-A1.json # Multi-module: prefixed by module
|
||||
│ ├── IMPL-A2.json
|
||||
│ ├── IMPL-B1.json
|
||||
│ └── ...
|
||||
├── IMPL_PLAN.md # Output: Implementation plan (grouped by module)
|
||||
└── TODO_LIST.md # Output: TODO list (hierarchical)
|
||||
```
|
||||
|
||||
**Command Preparation**:
|
||||
1. **Assemble Session Paths** for agent prompt:
|
||||
- `session_metadata_path`
|
||||
- `context_package_path`
|
||||
- Output directory paths
|
||||
|
||||
2. **Provide Metadata** (simple values):
|
||||
- `session_id`
|
||||
- `mcp_capabilities` (available MCP tools)
|
||||
|
||||
3. **Auto Module Detection** (determines single vs parallel mode):
|
||||
```javascript
|
||||
function autoDetectModules(contextPackage, projectRoot) {
|
||||
// === Complexity Gate: Only parallelize for High complexity ===
|
||||
const complexity = contextPackage.metadata?.complexity || 'Medium';
|
||||
if (complexity !== 'High') {
|
||||
// Force single agent mode for Low/Medium complexity
|
||||
// This maximizes agent context reuse for related tasks
|
||||
return [{ name: 'main', prefix: '', paths: ['.'] }];
|
||||
}
|
||||
|
||||
// Priority 1: Explicit frontend/backend separation
|
||||
if (exists('src/frontend') && exists('src/backend')) {
|
||||
return [
|
||||
{ name: 'frontend', prefix: 'A', paths: ['src/frontend'] },
|
||||
{ name: 'backend', prefix: 'B', paths: ['src/backend'] }
|
||||
];
|
||||
}
|
||||
|
||||
// Priority 2: Monorepo structure
|
||||
if (exists('packages/*') || exists('apps/*')) {
|
||||
return detectMonorepoModules(); // Returns 2-3 main packages
|
||||
}
|
||||
|
||||
// Priority 3: Context-package dependency clustering
|
||||
const modules = clusterByDependencies(contextPackage.dependencies?.internal);
|
||||
if (modules.length >= 2) return modules.slice(0, 3);
|
||||
|
||||
// Default: Single module (original flow)
|
||||
return [{ name: 'main', prefix: '', paths: ['.'] }];
|
||||
}
|
||||
```
|
||||
|
||||
**Decision Logic**:
|
||||
- `complexity !== 'High'` → Force Phase 2A (Single Agent, maximize context reuse)
|
||||
- `modules.length == 1` → Phase 2A (Single Agent, original flow)
|
||||
- `modules.length >= 2 && complexity == 'High'` → Phase 2B + Phase 3 (N+1 Parallel)
|
||||
|
||||
**Note**: CLI tool usage is now determined semantically by action-planning-agent based on user's task description, not by flags.
|
||||
|
||||
### Phase 2A: Single Agent Planning (Original Flow)
|
||||
|
||||
**Condition**: `modules.length == 1` (no multi-module detected)
|
||||
|
||||
**Purpose**: Generate IMPL_PLAN.md, task JSONs, and TODO_LIST.md - planning documents only, NOT code implementation.
|
||||
|
||||
**Agent Invocation**:
|
||||
```javascript
|
||||
// Spawn action-planning-agent
|
||||
const planningAgentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/action-planning-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## TASK OBJECTIVE
|
||||
Generate implementation planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) for workflow session
|
||||
|
||||
IMPORTANT: This is PLANNING ONLY - you are generating planning documents, NOT implementing code.
|
||||
|
||||
CRITICAL: Follow the progressive loading strategy defined in agent specification (load analysis.md files incrementally due to file size)
|
||||
|
||||
## PLANNING NOTES (PHASE 1-2 CONTEXT)
|
||||
Load: .workflow/active/${session_id}/planning-notes.md
|
||||
|
||||
This document contains:
|
||||
- User Intent: Original GOAL and KEY_CONSTRAINTS from Phase 1
|
||||
- Context Findings: Critical files, architecture, and constraints from Phase 2
|
||||
- Conflict Decisions: Resolved conflicts and planning constraints from Phase 2
|
||||
- Consolidated Constraints: All constraints from all phases
|
||||
|
||||
**USAGE**: Read planning-notes.md FIRST. Use Consolidated Constraints list to guide task sequencing and dependencies.
|
||||
|
||||
## SESSION PATHS
|
||||
Input:
|
||||
- Session Metadata: .workflow/active/${session_id}/workflow-session.json
|
||||
- Planning Notes: .workflow/active/${session_id}/planning-notes.md
|
||||
- Context Package: .workflow/active/${session_id}/.process/context-package.json
|
||||
|
||||
Output:
|
||||
- Task Dir: .workflow/active/${session_id}/.task/
|
||||
- IMPL_PLAN: .workflow/active/${session_id}/IMPL_PLAN.md
|
||||
- TODO_LIST: .workflow/active/${session_id}/TODO_LIST.md
|
||||
|
||||
## CONTEXT METADATA
|
||||
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}
|
||||
|
||||
## EXECUTION METHOD MAPPING
|
||||
Based on userConfig.executionMethod, set task-level meta.execution_config:
|
||||
|
||||
"agent" →
|
||||
meta.execution_config = { method: "agent", cli_tool: null, enable_resume: false }
|
||||
Agent executes implementation_approach steps directly
|
||||
|
||||
"cli" →
|
||||
meta.execution_config = { method: "cli", cli_tool: userConfig.preferredCliTool, enable_resume: true }
|
||||
Agent executes pre_analysis, then hands off full context to CLI via buildCliHandoffPrompt()
|
||||
|
||||
"hybrid" →
|
||||
Per-task decision: Analyze task complexity, set method to "agent" OR "cli" per task
|
||||
- Simple tasks (≤3 files, straightforward logic) → method: "agent"
|
||||
- Complex tasks (>3 files, complex logic, refactoring) → method: "cli"
|
||||
CLI tool: userConfig.preferredCliTool, enable_resume: true
|
||||
|
||||
IMPORTANT: Do NOT add command field to implementation_approach steps. Execution routing is controlled by task-level meta.execution_config.method only.
|
||||
|
||||
## PRIORITIZED CONTEXT (from context-package.prioritized_context) - ALREADY SORTED
|
||||
Context sorting is ALREADY COMPLETED in context-gather Phase 2. DO NOT re-sort.
|
||||
Direct usage:
|
||||
- **user_intent**: Use goal/scope/key_constraints for task alignment
|
||||
- **priority_tiers.critical**: These files are PRIMARY focus for task generation
|
||||
- **priority_tiers.high**: These files are SECONDARY focus
|
||||
- **dependency_order**: Use this for task sequencing - already computed
|
||||
- **sorting_rationale**: Reference for understanding priority decisions
|
||||
|
||||
## EXPLORATION CONTEXT (from context-package.exploration_results) - SUPPLEMENT ONLY
|
||||
If prioritized_context is incomplete, fall back to exploration_results:
|
||||
- Load exploration_results from context-package.json
|
||||
- Use aggregated_insights.critical_files for focus_paths generation
|
||||
- Apply aggregated_insights.constraints to acceptance criteria
|
||||
- Reference aggregated_insights.all_patterns for implementation approach
|
||||
- Use aggregated_insights.all_integration_points for precise modification locations
|
||||
- Use conflict_indicators for risk-aware task sequencing
|
||||
|
||||
## CONFLICT RESOLUTION CONTEXT (if exists)
|
||||
- Check context-package.conflict_detection.resolution_file for conflict-resolution.json path
|
||||
- If exists, load .process/conflict-resolution.json:
|
||||
- Apply planning_constraints as task constraints (for brainstorm-less workflows)
|
||||
- Reference resolved_conflicts for implementation approach alignment
|
||||
- Handle custom_conflicts with explicit task notes
|
||||
|
||||
## EXPECTED DELIVERABLES
|
||||
1. Task JSON Files (.task/IMPL-*.json)
|
||||
- 6-field schema (id, title, status, context_package_path, meta, context, flow_control)
|
||||
- Quantified requirements with explicit counts
|
||||
- Artifacts integration from context package
|
||||
- **focus_paths generated directly from prioritized_context.priority_tiers (critical + high)**
|
||||
- NO re-sorting or re-prioritization - use pre-computed tiers as-is
|
||||
- Critical files are PRIMARY focus, High files are SECONDARY
|
||||
- Flow control with pre_analysis steps (use prioritized_context.dependency_order for task sequencing)
|
||||
- **CLI Execution IDs and strategies (MANDATORY)**
|
||||
|
||||
2. Implementation Plan (IMPL_PLAN.md)
|
||||
- Context analysis and artifact references
|
||||
- Task breakdown and execution strategy
|
||||
- Complete structure per agent definition
|
||||
|
||||
3. TODO List (TODO_LIST.md)
|
||||
- Hierarchical structure (containers, pending, completed markers)
|
||||
- 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 -p "[prompt]" --tool [tool] --mode write --id [cli_execution_id]\`
|
||||
- resume: \`ccw cli -p "[prompt]" --resume [resume_from] --tool [tool] --mode write\`
|
||||
- fork: \`ccw cli -p "[prompt]" --resume [resume_from] --id [cli_execution_id] --tool [tool] --mode write\`
|
||||
- merge_fork: \`ccw cli -p "[prompt]" --resume [merge_from.join(',')] --id [cli_execution_id] --tool [tool] --mode write\`
|
||||
|
||||
## QUALITY STANDARDS
|
||||
Hard Constraints:
|
||||
- Task count <= 18 (hard limit - request re-scope if exceeded)
|
||||
- All requirements quantified (explicit counts and enumerated lists)
|
||||
- Acceptance criteria measurable (include verification commands)
|
||||
- Artifact references mapped from context package
|
||||
- All documents follow agent-defined structure
|
||||
|
||||
## SUCCESS CRITERIA
|
||||
- All planning documents generated successfully:
|
||||
- Task JSONs valid and saved to .task/ directory
|
||||
- IMPL_PLAN.md created with complete structure
|
||||
- TODO_LIST.md generated matching task JSONs
|
||||
- Return completion status with document count and task breakdown summary
|
||||
|
||||
## PLANNING NOTES RECORD (REQUIRED)
|
||||
After completing, update planning-notes.md:
|
||||
|
||||
**File**: .workflow/active/${session_id}/planning-notes.md
|
||||
|
||||
1. **Task Generation (Phase 3)**: Task count and key tasks
|
||||
2. **N+1 Context**: Key decisions (with rationale) + deferred items
|
||||
|
||||
\`\`\`markdown
|
||||
## Task Generation (Phase 3)
|
||||
### [Action-Planning Agent] YYYY-MM-DD
|
||||
- **Tasks**: [count] ([IDs])
|
||||
|
||||
## N+1 Context
|
||||
### Decisions
|
||||
| Decision | Rationale | Revisit? |
|
||||
|----------|-----------|----------|
|
||||
| [choice] | [why] | [Yes/No] |
|
||||
|
||||
### Deferred
|
||||
- [ ] [item] - [reason]
|
||||
\`\`\`
|
||||
`
|
||||
});
|
||||
|
||||
// Wait for planning agent to complete
|
||||
const planningResult = wait({
|
||||
ids: [planningAgentId],
|
||||
timeout_ms: 900000 // 15 minutes
|
||||
});
|
||||
|
||||
// Close planning agent
|
||||
close_agent({ id: planningAgentId });
|
||||
```
|
||||
|
||||
### Phase 2B: N Parallel Planning (Multi-Module)
|
||||
|
||||
**Condition**: `modules.length >= 2` (multi-module detected)
|
||||
|
||||
**Purpose**: Launch N action-planning-agents simultaneously, one per module, for parallel task JSON generation.
|
||||
|
||||
**Note**: Phase 2B agents generate Task JSONs ONLY. IMPL_PLAN.md and TODO_LIST.md are generated by Phase 3 Coordinator.
|
||||
|
||||
**Parallel Agent Invocation**:
|
||||
```javascript
|
||||
// Spawn N agents in parallel (one per module)
|
||||
const moduleAgents = [];
|
||||
|
||||
modules.forEach(module => {
|
||||
const agentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/action-planning-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## TASK OBJECTIVE
|
||||
Generate task JSON files for ${module.name} module within workflow session
|
||||
|
||||
IMPORTANT: This is PLANNING ONLY - generate task JSONs, NOT implementing code.
|
||||
IMPORTANT: Generate Task JSONs ONLY. IMPL_PLAN.md and TODO_LIST.md by Phase 3 Coordinator.
|
||||
|
||||
CRITICAL: Follow the progressive loading strategy defined in agent specification (load analysis.md files incrementally due to file size)
|
||||
|
||||
## PLANNING NOTES (PHASE 1-2 CONTEXT)
|
||||
Load: .workflow/active/${session_id}/planning-notes.md
|
||||
|
||||
This document contains consolidated constraints and user intent to guide module-scoped task generation.
|
||||
|
||||
## MODULE SCOPE
|
||||
- Module: ${module.name} (${module.type})
|
||||
- Focus Paths: ${module.paths.join(', ')}
|
||||
- Task ID Prefix: IMPL-${module.prefix}
|
||||
- Task Limit: ≤6 tasks (hard limit for this module)
|
||||
- Other Modules: ${otherModules.join(', ')} (reference only, do NOT generate tasks for them)
|
||||
|
||||
## SESSION PATHS
|
||||
Input:
|
||||
- Session Metadata: .workflow/active/${session_id}/workflow-session.json
|
||||
- Planning Notes: .workflow/active/${session_id}/planning-notes.md
|
||||
- Context Package: .workflow/active/${session_id}/.process/context-package.json
|
||||
|
||||
Output:
|
||||
- Task Dir: .workflow/active/${session_id}/.task/
|
||||
|
||||
## CONTEXT METADATA
|
||||
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}
|
||||
|
||||
## EXECUTION METHOD MAPPING
|
||||
Based on userConfig.executionMethod, set task-level meta.execution_config:
|
||||
|
||||
"agent" →
|
||||
meta.execution_config = { method: "agent", cli_tool: null, enable_resume: false }
|
||||
Agent executes implementation_approach steps directly
|
||||
|
||||
"cli" →
|
||||
meta.execution_config = { method: "cli", cli_tool: userConfig.preferredCliTool, enable_resume: true }
|
||||
Agent executes pre_analysis, then hands off full context to CLI via buildCliHandoffPrompt()
|
||||
|
||||
"hybrid" →
|
||||
Per-task decision: Analyze task complexity, set method to "agent" OR "cli" per task
|
||||
- Simple tasks (≤3 files, straightforward logic) → method: "agent"
|
||||
- Complex tasks (>3 files, complex logic, refactoring) → method: "cli"
|
||||
CLI tool: userConfig.preferredCliTool, enable_resume: true
|
||||
|
||||
IMPORTANT: Do NOT add command field to implementation_approach steps. Execution routing is controlled by task-level meta.execution_config.method only.
|
||||
|
||||
## PRIORITIZED CONTEXT (from context-package.prioritized_context) - ALREADY SORTED
|
||||
Context sorting is ALREADY COMPLETED in context-gather Phase 2. DO NOT re-sort.
|
||||
Filter by module scope (${module.paths.join(', ')}):
|
||||
- **user_intent**: Use for task alignment within module
|
||||
- **priority_tiers.critical**: Filter for files in ${module.paths.join(', ')} → PRIMARY focus
|
||||
- **priority_tiers.high**: Filter for files in ${module.paths.join(', ')} → SECONDARY focus
|
||||
- **dependency_order**: Use module-relevant entries for task sequencing
|
||||
|
||||
## EXPLORATION CONTEXT (from context-package.exploration_results) - SUPPLEMENT ONLY
|
||||
If prioritized_context is incomplete for this module, fall back to exploration_results:
|
||||
- Load exploration_results from context-package.json
|
||||
- Filter for ${module.name} module: Use aggregated_insights.critical_files matching ${module.paths.join(', ')}
|
||||
- Apply module-relevant constraints from aggregated_insights.constraints
|
||||
- Reference aggregated_insights.all_patterns applicable to ${module.name}
|
||||
- Use aggregated_insights.all_integration_points for precise modification locations within module scope
|
||||
- Use conflict_indicators for risk-aware task sequencing
|
||||
|
||||
## CONFLICT RESOLUTION CONTEXT (if exists)
|
||||
- Check context-package.conflict_detection.resolution_file for conflict-resolution.json path
|
||||
- If exists, load .process/conflict-resolution.json:
|
||||
- Apply planning_constraints relevant to ${module.name} as task constraints
|
||||
- Reference resolved_conflicts affecting ${module.name} for implementation approach alignment
|
||||
- Handle custom_conflicts with explicit task notes
|
||||
|
||||
## CROSS-MODULE DEPENDENCIES
|
||||
- For dependencies ON other modules: Use placeholder depends_on: ["CROSS::{module}::{pattern}"]
|
||||
- Example: depends_on: ["CROSS::B::api-endpoint"] (this module depends on B's api-endpoint task)
|
||||
- Phase 3 Coordinator resolves to actual task IDs
|
||||
- For dependencies FROM other modules: Document in task context as "provides_for" annotation
|
||||
|
||||
## EXPECTED DELIVERABLES
|
||||
Task JSON Files (.task/IMPL-${module.prefix}*.json):
|
||||
- 6-field schema (id, title, status, context_package_path, meta, context, flow_control)
|
||||
- Task ID format: IMPL-${module.prefix}1, IMPL-${module.prefix}2, ...
|
||||
- Quantified requirements with explicit counts
|
||||
- Artifacts integration from context package (filtered for ${module.name})
|
||||
- **focus_paths generated directly from prioritized_context.priority_tiers filtered by ${module.paths.join(', ')}**
|
||||
- NO re-sorting - use pre-computed tiers filtered for this module
|
||||
- Critical files are PRIMARY focus, High files are SECONDARY
|
||||
- Flow control with pre_analysis steps (use prioritized_context.dependency_order for module task sequencing)
|
||||
- **CLI Execution IDs and strategies (MANDATORY)**
|
||||
- Focus ONLY on ${module.name} module scope
|
||||
|
||||
## CLI EXECUTION ID REQUIREMENTS (MANDATORY)
|
||||
Each task JSON MUST include:
|
||||
- **cli_execution_id**: Unique ID for CLI execution (format: \`{session_id}-IMPL-${module.prefix}{seq}\`)
|
||||
- **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", ...] }\`
|
||||
- Cross-module dep → \`{ "strategy": "cross_module_fork", "resume_from": "CROSS::{module}::{pattern}" }\`
|
||||
|
||||
**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
|
||||
5. **cross_module_fork**: Task depends on task from another module - Phase 3 resolves placeholder
|
||||
|
||||
**Execution Command Patterns**:
|
||||
- new: \`ccw cli -p "[prompt]" --tool [tool] --mode write --id [cli_execution_id]\`
|
||||
- resume: \`ccw cli -p "[prompt]" --resume [resume_from] --tool [tool] --mode write\`
|
||||
- fork: \`ccw cli -p "[prompt]" --resume [resume_from] --id [cli_execution_id] --tool [tool] --mode write\`
|
||||
- merge_fork: \`ccw cli -p "[prompt]" --resume [merge_from.join(',')] --id [cli_execution_id] --tool [tool] --mode write\`
|
||||
- cross_module_fork: (Phase 3 resolves placeholder, then uses fork pattern)
|
||||
|
||||
## QUALITY STANDARDS
|
||||
Hard Constraints:
|
||||
- Task count <= 9 for this module (hard limit - coordinate with Phase 3 if exceeded)
|
||||
- All requirements quantified (explicit counts and enumerated lists)
|
||||
- Acceptance criteria measurable (include verification commands)
|
||||
- Artifact references mapped from context package (module-scoped filter)
|
||||
- Focus paths use absolute paths or clear relative paths from project root
|
||||
- Cross-module dependencies use CROSS:: placeholder format
|
||||
|
||||
## SUCCESS CRITERIA
|
||||
- Task JSONs saved to .task/ with IMPL-${module.prefix}* naming
|
||||
- All task JSONs include cli_execution_id and cli_execution strategy
|
||||
- Cross-module dependencies use CROSS:: placeholder format consistently
|
||||
- Focus paths scoped to ${module.paths.join(', ')} only
|
||||
- Return: task count, task IDs, dependency summary (internal + cross-module)
|
||||
|
||||
## PLANNING NOTES RECORD (REQUIRED)
|
||||
After completing, append to planning-notes.md:
|
||||
|
||||
\`\`\`markdown
|
||||
### [${module.name}] YYYY-MM-DD
|
||||
- **Tasks**: [count] ([IDs])
|
||||
- **CROSS deps**: [placeholders used]
|
||||
\`\`\`
|
||||
`
|
||||
});
|
||||
|
||||
moduleAgents.push(agentId);
|
||||
});
|
||||
|
||||
// Batch wait for all module agents
|
||||
const moduleResults = wait({
|
||||
ids: moduleAgents,
|
||||
timeout_ms: 900000 // 15 minutes
|
||||
});
|
||||
|
||||
// Close all module agents
|
||||
moduleAgents.forEach(agentId => {
|
||||
close_agent({ id: agentId });
|
||||
});
|
||||
```
|
||||
|
||||
**Output Structure** (direct to .task/):
|
||||
```
|
||||
.task/
|
||||
├── IMPL-A1.json # Module A (e.g., frontend)
|
||||
├── IMPL-A2.json
|
||||
├── IMPL-B1.json # Module B (e.g., backend)
|
||||
├── IMPL-B2.json
|
||||
└── IMPL-C1.json # Module C (e.g., shared)
|
||||
```
|
||||
|
||||
**Task ID Naming**:
|
||||
- Format: `IMPL-{prefix}{seq}.json`
|
||||
- Prefix: A, B, C... (assigned by detection order)
|
||||
- Sequence: 1, 2, 3... (per-module increment)
|
||||
|
||||
### Phase 3: Integration (+1 Coordinator Agent, Multi-Module Only)
|
||||
|
||||
**Condition**: Only executed when `modules.length >= 2`
|
||||
|
||||
**Purpose**: Collect all module tasks, resolve cross-module dependencies, generate unified IMPL_PLAN.md and TODO_LIST.md documents.
|
||||
|
||||
**Coordinator Agent Invocation**:
|
||||
```javascript
|
||||
// Wait for all Phase 2B agents to complete (already done above)
|
||||
|
||||
// Spawn +1 Coordinator Agent
|
||||
const coordinatorAgentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/action-planning-agent.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
## TASK OBJECTIVE
|
||||
Integrate all module task JSONs, resolve cross-module dependencies, and generate unified IMPL_PLAN.md and TODO_LIST.md
|
||||
|
||||
IMPORTANT: This is INTEGRATION ONLY - consolidate existing task JSONs, NOT creating new tasks.
|
||||
|
||||
## SESSION PATHS
|
||||
Input:
|
||||
- Session Metadata: .workflow/active/${session_id}/workflow-session.json
|
||||
- Context Package: .workflow/active/${session_id}/.process/context-package.json
|
||||
- Task JSONs: .workflow/active/${session_id}/.task/IMPL-*.json (from Phase 2B)
|
||||
Output:
|
||||
- Updated Task JSONs: .workflow/active/${session_id}/.task/IMPL-*.json (resolved dependencies)
|
||||
- IMPL_PLAN: .workflow/active/${session_id}/IMPL_PLAN.md
|
||||
- TODO_LIST: .workflow/active/${session_id}/TODO_LIST.md
|
||||
|
||||
## CONTEXT METADATA
|
||||
Session ID: ${session_id}
|
||||
Modules: ${modules.map(m => m.name + '(' + m.prefix + ')').join(', ')}
|
||||
Module Count: ${modules.length}
|
||||
|
||||
## INTEGRATION STEPS
|
||||
1. Collect all .task/IMPL-*.json, group by module prefix
|
||||
2. Resolve CROSS:: dependencies → actual task IDs, update task JSONs
|
||||
3. Generate IMPL_PLAN.md (multi-module format per agent specification)
|
||||
4. Generate TODO_LIST.md (hierarchical format per agent specification)
|
||||
|
||||
## CROSS-MODULE DEPENDENCY RESOLUTION
|
||||
- Pattern: CROSS::{module}::{pattern} → IMPL-{module}* matching title/context
|
||||
- Example: CROSS::B::api-endpoint → IMPL-B1 (if B1 title contains "api-endpoint")
|
||||
- Log unresolved as warnings
|
||||
|
||||
## EXPECTED DELIVERABLES
|
||||
1. Updated Task JSONs with resolved dependency IDs
|
||||
2. IMPL_PLAN.md - multi-module format with cross-dependency section
|
||||
3. TODO_LIST.md - hierarchical by module with cross-dependency section
|
||||
|
||||
## SUCCESS CRITERIA
|
||||
- No CROSS:: placeholders remaining in task JSONs
|
||||
- IMPL_PLAN.md and TODO_LIST.md generated with multi-module structure
|
||||
- Return: task count, per-module breakdown, resolved dependency count
|
||||
|
||||
## PLANNING NOTES RECORD (REQUIRED)
|
||||
After integration, update planning-notes.md:
|
||||
|
||||
\`\`\`markdown
|
||||
### [Coordinator] YYYY-MM-DD
|
||||
- **Total**: [count] tasks
|
||||
- **Resolved**: [CROSS:: resolutions]
|
||||
|
||||
## N+1 Context
|
||||
### Decisions
|
||||
| Decision | Rationale | Revisit? |
|
||||
|----------|-----------|----------|
|
||||
| CROSS::X → IMPL-Y | [why this resolution] | [Yes/No] |
|
||||
|
||||
### Deferred
|
||||
- [ ] [unresolved CROSS or conflict] - [reason]
|
||||
\`\`\`
|
||||
`
|
||||
});
|
||||
|
||||
// Wait for coordinator agent to complete
|
||||
const coordinatorResult = wait({
|
||||
ids: [coordinatorAgentId],
|
||||
timeout_ms: 600000 // 10 minutes
|
||||
});
|
||||
|
||||
// Close coordinator agent
|
||||
close_agent({ id: coordinatorAgentId });
|
||||
```
|
||||
|
||||
**Dependency Resolution Algorithm**:
|
||||
```javascript
|
||||
function resolveCrossModuleDependency(placeholder, allTasks) {
|
||||
const [, targetModule, pattern] = placeholder.match(/CROSS::(\w+)::(.+)/);
|
||||
const candidates = allTasks.filter(t =>
|
||||
t.id.startsWith(`IMPL-${targetModule}`) &&
|
||||
(t.title.toLowerCase().includes(pattern.toLowerCase()) ||
|
||||
t.context?.description?.toLowerCase().includes(pattern.toLowerCase()))
|
||||
);
|
||||
return candidates.length > 0
|
||||
? candidates.sort((a, b) => a.id.localeCompare(b.id))[0].id
|
||||
: placeholder; // Keep for manual resolution
|
||||
}
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
- **Files**:
|
||||
- `.workflow/active/{sessionId}/IMPL_PLAN.md`
|
||||
- `.workflow/active/{sessionId}/.task/IMPL-*.json`
|
||||
- `.workflow/active/{sessionId}/TODO_LIST.md`
|
||||
- **Updated**: `planning-notes.md` with task generation record and N+1 context
|
||||
|
||||
## Next Step
|
||||
|
||||
Return to orchestrator. Present user with action choices (or auto-continue if `--yes`):
|
||||
1. Verify Plan Quality (Recommended) → `workflow:plan-verify`
|
||||
2. Start Execution → Phase 4 (phases/04-execution.md)
|
||||
3. Review Status Only → `workflow:status`
|
||||
454
.codex/skills/workflow-plan-execute/phases/04-execution.md
Normal file
454
.codex/skills/workflow-plan-execute/phases/04-execution.md
Normal file
@@ -0,0 +1,454 @@
|
||||
# Phase 4: Execution (Conditional)
|
||||
|
||||
Execute implementation tasks using agent orchestration with lazy loading, progress tracking, and optional auto-commit. This phase is triggered conditionally after Phase 3 completes.
|
||||
|
||||
## Trigger Conditions
|
||||
|
||||
- **User Selection**: User chooses "Start Execution" in Phase 3 User Decision
|
||||
- **Auto Mode** (`--yes`): Automatically enters Phase 4 after Phase 3 completes
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`:
|
||||
- **Completion Choice**: Automatically completes session (runs `workflow:session:complete --yes`)
|
||||
|
||||
When `--with-commit`:
|
||||
- **Auto-Commit**: After each agent task completes, commit changes based on summary document
|
||||
- **Commit Principle**: Minimal commits - only commit files modified by the completed task
|
||||
- **Commit Message**: Generated from task summary with format: "feat/fix/refactor: {task-title} - {summary}"
|
||||
|
||||
## Key Design Principles
|
||||
|
||||
1. **No Redundant Discovery**: Session ID and planning docs already available from Phase 1-3
|
||||
2. **Autonomous Execution**: Complete entire workflow without user interruption
|
||||
3. **Lazy Loading**: Task JSONs read on-demand during execution, not upfront
|
||||
4. **ONE AGENT = ONE TASK JSON**: Each agent instance executes exactly one task JSON file
|
||||
5. **IMPL_PLAN-Driven Strategy**: Execution model derived from planning document
|
||||
6. **Continuous Progress Tracking**: TodoWrite updates throughout entire workflow
|
||||
7. **Subagent Lifecycle**: Explicit lifecycle management with spawn_agent → wait → close_agent
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
Step 1: TodoWrite Generation
|
||||
├─ Update session status to "active"
|
||||
├─ Parse TODO_LIST.md for task statuses
|
||||
├─ Generate TodoWrite for entire workflow
|
||||
└─ Prepare session context paths
|
||||
|
||||
Step 2: Execution Strategy Parsing
|
||||
├─ Parse IMPL_PLAN.md Section 4 (Execution Model)
|
||||
└─ Fallback: Analyze task structure for smart defaults
|
||||
|
||||
Step 3: Task Execution Loop
|
||||
├─ Get next in_progress task from TodoWrite
|
||||
├─ Lazy load task JSON
|
||||
├─ Launch agent (spawn_agent → wait → close_agent)
|
||||
├─ Mark task completed (update IMPL-*.json status)
|
||||
├─ [with-commit] Auto-commit changes
|
||||
└─ Advance to next task
|
||||
|
||||
Step 4: Completion
|
||||
├─ Synchronize all statuses
|
||||
├─ Generate summaries
|
||||
└─ AskUserQuestion: Review or Complete Session
|
||||
```
|
||||
|
||||
## Step 1: TodoWrite Generation
|
||||
|
||||
### Step 1.0: Update Session Status to Active
|
||||
|
||||
Before generating TodoWrite, update session status from "planning" to "active":
|
||||
```bash
|
||||
# Update session status (idempotent - safe to run if already active)
|
||||
jq '.status = "active" | .execution_started_at = (.execution_started_at // now | todate)' \
|
||||
.workflow/active/${sessionId}/workflow-session.json > tmp.json && \
|
||||
mv tmp.json .workflow/active/${sessionId}/workflow-session.json
|
||||
```
|
||||
This ensures the dashboard shows the session as "ACTIVE" during execution.
|
||||
|
||||
### Step 1.1: Parse TODO_LIST.md
|
||||
|
||||
```
|
||||
1. Create TodoWrite List: Generate task list from TODO_LIST.md (not from task JSONs)
|
||||
- Parse TODO_LIST.md to extract all tasks with current statuses
|
||||
- Identify first pending task with met dependencies
|
||||
- Generate comprehensive TodoWrite covering entire workflow
|
||||
2. Prepare Session Context: Inject workflow paths for agent use
|
||||
3. Validate Prerequisites: Ensure IMPL_PLAN.md and TODO_LIST.md exist and are valid
|
||||
```
|
||||
|
||||
**Performance Optimization**: TODO_LIST.md provides task metadata and status. Task JSONs are NOT loaded here - deferred to Step 3 (lazy loading).
|
||||
|
||||
## Step 2: Execution Strategy Parsing
|
||||
|
||||
### Step 2A: Parse Execution Strategy from IMPL_PLAN.md
|
||||
|
||||
Read IMPL_PLAN.md Section 4 to extract:
|
||||
- **Execution Model**: Sequential | Parallel | Phased | TDD Cycles
|
||||
- **Parallelization Opportunities**: Which tasks can run in parallel
|
||||
- **Serialization Requirements**: Which tasks must run sequentially
|
||||
- **Critical Path**: Priority execution order
|
||||
|
||||
### Step 2B: Intelligent Fallback
|
||||
|
||||
If IMPL_PLAN.md lacks execution strategy, use intelligent fallback:
|
||||
1. **Analyze task structure**:
|
||||
- Check `meta.execution_group` in task JSONs
|
||||
- Analyze `depends_on` relationships
|
||||
- Understand task complexity and risk
|
||||
2. **Apply smart defaults**:
|
||||
- No dependencies + same execution_group → Parallel
|
||||
- Has dependencies → Sequential (wait for deps)
|
||||
- Critical/high-risk tasks → Sequential
|
||||
3. **Conservative approach**: When uncertain, prefer sequential execution
|
||||
|
||||
### Execution Models
|
||||
|
||||
#### 1. Sequential Execution
|
||||
**When**: IMPL_PLAN specifies "Sequential" OR no clear parallelization guidance
|
||||
**Pattern**: Execute tasks one by one in TODO_LIST order via spawn_agent → wait → close_agent per task
|
||||
**TodoWrite**: ONE task marked as `in_progress` at a time
|
||||
|
||||
#### 2. Parallel Execution
|
||||
**When**: IMPL_PLAN specifies "Parallel" with clear parallelization opportunities
|
||||
**Pattern**: Execute independent task groups concurrently by spawning multiple agents and batch waiting
|
||||
**TodoWrite**: MULTIPLE tasks (in same batch) marked as `in_progress` simultaneously
|
||||
**Agent Instantiation**: spawn one agent per task (respects ONE AGENT = ONE TASK JSON rule), then batch wait
|
||||
|
||||
#### 3. Phased Execution
|
||||
**When**: IMPL_PLAN specifies "Phased" with phase breakdown
|
||||
**Pattern**: Execute tasks in phases, respect phase boundaries
|
||||
**TodoWrite**: Within each phase, follow Sequential or Parallel rules
|
||||
|
||||
## Step 3: Task Execution Loop
|
||||
|
||||
### Execution Loop Pattern
|
||||
```
|
||||
while (TODO_LIST.md has pending tasks) {
|
||||
next_task_id = getTodoWriteInProgressTask()
|
||||
task_json = Read(.workflow/active/{session}/.task/{next_task_id}.json) // Lazy load
|
||||
executeTaskWithAgent(task_json) // spawn_agent → wait → close_agent
|
||||
updateTodoListMarkCompleted(next_task_id)
|
||||
advanceTodoWriteToNextTask()
|
||||
}
|
||||
```
|
||||
|
||||
### Execution Process per Task
|
||||
1. **Identify Next Task**: From TodoWrite, get the next `in_progress` task ID
|
||||
2. **Load Task JSON on Demand**: Read `.task/{task-id}.json` for current task ONLY
|
||||
3. **Validate Task Structure**: Ensure all required fields exist (id, title, status, meta, context, flow_control)
|
||||
4. **Launch Agent**: Invoke specialized agent via spawn_agent with complete context including flow control steps
|
||||
5. **Wait for Completion**: wait for agent result, handle timeout
|
||||
6. **Close Agent**: close_agent to free resources
|
||||
7. **Collect Results**: Gather implementation results and outputs
|
||||
8. **[with-commit] Auto-Commit**: If `--with-commit` flag enabled, commit changes based on summary
|
||||
9. **Continue Workflow**: Identify next pending task from TODO_LIST.md and repeat
|
||||
|
||||
**Note**: TODO_LIST.md updates are handled by agents (e.g., code-developer.md), not by the orchestrator.
|
||||
|
||||
### Agent Prompt Template (Sequential)
|
||||
|
||||
**Path-Based Invocation**: Pass paths and trigger markers, let agent parse task JSON autonomously.
|
||||
|
||||
```javascript
|
||||
// Step 1: Spawn agent
|
||||
const agentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/${meta.agent}.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
Implement task ${task.id}: ${task.title}
|
||||
|
||||
[FLOW_CONTROL]
|
||||
|
||||
**Input**:
|
||||
- Task JSON: ${session.task_json_path}
|
||||
- Context Package: ${session.context_package_path}
|
||||
|
||||
**Output Location**:
|
||||
- Workflow: ${session.workflow_dir}
|
||||
- TODO List: ${session.todo_list_path}
|
||||
- Summaries: ${session.summaries_dir}
|
||||
|
||||
**Execution**: Read task JSON → Execute pre_analysis → Check execution_config.method → (CLI: handoff to CLI tool | Agent: direct implementation) → Update TODO_LIST.md → Generate summary
|
||||
`
|
||||
});
|
||||
|
||||
// Step 2: Wait for completion
|
||||
const result = wait({
|
||||
ids: [agentId],
|
||||
timeout_ms: 600000 // 10 minutes per task
|
||||
});
|
||||
|
||||
// Step 3: Close agent (IMPORTANT: always close)
|
||||
close_agent({ id: agentId });
|
||||
```
|
||||
|
||||
**Key Markers**:
|
||||
- `Implement` keyword: Triggers tech stack detection and guidelines loading
|
||||
- `[FLOW_CONTROL]`: Triggers flow_control.pre_analysis execution
|
||||
|
||||
### Parallel Execution Pattern
|
||||
|
||||
```javascript
|
||||
// Step 1: Spawn agents for parallel batch
|
||||
const batchAgents = [];
|
||||
parallelTasks.forEach(task => {
|
||||
const agentId = spawn_agent({
|
||||
message: `
|
||||
## TASK ASSIGNMENT
|
||||
|
||||
### MANDATORY FIRST STEPS (Agent Execute)
|
||||
1. **Read role definition**: ~/.codex/agents/${task.meta.agent}.md (MUST read first)
|
||||
2. Read: .workflow/project-tech.json
|
||||
3. Read: .workflow/project-guidelines.json
|
||||
|
||||
---
|
||||
|
||||
Implement task ${task.id}: ${task.title}
|
||||
|
||||
[FLOW_CONTROL]
|
||||
|
||||
**Input**:
|
||||
- Task JSON: ${session.task_json_path}
|
||||
- Context Package: ${session.context_package_path}
|
||||
|
||||
**Output Location**:
|
||||
- Workflow: ${session.workflow_dir}
|
||||
- TODO List: ${session.todo_list_path}
|
||||
- Summaries: ${session.summaries_dir}
|
||||
|
||||
**Execution**: Read task JSON → Execute pre_analysis → Check execution_config.method → (CLI: handoff to CLI tool | Agent: direct implementation) → Update TODO_LIST.md → Generate summary
|
||||
`
|
||||
});
|
||||
batchAgents.push({ agentId, taskId: task.id });
|
||||
});
|
||||
|
||||
// Step 2: Batch wait for all agents
|
||||
const batchResult = wait({
|
||||
ids: batchAgents.map(a => a.agentId),
|
||||
timeout_ms: 600000
|
||||
});
|
||||
|
||||
// Step 3: Check results and handle timeouts
|
||||
if (batchResult.timed_out) {
|
||||
console.log('Some parallel tasks timed out, continuing with completed results');
|
||||
}
|
||||
|
||||
// Step 4: Close all agents
|
||||
batchAgents.forEach(a => close_agent({ id: a.agentId }));
|
||||
```
|
||||
|
||||
### Agent Assignment Rules
|
||||
```
|
||||
meta.agent specified → Use specified agent
|
||||
meta.agent missing → Infer from meta.type:
|
||||
- "feature" → @code-developer (role: ~/.codex/agents/code-developer.md)
|
||||
- "test-gen" → @code-developer (role: ~/.codex/agents/code-developer.md)
|
||||
- "test-fix" → @test-fix-agent (role: ~/.codex/agents/test-fix-agent.md)
|
||||
- "review" → @universal-executor (role: ~/.codex/agents/universal-executor.md)
|
||||
- "docs" → @doc-generator (role: ~/.codex/agents/doc-generator.md)
|
||||
```
|
||||
|
||||
### Task Status Logic
|
||||
```
|
||||
pending + dependencies_met → executable
|
||||
completed → skip
|
||||
blocked → skip until dependencies clear
|
||||
```
|
||||
|
||||
## Step 4: Completion
|
||||
|
||||
### Process
|
||||
1. **Update Task Status**: Mark completed tasks in JSON files
|
||||
2. **Generate Summary**: Create task summary in `.summaries/`
|
||||
3. **Update TodoWrite**: Mark current task complete, advance to next
|
||||
4. **Synchronize State**: Update session state and workflow status
|
||||
5. **Check Workflow Complete**: Verify all tasks are completed
|
||||
6. **User Choice**: When all tasks finished, ask user to choose next step:
|
||||
|
||||
```javascript
|
||||
// Parse --yes flag
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
|
||||
if (autoYes) {
|
||||
// Auto mode: Complete session automatically
|
||||
console.log(`[--yes] Auto-selecting: Complete Session`)
|
||||
// Execute: workflow:session:complete --yes
|
||||
} else {
|
||||
// Interactive mode: Ask user
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "All tasks completed. What would you like to do next?",
|
||||
header: "Next Step",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{
|
||||
label: "Enter Review",
|
||||
description: "Run specialized review (security/architecture/quality/action-items)"
|
||||
},
|
||||
{
|
||||
label: "Complete Session",
|
||||
description: "Archive session and update manifest"
|
||||
}
|
||||
]
|
||||
}]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Based on user selection**:
|
||||
- **"Enter Review"**: Execute `workflow:review`
|
||||
- **"Complete Session"**: Execute `workflow:session:complete`
|
||||
|
||||
### Post-Completion Expansion
|
||||
|
||||
After completion, ask user whether to expand to issues (test/enhance/refactor/doc). Selected items invoke `issue:new "{summary} - {dimension}"`.
|
||||
|
||||
## Auto-Commit Mode (--with-commit)
|
||||
|
||||
**Behavior**: After each agent task completes, automatically commit changes based on summary document.
|
||||
|
||||
**Minimal Principle**: Only commit files modified by the completed task.
|
||||
|
||||
**Commit Message Format**: `{type}: {task-title} - {summary}`
|
||||
|
||||
**Type Mapping** (from `meta.type`):
|
||||
- `feature` → `feat` | `bugfix` → `fix` | `refactor` → `refactor`
|
||||
- `test-gen` → `test` | `docs` → `docs` | `review` → `chore`
|
||||
|
||||
**Implementation**:
|
||||
```bash
|
||||
# 1. Read summary from .summaries/{task-id}-summary.md
|
||||
# 2. Extract files from "Files Modified" section
|
||||
# 3. Commit: git add <files> && git commit -m "{type}: {title} - {summary}"
|
||||
```
|
||||
|
||||
**Error Handling**: Skip commit on no changes/missing summary, log errors, continue workflow.
|
||||
|
||||
## TodoWrite Coordination
|
||||
|
||||
### TodoWrite Rules
|
||||
|
||||
**Rule 1: Initial Creation**
|
||||
- Generate TodoWrite from TODO_LIST.md pending tasks
|
||||
|
||||
**Rule 2: In-Progress Task Count (Execution-Model-Dependent)**
|
||||
- **Sequential execution**: Mark ONLY ONE task as `in_progress` at a time
|
||||
- **Parallel batch execution**: Mark ALL tasks in current batch as `in_progress` simultaneously
|
||||
- **Execution group indicator**: Show `[execution_group: group-id]` for parallel tasks
|
||||
|
||||
**Rule 3: Status Updates**
|
||||
- **Immediate Updates**: Update status after each task/batch completion without user interruption
|
||||
- **Status Synchronization**: Sync with JSON task files after updates
|
||||
- **Continuous Tracking**: Maintain TodoWrite throughout entire workflow execution until completion
|
||||
|
||||
**Rule 4: Workflow Completion Check**
|
||||
- When all tasks marked `completed`, prompt user to choose review or complete session
|
||||
|
||||
### TodoWrite Examples
|
||||
|
||||
**Sequential Execution**:
|
||||
```javascript
|
||||
TodoWrite({
|
||||
todos: [
|
||||
{
|
||||
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
|
||||
status: "in_progress", // ONE task in progress
|
||||
activeForm: "Executing IMPL-1.1: Design auth schema"
|
||||
},
|
||||
{
|
||||
content: "Execute IMPL-1.2: Implement auth logic [code-developer] [FLOW_CONTROL]",
|
||||
status: "pending",
|
||||
activeForm: "Executing IMPL-1.2: Implement auth logic"
|
||||
}
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
**Parallel Batch Execution**:
|
||||
```javascript
|
||||
TodoWrite({
|
||||
todos: [
|
||||
{
|
||||
content: "Execute IMPL-1.1: Build Auth API [code-developer] [execution_group: parallel-auth-api]",
|
||||
status: "in_progress",
|
||||
activeForm: "Executing IMPL-1.1: Build Auth API"
|
||||
},
|
||||
{
|
||||
content: "Execute IMPL-1.2: Build User UI [code-developer] [execution_group: parallel-ui-comp]",
|
||||
status: "in_progress",
|
||||
activeForm: "Executing IMPL-1.2: Build User UI"
|
||||
},
|
||||
{
|
||||
content: "Execute IMPL-2.1: Integration Tests [test-fix-agent] [depends_on: IMPL-1.1, IMPL-1.2]",
|
||||
status: "pending",
|
||||
activeForm: "Executing IMPL-2.1: Integration Tests"
|
||||
}
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
## Error Handling & Recovery
|
||||
|
||||
### Common Errors & Recovery
|
||||
|
||||
| Error Type | Cause | Recovery Strategy | Max Attempts |
|
||||
|-----------|-------|------------------|--------------|
|
||||
| **Execution Errors** |
|
||||
| Agent failure | Agent crash/timeout | Retry with simplified context (close_agent first, then spawn new) | 2 |
|
||||
| Flow control error | Command failure | Skip optional, fail critical | 1 per step |
|
||||
| Context loading error | Missing dependencies | Reload from JSON, use defaults | 3 |
|
||||
| JSON file corruption | File system issues | Restore from backup/recreate | 1 |
|
||||
| **Lifecycle Errors** |
|
||||
| Agent timeout | wait timed out | send_input to prompt completion, or close_agent and retry | 2 |
|
||||
| Orphaned agent | Agent not closed after error | Ensure close_agent in error paths | N/A |
|
||||
|
||||
### Error Recovery with Lifecycle Management
|
||||
```javascript
|
||||
// Safe agent execution pattern with error handling
|
||||
let agentId = null;
|
||||
try {
|
||||
agentId = spawn_agent({ message: taskPrompt });
|
||||
const result = wait({ ids: [agentId], timeout_ms: 600000 });
|
||||
|
||||
if (result.timed_out) {
|
||||
// Option 1: Send prompt to complete
|
||||
send_input({ id: agentId, message: "Please wrap up and generate summary." });
|
||||
const retryResult = wait({ ids: [agentId], timeout_ms: 120000 });
|
||||
}
|
||||
|
||||
// Process results...
|
||||
close_agent({ id: agentId });
|
||||
} catch (error) {
|
||||
// Ensure cleanup on error
|
||||
if (agentId) close_agent({ id: agentId });
|
||||
// Handle error (retry or skip task)
|
||||
}
|
||||
```
|
||||
|
||||
### Error Prevention
|
||||
- **Lazy Loading**: Reduces upfront memory usage and validation errors
|
||||
- **Atomic Updates**: Update JSON files atomically to prevent corruption
|
||||
- **Dependency Validation**: Check all depends_on references exist
|
||||
- **Context Verification**: Ensure all required context is available
|
||||
- **Lifecycle Cleanup**: Always close_agent in both success and error paths
|
||||
|
||||
## Output
|
||||
|
||||
- **Updated**: Task JSON status fields (completed)
|
||||
- **Created**: `.summaries/IMPL-*-summary.md` per task
|
||||
- **Updated**: `TODO_LIST.md` (by agents)
|
||||
- **Updated**: `workflow-session.json` status
|
||||
- **Created**: Git commits (if `--with-commit`)
|
||||
|
||||
## Next Step
|
||||
|
||||
Return to orchestrator. Orchestrator handles completion summary output.
|
||||
Reference in New Issue
Block a user