Add merge-plans-with-file and quick-plan-with-file prompts for enhanced planning workflows

- Introduced merge-plans-with-file prompt for aggregating multiple planning artifacts, resolving conflicts, and synthesizing a unified execution plan.
- Implemented detailed execution process including discovery, normalization, conflict detection, resolution, and synthesis phases.
- Added quick-plan-with-file prompt for rapid planning with minimal documentation, utilizing multi-agent analysis for actionable outputs.
- Both prompts support various input formats and provide structured outputs for execution and documentation.
This commit is contained in:
catlog22
2026-01-29 21:21:29 +08:00
parent f3c773a81e
commit d5199ad2d4
5 changed files with 2688 additions and 26 deletions

View File

@@ -231,53 +231,97 @@ ${newFocusFromUser}
### Phase 2: Divergent Exploration (Multi-Perspective)
#### Step 2.1: Creative Perspective Analysis
Launch 3 parallel agents for multi-perspective brainstorming:
Explore from creative/innovative angle:
```javascript
const cliPromises = []
- Think beyond obvious solutions - what would be surprising/delightful?
- Cross-domain inspiration (what can we learn from other industries?)
- Challenge assumptions - what if the opposite were true?
- Generate 'moonshot' ideas alongside practical ones
- Consider future trends and emerging technologies
// Agent 1: Creative/Innovative Perspective (Gemini)
cliPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Creative brainstorming for '$TOPIC' - generate innovative, unconventional ideas
Success: 5+ unique creative solutions that push boundaries
Output:
TASK:
• Think beyond obvious solutions - what would be surprising/delightful?
• Explore cross-domain inspiration (what can we learn from other industries?)
• Challenge assumptions - what if the opposite were true?
• Generate 'moonshot' ideas alongside practical ones
• Consider future trends and emerging technologies
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: ${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- 5+ creative ideas with brief descriptions
- Each idea rated: novelty (1-5), potential impact (1-5)
- Key assumptions challenged
- Cross-domain inspirations
- One 'crazy' idea that might just work
#### Step 2.2: Pragmatic Perspective Analysis
CONSTRAINTS: ${brainstormMode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely'}
" --tool gemini --mode analysis`,
run_in_background: true
})
)
Evaluate from implementation reality:
// Agent 2: Pragmatic/Implementation Perspective (Codex)
cliPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Pragmatic analysis for '$TOPIC' - focus on implementation reality
Success: Actionable approaches with clear implementation paths
- Technical feasibility of core concept
- Existing patterns/libraries that could help
- Integration with current codebase
- Implementation complexity estimates
- Potential technical blockers
- Incremental implementation approach
TASK:
• Evaluate technical feasibility of core concept
• Identify existing patterns/libraries that could help
• Consider integration with current codebase
• Estimate implementation complexity
• Highlight potential technical blockers
• Suggest incremental implementation approach
Output:
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: \${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- 3-5 practical implementation approaches
- Each rated: effort (1-5), risk (1-5), reuse potential (1-5)
- Technical dependencies identified
- Quick wins vs long-term solutions
- Recommended starting point
#### Step 2.3: Systematic Perspective Analysis
CONSTRAINTS: Focus on what can actually be built with current tech stack
" --tool codex --mode analysis\`,
run_in_background: true
})
)
Analyze from architectural standpoint:
// Agent 3: Systematic/Architectural Perspective (Claude)
cliPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Systematic analysis for '$TOPIC' - architectural and structural thinking
Success: Well-structured solution framework with clear tradeoffs
- Decompose the problem into sub-problems
- Identify architectural patterns that apply
- Map dependencies and interactions
- Consider scalability implications
- Evaluate long-term maintainability
- Propose systematic solution structure
TASK:
• Decompose the problem into sub-problems
• Identify architectural patterns that apply
• Map dependencies and interactions
• Consider scalability implications
• Evaluate long-term maintainability
• Propose systematic solution structure
Output:
MODE: analysis
CONTEXT: @**/* | Topic: $TOPIC
Exploration vectors: \${explorationVectors.map(v => v.title).join(', ')}
EXPECTED:
- Problem decomposition diagram (text)
- 2-3 architectural approaches with tradeoffs
- Dependency mapping
@@ -285,6 +329,29 @@ Output:
- Recommended architecture pattern
- Risk matrix
CONSTRAINTS: Consider existing system architecture
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Wait for all CLI analyses to complete
const [creativeResult, pragmaticResult, systematicResult] = await Promise.all(cliPromises)
// Parse results from each perspective
const creativeIdeas = parseCreativeResult(creativeResult)
const pragmaticApproaches = parsePragmaticResult(pragmaticResult)
const architecturalOptions = parseSystematicResult(systematicResult)
```
**Multi-Perspective Coordination**:
| Agent | Perspective | Tool | Focus Areas |
|-------|-------------|------|-------------|
| 1 | Creative/Innovative | Gemini | Novel ideas, cross-domain inspiration, moonshots |
| 2 | Pragmatic/Implementation | Codex | Feasibility, tech stack, blockers, quick wins |
| 3 | Systematic/Architectural | Claude | Decomposition, patterns, scalability, risks |
#### Step 2.4: Aggregate Multi-Perspective Findings
```javascript

View File

@@ -0,0 +1,530 @@
---
description: Merge multiple planning/brainstorm/analysis outputs, resolve conflicts, and synthesize unified plan. Multi-team input aggregation and plan crystallization
argument-hint: "PATTERN=\"<plan pattern or topic>\" [--rule=consensus|priority|hierarchy] [--output=<path>] [--auto] [--verbose]"
---
# Codex Merge-Plans-With-File Prompt
## Overview
Plan aggregation and conflict resolution workflow. Takes multiple planning artifacts (brainstorm conclusions, analysis recommendations, quick-plans, implementation plans) and synthesizes them into a unified, conflict-resolved execution plan.
**Core workflow**: Load Sources → Parse Plans → Conflict Analysis → Arbitration → Unified Plan
**Key features**:
- **Multi-Source Support**: brainstorm, analysis, quick-plan, IMPL_PLAN, task JSONs
- **Conflict Detection**: Identify contradictions across all input plans
- **Resolution Rules**: consensus, priority-based, or hierarchical resolution
- **Unified Synthesis**: Single authoritative plan from multiple perspectives
- **Decision Tracking**: Full audit trail of conflicts and resolutions
## Target Pattern
**$PATTERN**
- `--rule`: Conflict resolution (consensus | priority | hierarchy) - consensus by default
- `--output`: Output directory (default: .workflow/.merged/{pattern})
- `--auto`: Auto-resolve conflicts using rule, skip confirmations
- `--verbose`: Include detailed conflict analysis
## Execution Process
```
Phase 1: Discovery & Loading
├─ Search for artifacts matching pattern
├─ Load synthesis.json, conclusions.json, IMPL_PLAN.md, task JSONs
├─ Parse into normalized task structure
└─ Validate completeness
Phase 2: Plan Normalization
├─ Convert all formats to common task representation
├─ Extract: tasks, dependencies, effort, risks
├─ Identify scope and boundaries
└─ Aggregate recommendations
Phase 3: Conflict Detection (Parallel)
├─ Architecture conflicts: different design approaches
├─ Task conflicts: overlapping or duplicated tasks
├─ Effort conflicts: different estimates
├─ Risk conflicts: different risk assessments
├─ Scope conflicts: different feature sets
└─ Generate conflict matrix
Phase 4: Conflict Resolution
├─ Analyze source rationale for each conflict
├─ Apply resolution rule (consensus / priority / hierarchy)
├─ Escalate unresolvable conflicts to user (unless --auto)
├─ Document decision rationale
└─ Generate resolutions.json
Phase 5: Plan Synthesis
├─ Merge task lists (deduplicate, combine insights)
├─ Integrate dependencies
├─ Consolidate effort and risk estimates
├─ Generate execution sequence
└─ Output unified-plan.json
Output:
├─ .workflow/.merged/{sessionId}/merge.md (process log)
├─ .workflow/.merged/{sessionId}/source-index.json (input sources)
├─ .workflow/.merged/{sessionId}/conflicts.json (conflict matrix)
├─ .workflow/.merged/{sessionId}/resolutions.json (decisions)
├─ .workflow/.merged/{sessionId}/unified-plan.json (for execution)
└─ .workflow/.merged/{sessionId}/unified-plan.md (human-readable)
```
## Implementation Details
### Phase 1: Discover & Load Sources
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
const mergeSlug = "$PATTERN".toLowerCase()
.replace(/[*?]/g, '-')
.replace(/[^a-z0-9\u4e00-\u9fa5-]+/g, '-')
.substring(0, 30)
const sessionId = `MERGE-${mergeSlug}-${getUtc8ISOString().substring(0, 10)}`
const sessionFolder = `.workflow/.merged/${sessionId}`
bash(`mkdir -p ${sessionFolder}`)
// Search paths for matching artifacts
const searchPaths = [
`.workflow/.brainstorm/*${$PATTERN}*/synthesis.json`,
`.workflow/.analysis/*${$PATTERN}*/conclusions.json`,
`.workflow/.planning/*${$PATTERN}*/synthesis.json`,
`.workflow/.plan/*${$PATTERN}*IMPL_PLAN.md`,
`.workflow/**/*${$PATTERN}*.json`
]
// Load and validate each source
const sourcePlans = []
for (const pattern of searchPaths) {
const matches = glob(pattern)
for (const path of matches) {
const plan = loadAndParsePlan(path)
if (plan?.tasks?.length > 0) {
sourcePlans.push({ path, type: inferType(path), plan })
}
}
}
```
### Phase 2: Normalize Plans
Convert all source formats to common structure:
```javascript
const normalizedPlans = sourcePlans.map((src, idx) => ({
index: idx,
source: src.path,
type: src.type,
metadata: {
title: src.plan.title || `Plan ${idx + 1}`,
topic: src.plan.topic,
complexity: src.plan.complexity_level || 'unknown'
},
tasks: src.plan.tasks.map(task => ({
id: `T${idx}-${task.id || task.title.substring(0, 20)}`,
title: task.title,
description: task.description,
type: task.type || inferTaskType(task),
priority: task.priority || 'normal',
effort: { estimated: task.effort_estimate, from_plan: idx },
risk: { level: task.risk_level || 'medium', from_plan: idx },
dependencies: task.dependencies || [],
source_plan_index: idx
}))
}))
```
### Phase 3: Parallel Conflict Detection
Launch parallel agents to detect and analyze conflicts:
```javascript
// Parallel conflict detection with CLI agents
const conflictPromises = []
// Agent 1: Detect effort and task conflicts
conflictPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Detect effort conflicts and task duplicates across multiple plans
Success: Complete identification of conflicting estimates and duplicate tasks
TASK:
• Identify tasks with significantly different effort estimates (>50% variance)
• Detect duplicate/similar tasks across plans
• Analyze effort estimation reasoning
• Suggest resolution for each conflict
MODE: analysis
CONTEXT:
- Plan 1: ${JSON.stringify(normalizedPlans[0]?.tasks?.slice(0,3) || [], null, 2)}
- Plan 2: ${JSON.stringify(normalizedPlans[1]?.tasks?.slice(0,3) || [], null, 2)}
- [Additional plans...]
EXPECTED:
- Effort conflicts detected (task name, estimate in each plan, variance %)
- Duplicate task analysis (similar tasks, scope differences)
- Resolution recommendation for each conflict
- Confidence level for each detection
CONSTRAINTS: Focus on significant conflicts (>30% effort variance)
" --tool gemini --mode analysis`,
run_in_background: true
})
)
// Agent 2: Analyze architecture and scope conflicts
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Analyze architecture and scope conflicts across plans
Success: Clear identification of design approach differences and scope gaps
TASK:
• Identify different architectural approaches in plans
• Detect scope differences (features included/excluded)
• Analyze design philosophy conflicts
• Suggest approach to reconcile different visions
MODE: analysis
CONTEXT:
- Plan 1 architecture: \${normalizedPlans[0]?.metadata?.complexity || 'unknown'}
- Plan 2 architecture: \${normalizedPlans[1]?.metadata?.complexity || 'unknown'}
- Different design approaches detected: \${JSON.stringify(['approach1', 'approach2'])}
EXPECTED:
- Architecture conflicts identified (approach names and trade-offs)
- Scope conflicts (features/components in plan A but not B, vice versa)
- Design philosophy alignment/misalignment
- Recommendation for unified approach
- Pros/cons of each architectural approach
CONSTRAINTS: Consider both perspectives objectively
" --tool codex --mode analysis\`,
run_in_background: true
})
)
// Agent 3: Analyze risk assessment conflicts
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Analyze risk assessment conflicts across plans
Success: Unified risk assessment with conflict resolution
TASK:
• Identify tasks/areas with significantly different risk ratings
• Analyze risk assessment reasoning
• Detect missing risks in some plans
• Propose unified risk assessment
MODE: analysis
CONTEXT:
- Risk areas with disagreement: [list areas]
- Plan 1 risk ratings: [risk matrix]
- Plan 2 risk ratings: [risk matrix]
EXPECTED:
- Risk conflicts identified (area, plan A rating, plan B rating)
- Explanation of why assessments differ
- Missing risks analysis (important in one plan but not others)
- Unified risk rating recommendation
- Confidence level for each assessment
CONSTRAINTS: Be realistic in risk assessment, not pessimistic
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Agent 4: Synthesize conflicts into resolution strategy
conflictPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Synthesize all conflicts into unified resolution strategy
Success: Clear path to merge plans with informed trade-off decisions
TASK:
• Analyze all detected conflicts holistically
• Identify which conflicts are critical vs. non-critical
• Propose resolution for each conflict type
• Suggest unified approach that honors valid insights from all plans
MODE: analysis
CONTEXT:
- Total conflicts detected: [number]
- Conflict types: effort, architecture, scope, risk
- Resolution rule: \${resolutionRule}
- Plan importance: \${normalizedPlans.map(p => p.metadata.title).join(', ')}
EXPECTED:
- Conflict priority ranking (critical, important, minor)
- Recommended resolution for each conflict
- Rationale for each recommendation
- Potential issues with proposed resolution
- Fallback options if recommendation not accepted
- Overall merge strategy and sequencing
CONSTRAINTS: Aim for solution that maximizes learning from all perspectives
" --tool gemini --mode analysis\`,
run_in_background: true
})
)
// Wait for all conflict detection agents to complete
const [effortConflicts, archConflicts, riskConflicts, resolutionStrategy] =
await Promise.all(conflictPromises)
// Parse and consolidate all conflict findings
const allConflicts = {
effort: parseEffortConflicts(effortConflicts),
architecture: parseArchConflicts(archConflicts),
risk: parseRiskConflicts(riskConflicts),
strategy: parseResolutionStrategy(resolutionStrategy),
timestamp: getUtc8ISOString()
}
Write(\`\${sessionFolder}/conflicts.json\`, JSON.stringify(allConflicts, null, 2))
```
**Conflict Detection Workflow**:
| Agent | Conflict Type | Focus | Output |
|-------|--------------|--------|--------|
| Gemini | Effort & Tasks | Duplicate detection, estimate variance | Conflicts with variance %, resolution suggestions |
| Codex | Architecture & Scope | Design approach differences | Design conflicts, scope gaps, recommendations |
| Claude | Risk Assessment | Risk rating disagreements | Risk conflicts, missing risks, unified assessment |
| Gemini | Resolution Strategy | Holistic synthesis | Priority ranking, resolution path, trade-offs |
### Phase 4: Resolve Conflicts
**Rule: Consensus (default)**
- Use median/average of conflicting estimates
- Merge scope differences
- Document minority viewpoints
**Rule: Priority**
- First plan has highest authority
- Later plans supplement but don't override
**Rule: Hierarchy**
- User ranks plan importance
- Higher-ranked plan wins conflicts
```javascript
const resolutions = {}
if (rule === 'consensus') {
for (const conflict of conflicts.effort) {
resolutions[conflict.task] = {
resolved: calculateMedian(conflict.estimates),
method: 'consensus-median',
rationale: 'Used median of all estimates'
}
}
} else if (rule === 'priority') {
for (const conflict of conflicts.effort) {
const primary = conflict.estimates[0] // First plan
resolutions[conflict.task] = {
resolved: primary.value,
method: 'priority-based',
rationale: `Selected from plan ${primary.from_plan} (highest priority)`
}
}
} else if (rule === 'hierarchy') {
// Request user ranking if not --auto
const ranking = getUserPlanRanking(normalizedPlans)
// Apply hierarchy-based resolution
}
Write(`${sessionFolder}/resolutions.json`, JSON.stringify(resolutions, null, 2))
```
### Phase 5: Generate Unified Plan
```javascript
const unifiedPlan = {
session_id: sessionId,
merge_timestamp: getUtc8ISOString(),
summary: {
total_source_plans: sourcePlans.length,
original_tasks: allTasks.length,
merged_tasks: deduplicatedTasks.length,
conflicts_resolved: Object.keys(resolutions).length,
resolution_rule: rule
},
tasks: deduplicatedTasks.map(task => ({
id: task.id,
title: task.title,
description: task.description,
effort: task.resolved_effort,
risk: task.resolved_risk,
dependencies: task.merged_dependencies,
source_plans: task.contributing_plans
})),
execution_sequence: topologicalSort(tasks),
critical_path: identifyCriticalPath(tasks),
risks: aggregateRisks(tasks),
success_criteria: aggregateCriteria(tasks)
}
Write(`${sessionFolder}/unified-plan.json`, JSON.stringify(unifiedPlan, null, 2))
```
### Phase 6: Generate Human-Readable Plan
```markdown
# Merged Planning Session
**Session ID**: ${sessionId}
**Pattern**: $PATTERN
**Created**: ${timestamp}
---
## Merge Summary
**Source Plans**: ${summary.total_source_plans}
**Original Tasks**: ${summary.original_tasks}
**Merged Tasks**: ${summary.merged_tasks}
**Conflicts Resolved**: ${summary.conflicts_resolved}
**Resolution Method**: ${summary.resolution_rule}
---
## Unified Task List
${tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}**
- Effort: ${task.effort}
- Risk: ${task.risk}
- From plans: ${task.source_plans.join(', ')}
`).join('\n')}
---
## Execution Sequence
**Critical Path**: ${critical_path.join(' → ')}
---
## Conflict Resolution Report
${Object.entries(resolutions).map(([key, res]) => `
- **${key}**: ${res.rationale}
`).join('\n')}
---
## Next Steps
**Execute**:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/unified-plan.json
\`\`\`
```
## Session Folder Structure
```
.workflow/.merged/{sessionId}/
├── merge.md # Process log
├── source-index.json # All input sources
├── conflicts.json # Detected conflicts
├── resolutions.json # How resolved
├── unified-plan.json # Merged plan (for execution)
└── unified-plan.md # Human-readable
```
## Resolution Rules Comparison
| Rule | Method | Best For | Tradeoff |
|------|--------|----------|----------|
| **Consensus** | Median/average | Similar-quality inputs | May miss extremes |
| **Priority** | First wins | Clear authority order | Discards alternatives |
| **Hierarchy** | User-ranked | Mixed stakeholders | Needs user input |
## Input Format Support
| Source Type | Detection Pattern | Parsing |
|-------------|-------------------|---------|
| Brainstorm | `.brainstorm/*/synthesis.json` | Top ideas → tasks |
| Analysis | `.analysis/*/conclusions.json` | Recommendations → tasks |
| Quick-Plan | `.planning/*/synthesis.json` | Direct task list |
| IMPL_PLAN | `*IMPL_PLAN.md` | Markdown → tasks |
| Task JSON | `*.json` with `tasks` | Direct mapping |
## Error Handling
| Situation | Action |
|-----------|--------|
| No plans found | List available plans, suggest search terms |
| Incompatible format | Skip, continue with others |
| Circular dependencies | Alert user, suggest manual review |
| Unresolvable conflict | Require user decision (unless --auto) |
## Integration Flow
```
Brainstorm Sessions / Analyses / Plans
├─ synthesis.json (session 1)
├─ conclusions.json (session 2)
├─ synthesis.json (session 3)
merge-plans-with-file
├─ unified-plan.json
unified-execute-with-file
Implementation
```
## Usage Patterns
**Pattern 1: Merge all auth-related plans**
```
PATTERN="authentication" --rule=consensus --auto
→ Finds all auth plans
→ Merges with consensus method
```
**Pattern 2: Prioritized merge**
```
PATTERN="payment" --rule=priority
→ First plan has authority
→ Others supplement
```
**Pattern 3: Team input merge**
```
PATTERN="feature-*" --rule=hierarchy
→ Asks for plan ranking
→ Applies hierarchy resolution
```
---
**Now execute merge-plans-with-file for pattern**: $PATTERN

