claude-code-workflow 6.3.51 → 6.3.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,807 @@
1
+ ---
2
+ name: merge-plans-with-file
3
+ description: Merge multiple planning/brainstorm/analysis outputs, resolve conflicts, and synthesize unified plan. Designed for multi-team input aggregation and final plan crystallization
4
+ argument-hint: "[-y|--yes] [-r|--rule consensus|priority|hierarchy] \"plan or topic name\""
5
+ allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
6
+ ---
7
+
8
+ ## Auto Mode
9
+
10
+ When `--yes` or `-y`: Auto-resolve conflicts using specified rule (consensus/priority/hierarchy), minimal user prompts.
11
+
12
+ # Workflow Merge-Plans-With-File Command (/workflow:merge-plans-with-file)
13
+
14
+ ## Overview
15
+
16
+ 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.
17
+
18
+ **Core workflow**: Load Sources → Parse Plans → Conflict Analysis → Arbitration → Unified Plan
19
+
20
+ **Key features**:
21
+ - **Multi-Source Support**: Brainstorm, analysis, quick-plan, IMPL_PLAN, task JSONs
22
+ - **Parallel Conflict Detection**: Identify all contradictions across input plans
23
+ - **Conflict Resolution**: Consensus, priority-based, or hierarchical resolution modes
24
+ - **Unified Synthesis**: Single authoritative plan from multiple perspectives
25
+ - **Decision Tracking**: Full audit trail of conflicts and resolutions
26
+ - **Resumable**: Save intermediate states, refine resolutions
27
+
28
+ ## Usage
29
+
30
+ ```bash
31
+ /workflow:merge-plans-with-file [FLAGS] <PLAN_NAME_OR_PATTERN>
32
+
33
+ # Flags
34
+ -y, --yes Auto-resolve conflicts using rule, skip confirmations
35
+ -r, --rule <rule> Conflict resolution rule: consensus (default) | priority | hierarchy
36
+ -o, --output <path> Output directory (default: .workflow/.merged/{name})
37
+
38
+ # Arguments
39
+ <plan-name-or-pattern> Plan name or glob pattern to identify input files/sessions
40
+ Examples: "auth-module", "*.analysis-*.json", "PLAN-*"
41
+
42
+ # Examples
43
+ /workflow:merge-plans-with-file "authentication" # Auto-detect all auth-related plans
44
+ /workflow:merge-plans-with-file -y -r priority "payment-system" # Auto-resolve with priority rule
45
+ /workflow:merge-plans-with-file -r hierarchy "feature-complete" # Use hierarchy rule (requires user ranking)
46
+ ```
47
+
48
+ ## Execution Process
49
+
50
+ ```
51
+ Discovery & Loading:
52
+ ├─ Search for planning artifacts matching pattern
53
+ ├─ Load all synthesis.json, conclusions.json, IMPL_PLAN.md
54
+ ├─ Parse each into normalized task/plan structure
55
+ └─ Validate data completeness
56
+
57
+ Session Initialization:
58
+ ├─ Create .workflow/.merged/{sessionId}/
59
+ ├─ Initialize merge.md with plan summary
60
+ ├─ Index all source plans
61
+ └─ Extract planning metadata and constraints
62
+
63
+ Phase 1: Plan Normalization
64
+ ├─ Convert all formats to common task representation
65
+ ├─ Extract tasks, dependencies, effort, risks
66
+ ├─ Identify plan scope and boundaries
67
+ ├─ Validate no duplicate tasks
68
+ └─ Aggregate recommendations from each plan
69
+
70
+ Phase 2: Conflict Detection (Parallel)
71
+ ├─ Architecture conflicts: different design approaches
72
+ ├─ Task conflicts: overlapping responsibilities or different priorities
73
+ ├─ Effort conflicts: vastly different estimates
74
+ ├─ Risk assessment conflicts: different risk levels
75
+ ├─ Scope conflicts: different feature inclusions
76
+ └─ Generate conflict matrix with severity levels
77
+
78
+ Phase 3: Consensus Building / Arbitration
79
+ ├─ For each conflict, analyze source rationale
80
+ ├─ Apply resolution rule (consensus/priority/hierarchy)
81
+ ├─ Escalate unresolvable conflicts to user (unless --yes)
82
+ ├─ Document decision rationale
83
+ └─ Generate resolutions.json
84
+
85
+ Phase 4: Plan Synthesis
86
+ ├─ Merge task lists (remove duplicates, combine insights)
87
+ ├─ Integrate dependencies from all sources
88
+ ├─ Consolidate effort and risk estimates
89
+ ├─ Generate unified execution sequence
90
+ ├─ Create final unified plan
91
+ └─ Output ready for execution
92
+
93
+ Output:
94
+ ├─ .workflow/.merged/{sessionId}/merge.md (merge process & decisions)
95
+ ├─ .workflow/.merged/{sessionId}/source-index.json (input sources)
96
+ ├─ .workflow/.merged/{sessionId}/conflicts.json (conflict matrix)
97
+ ├─ .workflow/.merged/{sessionId}/resolutions.json (how conflicts were resolved)
98
+ ├─ .workflow/.merged/{sessionId}/unified-plan.json (final merged plan)
99
+ └─ .workflow/.merged/{sessionId}/unified-plan.md (execution-ready markdown)
100
+ ```
101
+
102
+ ## Implementation
103
+
104
+ ### Phase 1: Plan Discovery & Loading
105
+
106
+ ```javascript
107
+ const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
108
+
109
+ // Parse arguments
110
+ const planPattern = "$PLAN_NAME_OR_PATTERN"
111
+ const resolutionRule = $ARGUMENTS.match(/--rule\s+(\w+)/)?.[1] || 'consensus'
112
+ const isAutoMode = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
113
+
114
+ // Generate session ID
115
+ const mergeSlug = planPattern.toLowerCase()
116
+ .replace(/[*?]/g, '-')
117
+ .replace(/[^a-z0-9\u4e00-\u9fa5-]+/g, '-')
118
+ .substring(0, 30)
119
+ const dateStr = getUtc8ISOString().substring(0, 10)
120
+ const sessionId = `MERGE-${mergeSlug}-${dateStr}`
121
+ const sessionFolder = `.workflow/.merged/${sessionId}`
122
+
123
+ bash(`mkdir -p ${sessionFolder}`)
124
+
125
+ // Discover all relevant planning artifacts
126
+ const discoveryPaths = [
127
+ `.workflow/.brainstorm/*/${planPattern}*/synthesis.json`,
128
+ `.workflow/.analysis/*/${planPattern}*/conclusions.json`,
129
+ `.workflow/.planning/*/${planPattern}*/synthesis.json`,
130
+ `.workflow/.plan/${planPattern}*IMPL_PLAN.md`,
131
+ `.workflow/*/${planPattern}*.json`
132
+ ]
133
+
134
+ const sourcePlans = []
135
+
136
+ for (const pattern of discoveryPaths) {
137
+ const matches = glob(pattern)
138
+ for (const path of matches) {
139
+ try {
140
+ const content = Read(path)
141
+ const plan = parsePlanFile(path, content)
142
+ if (plan && plan.tasks?.length > 0) {
143
+ sourcePlans.push({
144
+ source_path: path,
145
+ source_type: identifySourceType(path),
146
+ plan: plan,
147
+ loaded_at: getUtc8ISOString()
148
+ })
149
+ }
150
+ } catch (e) {
151
+ console.warn(`Failed to load plan from ${path}: ${e.message}`)
152
+ }
153
+ }
154
+ }
155
+
156
+ if (sourcePlans.length === 0) {
157
+ console.error(`
158
+ ## Error: No Plans Found
159
+
160
+ Pattern: ${planPattern}
161
+ Searched locations:
162
+ ${discoveryPaths.join('\n')}
163
+
164
+ Available plans in .workflow/:
165
+ `)
166
+ bash(`find .workflow -name "*.json" -o -name "*PLAN.md" | head -20`)
167
+ return { status: 'error', message: 'No plans found' }
168
+ }
169
+
170
+ console.log(`
171
+ ## Plans Discovered
172
+
173
+ Total: ${sourcePlans.length}
174
+ ${sourcePlans.map(sp => `- ${sp.source_type}: ${sp.source_path}`).join('\n')}
175
+ `)
176
+ ```
177
+
178
+ ---
179
+
180
+ ### Phase 2: Plan Normalization
181
+
182
+ ```javascript
183
+ // Normalize all plans to common format
184
+ const normalizedPlans = sourcePlans.map((sourcePlan, idx) => {
185
+ const plan = sourcePlan.plan
186
+ const tasks = plan.tasks || []
187
+
188
+ return {
189
+ index: idx,
190
+ source: sourcePlan.source_path,
191
+ source_type: sourcePlan.source_type,
192
+
193
+ metadata: {
194
+ title: plan.title || `Plan ${idx + 1}`,
195
+ topic: plan.topic || plan.planning_topic || 'unknown',
196
+ timestamp: plan.completed || plan.timestamp || sourcePlan.loaded_at,
197
+ source_ideas: plan.top_ideas?.length || 0,
198
+ complexity: plan.complexity_level || 'unknown'
199
+ },
200
+
201
+ // Normalized tasks
202
+ tasks: tasks.map(task => ({
203
+ id: task.id || `T${idx}-${task.title?.substring(0, 20)}`,
204
+ title: task.title || task.content,
205
+ description: task.description || '',
206
+ type: task.type || inferType(task),
207
+ priority: task.priority || 'normal',
208
+
209
+ // Effort estimation
210
+ effort: {
211
+ estimated: task.estimated_duration || task.effort_estimate || 'unknown',
212
+ from_plan: idx
213
+ },
214
+
215
+ // Risk assessment
216
+ risk: {
217
+ level: task.risk_level || 'medium',
218
+ from_plan: idx
219
+ },
220
+
221
+ // Dependencies
222
+ dependencies: task.dependencies || [],
223
+
224
+ // Source tracking
225
+ source_plan_index: idx,
226
+ original_id: task.id,
227
+
228
+ // Quality tracking
229
+ success_criteria: task.success_criteria || [],
230
+ challenges: task.challenges || []
231
+ }))
232
+ }
233
+ })
234
+
235
+ // Save source index
236
+ const sourceIndex = {
237
+ session_id: sessionId,
238
+ merge_timestamp: getUtc8ISOString(),
239
+ pattern: planPattern,
240
+ total_source_plans: sourcePlans.length,
241
+
242
+ sources: normalizedPlans.map(p => ({
243
+ index: p.index,
244
+ source_path: p.source,
245
+ source_type: p.source_type,
246
+ topic: p.metadata.topic,
247
+ task_count: p.tasks.length
248
+ }))
249
+ }
250
+
251
+ Write(`${sessionFolder}/source-index.json`, JSON.stringify(sourceIndex, null, 2))
252
+ ```
253
+
254
+ ---
255
+
256
+ ### Phase 3: Conflict Detection
257
+
258
+ ```javascript
259
+ // Detect conflicts across plans
260
+ const conflictDetector = {
261
+ // Architecture conflicts
262
+ architectureConflicts: [],
263
+
264
+ // Task conflicts (duplicates, different scope)
265
+ taskConflicts: [],
266
+
267
+ // Effort conflicts
268
+ effortConflicts: [],
269
+
270
+ // Risk assessment conflicts
271
+ riskConflicts: [],
272
+
273
+ // Scope conflicts
274
+ scopeConflicts: [],
275
+
276
+ // Priority conflicts
277
+ priorityConflicts: []
278
+ }
279
+
280
+ // Algorithm 1: Detect similar tasks across plans
281
+ const allTasks = normalizedPlans.flatMap(p => p.tasks)
282
+ const taskGroups = groupSimilarTasks(allTasks)
283
+
284
+ for (const group of taskGroups) {
285
+ if (group.tasks.length > 1) {
286
+ // Same task appears in multiple plans
287
+ const efforts = group.tasks.map(t => t.effort.estimated)
288
+ const effortVariance = calculateVariance(efforts)
289
+
290
+ if (effortVariance > 0.5) {
291
+ // Significant difference in effort estimates
292
+ conflictDetector.effortConflicts.push({
293
+ task_group: group.title,
294
+ conflicting_tasks: group.tasks.map((t, i) => ({
295
+ id: t.id,
296
+ from_plan: t.source_plan_index,
297
+ effort: t.effort.estimated
298
+ })),
299
+ variance: effortVariance,
300
+ severity: 'high'
301
+ })
302
+ }
303
+
304
+ // Check for scope differences
305
+ const scopeDifferences = analyzeScopeDifferences(group.tasks)
306
+ if (scopeDifferences.length > 0) {
307
+ conflictDetector.taskConflicts.push({
308
+ task_group: group.title,
309
+ scope_differences: scopeDifferences,
310
+ severity: 'medium'
311
+ })
312
+ }
313
+ }
314
+ }
315
+
316
+ // Algorithm 2: Architecture conflicts
317
+ const architectures = normalizedPlans.map(p => p.metadata.complexity)
318
+ if (new Set(architectures).size > 1) {
319
+ conflictDetector.architectureConflicts.push({
320
+ different_approaches: true,
321
+ complexity_levels: architectures.map((a, i) => ({
322
+ plan: i,
323
+ complexity: a
324
+ })),
325
+ severity: 'high'
326
+ })
327
+ }
328
+
329
+ // Algorithm 3: Risk assessment conflicts
330
+ const riskLevels = allTasks.map(t => ({ task: t.id, risk: t.risk.level }))
331
+ const taskRisks = {}
332
+ for (const tr of riskLevels) {
333
+ if (!taskRisks[tr.task]) taskRisks[tr.task] = []
334
+ taskRisks[tr.task].push(tr.risk)
335
+ }
336
+
337
+ for (const [task, risks] of Object.entries(taskRisks)) {
338
+ if (new Set(risks).size > 1) {
339
+ conflictDetector.riskConflicts.push({
340
+ task: task,
341
+ conflicting_risk_levels: risks,
342
+ severity: 'medium'
343
+ })
344
+ }
345
+ }
346
+
347
+ // Save conflicts
348
+ Write(`${sessionFolder}/conflicts.json`, JSON.stringify(conflictDetector, null, 2))
349
+ ```
350
+
351
+ ---
352
+
353
+ ### Phase 4: Conflict Resolution
354
+
355
+ ```javascript
356
+ // Resolve conflicts based on selected rule
357
+ const resolutions = {
358
+ resolution_rule: resolutionRule,
359
+ timestamp: getUtc8ISOString(),
360
+
361
+ effort_resolutions: [],
362
+ architecture_resolutions: [],
363
+ risk_resolutions: [],
364
+ scope_resolutions: [],
365
+ priority_resolutions: []
366
+ }
367
+
368
+ // Resolution Strategy 1: Consensus
369
+ if (resolutionRule === 'consensus') {
370
+ for (const conflict of conflictDetector.effortConflicts) {
371
+ // Use median or average
372
+ const efforts = conflict.conflicting_tasks.map(t => parseEffort(t.effort))
373
+ const resolved_effort = calculateMedian(efforts)
374
+
375
+ resolutions.effort_resolutions.push({
376
+ conflict: conflict.task_group,
377
+ original_estimates: efforts,
378
+ resolved_estimate: resolved_effort,
379
+ method: 'consensus-median',
380
+ rationale: 'Used median of all estimates'
381
+ })
382
+ }
383
+ }
384
+
385
+ // Resolution Strategy 2: Priority-Based
386
+ else if (resolutionRule === 'priority') {
387
+ // Use the plan from highest priority source (first or most recent)
388
+ for (const conflict of conflictDetector.effortConflicts) {
389
+ const highestPriority = conflict.conflicting_tasks[0] // First plan has priority
390
+
391
+ resolutions.effort_resolutions.push({
392
+ conflict: conflict.task_group,
393
+ conflicting_estimates: conflict.conflicting_tasks.map(t => t.effort),
394
+ resolved_estimate: highestPriority.effort,
395
+ selected_from_plan: highestPriority.from_plan,
396
+ method: 'priority-based',
397
+ rationale: `Selected estimate from plan ${highestPriority.from_plan} (highest priority)`
398
+ })
399
+ }
400
+ }
401
+
402
+ // Resolution Strategy 3: Hierarchy (requires user ranking)
403
+ else if (resolutionRule === 'hierarchy') {
404
+ if (!isAutoMode) {
405
+ // Ask user to rank plan importance
406
+ const planRanking = AskUserQuestion({
407
+ questions: [{
408
+ question: "请按重要性排序这些规划(从最重要到最不重要):",
409
+ header: "Plan Ranking",
410
+ multiSelect: false,
411
+ options: normalizedPlans.slice(0, 5).map(p => ({
412
+ label: `Plan ${p.index}: ${p.metadata.title.substring(0, 40)}`,
413
+ description: `${p.tasks.length} tasks, complexity: ${p.metadata.complexity}`
414
+ }))
415
+ }]
416
+ })
417
+
418
+ // Apply hierarchy
419
+ const hierarchy = extractHierarchy(planRanking)
420
+ for (const conflict of conflictDetector.effortConflicts) {
421
+ const topPriorityTask = conflict.conflicting_tasks
422
+ .sort((a, b) => hierarchy[a.from_plan] - hierarchy[b.from_plan])[0]
423
+
424
+ resolutions.effort_resolutions.push({
425
+ conflict: conflict.task_group,
426
+ resolved_estimate: topPriorityTask.effort,
427
+ selected_from_plan: topPriorityTask.from_plan,
428
+ method: 'hierarchy-based',
429
+ rationale: `Selected from highest-ranked plan`
430
+ })
431
+ }
432
+ }
433
+ }
434
+
435
+ Write(`${sessionFolder}/resolutions.json`, JSON.stringify(resolutions, null, 2))
436
+ ```
437
+
438
+ ---
439
+
440
+ ### Phase 5: Plan Synthesis
441
+
442
+ ```javascript
443
+ // Merge all tasks into unified plan
444
+ const unifiedTasks = []
445
+ const processedTaskIds = new Set()
446
+
447
+ for (const task of allTasks) {
448
+ const taskKey = generateTaskKey(task)
449
+
450
+ if (processedTaskIds.has(taskKey)) {
451
+ // Task already added, skip
452
+ continue
453
+ }
454
+
455
+ processedTaskIds.add(taskKey)
456
+
457
+ // Apply resolution if this task has conflicts
458
+ let resolvedTask = { ...task }
459
+
460
+ const effortResolution = resolutions.effort_resolutions
461
+ .find(r => r.conflict === taskKey)
462
+ if (effortResolution) {
463
+ resolvedTask.effort.estimated = effortResolution.resolved_estimate
464
+ resolvedTask.effort.resolution_method = effortResolution.method
465
+ }
466
+
467
+ unifiedTasks.push({
468
+ id: taskKey,
469
+ title: task.title,
470
+ description: task.description,
471
+ type: task.type,
472
+ priority: task.priority,
473
+
474
+ effort: resolvedTask.effort,
475
+ risk: task.risk,
476
+ dependencies: task.dependencies,
477
+
478
+ success_criteria: [...new Set([
479
+ ...task.success_criteria,
480
+ ...findRelatedTasks(task, allTasks)
481
+ .flatMap(t => t.success_criteria)
482
+ ])],
483
+
484
+ challenges: [...new Set([
485
+ ...task.challenges,
486
+ ...findRelatedTasks(task, allTasks)
487
+ .flatMap(t => t.challenges)
488
+ ])],
489
+
490
+ source_plans: [
491
+ ...new Set(allTasks
492
+ .filter(t => generateTaskKey(t) === taskKey)
493
+ .map(t => t.source_plan_index))
494
+ ]
495
+ })
496
+ }
497
+
498
+ // Generate execution sequence
499
+ const executionSequence = topologicalSort(unifiedTasks)
500
+ const criticalPath = identifyCriticalPath(unifiedTasks, executionSequence)
501
+
502
+ // Final unified plan
503
+ const unifiedPlan = {
504
+ session_id: sessionId,
505
+ merge_timestamp: getUtc8ISOString(),
506
+
507
+ summary: {
508
+ total_source_plans: normalizedPlans.length,
509
+ original_tasks_total: allTasks.length,
510
+ merged_tasks: unifiedTasks.length,
511
+ conflicts_resolved: Object.values(conflictDetector).flat().length,
512
+ resolution_rule: resolutionRule
513
+ },
514
+
515
+ merged_metadata: {
516
+ topics: [...new Set(normalizedPlans.map(p => p.metadata.topic))],
517
+ average_complexity: calculateAverage(normalizedPlans.map(p => parseComplexity(p.metadata.complexity))),
518
+ combined_scope: estimateScope(unifiedTasks)
519
+ },
520
+
521
+ tasks: unifiedTasks,
522
+
523
+ execution_sequence: executionSequence,
524
+ critical_path: criticalPath,
525
+
526
+ risks: aggregateRisks(unifiedTasks),
527
+ success_criteria: aggregateSuccessCriteria(unifiedTasks),
528
+
529
+ audit_trail: {
530
+ source_plans: normalizedPlans.length,
531
+ conflicts_detected: Object.values(conflictDetector).flat().length,
532
+ conflicts_resolved: Object.values(resolutions).flat().length,
533
+ resolution_method: resolutionRule
534
+ }
535
+ }
536
+
537
+ Write(`${sessionFolder}/unified-plan.json`, JSON.stringify(unifiedPlan, null, 2))
538
+ ```
539
+
540
+ ---
541
+
542
+ ### Phase 6: Generate Execution Plan
543
+
544
+ ```markdown
545
+ # Merged Planning Session
546
+
547
+ **Session ID**: ${sessionId}
548
+ **Pattern**: ${planPattern}
549
+ **Created**: ${getUtc8ISOString()}
550
+
551
+ ---
552
+
553
+ ## Merge Summary
554
+
555
+ **Source Plans**: ${unifiedPlan.summary.total_source_plans}
556
+ **Original Tasks**: ${unifiedPlan.summary.original_tasks_total}
557
+ **Merged Tasks**: ${unifiedPlan.summary.merged_tasks}
558
+ **Tasks Deduplicated**: ${unifiedPlan.summary.original_tasks_total - unifiedPlan.summary.merged_tasks}
559
+ **Conflicts Resolved**: ${unifiedPlan.summary.conflicts_resolved}
560
+
561
+ **Resolution Method**: ${unifiedPlan.summary.resolution_rule}
562
+
563
+ ---
564
+
565
+ ## Merged Plan Overview
566
+
567
+ **Topics**: ${unifiedPlan.merged_metadata.topics.join(', ')}
568
+ **Combined Complexity**: ${unifiedPlan.merged_metadata.average_complexity}
569
+ **Total Scope**: ${unifiedPlan.merged_metadata.combined_scope}
570
+
571
+ ---
572
+
573
+ ## Unified Task List
574
+
575
+ ${unifiedPlan.tasks.map((task, i) => `
576
+ ${i+1}. **${task.id}: ${task.title}**
577
+ - Type: ${task.type}
578
+ - Effort: ${task.effort.estimated}
579
+ - Risk: ${task.risk.level}
580
+ - Source Plans: ${task.source_plans.join(', ')}
581
+ - ${task.description}
582
+ `).join('\n')}
583
+
584
+ ---
585
+
586
+ ## Execution Sequence
587
+
588
+ **Critical Path**: ${unifiedPlan.critical_path.join(' → ')}
589
+
590
+ **Execution Order**:
591
+ ${unifiedPlan.execution_sequence.map((id, i) => `${i+1}. ${id}`).join('\n')}
592
+
593
+ ---
594
+
595
+ ## Conflict Resolution Report
596
+
597
+ **Total Conflicts**: ${unifiedPlan.summary.conflicts_resolved}
598
+
599
+ **Resolved Conflicts**:
600
+ ${Object.entries(resolutions).flatMap(([key, items]) =>
601
+ items.slice(0, 3).map((item, i) => `
602
+ - ${key.replace('_', ' ')}: ${item.rationale || item.method}
603
+ `)
604
+ ).join('\n')}
605
+
606
+ **Full Report**: See \`conflicts.json\` and \`resolutions.json\`
607
+
608
+ ---
609
+
610
+ ## Risks & Considerations
611
+
612
+ **Aggregated Risks**:
613
+ ${unifiedPlan.risks.slice(0, 5).map(r => `- **${r.title}**: ${r.mitigation}`).join('\n')}
614
+
615
+ **Combined Success Criteria**:
616
+ ${unifiedPlan.success_criteria.slice(0, 5).map(c => `- ${c}`).join('\n')}
617
+
618
+ ---
619
+
620
+ ## Next Steps
621
+
622
+ ### Option 1: Direct Execution
623
+ Execute merged plan with unified-execute-with-file:
624
+ \`\`\`
625
+ /workflow:unified-execute-with-file -p ${sessionFolder}/unified-plan.json
626
+ \`\`\`
627
+
628
+ ### Option 2: Detailed Planning
629
+ Create detailed IMPL_PLAN from merged plan:
630
+ \`\`\`
631
+ /workflow:plan "Based on merged plan from $(echo ${planPattern})"
632
+ \`\`\`
633
+
634
+ ### Option 3: Review Conflicts
635
+ Review detailed conflict analysis:
636
+ \`\`\`
637
+ cat ${sessionFolder}/resolutions.json
638
+ \`\`\`
639
+
640
+ ---
641
+
642
+ ## Artifacts
643
+
644
+ - **source-index.json** - All input plans and sources
645
+ - **conflicts.json** - Conflict detection results
646
+ - **resolutions.json** - How each conflict was resolved
647
+ - **unified-plan.json** - Merged plan data structure (for execution)
648
+ - **unified-plan.md** - This document (human-readable)
649
+ ```
650
+
651
+ ---
652
+
653
+ ## Session Folder Structure
654
+
655
+ ```
656
+ .workflow/.merged/{sessionId}/
657
+ ├── merge.md # Merge process and decisions
658
+ ├── source-index.json # All input plan sources
659
+ ├── conflicts.json # Detected conflicts
660
+ ├── resolutions.json # Conflict resolutions applied
661
+ ├── unified-plan.json # Merged plan (machine-parseable, for execution)
662
+ └── unified-plan.md # Execution-ready plan (human-readable)
663
+ ```
664
+
665
+ ---
666
+
667
+ ## Resolution Rules
668
+
669
+ ### Rule 1: Consensus (default)
670
+ - Use median or average of conflicting estimates
671
+ - Good for: Multiple similar perspectives
672
+ - Tradeoff: May miss important minority viewpoints
673
+
674
+ ### Rule 2: Priority-Based
675
+ - First plan has highest priority, subsequent plans are fallback
676
+ - Good for: Clear ranking of plan sources
677
+ - Tradeoff: Discards valuable alternative perspectives
678
+
679
+ ### Rule 3: Hierarchy
680
+ - User explicitly ranks importance of each plan
681
+ - Good for: Mixed-source plans (engineering + product + leadership)
682
+ - Tradeoff: Requires user input
683
+
684
+ ---
685
+
686
+ ## Input Format Support
687
+
688
+ | Source Type | Detection | Parsing | Notes |
689
+ |-------------|-----------|---------|-------|
690
+ | **Brainstorm** | `.brainstorm/*/synthesis.json` | Top ideas → tasks | Ideas converted to work items |
691
+ | **Analysis** | `.analysis/*/conclusions.json` | Recommendations → tasks | Recommendations prioritized |
692
+ | **Quick-Plan** | `.planning/*/synthesis.json` | Direct task list | Already normalized |
693
+ | **IMPL_PLAN** | `*IMPL_PLAN.md` | Markdown → tasks | Parsed from markdown structure |
694
+ | **Task JSON** | `.json` with `tasks` key | Direct mapping | Requires standard schema |
695
+
696
+ ---
697
+
698
+ ## Error Handling
699
+
700
+ | Situation | Action |
701
+ |-----------|--------|
702
+ | No plans found | Suggest search terms, list available plans |
703
+ | Incompatible formats | Skip unsupported format, continue with others |
704
+ | Circular dependencies | Alert user, suggest manual review |
705
+ | Unresolvable conflicts | Require user decision (unless --yes + conflict rule) |
706
+ | Contradictory recommendations | Document both options for user consideration |
707
+
708
+ ---
709
+
710
+ ## Usage Patterns
711
+
712
+ ### Pattern 1: Merge Multiple Brainstorms
713
+
714
+ ```bash
715
+ /workflow:merge-plans-with-file "authentication" -y -r consensus
716
+ # → Finds all brainstorm sessions with "auth"
717
+ # → Merges top ideas into unified task list
718
+ # → Uses consensus method for conflicts
719
+ ```
720
+
721
+ ### Pattern 2: Synthesize Team Input
722
+
723
+ ```bash
724
+ /workflow:merge-plans-with-file "payment-integration" -r hierarchy
725
+ # → Loads plans from different team members
726
+ # → Asks for ranking by importance
727
+ # → Applies hierarchy-based conflict resolution
728
+ ```
729
+
730
+ ### Pattern 3: Bridge Planning Phases
731
+
732
+ ```bash
733
+ /workflow:merge-plans-with-file "user-auth" -f analysis
734
+ # → Takes analysis conclusions
735
+ # → Merges with existing quick-plans
736
+ # → Produces execution-ready plan
737
+ ```
738
+
739
+ ---
740
+
741
+ ## Advanced: Custom Conflict Resolution
742
+
743
+ For complex conflict scenarios, create custom resolution script:
744
+
745
+ ```
746
+ .workflow/.merged/{sessionId}/
747
+ └── custom-resolutions.js (optional)
748
+ - Define custom conflict resolution logic
749
+ - Applied after automatic resolution
750
+ - Override specific decisions
751
+ ```
752
+
753
+ ---
754
+
755
+ ## Best Practices
756
+
757
+ 1. **Before merging**:
758
+ - Ensure all source plans have same quality level
759
+ - Verify plans address same scope/topic
760
+ - Document any special considerations
761
+
762
+ 2. **During merging**:
763
+ - Review conflict matrix (conflicts.json)
764
+ - Understand resolution rationale (resolutions.json)
765
+ - Challenge assumptions if results seem odd
766
+
767
+ 3. **After merging**:
768
+ - Validate unified plan makes sense
769
+ - Review critical path
770
+ - Ensure no important details lost
771
+ - Execute or iterate if needed
772
+
773
+ ---
774
+
775
+ ## Integration with Other Workflows
776
+
777
+ ```
778
+ Multiple Brainstorms / Analyses
779
+
780
+ ├─ brainstorm-with-file (session 1)
781
+ ├─ brainstorm-with-file (session 2)
782
+ ├─ analyze-with-file (session 3)
783
+
784
+
785
+ merge-plans-with-file ◄──── This workflow
786
+
787
+
788
+ unified-plan.json
789
+
790
+ ├─ /workflow:unified-execute-with-file (direct execution)
791
+ ├─ /workflow:plan (detailed planning)
792
+ └─ /workflow:quick-plan-with-file (refinement)
793
+ ```
794
+
795
+ ---
796
+
797
+ ## Comparison: When to Use Which Merge Rule
798
+
799
+ | Rule | Use When | Pros | Cons |
800
+ |------|----------|------|------|
801
+ | **Consensus** | Similar-quality inputs | Fair, balanced | May miss extremes |
802
+ | **Priority** | Clear hierarchy | Simple, predictable | May bias to first input |
803
+ | **Hierarchy** | Mixed stakeholders | Respects importance | Requires user ranking |
804
+
805
+ ---
806
+
807
+ **Ready to execute**: Run `/workflow:merge-plans-with-file` to start merging plans!