
Workflow Plan
- 78 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Generate structured development plans from requirements
About
Generates detailed implementation plans for development work. Breaks down requirements, defines scope, structures architecture, and creates actionable task lists.
- Plan generation
- Scope breakdown
- Task decomposition
Workflow Plan by the numbers
- 78 all-time installs (skills.sh)
- Ranked #904 of 2,715 Automation & Workflows skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill workflow-planAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 78 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Generate structured development plans from requirements
What you get
- implementation plan
- test suite
- passing tests
Files
<purpose> Unified planning skill combining 4-phase planning workflow, plan quality verification, and interactive replanning. Produces IMPL_PLAN.md, task JSONs, verification reports, and manages plan lifecycle through session-level artifact updates. Routes by mode (plan | verify | replan) and acts as a pure orchestrator: executes phases, parses outputs, and passes context. </purpose>
<process>
1. Architecture Overview
┌──────────────────────────────────────────────────────────────────┐
│ Workflow Plan Orchestrator (SKILL.md) │
│ → Route by mode: plan | verify | replan │
│ → Pure coordinator: Execute phases, parse outputs, pass context │
└──────────────────────────────────┬───────────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
↓ ↓ ↓
┌───────────┐ ┌───────────┐ ┌───────────┐
│ Plan Mode │ │ Verify │ │ Replan │
│ (default) │ │ Mode │ │ Mode │
│ Phase 1-4 │ │ Phase 5 │ │ Phase 6 │
└─────┬─────┘ └───────────┘ └───────────┘
│
┌───┼───┬───┐
↓ ↓ ↓ ↓
┌───┐┌───┐┌───┐┌───┐
│ 1 ││ 2 ││ 3 ││ 4 │
│Ses││Ctx││Con││Gen│
└───┘└───┘└───┘└─┬─┘
↓
┌───────────┐
│ Confirm │─── Verify ──→ Phase 5
│ (choice) │─── Execute ─→ Skill("workflow-execute")
└───────────┘─── Review ──→ Display session status inline2. Key Design Principles
1. Pure Orchestrator: SKILL.md routes and coordinates only; execution detail lives in phase files 2. Progressive Phase Loading: Read phase docs ONLY when that phase is about to execute 3. Multi-Mode Routing: Single skill handles plan/verify/replan via mode detection 4. Task Attachment Model: Sub-command tasks are ATTACHED, executed sequentially, then COLLAPSED 5. Auto-Continue: After each phase completes, automatically execute next pending phase 6. Accumulated State: planning-notes.md carries context across phases for N+1 decisions
3. Interactive Preference Collection
Before dispatching to phase execution, collect workflow preferences via AskUserQuestion:
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)
if (autoYes) {
// 自动模式:跳过所有询问,使用默认值
workflowPreferences = { autoYes: true, interactive: false }
} else {
const prefResponse = AskUserQuestion({
questions: [
{
question: "是否跳过所有确认步骤(自动模式)?",
header: "Auto Mode",
multiSelect: false,
options: [
{ label: "Interactive (Recommended)", description: "交互模式,包含确认步骤" },
{ label: "Auto", description: "跳过所有确认,自动执行" }
]
}
]
})
workflowPreferences = {
autoYes: prefResponse.autoMode === 'Auto'
}
// For replan mode, also collect interactive preference
if (mode === 'replan') {
const replanPref = AskUserQuestion({
questions: [
{
question: "是否使用交互式澄清模式?",
header: "Replan Mode",
multiSelect: false,
options: [
{ label: "Standard (Recommended)", description: "使用安全默认值" },
{ label: "Interactive", description: "通过提问交互式澄清修改范围" }
]
}
]
})
workflowPreferences.interactive = replanPref.replanMode === 'Interactive'
}
}workflowPreferences is passed to phase execution as context variable, referenced as workflowPreferences.autoYes, workflowPreferences.interactive within phases.
4. Mode Detection
const args = $ARGUMENTS
const mode = detectMode(args)
function detectMode(args) {
// Skill trigger determines mode
if (skillName === 'workflow-plan-verify') return 'verify'
if (skillName === 'workflow:replan') return 'replan'
return 'plan' // default: workflow-plan
}5. Compact Recovery (Phase Persistence)
Multi-phase planning (Phase 1-4/5/6) spans long conversations. Uses 双重保险: TodoWrite 跟踪 active phase 保护其不被压缩,sentinel 作为兜底。
⚠️ COMPACT DIRECTIVE: Context compression MUST check TodoWrite phase status.
The phase currently marked in_progress is the active execution phase — preserve its FULL content.Only compress phases markedcompletedorpending.
6. Execution Flow
Plan Mode (default)
Input Parsing:
└─ Convert user input to structured format (GOAL/SCOPE/CONTEXT)
Phase 1: Session Discovery
└─ Ref: Read("phases/01-session-discovery.md")
└─ Output: sessionId (WFS-xxx), planning-notes.md
Phase 2: Context Gathering
└─ Ref: Read("phases/02-context-gathering.md")
├─ Tasks attached: Analyze structure → Identify integration → Generate package
└─ Output: contextPath + conflictRisk
Phase 3: Conflict Resolution (conditional: conflictRisk ≥ medium)
└─ Decision (conflictRisk check):
├─ conflictRisk ≥ medium → Ref: Read("phases/03-conflict-resolution.md")
│ ├─ Tasks attached: Detect conflicts → Present to user → Apply strategies
│ └─ Output: Modified brainstorm artifacts
└─ conflictRisk < medium → Skip to Phase 4
Phase 4: Task Generation
└─ Ref: Read("phases/04-task-generation.md")
└─ Output: IMPL_PLAN.md, task JSONs, TODO_LIST.md
Plan Confirmation (User Decision Gate):
└─ Decision (user choice):
├─ "Verify Plan Quality" (Recommended) → Route to Phase 5 (plan-verify)
├─ "Start Execution" → Skill(skill="workflow-execute")
└─ "Review Status Only" → Display session status inlineVerify Mode
Phase 5: Plan Verification
└─ Ref: Read("phases/05-plan-verify.md")
└─ Output: PLAN_VERIFICATION.md with quality gate recommendationReplan Mode
Phase 6: Interactive Replan
└─ Ref: Read("phases/06-replan.md")
└─ Output: Updated IMPL_PLAN.md, task JSONs, TODO_LIST.mdPhase Reference Documents (read on-demand when phase executes):
| Phase | Document | Purpose | Mode | Compact |
|---|---|---|---|---|
| 1 | phases/01-session-discovery.md | Create or discover workflow session | plan | TodoWrite 驱动 |
| 2 | phases/02-context-gathering.md | Gather project context and analyze codebase | plan | TodoWrite 驱动 |
| 3 | phases/03-conflict-resolution.md | Detect and resolve conflicts (conditional) | plan | TodoWrite 驱动 |
| 4 | phases/04-task-generation.md | Generate implementation plan and task JSONs | plan | TodoWrite 驱动 + 🔄 sentinel |
| 5 | phases/05-plan-verify.md | Read-only verification with quality gate | verify | TodoWrite 驱动 |
| 6 | phases/06-replan.md | Interactive replanning with boundary clarification | replan | TodoWrite 驱动 |
Compact Rules: 1. TodoWrite `in_progress` → 保留完整内容,禁止压缩 2. TodoWrite `completed` → 可压缩为摘要 3. 🔄 sentinel fallback → Phase 4 包含 compact sentinel;若 compact 后仅存 sentinel 而无完整 Step 协议,必须立即 Read("phases/04-task-generation.md") 恢复
7. Core Rules
1. Start Immediately: First action is mode detection + TodoWrite initialization, second action is phase execution 2. No Preliminary Analysis: Do not read files, analyze structure, or gather context before Phase 1 3. Parse Every Output: Extract required data from each phase output for next phase 4. Auto-Continue via TodoList: Check TodoList status to execute next pending phase automatically 5. Track Progress: Update TodoWrite dynamically with task attachment/collapse pattern 6. Task Attachment Model: Skill execute attaches sub-tasks to current workflow. Orchestrator executes these attached tasks itself, then collapses them after completion 7. Progressive Phase Loading: Read phase docs ONLY when that phase is about to execute 8. DO NOT STOP: Continuous multi-phase workflow. After executing all attached tasks, immediately collapse them and execute next phase
8. Input Processing
Convert User Input to Structured Format:
1. Simple Text → Structure it:
User: "Build authentication system"
Structured:
GOAL: Build authentication system
SCOPE: Core authentication features
CONTEXT: New implementation2. Detailed Text → Extract components:
User: "Add JWT authentication with email/password login and token refresh"
Structured:
GOAL: Implement JWT-based authentication
SCOPE: Email/password login, token generation, token refresh endpoints
CONTEXT: JWT token-based security, refresh token rotation3. File Reference (e.g., requirements.md) → Read and structure:
- Read file content
- Extract goal, scope, requirements
- Format into structured description
9. Data Flow
Plan Mode
User Input (task description)
↓
[Convert to Structured Format]
↓ Structured Description:
↓ GOAL: [objective]
↓ SCOPE: [boundaries]
↓ CONTEXT: [background]
↓
Phase 1: session:start --auto "structured-description"
↓ Output: sessionId
↓ Write: planning-notes.md (User Intent section)
↓
Phase 2: context-gather --session sessionId "structured-description"
↓ Input: sessionId + structured description
↓ Output: contextPath (context-package.json) + conflictRisk
↓ Update: planning-notes.md (Context Findings + Consolidated Constraints)
↓
Phase 3: conflict-resolution [conditional: conflictRisk ≥ medium]
↓ Input: sessionId + contextPath + conflictRisk
↓ Output: Modified brainstorm artifacts
↓ Update: planning-notes.md (Conflict Decisions + Consolidated Constraints)
↓ Skip if conflictRisk is none/low → proceed directly to Phase 4
↓
Phase 4: task-generate-agent --session sessionId
↓ Input: sessionId + planning-notes.md + context-package.json + brainstorm artifacts
↓ Output: IMPL_PLAN.md, task JSONs, TODO_LIST.md
↓
Plan Confirmation (User Decision Gate):
├─ "Verify Plan Quality" (Recommended) → Route to Phase 5
├─ "Start Execution" → Skill(skill="workflow-execute")
└─ "Review Status Only" → Display session status inlineSession Memory Flow: Each phase receives session ID, which provides access to:
- Previous task summaries
- Existing context and analysis
- Brainstorming artifacts (potentially modified by Phase 3)
- Session-specific configuration
Verify Mode
Input: --session sessionId (or auto-detect)
↓
Phase 5: Load artifacts → Agent-driven verification → Generate report
↓ Output: PLAN_VERIFICATION.md with quality gateReplan Mode
Input: [--session sessionId] [task-id] "requirements"
↓
Phase 6: Mode detection → Clarification → Impact analysis → Backup → Apply → Verify
↓ Output: Updated artifacts + change summary10. TodoWrite Pattern
Core Concept: Dynamic task attachment and collapse for real-time visibility into workflow execution.
Key Principles
1. Task Attachment (when phase executed):
- Sub-tasks are attached to orchestrator's TodoWrite
- Phase 2, 3: Multiple sub-tasks attached
- Phase 1, 4: Single task (atomic)
- First attached task marked as
in_progress, others aspending - Orchestrator executes these attached tasks sequentially
2. Task Collapse (after sub-tasks complete):
- Applies to Phase 2, 3: Remove detailed sub-tasks from TodoWrite
- Collapse to high-level phase summary
- Phase 1, 4: No collapse needed (single task, just mark completed)
- Maintains clean orchestrator-level view
3. Continuous Execution: After completion, automatically proceed to next pending phase
Lifecycle: Initial pending → Phase executed (tasks ATTACHED) → Sub-tasks executed → Phase completed (tasks COLLAPSED for 2/3, marked completed for 1/4) → Next phase → Repeat
Phase 2 (Tasks Attached):
[
{"content": "Phase 1: Session Discovery", "status": "completed"},
{"content": "Phase 2: Context Gathering", "status": "in_progress"},
{"content": " → Analyze codebase structure", "status": "in_progress"},
{"content": " → Identify integration points", "status": "pending"},
{"content": " → Generate context package", "status": "pending"},
{"content": "Phase 4: Task Generation", "status": "pending"}
]Phase 2 (Collapsed):
[
{"content": "Phase 1: Session Discovery", "status": "completed"},
{"content": "Phase 2: Context Gathering", "status": "completed"},
{"content": "Phase 4: Task Generation", "status": "pending"}
]Phase 3 (Tasks Attached, conditional):
[
{"content": "Phase 1: Session Discovery", "status": "completed"},
{"content": "Phase 2: Context Gathering", "status": "completed"},
{"content": "Phase 3: Conflict Resolution", "status": "in_progress"},
{"content": " → Detect conflicts with CLI analysis", "status": "in_progress"},
{"content": " → Present conflicts to user", "status": "pending"},
{"content": " → Apply resolution strategies", "status": "pending"},
{"content": "Phase 4: Task Generation", "status": "pending"}
]Note: See individual Phase descriptions for detailed TodoWrite Update examples.
11. Post-Phase Updates
After each phase completes, update planning-notes.md:
- After Phase 1: Initialize with user intent (GOAL, KEY_CONSTRAINTS)
- After Phase 2: Add context findings (CRITICAL_FILES, ARCHITECTURE, CONFLICT_RISK, CONSTRAINTS)
- After Phase 3: Add conflict decisions (RESOLVED, MODIFIED_ARTIFACTS, CONSTRAINTS) if executed
- Memory State Check: After heavy phases (Phase 2-3), evaluate context window usage; if high (>120K tokens), trigger
compact
See phase files for detailed update code.
12. Error Handling
- Parsing Failure: If output parsing fails, retry command once, then report error
- Validation Failure: If validation fails, report which file/data is missing
- Command Failure: Keep phase
in_progress, report error to user, do not proceed to next phase - Session Not Found (verify/replan): Report error with available sessions list
- Task Not Found (replan): Report error with available tasks list
13. Coordinator Checklist
Plan Mode
- Pre-Phase: Convert user input to structured format (GOAL/SCOPE/CONTEXT)
- Initialize TodoWrite before any command (Phase 3 added dynamically after Phase 2)
- Execute Phase 1 immediately with structured description
- Parse session ID from Phase 1 output, store in memory
- Session Integrity: If reusing existing session, verify
sessionIntegrityfrom Step 1.2.5; log warnings for incomplete brainstorm artifacts - Pass session ID and structured description to Phase 2 command
- Parse context path from Phase 2 output, store in memory
- Extract conflictRisk from context-package.json: Determine Phase 3 execution
- If conflictRisk ≥ medium: Launch Phase 3 conflict-resolution with sessionId and contextPath
- Wait for Phase 3 to finish executing (if executed), verify conflict-resolution.json created
- If conflictRisk is none/low: Skip Phase 3, proceed directly to Phase 4
- Pass session ID to Phase 4 command
- Verify all Phase 4 outputs
- Plan Confirmation Gate: Present user with choice (Verify → Phase 5 / Execute / Review Status)
- If user selects Verify: Read phases/05-plan-verify.md, execute Phase 5 in-process
- If user selects Execute: Skill(skill="workflow-execute")
- If user selects Review: Display session status inline
- Auto mode (workflowPreferences.autoYes): Auto-select "Verify Plan Quality", then auto-continue to execute if PROCEED
- Update TodoWrite after each phase
- After each phase, automatically continue to next phase based on TodoList status
Verify Mode
- Detect/validate session (auto-detect from active sessions)
- Initialize TodoWrite with single verification task
- Execute Phase 5 verification agent
- Present quality gate result and next step options
Replan Mode
- Parse task ID from $ARGUMENTS (IMPL-N format, if present)
- Detect operation mode (task vs session)
- Initialize TodoWrite with replan-specific tasks
- Execute Phase 6 through all sub-phases (clarification → impact → backup → apply → verify)
14. Structure Template Reference
Minimal Structure:
GOAL: [What to achieve]
SCOPE: [What's included]
CONTEXT: [Relevant info]Detailed Structure (optional, when more context available):
GOAL: [Primary objective]
SCOPE: [Included features/components]
CONTEXT: [Existing system, constraints, dependencies]
REQUIREMENTS: [Specific technical requirements]
CONSTRAINTS: [Limitations or boundaries]15. Related Skills
Prerequisite Skills:
brainstormskill - Optional: Generate role-based analyses before planningbrainstormskill - Optional: Refine brainstorm analyses with clarifications
Called by Plan Mode (4 phases):
/workflow:session:start- Phase 1: Create or discover workflow sessionphases/02-context-gathering.md- Phase 2: Gather project context and analyze codebase (inline)phases/03-conflict-resolution.md- Phase 3: Detect and resolve conflicts (inline, conditional)memory-captureskill - Phase 3: Memory optimization (if context approaching limits)phases/04-task-generation.md- Phase 4: Generate task JSON files (inline)
Follow-up Skills:
workflow-planskill (plan-verify phase) - Verify plan quality (can also invoke via verify mode)- Display session status inline - Review task breakdown and current progress
Skill(skill="workflow-execute")- Begin implementation of generated tasks (skill: workflow-execute)workflow-planskill (replan phase) - Modify plan (can also invoke via replan mode)
</process>
<auto_mode> When workflowPreferences.autoYes is true (triggered by -y or --yes flag, or user selecting "Auto" mode):
- Skip all confirmation prompts, use default values
- Auto-select "Verify Plan Quality" at Plan Confirmation Gate
- Auto-continue to execution if verification returns PROCEED
- Skip interactive clarification in replan mode (use safe defaults)
</auto_mode>
<success_criteria>
- [ ] Mode correctly detected from skill trigger (plan / verify / replan)
- [ ] TodoWrite initialized and updated after each phase with attachment/collapse pattern
- [ ] All phases executed in sequence with proper data passing between phases
- [ ] Phase documents loaded progressively via Read() only when phase is about to execute
- [ ] planning-notes.md updated after each phase with accumulated context
- [ ] Phase 3 conditionally executed based on conflictRisk assessment
- [ ] Plan Confirmation Gate presented with correct options after Phase 4
- [ ] All output artifacts generated: IMPL_PLAN.md, task JSONs, TODO_LIST.md
- [ ] Compact recovery works: in_progress phases preserved, completed phases compressible
- [ ] Error handling covers parsing failures, validation failures, and missing sessions/tasks
</success_criteria>
Phase 1: Session Discovery
Create or discover workflow session and initialize planning notes document.
Objective
- Create a new workflow session via
/workflow:session:start - Extract session ID for subsequent phases
- Initialize planning-notes.md with user intent and N+1 context structure
Execution
Step 1.1: Execute Session Start
Skill(skill="workflow:session:start", args="--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 endpointsStep 1.2: Parse Output
- Extract:
SESSION_ID: WFS-[id](store assessionId)
Validation:
- 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.2.5: Session Integrity Check
For reused sessions (not newly created), validate key artifact completeness:
1. Baseline: workflow-session.json exists and is valid JSON; .process/ and .task/ directories exist (create if missing) 2. Brainstorm inheritance: If .brainstorming/ directory exists, check:
guidance-specification.mdexists → missing = WARN brainstorm Phase 2 incomplete*/analysis.mdcount → 0 = WARN brainstorm Phase 3 incompletefeature-specs/orfeature-index.json→ missing = WARN brainstorm Phase 4 (synthesis) incomplete
3. Existing notes detection: Store existingNotes = file_exists(planning-notes.md)
Store results in sessionIntegrity variable for downstream phases. Warnings are logged but do not block execution.
TodoWrite: Mark phase 1 completed, phase 2 in_progress
Step 1.3: Initialize Planning Notes (Conditional)
After Phase 1, initialize planning-notes.md with user intent.
Conditional logic:
- If
existingNotes = true: Only append## User Intent (Phase 1)section when missing from the file; do NOT overwrite existing content - If
existingNotes = false: Create new file using template below
// Create planning notes document with N+1 context support
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 3)
(To be filled if conflicts detected)
## Consolidated Constraints (Phase 4 Input)
1. ${userConstraints}
---
## Task Generation (Phase 4)
(To be filled by action-planning-agent)
## N+1 Context
### Decisions
| Decision | Rationale | Revisit? |
|----------|-----------|----------|
### Deferred
- [ ] (For N+1)
`)Output
- Variable:
sessionId(WFS-xxx) - File:
.workflow/active/[sessionId]/planning-notes.md - TodoWrite: Mark Phase 1 completed, Phase 2 in_progress
Next Phase
Return to orchestrator, then auto-continue to Phase 2: Context Gathering.
Phase 2: Context Gathering
Gather project context and analyze codebase via context-search-agent with parallel exploration.
Objective
- Gather project context using context-search-agent
- Identify critical files, architecture patterns, and constraints
- Detect conflict risk level for Phase 3 decision
- Update planning-notes.md with findings
Core Philosophy
- Agent Delegation: Delegate all discovery to
context-search-agentfor autonomous execution - Detection-First: Check for existing context-package before executing
- Plan Mode: Full comprehensive analysis (vs lightweight brainstorm mode)
- Standardized Output: Generate
.workflow/active/{session}/.process/context-package.json
Execution
Step 2.1: Context-Package Detection
Execute First - Check if valid package already exists:
const contextPackagePath = `.workflow/active/${sessionId}/.process/context-package.json`;
if (file_exists(contextPackagePath)) {
const existing = Read(contextPackagePath);
// Validate package belongs to current session
if (existing?.metadata?.session_id === sessionId) {
console.log("Valid context-package found for session:", sessionId);
console.log("Stats:", existing.statistics);
console.log("Conflict Risk:", existing.conflict_detection.risk_level);
// Skip Steps 2.2-2.4, but STILL execute Step 2.5 (planning-notes update)
contextPath = contextPackagePath;
conflictRisk = existing.conflict_detection.risk_level;
// → Jump to Step 2.5 (do NOT return before updating planning-notes)
}
}Step 2.2: Complexity Assessment & Parallel Explore
Only execute if Step 2.1 finds no valid package
// 2.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/${sessionId}/.process`;
// 2.2.2 Launch Parallel Explore Agents
const explorationTasks = selectedAngles.map((angle, index) =>
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description=`Explore: ${angle}`,
prompt=`
## Task Objective
Execute **${angle}** exploration for task planning context. Analyze codebase from this specific angle to discover relevant structure, patterns, and constraints.
## Assigned Context
- **Exploration Angle**: ${angle}
- **Task Description**: ${task_description}
- **Session ID**: ${sessionId}
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
- **Output File**: ${sessionFolder}/exploration-${angle}.json
## Agent Initialization
The cli-explore-agent autonomously executes project structure discovery, schema loading, project context loading, and keyword search as part of its Phase 1 initialization. No manual steps needed.
## Exploration Strategy (${angle} focus)
**Step 1: Structural Scan** (Bash)
- Identify modules related to ${angle}
- 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?
**Step 3: Write Output**
- Consolidate ${angle} findings into JSON
- Identify ${angle}-specific clarification needs
## Expected Output
**File**: ${sessionFolder}/exploration-${angle}.json
**Required Fields** (all ${angle} focused):
- Follow explore-json-schema.json exactly (loaded during agent initialization)
- All fields scoped to ${angle} perspective
- Ensure rationale is specific to ${angle} topic (not generic)
- Include file:line locations in integration_points
## Success Criteria
- [ ] At least 3 relevant files identified with ${angle} rationale
- [ ] Patterns are actionable (code examples, not generic advice)
- [ ] Integration points include file:line locations
- [ ] Constraints are project-specific to ${angle}
- [ ] JSON output follows schema exactly
- [ ] clarification_needs includes options + recommended
## Output
Write: ${sessionFolder}/exploration-${angle}.json
Return: 2-3 sentence summary of ${angle} findings
`
)
);
// 2.2.3 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: sessionId,
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 2.3: Invoke Context-Search Agent
Only execute after Step 2.2 completes
// Load user intent from planning-notes.md (from Phase 1)
const planningNotesPath = `.workflow/active/${sessionId}/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();
}
Task(
subagent_type="context-search-agent",
run_in_background=false,
description="Gather comprehensive context for plan",
prompt=`
## Execution Mode
**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution with priority sorting
## Session Information
- **Session ID**: ${sessionId}
- **Task Description**: ${task_description}
- **Output Path**: .workflow/${sessionId}/.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.2)
- **Manifest**: ${sessionFolder}/explorations-manifest.json
- **Exploration Count**: ${explorationManifest.exploration_count}
- **Angles**: ${explorationManifest.angles_explored.join(', ')}
- **Complexity**: ${complexity}
## Mission
Execute complete context-search-agent workflow (Phase 1-3) for implementation planning.
Key emphasis:
- Run: ccw spec load --category exploration FIRST (per your spec Phase 1.1b)
- Synthesize exploration results with project context
- Generate prioritized_context with user_intent alignment
- Apply specs/*.md constraints during conflict detection
Input priority: User Intent > project-tech.json > Exploration results > Code discovery > Web examples
## Output Requirements
Complete context-package.json must include a **prioritized_context** section:{ "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, exploration critical files, and dependency graph" } }
All other required fields (metadata, project_context, project_guidelines, assets, dependencies, brainstorm_artifacts, conflict_detection, exploration_results) follow context-search-agent standard output schema.
## Planning Notes Record (REQUIRED)
After completing context-package.json, append to planning-notes.md:
**File**: .workflow/active/${sessionId}/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.
`
)Step 2.4: Output Verification
After agent completes, verify output:
// Verify file was created
const outputPath = `.workflow/active/${sessionId}/.process/context-package.json`;
if (!file_exists(outputPath)) {
throw new Error("Agent failed to generate context-package.json");
}
// Store variables for subsequent phases
contextPath = outputPath;
// 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`);
}
conflictRisk = pkg.conflict_detection?.risk_level || 'low';TodoWrite Update (Phase 2 in progress - tasks attached)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "in_progress", "activeForm": "Executing context gathering"},
{"content": " -> Analyze codebase structure", "status": "in_progress", "activeForm": "Analyzing codebase structure"},
{"content": " -> Identify integration points", "status": "pending", "activeForm": "Identifying integration points"},
{"content": " -> Generate context package", "status": "pending", "activeForm": "Generating context package"},
{"content": "Phase 4: Task Generation", "status": "pending", "activeForm": "Executing task generation"}
]TodoWrite Update (Phase 2 completed - tasks collapsed)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 4: Task Generation", "status": "pending", "activeForm": "Executing task generation"}
]Step 2.5: Update Planning Notes
After context gathering completes, update planning-notes.md with findings:
// Read context-package to extract key findings
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 || []
// Append Phase 2 findings to planning-notes.md
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'}`
})
// Append Phase 2 constraints to consolidated list
Edit(planningNotesPath, {
old: '## Consolidated Constraints (Phase 4 Input)',
new: `## Consolidated Constraints (Phase 4 Input)
${constraints.map((c, i) => `${i + 2}. [Context] ${c}`).join('\n')}`
})Auto-Continue: Return to user showing Phase 2 results, then auto-continue to Phase 3/4 (depending on conflictRisk).
Output
- Variable:
contextPath(path to context-package.json) - Variable:
conflictRisk(none/low/medium/high) - File:
context-package.json - TodoWrite: Mark Phase 2 completed, determine Phase 3 or Phase 4
Next Phase
Return to orchestrator. Orchestrator checks conflictRisk:
- If
conflictRisk >= medium-> Phase 3: Conflict Resolution - If
conflictRisk < medium-> Phase 4: Task Generation
Phase 3: Conflict Resolution
Detect and resolve conflicts with CLI analysis. This phase is conditional - only executes when conflict_risk >= medium.
Objective
- Detect conflicts between planned changes and existing codebase
- Detect module scenario uniqueness (functional overlaps)
- Present conflicts to user with resolution strategies
- Apply selected resolution strategies
- Update planning-notes.md with conflict decisions
Trigger Condition
Only execute when context-package.json indicates conflict_risk is "medium" or "high". If conflict_risk is "none" or "low", skip directly to Phase 4.
Conflict Categories
| Category | Description |
|---|---|
| Architecture | Incompatible design patterns, module structure changes |
| API | Breaking contract changes, signature modifications |
| Data Model | Schema modifications, type breaking changes |
| Dependency | Version incompatibilities, setup conflicts |
| ModuleOverlap | Functional overlap, scenario boundary ambiguity, duplicate responsibility |
Execution
Step 3.1: Validation
// 1. Verify session directory exists
const sessionDir = `.workflow/active/${sessionId}`;
if (!file_exists(sessionDir)) {
throw new Error(`Session directory not found: ${sessionDir}`);
}
// 2. Load context-package.json
const contextPackage = JSON.parse(Read(contextPath));
// 3. Check conflict_risk (skip if none/low)
const conflictRisk = contextPackage.conflict_detection?.risk_level || 'low';
if (conflictRisk === 'none' || conflictRisk === 'low') {
console.log("No significant conflicts detected, proceeding to task generation");
// Skip directly to Phase 4
return;
}Step 3.2: CLI-Powered Conflict Analysis
Agent Delegation:
Task(subagent_type="cli-execution-agent", run_in_background=false, prompt=`
## Context
- Session: ${sessionId}
- Risk: ${conflictRisk}
- Files: ${existing_files_list}
## Exploration Context (from context-package.exploration_results)
- Exploration Count: ${contextPackage.exploration_results?.exploration_count || 0}
- Angles Analyzed: ${JSON.stringify(contextPackage.exploration_results?.angles || [])}
- Pre-identified Conflict Indicators: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.conflict_indicators || [])}
- Critical Files: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.critical_files?.map(f => f.path) || [])}
- All Patterns: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.all_patterns || [])}
- All Integration Points: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.all_integration_points || [])}
## Analysis Steps
### 0. Load Output Schema (MANDATORY)
Execute: cat ~/.ccw/workflows/cli-templates/schemas/conflict-resolution-schema.json
### 1. Load Context
- Read existing files from conflict_detection.existing_files
- Load plan from .workflow/active/${sessionId}/.process/context-package.json
- Load exploration_results and use aggregated_insights for enhanced analysis
- Extract role analyses and requirements
### 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
- Use exploration integration_points for precise locations
- Cross-validate with exploration critical_files
- Generate clarification questions for boundary definition
MODE: analysis
CONTEXT: @**/*.ts @**/*.js @**/*.tsx @**/*.jsx @.workflow/active/${sessionId}/**/*
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
Output to conflict-resolution.json (generated in Phase 4)
**Schema Reference**: Execute cat ~/.ccw/workflows/cli-templates/schemas/conflict-resolution-schema.json to get full schema
Return JSON following the schema. 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 to planning-notes.md:
**File**: .workflow/active/${sessionId}/planning-notes.md
**Location**: Under "## Conflict Decisions (Phase 3)" section
**Format**:
### [Conflict-Resolution Agent] YYYY-MM-DD
- **Note**: [Brief summary of conflict types, strategies, key decisions]
`)Step 3.3: Iterative User Interaction
const autoYes = workflowPreferences?.autoYes || false;
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(`[autoYes] Auto-selecting recommended strategy`)
selectedStrategy = conflict.strategies[conflict.recommended || 0]
clarified = true // Skip clarification loop
} else {
AskUserQuestion({
questions: [{
question: formatStrategiesForDisplay(conflict.strategies),
header: "Strategy",
multiSelect: false,
options: [
...conflict.strategies.map((s, i) => ({
label: `${s.name}${i === conflict.recommended ? ' (Recommended)' : ''}`,
description: `${s.complexity} complexity | ${s.risk} risk${s.clarification_needed?.length ? ' | Needs clarification' : ''}`
})),
{ label: "Custom modification", description: `Suggestions: ${conflict.modification_suggestions?.slice(0,2).join('; ')}` }
]
}]
})
// 3. Handle selection
if (userChoice === "Custom modification") {
customConflicts.push({ id, brief, category, suggestions, overlap_analysis })
break
}
selectedStrategy = findStrategyByName(userChoice)
}
// 4. Clarification (if needed) - batched max 4 per call
if (!autoYes && selectedStrategy.clarification_needed?.length > 0) {
for (batch of chunk(selectedStrategy.clarification_needed, 4)) {
AskUserQuestion({
questions: batch.map((q, i) => ({
question: q, header: `Clarify${i+1}`, multiSelect: false,
options: [{ label: "Provide details", description: "Enter answer" }]
}))
})
userClarifications.push(...collectAnswers(batch))
}
// 5. Agent re-analysis
reanalysisResult = Agent({
subagent_type: "cli-execution-agent",
run_in_background: false,
prompt: `Conflict: ${conflict.id}, Strategy: ${selectedStrategy.name}
User Clarifications: ${JSON.stringify(userClarifications)}
Output: { uniqueness_confirmed, rationale, updated_strategy, remaining_questions }`
})
if (reanalysisResult.uniqueness_confirmed) {
selectedStrategy = { ...reanalysisResult.updated_strategy, clarifications: userClarifications }
clarified = true
} else {
selectedStrategy.clarification_needed = reanalysisResult.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 || []
}))Step 3.4: Apply Modifications
// 1. Extract 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(`Applying ${modifications.length} modifications...`);
// 2. Apply each modification using Edit tool (with fallback to context-package.json)
const appliedModifications = [];
const failedModifications = [];
const fallbackConstraints = []; // For files that don't exist
modifications.forEach((mod, idx) => {
try {
console.log(`[${idx + 1}/${modifications.length}] Modifying ${mod.file}...`);
// Check if target file exists (brainstorm files may not exist in lite workflow)
if (!file_exists(mod.file)) {
console.log(` File not found, writing to context-package.json 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; // Skip to next modification
}
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);
console.log(` Success`);
} catch (error) {
console.log(` Failed: ${error.message}`);
failedModifications.push({ ...mod, error: error.message });
}
});
// 3. Generate conflict-resolution.json output file
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));
// 4. Update context-package.json with resolution details
const contextPkg = JSON.parse(Read(contextPath));
contextPkg.conflict_detection.conflict_risk = "resolved";
contextPkg.conflict_detection.resolution_file = resolutionPath;
contextPkg.conflict_detection.resolved_conflicts = selectedStrategies.map(s => s.conflict_id);
contextPkg.conflict_detection.custom_conflicts = customConflicts.map(c => c.id);
contextPkg.conflict_detection.resolved_at = new Date().toISOString();
Write(contextPath, JSON.stringify(contextPkg, null, 2));
// 5. Output custom conflict summary with overlap analysis (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(`Overlap info: New module: ${conflict.overlap_analysis.new_module.name}`);
}
conflict.suggestions.forEach(s => console.log(` - ${s}`));
});
}TodoWrite Update (Phase 3 in progress, if conflict_risk >= medium)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 3: Conflict Resolution", "status": "in_progress", "activeForm": "Resolving conflicts"},
{"content": " -> Detect conflicts with CLI analysis", "status": "in_progress", "activeForm": "Detecting conflicts"},
{"content": " -> Present conflicts to user", "status": "pending", "activeForm": "Presenting conflicts"},
{"content": " -> Apply resolution strategies", "status": "pending", "activeForm": "Applying resolution strategies"},
{"content": "Phase 4: Task Generation", "status": "pending", "activeForm": "Executing task generation"}
]TodoWrite Update (Phase 3 completed - tasks collapsed)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 3: Conflict Resolution", "status": "completed", "activeForm": "Resolving conflicts"},
{"content": "Phase 4: Task Generation", "status": "pending", "activeForm": "Executing task generation"}
]Step 3.5: Update Planning Notes
After conflict resolution completes (if executed), update planning-notes.md:
if (conflictRisk === 'medium' || conflictRisk === 'high') {
const conflictResPath = `.workflow/active/${sessionId}/.process/conflict-resolution.json`;
if (file_exists(conflictResPath)) {
const conflictRes = JSON.parse(Read(conflictResPath));
const resolved = conflictRes.resolved_conflicts || [];
const modifiedArtifacts = conflictRes.modified_artifacts || [];
const planningConstraints = conflictRes.planning_constraints || [];
// Update Phase 3 section
Edit(planningNotesPath, {
old: '## Conflict Decisions (Phase 3)\n(To be filled if conflicts detected)',
new: `## Conflict Decisions (Phase 3)
- **RESOLVED**: ${resolved.map(r => `${r.type} -> ${r.strategy}`).join('; ') || 'None'}
- **MODIFIED_ARTIFACTS**: ${modifiedArtifacts.join(', ') || 'None'}
- **CONSTRAINTS**: ${planningConstraints.join('; ') || 'None'}`
})
// Append Phase 3 constraints to consolidated list
if (planningConstraints.length > 0) {
const currentNotes = Read(planningNotesPath);
const constraintCount = (currentNotes.match(/^\d+\./gm) || []).length;
Edit(planningNotesPath, {
old: '## Consolidated Constraints (Phase 4 Input)',
new: `## Consolidated Constraints (Phase 4 Input)
${planningConstraints.map((c, i) => `${constraintCount + i + 1}. [Conflict] ${c}`).join('\n')}`
})
}
}
}Auto-Continue: Return to user showing conflict resolution results and selected strategies, then auto-continue.
Auto Mode: When workflowPreferences.autoYes is true, conflict-resolution automatically applies recommended resolution strategies without user confirmation.
Step 3.6: Memory State Check
Evaluate current context window usage and memory state:
- If memory usage is high (>120K tokens or approaching context limits):
Skill(skill="memory-capture")- Memory compaction is particularly important after analysis phase which may generate extensive documentation
- Ensures optimal performance and prevents context overflow
Output
- File:
conflict-resolution.json(if conflicts resolved) - TodoWrite: Mark Phase 3 completed, Phase 4 in_progress
Next Phase
Return to orchestrator, then auto-continue to Phase 4: Task Generation.
Phase 4: Task Generation
📌 COMPACT SENTINEL [Phase 4: Task-Generation]
This phase contains 6 execution steps (Step 4.0 — 4.4).
If you can read this sentinel but cannot find the full Step protocol below, context has been compressed.
Recovery: Read("phases/04-task-generation.md")Generate implementation plan and task JSONs via action-planning-agent.
Objective
- Generate IMPL_PLAN.md, task JSONs, and TODO_LIST.md
- Present user with plan confirmation choices (verify / execute / review)
- Route to Phase 5 (verify) if user selects verification
Relationship with Brainstorm Phase
- If brainstorm role analyses exist ([role]/analysis.md files), they are incorporated as input
- User's original intent is ALWAYS primary: New or refined user goals override brainstorm recommendations
- Role analysis.md files define "WHAT": Requirements, design specs, role-specific insights
- IMPL_PLAN.md defines "HOW": Executable task breakdown, dependencies, implementation sequence
- Task generation translates high-level role analyses into concrete, actionable work items
- Intent priority: Current user prompt > role analysis.md files > guidance-specification.md
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/3
- Use
context-package.json.prioritized_contextdirectly - DO NOT re-sort files or re-compute priorities
priority_tiersanddependency_orderare 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
Execution
Step 4.0: User Configuration (Interactive)
Auto Mode Check:
const autoYes = workflowPreferences?.autoYes || false;
if (autoYes) {
console.log(`[autoYes] Using defaults: No materials, Agent executor, Codex CLI`)
userConfig = {
supplementaryMaterials: { type: "none", content: [] },
executionMethod: "agent",
preferredCliTool: "codex",
enableResume: true
}
// Skip to Step 4.1
}User Questions (skipped if autoYes):
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" }
]
}
]
})Step 4.1: Context Preparation & Module Detection
Command prepares session paths, metadata, detects module structure. Context priority sorting is NOT performed here.
// 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
// ├── .task/ # Output: Task JSON files
// ├── plan.json # Output: Structured plan overview
// ├── IMPL_PLAN.md # Output: Implementation plan
// └── TODO_LIST.md # Output: TODO list
// Auto Module Detection (determines single vs parallel mode)
function autoDetectModules(contextPackage, projectRoot) {
// Complexity Gate: Only parallelize for High complexity
const complexity = contextPackage.metadata?.complexity || 'Medium';
if (complexity !== 'High') {
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();
}
// 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)
// modules.length == 1 -> Phase 2A (Single Agent, original flow)
// modules.length >= 2 && complexity == 'High' -> Phase 2B + Phase 3 (N+1 Parallel)Step 4.2A: Single Agent Planning (modules.length == 1)
Purpose: Generate IMPL_PLAN.md, task JSONs, and TODO_LIST.md - planning documents only, NOT code implementation.
Design Note: The agent specification (action-planning-agent.md) already defines schemas, strategies, quality standards, and loading algorithms. This prompt provides instance-specific parameters only — session paths, user config, and context-package consumption guidance unique to this session.
Task(
subagent_type="action-planning-agent",
run_in_background=false,
description="Generate planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md)",
prompt=`
## TASK OBJECTIVE
Generate implementation planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) for workflow session ${sessionId}
## SESSION PATHS
Session Root: .workflow/active/${sessionId}/
Input:
- Session Metadata: .workflow/active/${sessionId}/workflow-session.json
- Planning Notes: .workflow/active/${sessionId}/planning-notes.md
- Context Package: .workflow/active/${sessionId}/.process/context-package.json
Output:
- Task Dir: .workflow/active/${sessionId}/.task/
- IMPL_PLAN: .workflow/active/${sessionId}/IMPL_PLAN.md
- TODO_LIST: .workflow/active/${sessionId}/TODO_LIST.md
## CONTEXT METADATA
Session ID: ${sessionId}
MCP Capabilities: {exa_code, exa_web, code_index}
## PROJECT CONTEXT (MANDATORY - load via ccw spec)
Execute: ccw spec load --category planning
This loads:
- Technology stack, architecture, key components, build system, test framework
- User-maintained rules and constraints (coding_conventions, naming_rules, forbidden_patterns, quality_gates)
Usage:
- Populate plan.json shared_context, align task tech choices, set correct test commands
- Apply as HARD CONSTRAINTS on all generated tasks — task implementation steps,
acceptance criteria, and convergence.verification MUST respect these guidelines
If spec load returns empty: Proceed normally with context-package.project_context
Loading order: ccw spec load → planning-notes.md → context-package.json
## USER CONFIGURATION (from Step 4.0)
Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli
Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto
Supplementary Materials: ${userConfig.supplementaryMaterials}
## PRIORITIZED CONTEXT (from context-package.prioritized_context) - ALREADY SORTED
Context sorting is ALREADY COMPLETED in Phase 2/3. DO NOT re-sort.
Direct usage:
- **user_intent**: Use goal/scope/key_constraints for task alignment
- **priority_tiers.critical**: PRIMARY focus for task generation
- **priority_tiers.high**: SECONDARY focus
- **dependency_order**: Use 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:
- 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
## BRAINSTORM ARTIFACT VALIDATION (before feature spec loading)
If .brainstorming/ directory exists in session, verify completeness:
- guidance-specification.md missing → WARN: brainstorm Phase 2 incomplete, planning proceeds without framework
- */analysis.md count = 0 → WARN: brainstorm Phase 3 incomplete, no role analyses available
- feature-specs/ AND feature-index.json both missing → WARN: brainstorm Phase 4 incomplete, skip feature specs
Log warnings to console. Populate agent prompt FEATURE SPECIFICATIONS section only when artifacts actually exist.
## FEATURE SPECIFICATIONS (conditional — only when validated above)
If context-package has brainstorm_artifacts.feature_index_path:
Feature Index: [from context-package]
Feature Spec Dir: [from context-package]
Else if .workflow/active/${sessionId}/.brainstorming/feature-specs/ exists:
Feature Index: .workflow/active/${sessionId}/.brainstorming/feature-specs/feature-index.json
If the directory does not exist, skip this section.
## SESSION-SPECIFIC NOTES
- Deliverables: Task JSONs + IMPL_PLAN.md + plan.json + TODO_LIST.md (all 4 required)
- focus_paths: Derive from prioritized_context.priority_tiers (critical + high)
- Task sequencing: Use dependency_order from context-package (pre-computed)
- All other schemas, strategies, quality standards: Follow agent specification
`
)Step 4.2B: N Parallel Planning (modules.length >= 2)
Condition: modules.length >= 2 (multi-module detected)
Purpose: Launch N action-planning-agents simultaneously, one per module.
// Launch N agents in parallel (one per module)
const planningTasks = modules.map(module =>
Task(
subagent_type="action-planning-agent",
run_in_background=false,
description=`Generate ${module.name} module task JSONs`,
prompt=`
## 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.
## PLANNING NOTES (PHASE 1-3 CONTEXT)
Load: .workflow/active/${sessionId}/planning-notes.md
## 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)
## SESSION PATHS
Input:
- Session Metadata: .workflow/active/${sessionId}/workflow-session.json
- Planning Notes: .workflow/active/${sessionId}/planning-notes.md
- Context Package: .workflow/active/${sessionId}/.process/context-package.json
Output:
- Task Dir: .workflow/active/${sessionId}/.task/
## CROSS-MODULE DEPENDENCIES
- For dependencies ON other modules: Use placeholder depends_on: ["CROSS::{module}::{pattern}"]
- Example: depends_on: ["CROSS::B::api-endpoint"]
- Phase 3 Coordinator resolves to actual task IDs
## CLI EXECUTION ID REQUIREMENTS (MANDATORY)
Each task JSON MUST include:
- **cli_execution.id**: Unique ID (format: {session_id}-IMPL-${module.prefix}{seq})
- Cross-module dep -> { "strategy": "cross_module_fork", "resume_from": "CROSS::{module}::{pattern}" }
## QUALITY STANDARDS
- Task count <= 9 for this module
- Focus paths scoped to ${module.paths.join(', ')} only
- Cross-module dependencies use CROSS:: placeholder format
## PLANNING NOTES RECORD (REQUIRED)
### [${module.name}] YYYY-MM-DD
- **Tasks**: [count] ([IDs])
- **CROSS deps**: [placeholders used]
`
)
);
// Execute all in parallel
await Promise.all(planningTasks);Step 4.3: Integration (+1 Coordinator, Multi-Module Only)
Condition: Only executed when modules.length >= 2
Task(
subagent_type="action-planning-agent",
run_in_background=false,
description="Integrate module tasks and generate unified documents",
prompt=`
## 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/${sessionId}/workflow-session.json
- Context Package: .workflow/active/${sessionId}/.process/context-package.json
- Task JSONs: .workflow/active/${sessionId}/.task/IMPL-*.json (from Phase 2B)
Output:
- Updated Task JSONs: .workflow/active/${sessionId}/.task/IMPL-*.json (resolved dependencies)
- IMPL_PLAN: .workflow/active/${sessionId}/IMPL_PLAN.md
- TODO_LIST: .workflow/active/${sessionId}/TODO_LIST.md
## 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)
4. Generate TODO_LIST.md (hierarchical format)
## CROSS-MODULE DEPENDENCY RESOLUTION
- Pattern: CROSS::{module}::{pattern} -> IMPL-{module}* matching title/context
- Log unresolved as warnings
## PLANNING NOTES RECORD (REQUIRED)
### [Coordinator] YYYY-MM-DD
- **Total**: [count] tasks
- **Resolved**: [CROSS:: resolutions]
`
)Executor Label (computed after Step 4.0):
const executorLabel = userConfig.executionMethod === 'agent' ? 'Agent'
: userConfig.executionMethod === 'hybrid' ? 'Hybrid'
: `CLI (${userConfig.preferredCliTool})`TodoWrite Update (Phase 4 in progress)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 4: Task Generation [${executorLabel}]", "status": "in_progress", "activeForm": "Generating tasks [${executorLabel}]"}
]TodoWrite Update (Phase 4 completed)
[
{"content": "Phase 1: Session Discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Phase 2: Context Gathering", "status": "completed", "activeForm": "Executing context gathering"},
{"content": "Phase 4: Task Generation [${executorLabel}]", "status": "completed", "activeForm": "Generating tasks [${executorLabel}]"}
]Step 4.4: Plan Confirmation (User Decision Gate)
After Phase 4 completes, present user with action choices:
console.log(`
Planning complete for session: ${sessionId}
Tasks generated: ${taskCount}
Plan: .workflow/active/${sessionId}/IMPL_PLAN.md
`);
// Ask user for next action
const userChoice = AskUserQuestion({
questions: [{
question: "Planning complete. What would you like to do next?",
header: "Next Action",
multiSelect: false,
options: [
{
label: "Verify Plan Quality (Recommended)",
description: "Run quality verification to catch issues before execution."
},
{
label: "Start Execution",
description: "Begin implementing tasks immediately."
},
{
label: "Review Status Only",
description: "View task breakdown and session status without taking further action."
}
]
}]
});
// Execute based on user choice
if (userChoice.answers["Next Action"] === "Verify Plan Quality (Recommended)") {
console.log("\nStarting plan verification...\n");
// Route to Phase 5 (plan-verify) within this skill
} else if (userChoice.answers["Next Action"] === "Start Execution") {
console.log("\nStarting task execution...\n");
Skill(skill="workflow-execute", args="--session " + sessionId);
} else if (userChoice.answers["Next Action"] === "Review Status Only") {
console.log("\nDisplaying session status...\n");
// Display session status inline
const sessionMeta = JSON.parse(Read(`.workflow/active/${sessionId}/workflow-session.json`));
const todoList = Read(`.workflow/active/${sessionId}/TODO_LIST.md`);
console.log(`Session: ${sessionId}`);
console.log(`Status: ${sessionMeta.status}`);
console.log(`\n--- TODO List ---\n${todoList}`);
}Auto Mode: When workflowPreferences.autoYes is true, auto-select "Verify Plan Quality", then auto-continue to execute if quality gate is PROCEED.
Return to Orchestrator: Based on user's choice:
- Verify -> Orchestrator reads phases/05-plan-verify.md and executes Phase 5 in-process
- Execute -> Skill(skill="workflow-execute")
- Review -> Display session status inline
Output
- File:
IMPL_PLAN.md(implementation plan) - File:
IMPL-*.json(task JSON files) - File:
TODO_LIST.md(task list) - File:
plan.json(structured plan overview) - TodoWrite: Mark Phase 4 completed
Next Phase (Conditional)
Based on user's plan confirmation choice:
- If "Verify" -> Phase 5: Plan Verification
- If "Execute" -> Skill(skill="workflow-execute")
- If "Review" -> Display session status inline
Phase 5: Plan Verification
Perform READ-ONLY verification analysis between IMPL_PLAN.md, task JSONs, and brainstorming artifacts. Generates structured report with quality gate recommendation. Does NOT modify any source files.
Objective
- Generate comprehensive verification report identifying inconsistencies, duplications, ambiguities
- Produce quality gate recommendation (BLOCK_EXECUTION / PROCEED_WITH_FIXES / PROCEED_WITH_CAUTION / PROCEED)
- Route to next action based on quality gate result
Entry Points
- From Plan Mode: After Phase 4 completes, user selects "Verify Plan Quality"
- From Verify Mode: Directly triggered via
workflow-planskill (plan-verify phase)
User Input
$ARGUMENTSYou MUST consider the user input before proceeding (if not empty).
Operating Constraints
STRICTLY READ-ONLY FOR SOURCE ARTIFACTS:
- MUST NOT modify
IMPL_PLAN.md, anytask.jsonfiles, or brainstorming artifacts - MUST NOT create or delete task files
- MUST ONLY write the verification report to
.process/PLAN_VERIFICATION.md
Synthesis Authority: The role analysis documents are authoritative for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements.
Quality Gate Authority: The verification report provides a binding recommendation based on objective severity criteria. User MUST review critical/high issues before proceeding with implementation.
Execution
Step 5.0: Load Validation Context
Run ccw spec load --category validation for verification rules and acceptance criteria.
Step 5.1: Initialize Analysis Context
# Detect active workflow session
IF --session parameter provided:
session_id = provided session
ELSE:
# Auto-detect active session
active_sessions = bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null)
IF active_sessions is empty:
ERROR: "No active workflow session found. Use --session <session-id>"
EXIT
ELSE IF active_sessions has multiple entries:
# Use most recently modified session
session_id = bash(ls -td .workflow/active/WFS-*/ 2>/dev/null | head -1 | xargs basename)
ELSE:
session_id = basename(active_sessions[0])
# Derive absolute paths
session_dir = .workflow/active/WFS-{session}
brainstorm_dir = session_dir/.brainstorming
task_dir = session_dir/.task
process_dir = session_dir/.process
session_file = session_dir/workflow-session.json
# Create .process directory if not exists (report output location)
IF NOT EXISTS(process_dir):
bash(mkdir -p "{process_dir}")
# Validate required artifacts
# Note: "role analysis documents" refers to [role]/analysis.md files (e.g., product-manager/analysis.md)
SYNTHESIS_DIR = brainstorm_dir # Contains role analysis files: */analysis.md
IMPL_PLAN = session_dir/IMPL_PLAN.md
TASK_FILES = Glob(task_dir/*.json)
PLANNING_NOTES = session_dir/planning-notes.md # N+1 context and constraints
# Abort if missing - in order of dependency
SESSION_FILE_EXISTS = EXISTS(session_file)
IF NOT SESSION_FILE_EXISTS:
WARNING: "workflow-session.json not found. User intent alignment verification will be skipped."
# Continue execution - this is optional context, not blocking
PLANNING_NOTES_EXISTS = EXISTS(PLANNING_NOTES)
IF NOT PLANNING_NOTES_EXISTS:
WARNING: "planning-notes.md not found. Constraints/N+1 context verification will be skipped."
# Continue execution - optional context
SYNTHESIS_FILES = Glob(brainstorm_dir/*/analysis.md)
IF SYNTHESIS_FILES.count == 0:
WARNING: "No role analysis documents found in .brainstorming/*/analysis.md. Synthesis-based dimensions (E, G) will use reduced coverage."
SYNTHESIS_AVAILABLE = false
# Continue execution - brainstorm artifacts are optional for direct planning workflows
ELSE:
SYNTHESIS_AVAILABLE = true
IF NOT EXISTS(IMPL_PLAN):
ERROR: "IMPL_PLAN.md not found. Run /workflow-plan first"
EXIT
IF TASK_FILES.count == 0:
ERROR: "No task JSON files found. Run /workflow-plan first"
EXITStep 5.2: Load Artifacts (Progressive Disclosure)
Load only minimal necessary context from each artifact:
From workflow-session.json (OPTIONAL - Primary Reference for User Intent):
- ONLY IF EXISTS: Load user intent context
- Original user prompt/intent (project or description field)
- User's stated goals and objectives
- User's scope definition
- IF MISSING: Set user_intent_analysis = "SKIPPED: workflow-session.json not found"
From planning-notes.md (OPTIONAL - Constraints & N+1 Context):
- ONLY IF EXISTS: Load planning context
- Consolidated Constraints (numbered list from Phase 1-3)
- N+1 Context: Decisions table (Decision | Rationale | Revisit?)
- N+1 Context: Deferred items list
- IF MISSING: Set planning_notes_analysis = "SKIPPED: planning-notes.md not found"
From role analysis documents (AUTHORITATIVE SOURCE):
- Functional Requirements (IDs, descriptions, acceptance criteria)
- Non-Functional Requirements (IDs, targets)
- Business Requirements (IDs, success metrics)
- Key Architecture Decisions
- Risk factors and mitigation strategies
- Implementation Roadmap (high-level phases)
From IMPL_PLAN.md:
- Summary and objectives
- Context Analysis
- Implementation Strategy
- Task Breakdown Summary
- Success Criteria
- Brainstorming Artifacts References (if present)
From task.json files:
- Task IDs
- Titles and descriptions
- Status
- Dependencies (depends_on, blocks)
- Context (requirements, focus_paths, acceptance, artifacts)
- Flow control (pre_analysis, implementation_approach)
- Meta (complexity, priority)
Step 5.3: Build Semantic Models
Create internal representations (do not include raw artifacts in output):
Requirements inventory:
- Each functional/non-functional/business requirement with stable ID
- Requirement text, acceptance criteria, priority
Architecture decisions inventory:
- ADRs from synthesis
- Technology choices
- Data model references
Task coverage mapping:
- Map each task to one or more requirements (by ID reference or keyword inference)
- Map each requirement to covering tasks
Dependency graph:
- Task-to-task dependencies (depends_on, blocks)
- Requirement-level dependencies (from synthesis)
Step 5.4: Detection Passes (Agent-Driven Multi-Dimensional Analysis)
Execution Strategy:
- Single
cli-explore-agentinvocation - Agent executes multiple CLI analyses internally (different dimensions: A-J)
- Token Budget: 50 findings maximum (aggregate remainder in overflow summary)
- Priority Allocation: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15)
- Early Exit: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM checks
Execution Order (Agent orchestrates internally):
1. Tier 1 (CRITICAL Path): A, B, C, I - User intent, coverage, consistency, constraints compliance (full analysis) 2. Tier 2 (HIGH Priority): D, E, J - Dependencies, synthesis alignment, N+1 context validation (limit 15 findings) 3. Tier 3 (MEDIUM Priority): F - Specification quality (limit 20 findings) 4. Tier 4 (LOW Priority): G, H - Duplication, feasibility (limit 15 findings)
---
Step 5.4.1: Launch Unified Verification Agent
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description="Multi-dimensional plan verification",
prompt=`
## Plan Verification Task
### MANDATORY FIRST STEPS
1. Read: ~/.ccw/workflows/cli-templates/schemas/plan-verify-agent-schema.json (dimensions & rules)
2. Read: ~/.ccw/workflows/cli-templates/schemas/verify-json-schema.json (output schema)
3. Read: ${session_file} (user intent)
4. Read: ${PLANNING_NOTES} (constraints & N+1 context)
5. Read: ${IMPL_PLAN} (implementation plan)
6. Glob: ${task_dir}/*.json (task files)
7. Glob: ${SYNTHESIS_DIR}/*/analysis.md (role analyses)
### Execution Flow
**Load schema → Execute tiered CLI analysis → Aggregate findings → Write JSON**
FOR each tier in [1, 2, 3, 4]:
- Load tier config from plan-verify-agent-schema.json
- Execute: ccw cli -p "PURPOSE: Verify dimensions {tier.dimensions}
TASK: {tier.checks from schema}
CONTEXT: @${session_dir}/**/*
EXPECTED: Findings JSON with dimension, severity, location, summary, recommendation
CONSTRAINTS: Limit {tier.limit} findings
" --tool gemini --mode analysis --rule {tier.rule}
- Parse findings, check early exit condition
- IF tier == 1 AND critical_count > 0: skip tier 3-4
### Output
Write: ${process_dir}/verification-findings.json (follow verify-json-schema.json)
Return: Quality gate decision + 2-3 sentence summary
`
)---
Step 5.4.2: Load and Organize Findings
// Load findings (single parse for all subsequent use)
const data = JSON.parse(Read(`${process_dir}/verification-findings.json`))
const { session_id, timestamp, verification_tiers_completed, findings, summary } = data
const { critical_count, high_count, medium_count, low_count, total_findings, coverage_percentage, recommendation } = summary
// Group by severity and dimension
const bySeverity = Object.groupBy(findings, f => f.severity)
const byDimension = Object.groupBy(findings, f => f.dimension)
// Dimension metadata (from schema)
const DIMS = {
A: "User Intent Alignment", B: "Requirements Coverage", C: "Consistency Validation",
D: "Dependency Integrity", E: "Synthesis Alignment", F: "Task Specification Quality",
G: "Duplication Detection", H: "Feasibility Assessment",
I: "Constraints Compliance", J: "N+1 Context Validation"
}Step 5.5: Generate Report
// Helper: render dimension section
const renderDimension = (dim) => {
const items = byDimension[dim] || []
return items.length > 0
? items.map(f => `### ${f.id}: ${f.summary}\n- **Severity**: ${f.severity}\n- **Location**: ${f.location.join(', ')}\n- **Recommendation**: ${f.recommendation}`).join('\n\n')
: `> No ${DIMS[dim]} issues detected.`
}
// Helper: render severity section
const renderSeverity = (severity, impact) => {
const items = bySeverity[severity] || []
return items.length > 0
? items.map(f => `#### ${f.id}: ${f.summary}\n- **Dimension**: ${f.dimension_name}\n- **Location**: ${f.location.join(', ')}\n- **Impact**: ${impact}\n- **Recommendation**: ${f.recommendation}`).join('\n\n')
: `> No ${severity.toLowerCase()}-severity issues detected.`
}
// Build Markdown report
const fullReport = `
# Plan Verification Report
**Session**: WFS-${session_id} | **Generated**: ${timestamp}
**Tiers Completed**: ${verification_tiers_completed.join(', ')}
---
## Executive Summary
| Metric | Value | Status |
|--------|-------|--------|
| Risk Level | ${critical_count > 0 ? 'CRITICAL' : high_count > 0 ? 'HIGH' : medium_count > 0 ? 'MEDIUM' : 'LOW'} | ${critical_count > 0 ? 'RED' : high_count > 0 ? 'ORANGE' : medium_count > 0 ? 'YELLOW' : 'GREEN'} |
| Critical/High/Medium/Low | ${critical_count}/${high_count}/${medium_count}/${low_count} | |
| Coverage | ${coverage_percentage}% | ${coverage_percentage >= 90 ? 'GREEN' : coverage_percentage >= 75 ? 'YELLOW' : 'RED'} |
**Recommendation**: **${recommendation}**
---
## Findings Summary
| ID | Dimension | Severity | Location | Summary |
|----|-----------|----------|----------|---------|
${findings.map(f => `| ${f.id} | ${f.dimension_name} | ${f.severity} | ${f.location.join(', ')} | ${f.summary} |`).join('\n')}
---
## Analysis by Dimension
${['A','B','C','D','E','F','G','H','I','J'].map(d => `### ${d}. ${DIMS[d]}\n\n${renderDimension(d)}`).join('\n\n---\n\n')}
---
## Findings by Severity
### CRITICAL (${critical_count})
${renderSeverity('CRITICAL', 'Blocks execution')}
### HIGH (${high_count})
${renderSeverity('HIGH', 'Fix before execution recommended')}
### MEDIUM (${medium_count})
${renderSeverity('MEDIUM', 'Address during/after implementation')}
### LOW (${low_count})
${renderSeverity('LOW', 'Optional improvement')}
---
## Next Steps
${recommendation === 'BLOCK_EXECUTION' ? 'BLOCK: Fix critical issues then re-verify' :
recommendation === 'PROCEED_WITH_FIXES' ? 'FIX RECOMMENDED: Address high issues then re-verify or execute' :
'READY: Proceed to Skill(skill="workflow-execute")'}
Re-verify: \`/workflow-plan-verify --session ${session_id}\`
Execute: \`Skill(skill="workflow-execute", args="--resume-session=${session_id}")\`
`
// Write report
Write(`${process_dir}/PLAN_VERIFICATION.md`, fullReport)
console.log(`Report: ${process_dir}/PLAN_VERIFICATION.md\n${recommendation} | C:${critical_count} H:${high_count} M:${medium_count} L:${low_count} | Coverage:${coverage_percentage}%`)Step 5.6: Next Step Selection
// Reference workflowPreferences (set by SKILL.md via AskUserQuestion)
const autoYes = workflowPreferences.autoYes
const canExecute = recommendation !== 'BLOCK_EXECUTION'
// Auto mode
if (autoYes) {
if (canExecute) {
Skill(skill="workflow-execute", args="--resume-session=\"${session_id}\"")
} else {
console.log(`[Auto] BLOCK_EXECUTION - Fix ${critical_count} critical issues first.`)
}
return
}
// Interactive mode - build options based on quality gate
const options = canExecute
? [
{ label: canExecute && recommendation === 'PROCEED_WITH_FIXES' ? "Execute Anyway" : "Execute (Recommended)",
description: "Proceed to Skill(skill=\"workflow-execute\")" },
{ label: "Review Report", description: "Review findings before deciding" },
{ label: "Re-verify", description: "Re-run after manual fixes" }
]
: [
{ label: "Review Report", description: "Review critical issues" },
{ label: "Re-verify", description: "Re-run after fixing issues" }
]
const selection = AskUserQuestion({
questions: [{
question: `Quality gate: ${recommendation}. Next step?`,
header: "Action",
multiSelect: false,
options
}]
})
// Handle selection
if (selection.includes("Execute")) {
Skill(skill="workflow-execute", args="--resume-session=\"${session_id}\"")
} else if (selection === "Re-verify") {
// Direct phase re-execution: re-read and execute this phase
Read("phases/05-plan-verify.md")
// Re-execute with current session context
}Output
- File:
PLAN_VERIFICATION.md(verification report with quality gate) - File:
verification-findings.json(structured findings data)
Completion
Phase 5 is a terminal phase. Based on quality gate result, user routes to:
- Execute → Skill(skill="workflow-execute")
- Re-verify → Re-run Phase 5
- Review → Manual inspection
Phase 6: Interactive Replan
Interactive workflow replanning with session-level artifact updates and boundary clarification through guided questioning.
Objective
- Intelligently replan workflow sessions or individual tasks
- Interactive clarification to define modification boundaries
- Impact analysis with automatic detection of affected files and dependencies
- Backup management with restore capability
- Comprehensive artifact updates (IMPL_PLAN.md, TODO_LIST.md, task JSONs)
Entry Point
Triggered via Replan Mode routing in SKILL.md.
Input
Replan accepts requirements text as arguments. Session and mode preferences are provided via workflowPreferences context variables (set by SKILL.md via AskUserQuestion).
Input: requirements text (positional argument)
Context: workflowPreferences.autoYes, workflowPreferences.interactive
Session: auto-detected from .workflow/active/ or specified via workflowPreferences.sessionIdTask Replan Mode
# Direct task update
Replan input: IMPL-1 "requirements text"
# Interactive mode (workflowPreferences.interactive = true)
Replan input: IMPL-1 "requirements text"Language Convention
Interactive question options use Chinese (user-facing UI text) with English identifiers in parentheses. Structural content uses English. This is intentional for Chinese-language workflows.
Execution
Input Parsing
Parse input:
// Reference workflowPreferences (set by SKILL.md via AskUserQuestion)
const sessionFlag = workflowPreferences.sessionId
const interactive = workflowPreferences.interactive
const taskIdMatch = $ARGUMENTS.match(/\b(IMPL-\d+(?:\.\d+)?)\b/)
const taskId = taskIdMatch?.[1]Step 6.1: Mode Detection & Session Discovery
Process: 1. Detect Operation Mode:
- Check if task ID provided (IMPL-N or IMPL-N.M format) → Task mode
- Otherwise → Session mode
2. Discover/Validate Session:
- Use
--sessionflag if provided - Otherwise auto-detect from
.workflow/active/ - Validate session exists
3. Load Session Context:
- Read
workflow-session.json - List existing tasks
- Read
IMPL_PLAN.mdandTODO_LIST.md
4. Parse Execution Intent (from requirements text):
// Dynamic tool detection from cli-tools.json
// Read enabled tools: ["gemini", "qwen", "codex", ...]
const enabledTools = loadEnabledToolsFromConfig(); // See ~/.claude/cli-tools.json
// Build dynamic patterns from enabled tools
function buildExecPatterns(tools) {
const patterns = {
agent: /改为\s*Agent\s*执行|使用\s*Agent\s*执行/i
};
tools.forEach(tool => {
// Pattern: "使用 {tool} 执行" or "改用 {tool}"
patterns[`cli_${tool}`] = new RegExp(
`使用\\s*(${tool})\\s*执行|改用\\s*(${tool})`, 'i'
);
});
return patterns;
}
const execPatterns = buildExecPatterns(enabledTools);
let executionIntent = null
for (const [key, pattern] of Object.entries(execPatterns)) {
if (pattern.test(requirements)) {
executionIntent = key.startsWith('cli_')
? { method: 'cli', cli_tool: key.replace('cli_', '') }
: { method: 'agent', cli_tool: null }
break
}
}Output: Session validated, context loaded, mode determined, executionIntent parsed
---
Auto Mode Support
When workflowPreferences.autoYes === true, the phase skips interactive clarification and uses safe defaults:
// Reference workflowPreferences (set by SKILL.md via AskUserQuestion)
const autoYes = workflowPreferences.autoYesAuto Mode Defaults:
- Modification Scope:
tasks_only(safest - only update task details) - Affected Modules: All modules related to the task
- Task Changes:
update_only(no structural changes) - Dependency Changes:
no(preserve existing dependencies) - User Confirmation: Auto-confirm execution
Note: workflowPreferences.interactive overrides workflowPreferences.autoYes (forces interactive mode).
---
Step 6.2: Interactive Requirement Clarification
Purpose: Define modification scope through guided questioning
Auto Mode Check:
if (autoYes && !interactive) {
// Use defaults and skip to Step 6.3
console.log(`[Auto] Using safe defaults for replan:`)
console.log(` - Scope: tasks_only`)
console.log(` - Changes: update_only`)
console.log(` - Dependencies: preserve existing`)
userSelections = {
scope: 'tasks_only',
modules: 'all_affected',
task_changes: 'update_only',
dependency_changes: false
}
// Proceed to Step 6.3
}Session Mode Questions
Q1: Modification Scope
Options:
- 仅更新任务细节 (tasks_only)
- 修改规划方案 (plan_update)
- 重构任务结构 (task_restructure)
- 全面重规划 (comprehensive)Q2: Affected Modules (if scope >= plan_update)
Options: Dynamically generated from existing tasks' focus_paths
- 认证模块 (src/auth)
- 用户管理 (src/user)
- 全部模块Q3: Task Changes (if scope >= task_restructure)
Options:
- 添加/删除任务 (add_remove)
- 合并/拆分任务 (merge_split)
- 仅更新内容 (update_only)
// Note: Max 4 options for AskUserQuestionQ4: Dependency Changes
Options:
- 是,需要重新梳理依赖
- 否,保持现有依赖Task Mode Questions
Q1: Update Type
Options:
- 需求和验收标准 (requirements & acceptance)
- 实现方案 (implementation_approach)
- 文件范围 (focus_paths)
- 依赖关系 (depends_on)
- 全部更新Q2: Ripple Effect
Options:
- 是,需要同步更新依赖任务
- 否,仅影响当前任务
- 不确定,请帮我分析Output: User selections stored, modification boundaries defined
---
Step 6.3: Impact Analysis & Planning
Step 6.3.1: Analyze Required Changes
Determine affected files based on clarification:
interface ImpactAnalysis {
affected_files: {
impl_plan: boolean;
todo_list: boolean;
session_meta: boolean;
tasks: string[];
};
operations: {
type: 'create' | 'update' | 'delete' | 'merge' | 'split';
target: string;
reason: string;
}[];
backup_strategy: {
timestamp: string;
files: string[];
};
}Step 6.3.2: Generate Modification Plan
## Modification Plan
### Impact Scope
- [ ] IMPL_PLAN.md: Update technical section 3
- [ ] TODO_LIST.md: Add 2 new tasks, delete 1 obsolete task
- [ ] IMPL-001.json: Update implementation approach
- [ ] workflow-session.json: Update task count
### Change Operations
1. **Create**: IMPL-004.json (2FA implementation)
2. **Update**: IMPL-001.json (add 2FA preparation)
3. **Delete**: IMPL-003.json (replaced by new approach)Step 6.3.3: User Confirmation
// Reference workflowPreferences (set by SKILL.md via AskUserQuestion)
const autoYes = workflowPreferences.autoYes
if (autoYes) {
// Auto mode: Auto-confirm execution
console.log(`[Auto] Auto-confirming replan execution`)
userConfirmation = 'confirm'
// Proceed to Step 6.4
} else {
// Interactive mode: Ask user
AskUserQuestion({
questions: [{
question: "Modification plan generated. Confirm action:",
header: "Confirm",
options: [
{ label: "Confirm Execute", description: "Apply all modifications" },
{ label: "Adjust Plan", description: "Re-answer questions to adjust scope" },
{ label: "Cancel", description: "Abort this replan" }
],
multiSelect: false
}]
})
}Output: Modification plan confirmed or adjusted
---
Step 6.4: Backup Creation
Process:
1. Create Backup Directory:
timestamp=$(date -u +"%Y-%m-%dT%H-%M-%S")
backup_dir=".workflow/active/$SESSION_ID/.process/backup/replan-$timestamp"
mkdir -p "$backup_dir"2. Backup All Affected Files:
- IMPL_PLAN.md
- TODO_LIST.md
- workflow-session.json
- Affected task JSONs
3. Create Backup Manifest:
# Replan Backup Manifest
**Timestamp**: {timestamp}
**Reason**: {replan_reason}
**Scope**: {modification_scope}
## Restoration Command
cp {backup_dir}/* .workflow/active/{session}/Output: All files safely backed up with manifest
---
Step 6.5: Apply Modifications
Step 6.5.1: Update IMPL_PLAN.md (if needed)
Use Edit tool to modify specific sections:
- Update affected technical sections
- Update modification date
Step 6.5.2: Update TODO_LIST.md (if needed)
- Add new tasks with
[ ]checkbox - Mark deleted tasks as
[x] ~~task~~ (obsolete) - Update modified task descriptions
Step 6.5.3: Update Task JSONs
For each affected task:
const updated_task = {
...task,
context: {
...task.context,
requirements: [...updated_requirements],
acceptance: [...updated_acceptance]
},
flow_control: {
...task.flow_control,
implementation_approach: [...updated_steps]
},
// Update execution config if intent detected
...(executionIntent && {
meta: {
...task.meta,
execution_config: {
method: executionIntent.method,
cli_tool: executionIntent.cli_tool,
enable_resume: executionIntent.method !== 'agent'
}
}
})
};
Write({
file_path: `.workflow/active/${SESSION_ID}/.task/${task_id}.json`,
content: JSON.stringify(updated_task, null, 2)
});Note: Implementation approach steps are NO LONGER modified. CLI execution is controlled by task-level meta.execution_config only.
Step 6.5.4: Create New Tasks (if needed)
Generate complete task JSON with all required fields:
- id, title, status
- meta (type, agent)
- context (requirements, focus_paths, acceptance)
- flow_control (pre_analysis, implementation_approach, target_files)
Step 6.5.5: Delete Obsolete Tasks (if needed)
Move to backup instead of hard delete:
mv ".workflow/active/$SESSION_ID/.task/{task-id}.json" "$backup_dir/"Step 6.5.6: Update Session Metadata
Update workflow-session.json:
- progress.current_tasks
- progress.last_replan
- replan_history array
Output: All modifications applied, artifacts updated
---
Step 6.6: Verification & Summary
Step 6.6.1: Verify Consistency
1. Validate all task JSONs are valid JSON 2. Check task count within limits (max 10) 3. Verify dependency graph is acyclic
Step 6.6.2: Generate Change Summary
## Replan Complete
### Session Info
- **Session**: {session-id}
- **Timestamp**: {timestamp}
- **Backup**: {backup-path}
### Change Summary
**Scope**: {scope}
**Reason**: {reason}
### Modified Files
- IMPL_PLAN.md: {changes}
- TODO_LIST.md: {changes}
- Task JSONs: {count} files updated
### Task Changes
- **Added**: {task-ids}
- **Deleted**: {task-ids}
- **Updated**: {task-ids}
### Rollback
cp {backup-path}/* .workflow/active/{session}/Output: Summary displayed, replan complete
TodoWrite Progress Tracking
Session Mode Progress
[
{"content": "Mode detection and session discovery", "status": "completed", "activeForm": "Detecting mode and discovering session"},
{"content": "Interactive requirement clarification", "status": "completed", "activeForm": "Clarifying requirements interactively"},
{"content": "Impact analysis and plan generation", "status": "completed", "activeForm": "Analyzing impact and generating plan"},
{"content": "Backup creation", "status": "completed", "activeForm": "Creating backup"},
{"content": "Apply modifications to artifacts", "status": "completed", "activeForm": "Applying modifications"},
{"content": "Verify consistency", "status": "completed", "activeForm": "Verifying consistency"}
]Task Mode Progress
[
{"content": "Detect session and load task", "status": "completed", "activeForm": "Detecting session and loading task"},
{"content": "Interactive update confirmation", "status": "completed", "activeForm": "Confirming update interactively"},
{"content": "Apply task modifications", "status": "completed", "activeForm": "Applying task modifications"}
]Error Handling
Session Errors
# No active session found
ERROR: No active session found
Run /workflow:session:start to create a session
# Session not found
ERROR: Session WFS-invalid not found
Available sessions: [list]
# No changes specified
WARNING: No modifications specified
Provide requirements text or use interactive modeTask Errors
# Task not found
ERROR: Task IMPL-999 not found in session
Available tasks: [list]
# Task completed
WARNING: Task IMPL-001 is completed
Consider creating new task for additional work
# Circular dependency
ERROR: Circular dependency detected
Resolve dependency conflicts before proceedingValidation Errors
# Task limit exceeded
ERROR: Replan would create 12 tasks (limit: 10)
Consider: combining tasks, splitting sessions, or removing tasks
# Invalid JSON
ERROR: Generated invalid JSON
Backup preserved, rolling back changesFile Structure
.workflow/active/WFS-session-name/
├── workflow-session.json
├── IMPL_PLAN.md
├── TODO_LIST.md
├── .task/
│ ├── IMPL-001.json
│ ├── IMPL-002.json
│ └── IMPL-003.json
└── .process/
├── context-package.json
└── backup/
└── replan-{timestamp}/
├── MANIFEST.md
├── IMPL_PLAN.md
├── TODO_LIST.md
├── workflow-session.json
└── IMPL-*.jsonExamples
Session Replan - Add Feature
Replan input: "Add 2FA support"
# Interactive clarification
Q: Modification scope?
A: Comprehensive replan
Q: Affected modules?
A: Auth module, API endpoints
Q: Task changes?
A: Add new tasks, update content
# Execution
Backup created
IMPL_PLAN.md updated
TODO_LIST.md updated
IMPL-004.json created
IMPL-001.json, IMPL-002.json updated
Replan complete! Added 1 task, updated 2 tasksTask Replan - Update Requirements
/workflow:replan IMPL-002 "Update acceptance criteria to include rate limiting"
# Interactive clarification
Q: Update type?
A: Requirements and acceptance criteria
Q: Ripple effect?
A: Yes, sync dependent tasks
# Execution
Backup created
IMPL-002.json updated
- context.requirements updated
- context.acceptance updated
IMPL-003.json updated (dependent task synced)
Task requirements updated with ripple effect appliedTask Replan - Change Execution Method
/workflow:replan IMPL-001 "Use Codex for execution"
# Semantic parsing detects executionIntent:
# { method: 'cli', cli_tool: 'codex' }
# Execution (no interactive questions needed)
Backup created
IMPL-001.json updated
- meta.execution_config = { method: 'cli', cli_tool: 'codex', enable_resume: true }
Task execution method updated: Agent → CLI (codex)Completion
Phase 6 is a terminal phase. Replan complete with backup and summary.