View File

@@ -0,0 +1,450 @@
---
description: Multi-agent rapid planning with minimal documentation, conflict resolution, and actionable synthesis. Lightweight planning from raw task, brainstorm, or analysis artifacts
argument-hint: "TOPIC=\"<planning topic or task>\" [--from=brainstorm|analysis|task|raw] [--perspectives=arch,impl,risk,decision] [--auto] [--verbose]"
---
# Codex Quick-Plan-With-File Prompt
## Overview
Multi-agent rapid planning workflow with **minimal documentation overhead**. Coordinates parallel agent analysis (architecture, implementation, validation, decision), synthesizes conflicting perspectives into actionable decisions, and generates an implementation-ready plan.
**Core workflow**: Parse Input → Parallel Analysis → Conflict Resolution → Plan Synthesis → Output
**Key features**:
- **Format Agnostic**: Consumes brainstorm conclusions, analysis recommendations, quick tasks, or raw descriptions
- **Minimal Docs**: Single plan.md (no lengthy timeline documentation)
- **Parallel Multi-Agent**: 4 concurrent perspectives for rapid analysis
- **Conflict Resolution**: Automatic conflict detection and synthesis
- **Actionable Output**: Direct task breakdown ready for execution
## Target Planning
**$TOPIC**
- `--from`: Input source type (brainstorm | analysis | task | raw) - auto-detected if omitted
- `--perspectives`: Which perspectives to use (arch, impl, risk, decision) - all by default
- `--auto`: Auto-confirm decisions, minimal user prompts
- `--verbose`: Verbose output with all reasoning
## Execution Process
```
Phase 1: Input Validation & Loading
├─ Parse input: topic | artifact reference
├─ Load artifact if referenced (synthesis.json | conclusions.json)
├─ Extract constraints and key requirements
└─ Initialize session folder
Phase 2: Parallel Multi-Agent Analysis (concurrent)
├─ Agent 1 (Architecture): Design decomposition, patterns, scalability
├─ Agent 2 (Implementation): Tech stack, feasibility, effort estimates
├─ Agent 3 (Validation): Risk matrix, testing strategy, monitoring
├─ Agent 4 (Decision): Recommendations, tradeoffs, execution strategy
└─ Aggregate findings into perspectives.json
Phase 3: Conflict Detection & Resolution
├─ Detect: effort conflicts, architecture conflicts, risk conflicts
├─ Analyze rationale for each conflict
├─ Synthesis via arbitration: generate unified recommendation
├─ Document conflicts and resolutions
└─ Update plan.md
Phase 4: Plan Synthesis
├─ Consolidate all insights
├─ Generate task breakdown (5-8 major tasks)
├─ Create execution strategy and dependencies
├─ Document assumptions and risks
└─ Output plan.md + synthesis.json
Output:
├─ .workflow/.planning/{sessionId}/plan.md (minimal, actionable)
├─ .workflow/.planning/{sessionId}/perspectives.json (agent findings)
├─ .workflow/.planning/{sessionId}/conflicts.json (decision points)
└─ .workflow/.planning/{sessionId}/synthesis.json (task breakdown for execution)
```
## Implementation Details
### Phase 1: Session Setup & Input Loading
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse input
const planSlug = "$TOPIC".toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 30)
const sessionId = `PLAN-${planSlug}-${getUtc8ISOString().substring(0, 10)}`
const sessionFolder = `.workflow/.planning/${sessionId}`
// Detect input type
let artifact = null
if ($TOPIC.startsWith('BS-') || "$TOPIC".includes('brainstorm')) {
artifact = loadBrainstormArtifact($TOPIC)
} else if ($TOPIC.startsWith('ANL-') || "$TOPIC".includes('analysis')) {
artifact = loadAnalysisArtifact($TOPIC)
}
bash(`mkdir -p ${sessionFolder}`)
```
### Phase 2: Parallel Multi-Agent Analysis
Run 4 agents in parallel using ccw cli:
```javascript
// Launch all 4 agents concurrently with Bash run_in_background
const agentPromises = []
// Agent 1 - Architecture (Gemini)
agentPromises.push(
Bash({
command: `ccw cli -p "
PURPOSE: Architecture & high-level design for '${planningTopic}'
Success: Clear component decomposition and architectural approach
TASK:
• Decompose problem into major components/modules
• Identify architectural patterns and integration points
• Design component interfaces and data models
• Assess scalability and maintainability implications
• Propose architectural approach with rationale
MODE: analysis
CONTEXT: @**/*
${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Component decomposition (list with responsibilities)
- Module interfaces and contracts
- Data flow between components
- Architectural patterns applied (e.g., MVC, Event-Driven, etc.)
- Scalability assessment (1-5 rating with rationale)
- Architectural risks identified
CONSTRAINTS: Focus on long-term maintainability and extensibility
" --tool gemini --mode analysis`,
run_in_background: true
})
)
// Agent 2 - Implementation (Codex)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Implementation approach & technical feasibility for '\${planningTopic}'
Success: Concrete implementation strategy with realistic estimates
TASK:
• Evaluate technical feasibility of proposed approach
• Identify required technologies and dependencies
• Estimate effort: analysis/design/coding/testing/deployment
• Suggest implementation phases and milestones
• Highlight technical blockers and challenges
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Technology stack recommendation (languages, frameworks, tools)
- Implementation complexity: high|medium|low (with justification)
- Effort breakdown (hours or complexity: analysis, design, coding, testing, deployment)
- Key technical decisions with tradeoffs explained
- Potential blockers and mitigation strategies
- Suggested implementation phases with sequencing
- Reusable components or libraries identified
CONSTRAINTS: Realistic with current tech stack
" --tool codex --mode analysis\`,
run_in_background: true
})
)
// Agent 3 - Validation & Risk (Claude)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Risk analysis and validation strategy for '\${planningTopic}'
Success: Comprehensive risk matrix with testing and deployment strategy
TASK:
• Identify technical risks and failure scenarios
• Assess timeline and resource risks
• Define validation/testing strategy (unit, integration, e2e, performance)
• Suggest monitoring and observability requirements
• Propose deployment strategy and rollback plan
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Risk matrix (likelihood × impact, each 1-5)
- Top 3 technical risks with mitigation approaches
- Top 3 timeline/resource risks with mitigation
- Testing strategy (what to test, how, when, acceptance criteria)
- Deployment strategy (staged rollout, blue-green, canary, etc.)
- Rollback plan and recovery procedures
- Monitoring/observability requirements (metrics, logs, alerts)
- Overall risk rating: low|medium|high (with confidence)
CONSTRAINTS: Be realistic, not pessimistic
" --tool claude --mode analysis\`,
run_in_background: true
})
)
// Agent 4 - Strategic Decision (Gemini)
agentPromises.push(
Bash({
command: \`ccw cli -p "
PURPOSE: Strategic decisions and execution recommendations for '\${planningTopic}'
Success: Clear recommended approach with tradeoff analysis
TASK:
• Synthesize all perspectives into strategic recommendations
• Identify 2-3 critical decision points with recommended choices
• Clearly outline key tradeoffs (speed vs quality, scope vs timeline, risk vs cost)
• Propose go/no-go decision criteria and success metrics
• Suggest execution strategy and resource sequencing
MODE: analysis
CONTEXT: @**/*
\${artifact ? \`| Source artifact: \${artifact.type}\` : ''}
EXPECTED:
- Primary recommendation with strong rationale (1-2 paragraphs)
- Alternative approaches with pros/cons (2-3 alternatives)
- 2-3 critical decision points:
- What decision needs to be made
- Trade-offs for each option
- Recommended choice and why
- Key trade-offs explained (what we're optimizing for: speed/quality/risk/cost)
- Success metrics and go/no-go criteria
- Resource requirements and critical path items
- Suggested execution sequencing and phases
CONSTRAINTS: Focus on actionable decisions, provide clear rationale
" --tool gemini --mode analysis\`,
run_in_background: true
})
)
// Wait for all agents to complete
const [archResult, implResult, riskResult, decisionResult] = await Promise.all(agentPromises)
// Parse and extract findings from each agent result
const architecture = parseArchitectureResult(archResult)
const implementation = parseImplementationResult(implResult)
const validation = parseValidationResult(riskResult)
const recommendation = parseDecisionResult(decisionResult)
```
**Agent Focus Areas**:
| Agent | Perspective | Focus Areas |
|-------|-------------|------------|
| Gemini (Design) | Architecture patterns | Components, interfaces, scalability, patterns |
| Codex (Build) | Implementation reality | Tech stack, complexity, effort, blockers |
| Claude (Validate) | Risk & testing | Risk matrix, testing strategy, deployment, monitoring |
| Gemini (Decide) | Strategic synthesis | Recommendations, trade-offs, critical decisions |
### Phase 3: Parse & Aggregate Perspectives
```javascript
const perspectives = {
session_id: sessionId,
topic: "$TOPIC",
timestamp: getUtc8ISOString(),
architecture: {
components: [...],
patterns: [...],
scalability_rating: 3,
risks: [...]
},
implementation: {
technology_stack: [...],
complexity: "medium",
effort_breakdown: { analysis: 2, design: 3, coding: 8, testing: 4 },
blockers: [...]
},
validation: {
risk_matrix: [...],
top_risks: [{ title, impact, mitigation }, ...],
testing_strategy: "...",
monitoring: [...]
},
recommendation: {
primary_approach: "...",
alternatives: [...],
critical_decisions: [...],
tradeoffs: [...]
}
}
Write(`${sessionFolder}/perspectives.json`, JSON.stringify(perspectives, null, 2))
```
### Phase 4: Conflict Detection
Detect conflicts:
- Effort variance: Are estimates consistent?
- Risk disagreement: Do arch and validation agree on risks?
- Scope confusion: Are recommendations aligned?
- Architecture mismatch: Do design and implementation agree?
For each conflict: document it, then run synthesis arbitration.
### Phase 5: Generate Plan
```markdown
# Quick Planning Session
**Session ID**: ${sessionId}
**Topic**: $TOPIC
**Created**: ${timestamp}
---
## Executive Summary
${synthesis.executive_summary}
**Complexity**: ${synthesis.complexity_level}
**Estimated Effort**: ${formatEffort(synthesis.effort_breakdown)}
**Optimization Focus**: ${synthesis.optimization_focus}
---
## Architecture
**Primary Pattern**: ${synthesis.architecture_approach}
**Key Components**:
${synthesis.key_components.map((c, i) => `${i+1}. ${c.name}: ${c.responsibility}`).join('\n')}
---
## Implementation Strategy
**Technology Stack**:
${synthesis.technology_stack.map(t => `- ${t}`).join('\n')}
**Phases**:
${synthesis.phases.map((p, i) => `${i+1}. ${p.name} (${p.effort})`).join('\n')}
---
## Risk Assessment
**Overall Risk**: ${synthesis.overall_risk_level}
**Top 3 Risks**:
${synthesis.top_risks.map((r, i) => `${i+1}. **${r.title}** (Impact: ${r.impact})\n Mitigation: ${r.mitigation}`).join('\n\n')}
---
## Task Breakdown (Ready for Execution)
${synthesis.tasks.map((task, i) => `
${i+1}. **${task.id}: ${task.title}** (Effort: ${task.effort})
${task.description}
Dependencies: ${task.dependencies.join(', ') || 'none'}
`).join('\n')}
---
## Next Steps
**Execute with**:
\`\`\`
/workflow:unified-execute-with-file -p ${sessionFolder}/synthesis.json
\`\`\`
**Detailed planning if needed**:
\`\`\`
/workflow:plan "Based on: $TOPIC"
\`\`\`
```
## Session Folder Structure
```
.workflow/.planning/{sessionId}/
├── plan.md # Minimal, actionable
├── perspectives.json # Agent findings
├── conflicts.json # Conflicts & resolutions (if any)
└── synthesis.json # Task breakdown for execution
```
## Multi-Agent Coordination
| Agent | Perspective | Tools | Output |
|-------|-------------|-------|--------|
| Gemini (Design) | Architecture patterns | Design thinking, cross-domain | Components, patterns, scalability |
| Codex (Build) | Implementation reality | Tech stack evaluation | Stack, effort, feasibility |
| Claude (Validate) | Risk & testing | Risk assessment, QA | Risks, testing strategy |
| Gemini (Decide) | Strategic synthesis | Decision analysis | Recommendations, tradeoffs |
## Error Handling
| Situation | Action |
|-----------|--------|
| Agents conflict | Arbitration agent synthesizes recommendation |
| Missing blockers | Continue with available context, note gaps |
| Unclear input | Ask for clarification on planning focus |
| Estimate too high | Suggest MVP approach or phasing |
## Integration Flow
```
Raw Task / Brainstorm / Analysis
quick-plan-with-file (5-10 min)
├─ plan.md
├─ perspectives.json
└─ synthesis.json
unified-execute-with-file
Implementation
```
## Usage Patterns
**Pattern 1: Quick planning from task**
```
TOPIC="实现实时通知系统" --auto
→ Creates actionable plan in ~5 minutes
```
**Pattern 2: Convert brainstorm to execution plan**
```
TOPIC="BS-notifications-2025-01-28" --from=brainstorm
→ Reads synthesis.json from brainstorm
→ Generates implementation plan
```
**Pattern 3: From analysis to plan**
```
TOPIC="ANL-auth-2025-01-28" --from=analysis
→ Converts conclusions.json to executable plan
```
---
**Now execute quick-plan-with-file for topic**: $TOPIC