claude-code-workflow 7.2.14 → 7.2.15

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.
Files changed (75) hide show
  1. package/.claude/commands/workflow/analyze-with-file.md +7 -0
  2. package/.codex/skills/analyze-with-file/SKILL.md +1181 -1182
  3. package/.codex/skills/brainstorm/SKILL.md +723 -725
  4. package/.codex/skills/brainstorm-with-file/SKILL.md +10 -5
  5. package/.codex/skills/clean/SKILL.md +33 -26
  6. package/.codex/skills/collaborative-plan-with-file/SKILL.md +830 -831
  7. package/.codex/skills/csv-wave-pipeline/SKILL.md +906 -906
  8. package/.codex/skills/issue-discover/SKILL.md +57 -50
  9. package/.codex/skills/issue-discover/phases/01-issue-new.md +18 -11
  10. package/.codex/skills/issue-discover/phases/02-discover.md +31 -26
  11. package/.codex/skills/issue-discover/phases/03-discover-by-prompt.md +13 -11
  12. package/.codex/skills/issue-discover/phases/04-quick-execute.md +32 -27
  13. package/.codex/skills/parallel-dev-cycle/SKILL.md +402 -402
  14. package/.codex/skills/project-documentation-workflow/SKILL.md +13 -3
  15. package/.codex/skills/roadmap-with-file/SKILL.md +901 -897
  16. package/.codex/skills/session-sync/SKILL.md +222 -212
  17. package/.codex/skills/spec-add/SKILL.md +620 -613
  18. package/.codex/skills/spec-generator/SKILL.md +2 -2
  19. package/.codex/skills/spec-generator/phases/01-5-requirement-clarification.md +10 -10
  20. package/.codex/skills/spec-generator/phases/01-discovery.md +11 -18
  21. package/.codex/skills/spec-generator/phases/02-product-brief.md +5 -5
  22. package/.codex/skills/spec-generator/phases/03-requirements.md +7 -7
  23. package/.codex/skills/spec-generator/phases/04-architecture.md +4 -4
  24. package/.codex/skills/spec-generator/phases/05-epics-stories.md +5 -6
  25. package/.codex/skills/spec-generator/phases/06-readiness-check.md +10 -17
  26. package/.codex/skills/spec-generator/phases/07-issue-export.md +326 -329
  27. package/.codex/skills/spec-setup/SKILL.md +669 -657
  28. package/.codex/skills/team-arch-opt/SKILL.md +50 -50
  29. package/.codex/skills/team-arch-opt/agents/completion-handler.md +3 -3
  30. package/.codex/skills/team-brainstorm/SKILL.md +724 -725
  31. package/.codex/skills/team-coordinate/SKILL.md +51 -51
  32. package/.codex/skills/team-coordinate/agents/completion-handler.md +3 -3
  33. package/.codex/skills/team-coordinate/agents/plan-reviewer.md +4 -4
  34. package/.codex/skills/team-designer/SKILL.md +691 -691
  35. package/.codex/skills/team-designer/agents/requirement-clarifier.md +11 -12
  36. package/.codex/skills/team-executor/SKILL.md +45 -45
  37. package/.codex/skills/team-frontend/SKILL.md +45 -45
  38. package/.codex/skills/team-frontend/agents/completion-handler.md +3 -3
  39. package/.codex/skills/team-frontend/agents/qa-gate-reviewer.md +4 -4
  40. package/.codex/skills/team-frontend-debug/SKILL.md +50 -50
  41. package/.codex/skills/team-frontend-debug/agents/completion-handler.md +3 -3
  42. package/.codex/skills/team-frontend-debug/agents/conditional-skip-gate.md +4 -4
  43. package/.codex/skills/team-issue/SKILL.md +751 -740
  44. package/.codex/skills/team-iterdev/SKILL.md +825 -826
  45. package/.codex/skills/team-lifecycle-v4/SKILL.md +775 -775
  46. package/.codex/skills/team-lifecycle-v4/agents/quality-gate.md +165 -165
  47. package/.codex/skills/team-lifecycle-v4/agents/requirement-clarifier.md +163 -163
  48. package/.codex/skills/team-perf-opt/SKILL.md +50 -50
  49. package/.codex/skills/team-perf-opt/agents/completion-handler.md +3 -3
  50. package/.codex/skills/team-planex-v2/SKILL.md +652 -637
  51. package/.codex/skills/team-quality-assurance/SKILL.md +51 -52
  52. package/.codex/skills/team-review/SKILL.md +40 -40
  53. package/.codex/skills/team-roadmap-dev/SKILL.md +51 -51
  54. package/.codex/skills/team-roadmap-dev/agents/roadmap-discusser.md +8 -8
  55. package/.codex/skills/team-tech-debt/SKILL.md +50 -50
  56. package/.codex/skills/team-tech-debt/agents/plan-approver.md +5 -5
  57. package/.codex/skills/team-testing/SKILL.md +51 -52
  58. package/.codex/skills/team-uidesign/SKILL.md +40 -40
  59. package/.codex/skills/team-uidesign/agents/completion-handler.md +177 -177
  60. package/.codex/skills/team-ultra-analyze/SKILL.md +786 -787
  61. package/.codex/skills/team-ultra-analyze/agents/discussion-feedback.md +8 -8
  62. package/.codex/skills/team-ux-improve/SKILL.md +51 -52
  63. package/.codex/skills/team-ux-improve/agents/ux-designer.md +2 -2
  64. package/.codex/skills/team-ux-improve/agents/ux-explorer.md +1 -1
  65. package/.codex/skills/unified-execute-with-file/SKILL.md +797 -796
  66. package/.codex/skills/workflow-execute/SKILL.md +1117 -1118
  67. package/.codex/skills/workflow-lite-planex/SKILL.md +1144 -1141
  68. package/.codex/skills/workflow-plan/SKILL.md +631 -636
  69. package/.codex/skills/workflow-tdd-plan/SKILL.md +753 -759
  70. package/.codex/skills/workflow-test-fix-cycle/SKILL.md +402 -392
  71. package/README.md +25 -0
  72. package/ccw/dist/commands/install.d.ts.map +1 -1
  73. package/ccw/dist/commands/install.js +12 -0
  74. package/ccw/dist/commands/install.js.map +1 -1
  75. package/package.json +1 -1
@@ -1,1182 +1,1181 @@
1
- ---
2
- name: analyze-with-file
3
- description: Interactive collaborative analysis with documented discussions, inline exploration, and evolving understanding. Serial execution with no agent delegation.
4
- argument-hint: "TOPIC=\"<question or topic>\" [--depth=quick|standard|deep] [--continue]"
5
- ---
6
-
7
- # Codex Analyze-With-File Prompt
8
-
9
- ## Overview
10
-
11
- Interactive collaborative analysis workflow with **documented discussion process**. Records understanding evolution, facilitates multi-round Q&A, and uses inline search tools for deep exploration.
12
-
13
- **Core workflow**: Topic → Explore → Discuss → Document → Refine → Conclude → Plan Checklist
14
-
15
- **Key features**:
16
- - **Documented discussion timeline**: Captures understanding evolution across all phases
17
- - **Decision recording at every critical point**: Mandatory recording of key findings, direction changes, and trade-offs
18
- - **Multi-perspective analysis**: Supports up to 4 analysis perspectives (serial, inline)
19
- - **Interactive discussion**: Multi-round Q&A with user feedback and direction adjustments
20
- - **Plan output**: Generate structured plan checklist for downstream execution (e.g., `$csv-wave-pipeline`)
21
-
22
- ### Decision Recording Protocol
23
-
24
- **CRITICAL**: During analysis, the following situations **MUST** trigger immediate recording to discussion.md:
25
-
26
- | Trigger | What to Record | Target Section |
27
- |---------|---------------|----------------|
28
- | **Direction choice** | What was chosen, why, what alternatives were discarded | `#### Decision Log` |
29
- | **Key finding** | Finding content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
30
- | **Assumption change** | Old assumption → new understanding, reason, impact | `#### Corrected Assumptions` |
31
- | **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` |
32
- | **Disagreement & trade-off** | Conflicting viewpoints, trade-off basis, final choice | `#### Decision Log` |
33
- | **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` |
34
-
35
- **Decision Record Format**:
36
- ```markdown
37
- > **Decision**: [Description of the decision]
38
- > - **Context**: [What triggered this decision]
39
- > - **Options considered**: [Alternatives evaluated]
40
- > - **Chosen**: [Selected approach] — **Reason**: [Rationale]
41
- > - **Rejected**: [Why other options were discarded]
42
- > - **Impact**: [Effect on analysis direction/conclusions]
43
- ```
44
-
45
- **Key Finding Record Format**:
46
- ```markdown
47
- > **Finding**: [Content]
48
- > - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
49
- > - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
50
- > - **Scope**: [What areas this affects]
51
- ```
52
-
53
- **Recording Principles**:
54
- - **Immediacy**: Record decisions as they happen, not at the end of a phase
55
- - **Completeness**: Capture context, options, chosen approach, reason, and rejected alternatives
56
- - **Traceability**: Later phases must be able to trace back why a decision was made
57
- - **Depth**: Capture reasoning and hypothesis impact, not just outcomes
58
-
59
- ## Auto Mode
60
-
61
- When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles, skip interactive scoping.
62
-
63
- ## Quick Start
64
-
65
- ```bash
66
- # Basic usage
67
- /codex:analyze-with-file TOPIC="How to optimize this project's authentication architecture"
68
-
69
- # With depth selection
70
- /codex:analyze-with-file TOPIC="Performance bottleneck analysis" --depth=deep
71
-
72
- # Continue existing session
73
- /codex:analyze-with-file TOPIC="authentication architecture" --continue
74
-
75
- # Auto mode (skip confirmations)
76
- /codex:analyze-with-file -y TOPIC="Caching strategy analysis"
77
- ```
78
-
79
- ## Target Topic
80
-
81
- **$TOPIC**
82
-
83
- ## Analysis Flow
84
-
85
- ```
86
- Step 0: Session Setup
87
- ├─ Parse topic, flags (--depth, --continue, -y)
88
- ├─ Generate session ID: ANL-{slug}-{date}
89
- └─ Create session folder (or detect existing → continue mode)
90
-
91
- Step 1: Topic Understanding
92
- ├─ Parse topic, identify analysis dimensions
93
- ├─ Initial scoping with user (focus areas, perspectives, depth)
94
- └─ Initialize discussion.md
95
-
96
- Step 2: Exploration (Inline, No Agents)
97
- ├─ Detect codebase → search relevant modules, patterns
98
- │ ├─ Run `ccw spec load --category exploration` (if spec system available)
99
- │ ├─ Run `ccw spec load --category debug` (known issues and root-cause notes)
100
- │ └─ Use Grep, Glob, Read, mcp__ace-tool__search_context
101
- ├─ Multi-perspective analysis (if selected, serial)
102
- │ ├─ Single: Comprehensive analysis
103
- │ └─ Multi (≤4): Serial per-perspective analysis with synthesis
104
- ├─ Aggregate findings → explorations.json / perspectives.json
105
- ├─ Update discussion.md with Round 1
106
- │ ├─ Replace ## Current Understanding with initial findings
107
- │ └─ Update ## Table of Contents
108
- └─ Initial Intent Coverage Check (early drift detection)
109
-
110
- Step 3: Interactive Discussion (Multi-Round, max 5)
111
- ├─ Current Understanding Summary (round ≥ 2, before findings)
112
- ├─ Present exploration findings
113
- ├─ Gather user feedback
114
- ├─ Process response:
115
- │ ├─ Deepen → context-driven + heuristic options → deeper inline analysis
116
- │ ├─ Agree & Suggest → user-directed exploration
117
- │ ├─ Adjust → new inline analysis with adjusted focus
118
- │ ├─ Questions → direct answers with evidence
119
- │ └─ Complete → exit loop for synthesis
120
- ├─ Update discussion.md:
121
- │ ├─ Append round details + Narrative Synthesis
122
- │ ├─ Replace ## Current Understanding with latest state
123
- │ └─ Update ## Table of Contents
124
- ├─ Intent Drift Check (round ≥ 2, building on Phase 2 initial check)
125
- └─ Repeat until user selects complete or max rounds
126
-
127
- Step 4: Synthesis & Conclusion
128
- ├─ Intent Coverage Verification (mandatory gate)
129
- ├─ Consolidate all insights → conclusions.json (with steps[] per recommendation)
130
- ├─ Update discussion.md with final synthesis
131
- ├─ Interactive Recommendation Review (per-recommendation confirm/modify/reject)
132
- └─ Offer options: generate plan / create issue / export / done
133
-
134
- Step 5: Plan Generation (Optional - produces plan only, NO code modifications)
135
- ├─ Generate inline plan checklist → appended to discussion.md
136
- └─ Remind user to execute via $csv-wave-pipeline
137
- ```
138
-
139
- ## Configuration
140
-
141
- | Flag | Default | Description |
142
- |------|---------|-------------|
143
- | `-y, --yes` | false | Auto-confirm all decisions |
144
- | `--continue` | false | Continue existing session |
145
- | `--depth` | standard | Analysis depth: quick / standard / deep |
146
-
147
- **Session ID format**: `ANL-{slug}-{YYYY-MM-DD}`
148
- - slug: lowercase, alphanumeric + CJK characters, max 40 chars
149
- - date: YYYY-MM-DD (UTC+8)
150
- - Auto-detect continue: session folder + discussion.md exists → continue mode
151
-
152
- ## Implementation Details
153
-
154
- ### Session Initialization
155
-
156
- ##### Step 0: Initialize Session
157
-
158
- ```javascript
159
- const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
160
-
161
- // Parse flags
162
- const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
163
- const continueMode = $ARGUMENTS.includes('--continue')
164
- const depthMatch = $ARGUMENTS.match(/--depth[=\s](quick|standard|deep)/)
165
- const analysisDepth = depthMatch ? depthMatch[1] : 'standard'
166
-
167
- // Extract topic
168
- const topic = $ARGUMENTS.replace(/--yes|-y|--continue|--depth[=\s]\w+|TOPIC=/g, '').replace(/^["']|["']$/g, '').trim()
169
-
170
- // Determine project root
171
- const projectRoot = Bash('git rev-parse --show-toplevel 2>/dev/null || pwd').trim()
172
-
173
- const slug = topic.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40)
174
- const dateStr = getUtc8ISOString().substring(0, 10)
175
- const sessionId = `ANL-${slug}-${dateStr}`
176
- const sessionFolder = `${projectRoot}/.workflow/.analysis/${sessionId}`
177
-
178
- // Auto-detect continue: session folder + discussion.md exists → continue mode
179
- // If continue → load discussion.md + explorations, resume from last round
180
- Bash(`mkdir -p ${sessionFolder}`)
181
- ```
182
-
183
- ### Phase 1: Topic Understanding
184
-
185
- **Objective**: Parse the topic, identify relevant analysis dimensions, scope the analysis with user input, and initialize the discussion document.
186
-
187
- ##### Step 1.1: Parse Topic & Identify Dimensions
188
-
189
- Match topic keywords against analysis dimensions:
190
-
191
- ```javascript
192
- const ANALYSIS_DIMENSIONS = {
193
- architecture: ['架构', 'architecture', 'design', 'structure', '设计', 'pattern'],
194
- implementation: ['实现', 'implement', 'code', 'coding', '代码', 'logic'],
195
- performance: ['性能', 'performance', 'optimize', 'bottleneck', '优化', 'speed'],
196
- security: ['安全', 'security', 'auth', 'permission', '权限', 'vulnerability'],
197
- concept: ['概念', 'concept', 'theory', 'principle', '原理', 'understand'],
198
- comparison: ['比较', 'compare', 'vs', 'difference', '区别', 'versus'],
199
- decision: ['决策', 'decision', 'choice', 'tradeoff', '选择', 'trade-off']
200
- }
201
-
202
- // Match topic text against keyword lists
203
- // If multiple dimensions match, include all
204
- // If none match, default to "architecture" and "implementation"
205
- const dimensions = identifyDimensions(topic, ANALYSIS_DIMENSIONS)
206
- ```
207
-
208
- ##### Step 1.2: Initial Scoping (New Session Only)
209
-
210
- For new sessions, gather user preferences (skipped in auto mode or continue mode):
211
-
212
- ```javascript
213
- if (!autoYes && !continueMode) {
214
- // 1. Focus areas (multi-select)
215
- // Generate directions dynamically from detected dimensions (see Dimension-Direction Mapping)
216
- const focusAreas = AskUserQuestion({
217
- questions: [{
218
- question: "Select analysis focus areas:",
219
- header: "Focus",
220
- multiSelect: true,
221
- options: generateFocusOptions(dimensions) // Dynamic based on dimensions
222
- }]
223
- })
224
-
225
- // 2. Analysis perspectives (multi-select, max 4)
226
- const perspectives = AskUserQuestion({
227
- questions: [{
228
- question: "Select analysis perspectives (single = focused, multi = broader coverage):",
229
- header: "Perspectives",
230
- multiSelect: true,
231
- options: [
232
- { label: "Technical", description: "Implementation patterns, code structure, technical feasibility" },
233
- { label: "Architectural", description: "System design, scalability, component interactions" },
234
- { label: "Security", description: "Vulnerabilities, authentication, access control" },
235
- { label: "Performance", description: "Bottlenecks, optimization, resource utilization" }
236
- ]
237
- }]
238
- })
239
-
240
- // 3. Analysis depth (single-select, unless --depth already set)
241
- // Quick: surface level | Standard: moderate depth | Deep: comprehensive
242
- }
243
- ```
244
-
245
- ##### Step 1.3: Initialize discussion.md
246
-
247
- ```javascript
248
- const discussionMd = `# Analysis Discussion
249
-
250
- **Session ID**: ${sessionId}
251
- **Topic**: ${topic}
252
- **Started**: ${getUtc8ISOString()}
253
- **Dimensions**: ${dimensions.join(', ')}
254
- **Depth**: ${analysisDepth}
255
-
256
- ## Table of Contents
257
- <!-- TOC: Auto-updated after each round/phase. Links to major sections. -->
258
- - [Analysis Context](#analysis-context)
259
- - [Current Understanding](#current-understanding)
260
- - [Discussion Timeline](#discussion-timeline)
261
- - [Decision Trail](#decision-trail)
262
-
263
- ## Current Understanding
264
- <!-- REPLACEABLE BLOCK: Overwrite (not append) after each round with latest consolidated understanding.
265
- Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state. -->
266
-
267
- > To be populated after exploration.
268
-
269
- ## Analysis Context
270
- - Focus areas: ${focusAreas.join(', ')}
271
- - Perspectives: ${selectedPerspectives.map(p => p.name).join(', ')}
272
- - Depth: ${analysisDepth}
273
-
274
- ## Initial Questions
275
- ${generateInitialQuestions(topic, dimensions).map(q => `- ${q}`).join('\n')}
276
-
277
- ## Initial Decisions
278
- > Record why these dimensions and focus areas were selected.
279
-
280
- ---
281
-
282
- ## Discussion Timeline
283
-
284
- > Rounds will be appended below as analysis progresses.
285
- > Each round MUST include a Decision Log section for any decisions made.
286
-
287
- ---
288
-
289
- ## Decision Trail
290
-
291
- > Consolidated critical decisions across all rounds (populated in Phase 4).
292
- `
293
- Write(`${sessionFolder}/discussion.md`, discussionMd)
294
- ```
295
-
296
- **Success Criteria**:
297
- - Session folder created with discussion.md initialized
298
- - Analysis dimensions identified
299
- - User preferences captured (focus, perspectives, depth)
300
- - **Initial decisions recorded**: Dimension selection rationale, excluded dimensions with reasons, user preference intent
301
-
302
- ### Phase 2: Exploration
303
-
304
- **Objective**: Gather codebase context and execute analysis to build understanding. All exploration done inline — no agent delegation.
305
-
306
- ##### Step 2.1: Detect Codebase & Explore
307
-
308
- Search the codebase directly using available tools:
309
-
310
- ```javascript
311
- const hasCodebase = Bash(`
312
- test -f package.json && echo "nodejs" ||
313
- test -f go.mod && echo "golang" ||
314
- test -f Cargo.toml && echo "rust" ||
315
- test -f pyproject.toml && echo "python" ||
316
- test -f pom.xml && echo "java" ||
317
- test -d src && echo "generic" ||
318
- echo "none"
319
- `).trim()
320
-
321
- if (hasCodebase !== 'none') {
322
- // 1. Read project metadata (if exists)
323
- // - Run `ccw spec load --category exploration` (load project specs)
324
- // - Run `ccw spec load --category debug` (known issues and root-cause notes)
325
- // - .workflow/specs/*.md (project conventions)
326
-
327
- // 2. Search codebase for relevant content
328
- // Use: Grep, Glob, Read, or mcp__ace-tool__search_context
329
- // Search based on topic keywords and identified dimensions
330
- // Focus on:
331
- // - Modules/components related to the topic
332
- // - Existing patterns and code structure
333
- // - Integration points and constraints
334
- // - Relevant configuration and dependencies
335
-
336
- // 3. Write findings
337
- Write(`${sessionFolder}/exploration-codebase.json`, JSON.stringify({
338
- project_type: hasCodebase,
339
- relevant_files: [...], // [{path, relevance, summary}]
340
- patterns: [...], // [{pattern, files, description}]
341
- constraints: [...], // Architectural constraints found
342
- integration_points: [...], // [{location, description}]
343
- key_findings: [...], // Main insights from code search
344
- _metadata: { timestamp: getUtc8ISOString(), exploration_scope: '...' }
345
- }, null, 2))
346
- }
347
- ```
348
-
349
- ##### Step 2.2: Multi-Perspective Analysis (if selected)
350
-
351
- Analyze the topic from each selected perspective. All analysis done inline by the AI.
352
-
353
- **Single perspective** (default):
354
-
355
- ```javascript
356
- // Analyze comprehensively across all identified dimensions
357
- // Use exploration-codebase.json as context
358
- // Focus on: patterns, anti-patterns, potential issues, opportunities
359
-
360
- const findings = {
361
- session_id: sessionId,
362
- timestamp: getUtc8ISOString(),
363
- topic: topic,
364
- dimensions: dimensions,
365
- sources: [...], // [{type, file, summary}]
366
- key_findings: [...], // Main insights
367
- discussion_points: [...], // Questions for user engagement
368
- open_questions: [...] // Unresolved questions
369
- }
370
- Write(`${sessionFolder}/explorations.json`, JSON.stringify(findings, null, 2))
371
- ```
372
-
373
- **Multi-perspective** (2-4 perspectives, serial):
374
-
375
- ```javascript
376
- // Analyze each perspective sequentially
377
- // For each perspective:
378
- // 1. Focus search/analysis on that perspective's concern area
379
- // 2. Generate perspective-specific insights
380
- // 3. Write individual findings
381
-
382
- selectedPerspectives.forEach(perspective => {
383
- // Analyze from this perspective's angle
384
- // Use exploration-codebase.json + dimension focus
385
- // Write to explorations/{perspective.name}.json
386
- Write(`${sessionFolder}/explorations/${perspective.name}.json`, JSON.stringify({
387
- perspective: perspective.name,
388
- relevant_files: [...],
389
- patterns: [...],
390
- key_findings: [...],
391
- perspective_insights: [...],
392
- open_questions: [...],
393
- _metadata: { timestamp: getUtc8ISOString() }
394
- }, null, 2))
395
- })
396
- ```
397
-
398
- ##### Step 2.3: Aggregate Findings
399
-
400
- ```javascript
401
- // Single perspective → explorations.json already written
402
- // Multi-perspective → synthesize into perspectives.json
403
-
404
- if (selectedPerspectives.length > 1) {
405
- const synthesis = {
406
- session_id: sessionId,
407
- timestamp: getUtc8ISOString(),
408
- topic: topic,
409
- dimensions: dimensions,
410
-
411
- // Individual perspective findings
412
- perspectives: selectedPerspectives.map(p => ({
413
- name: p.name,
414
- findings: readJson(`${sessionFolder}/explorations/${p.name}.json`).key_findings,
415
- insights: readJson(`${sessionFolder}/explorations/${p.name}.json`).perspective_insights,
416
- questions: readJson(`${sessionFolder}/explorations/${p.name}.json`).open_questions
417
- })),
418
-
419
- // Cross-perspective synthesis
420
- synthesis: {
421
- convergent_themes: [...], // What all perspectives agree on
422
- conflicting_views: [...], // Where perspectives differ
423
- unique_contributions: [...] // Insights unique to specific perspectives
424
- },
425
-
426
- aggregated_findings: [...], // Main insights across all perspectives
427
- discussion_points: [...], // Questions for user engagement
428
- open_questions: [...] // Unresolved questions
429
- }
430
- Write(`${sessionFolder}/perspectives.json`, JSON.stringify(synthesis, null, 2))
431
- }
432
- ```
433
-
434
- ##### Step 2.4: Update discussion.md
435
-
436
- Append Round 1 with exploration results:
437
-
438
- **Single perspective round 1**:
439
- - Sources analyzed (files, patterns)
440
- - Key findings with evidence
441
- - Discussion points for user
442
- - Open questions
443
-
444
- **Multi-perspective round 1**:
445
- - Per-perspective summary (brief)
446
- - Synthesis section:
447
- - Convergent themes (what all perspectives agree on)
448
- - Conflicting views (where perspectives differ)
449
- - Unique contributions (insights from specific perspectives)
450
- - Discussion points
451
- - Open questions
452
-
453
- ##### Step 2.5: Initial Intent Coverage Check
454
-
455
- Perform the FIRST intent coverage check before entering Phase 3:
456
-
457
- ```javascript
458
- // Re-read original user intent / analysis context from discussion.md header
459
- // Check each intent item against Round 1 findings
460
- // Append to discussion.md:
461
-
462
- appendToDiscussion(`
463
- #### Initial Intent Coverage Check (Post-Exploration)
464
- ${originalIntents.map((intent, i) => {
465
- const status = assessCoverage(intent, explorationFindings)
466
- return `- ${status.icon} Intent ${i+1}: ${intent} — ${status.detail}`
467
- }).join('\n')}
468
-
469
- > 接下来的讨论将重点关注未覆盖 (❌) 和进行中 (🔄) 的意图。
470
- `)
471
-
472
- // Present to user at beginning of Phase 3 for early course correction
473
- ```
474
-
475
- **Success Criteria**:
476
- - exploration-codebase.json created with codebase context (if codebase exists)
477
- - explorations.json (single) or perspectives.json (multi) created with findings
478
- - discussion.md updated with Round 1 results
479
- - **Initial Intent Coverage Check** completed — early drift detection before interactive rounds
480
- - Ready for interactive discussion
481
- - **Key findings recorded** with evidence references and confidence levels
482
- - **Exploration decisions recorded** (why certain perspectives/search strategies were chosen)
483
-
484
- ### Phase 3: Interactive Discussion
485
-
486
- **Objective**: Iteratively refine understanding through multi-round user-guided discussion cycles.
487
-
488
- **Max Rounds**: 5 discussion rounds (can exit earlier if user indicates analysis is complete)
489
-
490
- ##### Step 3.1: Current Understanding Summary & Present Findings
491
-
492
- **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
493
- - Generate 1-2 sentence recap of established consensus and last round's direction
494
- - Example: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
495
- - Purpose: Reset context, prevent cognitive overload, make incremental progress visible
496
-
497
- Display current understanding and gather user direction:
498
-
499
- ```javascript
500
- // Round >= 2: Display Current Understanding Summary first
501
- if (round >= 2) {
502
- // Generate 1-2 sentence recap from previous round's narrative synthesis
503
- // Display before presenting new findings
504
- }
505
-
506
- // Display current findings summary from explorations.json or perspectives.json
507
- // Show key points, discussion points, open questions
508
-
509
- if (!autoYes) {
510
- const feedback = AskUserQuestion({
511
- questions: [{
512
- question: `Analysis round ${round}: Feedback on current findings?`,
513
- header: "Direction",
514
- multiSelect: false,
515
- options: [
516
- { label: "Deepen", description: "Analysis direction is correct, investigate deeper" },
517
- { label: "Agree & Suggest", description: "Agree with direction, but have specific next step in mind" },
518
- { label: "Adjust Direction", description: "Different understanding or focus needed" },
519
- { label: "Specific Questions", description: "Have specific questions to ask" },
520
- { label: "Analysis Complete", description: "Sufficient information obtained, proceed to synthesis" }
521
- ]
522
- }]
523
- })
524
- }
525
- ```
526
-
527
- ##### Step 3.2: Process User Response
528
-
529
- **Recording Checkpoint**: Regardless of which option the user selects, the following MUST be recorded to discussion.md:
530
- - User's original choice and expression
531
- - Impact of this choice on analysis direction
532
- - If direction changed, record a full Decision Record
533
-
534
- **Deepen** continue analysis in current direction:
535
- ```javascript
536
- // Generate deepen direction options dynamically:
537
- // - 2-3 context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions
538
- // - 1-2 heuristic options that break current frame:
539
- // e.g., "compare with best practices in [related domain]",
540
- // "analyze under extreme load scenarios",
541
- // "review from security audit perspective",
542
- // "explore simpler architectural alternatives"
543
- // AskUserQuestion with generated options (single-select)
544
- // Execute selected direction via inline search tools
545
- // Merge new findings into explorations.json
546
- // Record: Which assumptions were confirmed, specific angles for deeper exploration
547
- ```
548
-
549
- **Agree & Suggest** — user provides specific next step:
550
- ```javascript
551
- // Ask user for their specific direction (free text input)
552
- const userSuggestion = AskUserQuestion({
553
- questions: [{
554
- question: "请描述您希望下一步深入的方向:",
555
- header: "Your Direction",
556
- multiSelect: false,
557
- options: [/* user will select "Other" to type free text */]
558
- }]
559
- })
560
- // Execute user's specific direction via inline search tools
561
- // Record: User-driven exploration rationale and findings
562
- ```
563
-
564
- **Adjust Direction** — new focus area:
565
- ```javascript
566
- // Ask user for adjusted focus
567
- const adjustedFocus = AskUserQuestion({
568
- questions: [{
569
- question: "What should the new analysis focus be?",
570
- header: "New Focus",
571
- multiSelect: false,
572
- options: [
573
- { label: "Code Details", description: "Deeper into implementation specifics" },
574
- { label: "Architecture", description: "Broader structural analysis" },
575
- { label: "Best Practices", description: "Industry standards and recommendations" }
576
- ]
577
- }]
578
- })
579
-
580
- // Analyze from adjusted perspective using inline search
581
- // Compare new insights with prior analysis
582
- // Identify what was missed and why
583
- // Update explorations.json with adjusted findings
584
- // Record Decision: Trigger reason for direction adjustment, old vs new direction, expected impact
585
- ```
586
-
587
- **Specific Questions** — answer directly:
588
- ```javascript
589
- // Capture user questions via AskUserQuestion (text input)
590
- // Answer each question based on codebase search and analysis
591
- // Provide evidence and file references
592
- // Rate confidence for each answer (high/medium/low)
593
- // Document Q&A in discussion.md
594
- // Record: Knowledge gaps revealed by the question, new understanding from the answer
595
- ```
596
-
597
- **Analysis Complete** — exit loop, proceed to Phase 4.
598
- ```javascript
599
- // Record: Why concluding at this round (sufficient information / scope fully focused / user satisfied)
600
- ```
601
-
602
- ##### Step 3.3: Document Each Round
603
-
604
- Update discussion.md with results from each discussion round:
605
-
606
- **Append** to Discussion Timeline:
607
-
608
- | Section | Content |
609
- |---------|---------|
610
- | User Direction | Action taken (deepen/adjust/suggest/questions) and focus area |
611
- | Decision Log | Decisions made this round using Decision Record format (with rejected alternatives) |
612
- | Key Findings | Findings using Key Finding Record format (with confidence + hypothesis impact) |
613
- | Analysis Results | Detailed insights, evidence with file references |
614
- | Corrected Assumptions | Important wrong→right transformations with explanation |
615
- | Open Items | Remaining questions or areas for future investigation |
616
- | **Narrative Synthesis** | Round-end summary connecting this round to overall understanding evolution |
617
-
618
- **Replace** (not append) these sections:
619
-
620
- | Section | Update Rule |
621
- |---------|-------------|
622
- | `## Current Understanding` | Overwrite with latest consolidated understanding. Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state — NOT cumulative history |
623
- | `## Table of Contents` | Update links to include new Round N sections and any new headings |
624
-
625
- **Round Narrative Synthesis** (append after each round update):
626
- ```markdown
627
- ### Round N: Narrative Synthesis
628
- **起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
629
- **关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
630
- **决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
631
- **当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
632
- **遗留问题**: [remaining questions driving next round]
633
- ```
634
-
635
- **Documentation Standards**:
636
- - Clear timestamps for each round
637
- - Evidence-based findings with file references and confidence levels
638
- - Explicit tracking of assumption corrections
639
- - Organized by analysis dimension
640
- - Narrative synthesis linking rounds into coherent understanding evolution
641
-
642
- ##### Step 3.4: Intent Drift Check (every round ≥ 2, building on Phase 2 initial check)
643
-
644
- Re-read "User Intent" / "Analysis Context" from discussion.md header. Compare against the Initial Intent Coverage Check from Phase 2. For each original intent item, check updated coverage status:
645
-
646
- ```markdown
647
- #### Intent Coverage Check
648
- - ✅ Intent 1: [addressed in Round N]
649
- - 🔄 Intent 2: [in-progress, current focus]
650
- - ⚠️ Intent 3: [implicitly absorbed by X — needs explicit confirmation]
651
- - ❌ Intent 4: [not yet discussed]
652
- ```
653
-
654
- - If any item is "implicitly absorbed" (⚠️), note it explicitly in discussion.md — absorbed ≠ addressed
655
- - If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
656
-
657
- **Success Criteria**:
658
- - User feedback processed for each round
659
- - discussion.md updated with all discussion rounds
660
- - Assumptions documented and corrected
661
- - Exit condition reached (user selects complete or max rounds)
662
- - **All decision points recorded** with Decision Record format
663
- - **Direction changes documented** with before/after comparison and rationale
664
-
665
- ### Phase 4: Synthesis & Conclusion
666
-
667
- **Objective**: Consolidate insights from all discussion rounds, generate conclusions and recommendations.
668
-
669
- ##### Step 4.0: Intent Coverage Verification (MANDATORY before synthesis)
670
-
671
- Re-read all original user intent / analysis context items from discussion.md header. For EACH item, determine coverage status:
672
-
673
- - **✅ Addressed**: Explicitly discussed and concluded with clear design/recommendation
674
- - **🔀 Transformed**: Original intent evolved into a different solution — document the transformation chain
675
- - **⚠️ Absorbed**: Implicitly covered by a broader solution — flag for explicit confirmation
676
- - **❌ Missed**: Not discussed — MUST be either addressed now or explicitly listed as out-of-scope with reason
677
-
678
- Write "Intent Coverage Matrix" to discussion.md:
679
-
680
- ```markdown
681
- ### Intent Coverage Matrix
682
- | # | Original Intent | Status | Where Addressed | Notes |
683
- |---|----------------|--------|-----------------|-------|
684
- | 1 | [intent text] | ✅ Addressed | Round N, Conclusion #M | |
685
- | 2 | [intent text] | 🔀 Transformed | Round N → Round M | Original: X → Final: Y |
686
- | 3 | [intent text] | ❌ Missed | — | Reason for omission |
687
- ```
688
-
689
- **Gate**: If any item is ❌ Missed, MUST either:
690
- - (a) Add a dedicated discussion round to address it before continuing, OR
691
- - (b) Explicitly confirm with user that it is intentionally deferred
692
-
693
- ##### Step 4.1: Consolidate Insights
694
-
695
- ```javascript
696
- const conclusions = {
697
- session_id: sessionId,
698
- topic: topic,
699
- completed: getUtc8ISOString(),
700
- total_rounds: roundCount,
701
- summary: '...', // Executive summary
702
- key_conclusions: [ // Main conclusions
703
- { point: '...', evidence: '...', confidence: 'high|medium|low' }
704
- ],
705
- recommendations: [ // Actionable recommendations
706
- {
707
- action: '...', // What to do (imperative verb + target)
708
- rationale: '...', // Why this matters
709
- priority: 'high|medium|low',
710
- evidence_refs: ['file:line', ...], // Supporting evidence locations
711
- steps: [ // Granular sub-steps for execution
712
- { description: '...', target: 'file/module', verification: 'how to verify done' }
713
- ],
714
- review_status: 'accepted|modified|rejected|pending' // Set during Phase 4 review
715
- }
716
- ],
717
- open_questions: [...], // Unresolved questions
718
- follow_up_suggestions: [ // Next steps
719
- { type: 'issue|task|research', summary: '...' }
720
- ],
721
- decision_trail: [ // Consolidated decisions from all phases
722
- { round: 1, decision: '...', context: '...', options_considered: [...], chosen: '...', rejected_reasons: '...', reason: '...', impact: '...' }
723
- ],
724
- narrative_trail: [ // From Step 3.3 Narrative Synthesis
725
- { round: 1, starting_point: '...', key_progress: '...', hypothesis_impact: '...', updated_understanding: '...', remaining_questions: '...' }
726
- ],
727
- intent_coverage: [ // From Step 4.0
728
- { intent: '...', status: 'addressed|transformed|absorbed|missed', where_addressed: '...', notes: '...' }
729
- ]
730
- }
731
- Write(`${sessionFolder}/conclusions.json`, JSON.stringify(conclusions, null, 2))
732
- ```
733
-
734
- ##### Step 4.2: Final discussion.md Update
735
-
736
- Append conclusions section and finalize:
737
-
738
- **Synthesis & Conclusions Section**:
739
- - **Executive Summary**: Overview of analysis findings
740
- - **Key Conclusions**: Ranked by confidence level with supporting evidence
741
- - **Recommendations**: Prioritized action items with rationale
742
- - **Remaining Open Questions**: Unresolved items for future work
743
-
744
- **Current Understanding (Final) Section**:
745
-
746
- | Subsection | Content |
747
- |------------|---------|
748
- | What We Established | Confirmed points and validated findings |
749
- | What Was Clarified | Important corrections (~~wrong→right~~) |
750
- | Key Insights | Valuable learnings for future reference |
751
-
752
- **Decision Trail Section**:
753
-
754
- | Subsection | Content |
755
- |------------|---------|
756
- | Critical Decisions | Pivotal decisions that shaped the analysis outcome |
757
- | Direction Changes | Timeline of scope/focus adjustments with rationale |
758
- | Trade-offs Made | Key trade-offs and why certain paths were chosen |
759
-
760
- **Session Statistics**: Total discussion rounds, key findings count, dimensions covered, artifacts generated, **decision count**.
761
-
762
- ##### Step 4.3: Interactive Recommendation Review (skip in auto mode)
763
-
764
- Walk through each recommendation one-by-one for user confirmation before proceeding:
765
-
766
- ```javascript
767
- // Order recommendations by priority: high → medium → low
768
- const sortedRecs = conclusions.recommendations.sort(byPriority)
769
-
770
- for (const [index, rec] of sortedRecs.entries()) {
771
- // 1. Present recommendation details
772
- // Display: action, rationale, priority, steps[] (numbered sub-steps with target + verification)
773
-
774
- // 2. Gather user review
775
- const review = AskUserQuestion({
776
- questions: [{
777
- question: `Recommendation #${index + 1}: "${rec.action}" (${rec.priority} priority, ${rec.steps.length} steps). Your decision:`,
778
- header: `Rec #${index + 1}`,
779
- multiSelect: false,
780
- options: [
781
- { label: "Accept", description: "Accept this recommendation as-is" },
782
- { label: "Modify", description: "Adjust scope, steps, or priority" },
783
- { label: "Reject", description: "Remove this recommendation" },
784
- { label: "Accept All Remaining", description: "Skip review for remaining recommendations" }
785
- ]
786
- }]
787
- })
788
-
789
- // 3. Process review decision
790
- // Accept → rec.review_status = "accepted"
791
- // Modify → gather modification via free text update rec → rec.review_status = "modified"
792
- // Rejectgather reason rec.review_status = "rejected"
793
- // Accept All Remaining → mark all remaining as "accepted", break loop
794
-
795
- // 4. Record review decision to discussion.md Decision Log
796
- // 5. Update conclusions.json
797
- }
798
-
799
- // Display review summary:
800
- // Accepted: N | Modified: N | Rejected: N
801
- // Only accepted/modified recommendations proceed to next step
802
- ```
803
-
804
- **Review Summary Format** (append to discussion.md):
805
- ```markdown
806
- ### Recommendation Review Summary
807
- | # | Action | Priority | Steps | Review Status | Notes |
808
- |---|--------|----------|-------|---------------|-------|
809
- | 1 | [action] | high | 3 | Accepted | |
810
- | 2 | [action] | medium | 2 | ✏️ Modified | [modification notes] |
811
- | 3 | [action] | low | 1 | ❌ Rejected | [reason] |
812
- ```
813
-
814
- ##### Step 4.4: Post-Completion Options
815
-
816
- **Complexity Assessment** — determine available options:
817
-
818
- ```javascript
819
- // Assess recommendation complexity to decide available options
820
- const recs = conclusions.recommendations || []
821
- const complexity = assessComplexity(recs)
822
-
823
- function assessComplexity(recs) {
824
- if (recs.length === 0) return 'none'
825
- if (recs.length <= 2 && recs.every(r => r.priority === 'low')) return 'simple'
826
- if (recs.length >= 3 || recs.some(r => r.priority === 'high')) return 'complex'
827
- return 'moderate' // 1-2 medium-priority recommendations
828
- }
829
-
830
- // Complexity available options mapping:
831
- // none: Done | Create Issue | Export Report
832
- // simple: Done | Create Issue | Export Report
833
- // moderate: Generate Plan | Create Issue | Export Report | Done
834
- // complex: Generate Plan | Create Issue | Export Report | Done
835
- ```
836
-
837
- ```javascript
838
- if (!autoYes) {
839
- const options = buildOptionsForComplexity(complexity)
840
- AskUserQuestion({
841
- questions: [{
842
- question: `Analysis complete (${recs.length} recommendations, complexity: ${complexity}). Next step:`,
843
- header: "Next Step",
844
- multiSelect: false,
845
- options: options
846
- }]
847
- })
848
- } else {
849
- // Auto mode: generate plan only for moderate/complex, skip for simple/none
850
- if (complexity === 'complex' || complexity === 'moderate') {
851
- // Phase 5 (plan generation only, NO code modifications)
852
- } else {
853
- // → Done (conclusions.json is sufficient output)
854
- }
855
- }
856
- ```
857
-
858
- **Options by Complexity**:
859
-
860
- | Complexity | Available Options | Rationale |
861
- |------------|-------------------|-----------|
862
- | `none` | Done, Create Issue, Export Report | No actionable recommendations |
863
- | `simple` | Done, Create Issue, Export Report | 1-2 low-priority items don't warrant formal task JSON |
864
- | `moderate` | Generate Plan, Create Issue, Export Report, Done | Task structure helpful for downstream execution |
865
- | `complex` | Generate Plan, Create Issue, Export Report, Done | Full plan generation justified |
866
-
867
- | Selection | Action |
868
- |-----------|--------|
869
- | Generate Plan | Jump to Phase 5 (plan generation only, NO code modifications) |
870
- | Create Issue | `Skill(skill="issue:new", args="...")` (only reviewed recs) |
871
- | Export Report | Copy discussion.md + conclusions.json to user-specified location |
872
- | Done | Display artifact paths, end |
873
-
874
- **Success Criteria**:
875
- - conclusions.json created with complete synthesis
876
- - discussion.md finalized with conclusions and decision trail
877
- - **Intent Coverage Matrix** verified all original intents accounted for (no ❌ Missed without explicit user deferral)
878
- - User offered meaningful next step options
879
- - **Complete decision trail** documented and traceable from initial scoping to final conclusions
880
-
881
- ### Phase 5: Plan Generation (Optional — NO code modifications)
882
-
883
- **Objective**: Generate structured plan checklist from analysis recommendations. **This phase produces plans only — it does NOT modify any source code.**
884
-
885
- **Trigger**: User selects "Generate Plan" in Phase 4. In auto mode, triggered only for `moderate`/`complex` recommendations.
886
-
887
- ```javascript
888
- const recs = conclusions.recommendations || []
889
-
890
- // Build plan checklist from all accepted/modified recommendations
891
- const planChecklist = recs
892
- .filter(r => r.review_status !== 'rejected')
893
- .map((rec, index) => {
894
- const files = rec.evidence_refs
895
- ?.filter(ref => ref.includes(':'))
896
- .map(ref => ref.split(':')[0]) || []
897
-
898
- return `### ${index + 1}. ${rec.action}
899
- - **Priority**: ${rec.priority}
900
- - **Rationale**: ${rec.rationale}
901
- - **Target files**: ${files.join(', ') || 'TBD'}
902
- - **Evidence**: ${rec.evidence_refs?.join(', ') || 'N/A'}
903
- - [ ] Ready for execution`
904
- }).join('\n\n')
905
-
906
- // Append plan checklist to discussion.md
907
- appendToDiscussion(`
908
- ## Plan Checklist
909
-
910
- > **This is a plan only — no code was modified.**
911
- > To execute, use: \`$csv-wave-pipeline "<requirement summary>"\`
912
-
913
- - **Recommendations**: ${recs.length}
914
- - **Generated**: ${getUtc8ISOString()}
915
-
916
- ${planChecklist}
917
-
918
- ---
919
-
920
- ### Next Step: Execute
921
-
922
- Run \`$csv-wave-pipeline\` to execute these recommendations as wave-based batch tasks:
923
-
924
- \`\`\`bash
925
- $csv-wave-pipeline "${topic}"
926
- \`\`\`
927
- `)
928
- ```
929
-
930
- **Characteristics**:
931
- - Plan checklist appended directly to `discussion.md`
932
- - **No code modifications** plan output only
933
- - Reminds user to use `$csv-wave-pipeline` for execution
934
-
935
- **Success Criteria**:
936
- - Plan checklist in discussion.md with all accepted recommendations
937
- - User reminded about `$csv-wave-pipeline` for execution
938
- - **No source code modified** — strictly plan output
939
-
940
- ## Output Structure
941
-
942
- ```
943
- {projectRoot}/.workflow/.analysis/ANL-{slug}-{date}/
944
- ├── discussion.md # Evolution of understanding & discussions
945
- ├── exploration-codebase.json # Phase 2: Codebase context
946
- ├── explorations/ # Phase 2: Multi-perspective explorations (if selected)
947
- │ ├── technical.json
948
- ├── architectural.json
949
- │ └── ...
950
- ├── explorations.json # Phase 2: Single perspective aggregated findings
951
- ├── perspectives.json # Phase 2: Multi-perspective findings with synthesis
952
- └── conclusions.json # Phase 4: Final synthesis with recommendations
953
- ```
954
-
955
- > **Phase 5** appends a plan checklist to `discussion.md`. No additional files are generated.
956
-
957
- | File | Phase | Description |
958
- |------|-------|-------------|
959
- | `discussion.md` | 1-5 | Session metadata discussion timeline conclusions. Plan checklist appended here (simple path). |
960
- | `exploration-codebase.json` | 2 | Codebase context: relevant files, patterns, constraints |
961
- | `explorations/*.json` | 2 | Per-perspective exploration results (multi only) |
962
- | `explorations.json` | 2 | Single perspective aggregated findings |
963
- | `perspectives.json` | 2 | Multi-perspective findings with cross-perspective synthesis |
964
- | `conclusions.json` | 4 | Final synthesis: conclusions, recommendations, open questions |
965
-
966
- ## Analysis Dimensions Reference
967
-
968
- Dimensions guide the scope and focus of analysis:
969
-
970
- | Dimension | Keywords | Description |
971
- |-----------|----------|-------------|
972
- | architecture | 架构, architecture, design, structure, 设计, pattern | System design, component interactions, design patterns |
973
- | implementation | 实现, implement, code, coding, 代码, logic | Code patterns, implementation details, algorithms |
974
- | performance | 性能, performance, optimize, bottleneck, 优化, speed | Bottlenecks, optimization opportunities, resource usage |
975
- | security | 安全, security, auth, permission, 权限, vulnerability | Vulnerabilities, authentication, access control |
976
- | concept | 概念, concept, theory, principle, 原理, understand | Foundational ideas, principles, theory |
977
- | comparison | 比较, compare, vs, difference, 区别, versus | Comparing solutions, evaluating alternatives |
978
- | decision | 决策, decision, choice, tradeoff, 选择, trade-off | Trade-offs, impact analysis, decision rationale |
979
-
980
- ## Analysis Perspectives
981
-
982
- Optional multi-perspective analysis (single perspective is default, max 4):
983
-
984
- | Perspective | Focus | Best For |
985
- |------------|-------|----------|
986
- | **Technical** | Implementation patterns, code structure, technical feasibility | Understanding how and technical details |
987
- | **Architectural** | System design, scalability, component interactions | Understanding structure and organization |
988
- | **Security** | Security patterns, vulnerabilities, access control | Identifying security risks |
989
- | **Performance** | Bottlenecks, optimization, resource utilization | Finding performance issues |
990
-
991
- **Selection**: User can multi-select up to 4 perspectives in Phase 1, or default to single comprehensive view.
992
-
993
- ### Analysis Depth Levels
994
-
995
- | Depth | Scope | Description |
996
- |-------|-------|-------------|
997
- | Quick | Surface level understanding | Fast overview, minimal exploration |
998
- | Standard | Moderate depth with good coverage | Balanced analysis (default) |
999
- | Deep | Comprehensive detailed analysis | Thorough multi-round investigation |
1000
-
1001
- ## Dimension-Direction Mapping
1002
-
1003
- When user selects focus areas, generate directions dynamically from detected dimensions:
1004
-
1005
- | Dimension | Possible Directions |
1006
- |-----------|-------------------|
1007
- | architecture | System Design, Component Interactions, Technology Choices, Integration Points, Design Patterns, Scalability Strategy |
1008
- | implementation | Code Structure, Implementation Details, Code Patterns, Error Handling, Testing Approach, Algorithm Analysis |
1009
- | performance | Performance Bottlenecks, Optimization Opportunities, Resource Utilization, Caching Strategy, Concurrency Issues |
1010
- | security | Security Vulnerabilities, Authentication/Authorization, Access Control, Data Protection, Input Validation |
1011
- | concept | Conceptual Foundation, Core Mechanisms, Fundamental Patterns, Theory & Principles, Trade-offs & Reasoning |
1012
- | comparison | Solution Comparison, Pros & Cons Analysis, Technology Evaluation, Approach Differences |
1013
- | decision | Decision Criteria, Trade-off Analysis, Risk Assessment, Impact Analysis, Implementation Implications |
1014
-
1015
- **Implementation**: Present 2-3 top dimension-related directions, allow user to multi-select and add custom directions.
1016
-
1017
- ## Consolidation Rules
1018
-
1019
- When updating "Current Understanding" in discussion.md:
1020
-
1021
- | Rule | Description |
1022
- |------|-------------|
1023
- | Promote confirmed insights | Move validated findings to "What We Established" |
1024
- | Track corrections | Keep important wrong→right transformations |
1025
- | Focus on current state | What do we know NOW, not the journey |
1026
- | Avoid timeline repetition | Don't copy discussion details into consolidated section |
1027
- | Preserve key learnings | Keep insights valuable for future reference |
1028
-
1029
- **Example**:
1030
-
1031
- Bad (cluttered):
1032
- ```markdown
1033
- ## Current Understanding
1034
- In round 1 we discussed X, then in round 2 user said Y...
1035
- ```
1036
-
1037
- Good (consolidated):
1038
- ```markdown
1039
- ## Current Understanding
1040
-
1041
- ### What We Established
1042
- - The authentication flow uses JWT with refresh tokens
1043
- - Rate limiting is implemented at API gateway level
1044
-
1045
- ### What Was Clarified
1046
- - ~~Assumed Redis for sessions~~ → Actually uses database-backed sessions
1047
-
1048
- ### Key Insights
1049
- - Current architecture supports horizontal scaling
1050
- ```
1051
-
1052
- ## Templates
1053
-
1054
- ### discussion.md Structure
1055
-
1056
- The discussion.md file evolves through the analysis:
1057
-
1058
- - **Header**: Session ID, topic, start time, identified dimensions
1059
- - **Analysis Context**: Focus areas, perspectives, depth level
1060
- - **Initial Questions**: Key questions to guide the analysis
1061
- - **Initial Decisions**: Why these dimensions and focus areas were selected
1062
- - **Discussion Timeline**: Round-by-round findings with narrative synthesis
1063
- - Round 1: Initial Understanding + Exploration Results + **Initial Decision Log** + **Narrative Synthesis**
1064
- - Round 2-N: Current Understanding Summary + User feedback + direction adjustments + new insights + **Decision Log** + **Key Findings** + **Narrative Synthesis**
1065
- - **Decision Trail**: Consolidated critical decisions across all rounds
1066
- - **Synthesis & Conclusions**: Summary, key conclusions, recommendations
1067
- - **Current Understanding (Final)**: Consolidated insights
1068
- - **Session Statistics**: Rounds completed, findings count, artifacts generated, decision count
1069
-
1070
- ### Round Documentation Pattern
1071
-
1072
- Each discussion round follows a consistent structure:
1073
-
1074
- ```markdown
1075
- ### Round N - [Deepen|Adjust|Suggest|Q&A] (timestamp)
1076
-
1077
- #### User Input
1078
- What the user indicated they wanted to focus on
1079
-
1080
- #### Decision Log
1081
- > **Decision**: [Description of direction/scope/approach decision made this round]
1082
- > - **Context**: [What triggered this decision]
1083
- > - **Options considered**: [Alternatives evaluated]
1084
- > - **Chosen**: [Selected approach] **Reason**: [Rationale]
1085
- > - **Rejected**: [Why other options were discarded]
1086
- > - **Impact**: [Effect on analysis direction/conclusions]
1087
-
1088
- #### Key Findings
1089
- > **Finding**: [Content]
1090
- > - **Confidence**: [High/Medium/Low] **Why**: [Evidence basis]
1091
- > - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
1092
- > - **Scope**: [What areas this affects]
1093
-
1094
- #### Analysis Results
1095
- Detailed findings from this round's analysis
1096
- - Finding 1 (evidence: file:line)
1097
- - Finding 2 (evidence: file:line)
1098
-
1099
- #### Corrected Assumptions
1100
- - ~~Previous assumption~~ Corrected understanding
1101
- - Reason: Why the assumption was wrong
1102
-
1103
- #### Open Items
1104
- Remaining questions or areas for investigation
1105
-
1106
- #### Narrative Synthesis
1107
- **起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
1108
- **关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
1109
- **决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]
1110
- **当前理解**: 经过本轮,核心认知更新为 [updated understanding]
1111
- **遗留问题**: [remaining questions driving next round]
1112
- ```
1113
-
1114
- ## Error Handling
1115
-
1116
- | Situation | Action | Recovery |
1117
- |-----------|--------|----------|
1118
- | No codebase detected | Normal flow, pure topic analysis | Proceed without exploration-codebase.json |
1119
- | Codebase search fails | Continue with available context | Note limitation in discussion.md |
1120
- | No relevant findings | Broaden search keywords | Ask user for clarification |
1121
- | User timeout in discussion | Save state, show resume command | Use `--continue` to resume |
1122
- | Max rounds reached (5) | Force synthesis phase | Highlight remaining questions in conclusions |
1123
- | Session folder conflict | Append timestamp suffix | Create unique folder and continue |
1124
- | Plan generation: no recommendations | No plan to generate | Inform user, suggest lite-plan |
1125
-
1126
- ## Best Practices
1127
-
1128
- ### Core Principles
1129
-
1130
- 1. **No code modifications**: This skill is strictly read-only and plan-only. Phase 5 generates plan checklists in `discussion.md` but does NOT modify source code. Use `$csv-wave-pipeline` for execution.
1131
-
1132
- ### Before Starting Analysis
1133
-
1134
- 1. **Clear Topic Definition**: Detailed topics lead to better dimension identification
1135
- 2. **User Context**: Understanding focus preferences helps scope the analysis
1136
- 3. **Perspective Selection**: Choose 2-4 perspectives for complex topics, single for focused queries
1137
- 4. **Scope Understanding**: Being clear about depth expectations sets correct analysis intensity
1138
-
1139
- ### During Analysis
1140
-
1141
- 1. **Review Findings**: Check exploration results before proceeding to discussion
1142
- 2. **Document Assumptions**: Track what you think is true for correction later
1143
- 3. **Use Continue Mode**: Resume sessions to build on previous findings rather than starting over
1144
- 4. **Embrace Corrections**: Track wrong→right transformations as valuable learnings
1145
- 5. **Iterate Thoughtfully**: Each discussion round should meaningfully refine understanding
1146
- 6. **Record Decisions Immediately**: Never defer recording — capture decisions as they happen using the Decision Record format. A decision not recorded in-the-moment is a decision lost
1147
-
1148
- ### Documentation Practices
1149
-
1150
- 1. **Evidence-Based**: Every conclusion should reference specific code or patterns
1151
- 2. **Confidence Levels**: Indicate confidence (high/medium/low) for conclusions
1152
- 3. **Timeline Clarity**: Use clear timestamps for traceability
1153
- 4. **Evolution Tracking**: Document how understanding changed across rounds
1154
- 5. **Action Items**: Generate specific, actionable recommendations
1155
- 6. **Multi-Perspective Synthesis**: When using multiple perspectives, document convergent/conflicting themes
1156
- 7. **Link Decisions to Outcomes**: When writing conclusions, explicitly reference which decisions led to which outcomes — this creates an auditable trail from initial scoping to final recommendations
1157
-
1158
- ## When to Use
1159
-
1160
- **Use analyze-with-file when:**
1161
- - Exploring complex topics collaboratively with documented trail
1162
- - Need multi-round iterative refinement of understanding
1163
- - Decision-making requires exploring multiple perspectives
1164
- - Building shared understanding before implementation
1165
- - Want to document how understanding evolved
1166
-
1167
- **Use Plan Generation (Phase 5) when:**
1168
- - Analysis conclusions contain clear, actionable recommendations
1169
- - Simple: 1-2 itemsinline plan checklist in discussion.md
1170
- - Complex: 3+ recommendations detailed plan checklist
1171
- - **Then execute via**: `$csv-wave-pipeline` for wave-based batch execution
1172
-
1173
- **Consider alternatives when:**
1174
- - Specific bug diagnosis needed → use `debug-with-file`
1175
- - Generating new ideas/solutions → use `brainstorm-with-file`
1176
- - Complex planning with parallel perspectives → use `collaborative-plan-with-file`
1177
- - Ready to implement → use `lite-plan`
1178
- - Requirement decomposition needed → use `req-plan-with-file`
1179
-
1180
- ---
1181
-
1182
- **Now execute the analyze-with-file workflow for topic**: $TOPIC
1
+ ---
2
+ name: analyze-with-file
3
+ description: Interactive collaborative analysis with documented discussions, inline exploration, and evolving understanding. Serial execution with no agent delegation.
4
+ argument-hint: "TOPIC=\"<question or topic>\" [--depth=quick|standard|deep] [--continue]"
5
+ ---
6
+
7
+ # Codex Analyze-With-File Prompt
8
+
9
+ ## Overview
10
+
11
+ Interactive collaborative analysis workflow with **documented discussion process**. Records understanding evolution, facilitates multi-round Q&A, and uses inline search tools for deep exploration.
12
+
13
+ **Core workflow**: Topic → Explore → Discuss → Document → Refine → Conclude → Plan Checklist
14
+
15
+ **Key features**:
16
+ - **Documented discussion timeline**: Captures understanding evolution across all phases
17
+ - **Decision recording at every critical point**: Mandatory recording of key findings, direction changes, and trade-offs
18
+ - **Multi-perspective analysis**: Supports up to 4 analysis perspectives (serial, inline)
19
+ - **Interactive discussion**: Multi-round Q&A with user feedback and direction adjustments
20
+ - **Plan output**: Generate structured plan checklist for downstream execution (e.g., `$csv-wave-pipeline`)
21
+
22
+ ### Decision Recording Protocol
23
+
24
+ **CRITICAL**: During analysis, the following situations **MUST** trigger immediate recording to discussion.md:
25
+
26
+ | Trigger | What to Record | Target Section |
27
+ |---------|---------------|----------------|
28
+ | **Direction choice** | What was chosen, why, what alternatives were discarded | `#### Decision Log` |
29
+ | **Key finding** | Finding content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
30
+ | **Assumption change** | Old assumption → new understanding, reason, impact | `#### Corrected Assumptions` |
31
+ | **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` |
32
+ | **Disagreement & trade-off** | Conflicting viewpoints, trade-off basis, final choice | `#### Decision Log` |
33
+ | **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` |
34
+
35
+ **Decision Record Format**:
36
+ ```markdown
37
+ > **Decision**: [Description of the decision]
38
+ > - **Context**: [What triggered this decision]
39
+ > - **Options considered**: [Alternatives evaluated]
40
+ > - **Chosen**: [Selected approach] — **Reason**: [Rationale]
41
+ > - **Rejected**: [Why other options were discarded]
42
+ > - **Impact**: [Effect on analysis direction/conclusions]
43
+ ```
44
+
45
+ **Key Finding Record Format**:
46
+ ```markdown
47
+ > **Finding**: [Content]
48
+ > - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
49
+ > - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
50
+ > - **Scope**: [What areas this affects]
51
+ ```
52
+
53
+ **Recording Principles**:
54
+ - **Immediacy**: Record decisions as they happen, not at the end of a phase
55
+ - **Completeness**: Capture context, options, chosen approach, reason, and rejected alternatives
56
+ - **Traceability**: Later phases must be able to trace back why a decision was made
57
+ - **Depth**: Capture reasoning and hypothesis impact, not just outcomes
58
+
59
+ ## Auto Mode
60
+
61
+ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles, skip interactive scoping.
62
+
63
+ ## Quick Start
64
+
65
+ ```bash
66
+ # Basic usage
67
+ /codex:analyze-with-file TOPIC="How to optimize this project's authentication architecture"
68
+
69
+ # With depth selection
70
+ /codex:analyze-with-file TOPIC="Performance bottleneck analysis" --depth=deep
71
+
72
+ # Continue existing session
73
+ /codex:analyze-with-file TOPIC="authentication architecture" --continue
74
+
75
+ # Auto mode (skip confirmations)
76
+ /codex:analyze-with-file -y TOPIC="Caching strategy analysis"
77
+ ```
78
+
79
+ ## Target Topic
80
+
81
+ **$TOPIC**
82
+
83
+ ## Analysis Flow
84
+
85
+ ```
86
+ Step 0: Session Setup
87
+ ├─ Parse topic, flags (--depth, --continue, -y)
88
+ ├─ Generate session ID: ANL-{slug}-{date}
89
+ └─ Create session folder (or detect existing → continue mode)
90
+
91
+ Step 1: Topic Understanding
92
+ ├─ Parse topic, identify analysis dimensions
93
+ ├─ Initial scoping with user (focus areas, perspectives, depth)
94
+ └─ Initialize discussion.md
95
+
96
+ Step 2: Exploration (Inline, No Agents)
97
+ ├─ Detect codebase → search relevant modules, patterns
98
+ │ ├─ Run `ccw spec load --category exploration` (if spec system available)
99
+ │ ├─ Run `ccw spec load --category debug` (known issues and root-cause notes)
100
+ │ └─ Use Grep, Glob, Read, mcp__ace-tool__search_context
101
+ ├─ Multi-perspective analysis (if selected, serial)
102
+ │ ├─ Single: Comprehensive analysis
103
+ │ └─ Multi (≤4): Serial per-perspective analysis with synthesis
104
+ ├─ Aggregate findings → explorations.json / perspectives.json
105
+ ├─ Update discussion.md with Round 1
106
+ │ ├─ Replace ## Current Understanding with initial findings
107
+ │ └─ Update ## Table of Contents
108
+ └─ Initial Intent Coverage Check (early drift detection)
109
+
110
+ Step 3: Interactive Discussion (Multi-Round, max 5)
111
+ ├─ Current Understanding Summary (round ≥ 2, before findings)
112
+ ├─ Present exploration findings
113
+ ├─ Gather user feedback
114
+ ├─ Process response:
115
+ │ ├─ Deepen → context-driven + heuristic options → deeper inline analysis
116
+ │ ├─ Agree & Suggest → user-directed exploration
117
+ │ ├─ Adjust → new inline analysis with adjusted focus
118
+ │ ├─ Questions → direct answers with evidence
119
+ │ └─ Complete → exit loop for synthesis
120
+ ├─ Update discussion.md:
121
+ │ ├─ Append round details + Narrative Synthesis
122
+ │ ├─ Replace ## Current Understanding with latest state
123
+ │ └─ Update ## Table of Contents
124
+ ├─ Intent Drift Check (round ≥ 2, building on Phase 2 initial check)
125
+ └─ Repeat until user selects complete or max rounds
126
+
127
+ Step 4: Synthesis & Conclusion
128
+ ├─ Intent Coverage Verification (mandatory gate)
129
+ ├─ Consolidate all insights → conclusions.json (with steps[] per recommendation)
130
+ ├─ Update discussion.md with final synthesis
131
+ ├─ Interactive Recommendation Review (per-recommendation confirm/modify/reject)
132
+ └─ Offer options: generate plan / create issue / export / done
133
+
134
+ Step 5: Plan Generation (Optional - produces plan only, NO code modifications)
135
+ ├─ Generate inline plan checklist → appended to discussion.md
136
+ └─ Remind user to execute via $csv-wave-pipeline
137
+ ```
138
+
139
+ ## Configuration
140
+
141
+ | Flag | Default | Description |
142
+ |------|---------|-------------|
143
+ | `-y, --yes` | false | Auto-confirm all decisions |
144
+ | `--continue` | false | Continue existing session |
145
+ | `--depth` | standard | Analysis depth: quick / standard / deep |
146
+
147
+ **Session ID format**: `ANL-{slug}-{YYYY-MM-DD}`
148
+ - slug: lowercase, alphanumeric + CJK characters, max 40 chars
149
+ - date: YYYY-MM-DD (UTC+8)
150
+ - Auto-detect continue: session folder + discussion.md exists → continue mode
151
+
152
+ ## Implementation Details
153
+
154
+ ### Session Initialization
155
+
156
+ ##### Step 0: Initialize Session
157
+
158
+ ```javascript
159
+ const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
160
+
161
+ // Parse flags
162
+ const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
163
+ const continueMode = $ARGUMENTS.includes('--continue')
164
+ const depthMatch = $ARGUMENTS.match(/--depth[=\s](quick|standard|deep)/)
165
+ const analysisDepth = depthMatch ? depthMatch[1] : 'standard'
166
+
167
+ // Extract topic
168
+ const topic = $ARGUMENTS.replace(/--yes|-y|--continue|--depth[=\s]\w+|TOPIC=/g, '').replace(/^["']|["']$/g, '').trim()
169
+
170
+ // Determine project root
171
+ const projectRoot = Bash('git rev-parse --show-toplevel 2>/dev/null || pwd').trim()
172
+
173
+ const slug = topic.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40)
174
+ const dateStr = getUtc8ISOString().substring(0, 10)
175
+ const sessionId = `ANL-${slug}-${dateStr}`
176
+ const sessionFolder = `${projectRoot}/.workflow/.analysis/${sessionId}`
177
+
178
+ // Auto-detect continue: session folder + discussion.md exists → continue mode
179
+ // If continue → load discussion.md + explorations, resume from last round
180
+ Bash(`mkdir -p ${sessionFolder}`)
181
+ ```
182
+
183
+ ### Phase 1: Topic Understanding
184
+
185
+ **Objective**: Parse the topic, identify relevant analysis dimensions, scope the analysis with user input, and initialize the discussion document.
186
+
187
+ ##### Step 1.1: Parse Topic & Identify Dimensions
188
+
189
+ Match topic keywords against analysis dimensions:
190
+
191
+ ```javascript
192
+ const ANALYSIS_DIMENSIONS = {
193
+ architecture: ['架构', 'architecture', 'design', 'structure', '设计', 'pattern'],
194
+ implementation: ['实现', 'implement', 'code', 'coding', '代码', 'logic'],
195
+ performance: ['性能', 'performance', 'optimize', 'bottleneck', '优化', 'speed'],
196
+ security: ['安全', 'security', 'auth', 'permission', '权限', 'vulnerability'],
197
+ concept: ['概念', 'concept', 'theory', 'principle', '原理', 'understand'],
198
+ comparison: ['比较', 'compare', 'vs', 'difference', '区别', 'versus'],
199
+ decision: ['决策', 'decision', 'choice', 'tradeoff', '选择', 'trade-off']
200
+ }
201
+
202
+ // Match topic text against keyword lists
203
+ // If multiple dimensions match, include all
204
+ // If none match, default to "architecture" and "implementation"
205
+ const dimensions = identifyDimensions(topic, ANALYSIS_DIMENSIONS)
206
+ ```
207
+
208
+ ##### Step 1.2: Initial Scoping (New Session Only)
209
+
210
+ For new sessions, gather user preferences (skipped in auto mode or continue mode):
211
+
212
+ ```javascript
213
+ if (!autoYes && !continueMode) {
214
+ // 1. Focus areas (multi-select)
215
+ // Generate directions dynamically from detected dimensions (see Dimension-Direction Mapping)
216
+ const focusAreas = request_user_input({
217
+ questions: [{
218
+ header: "聚焦领域",
219
+ id: "focus",
220
+ question: "Select analysis focus areas:",
221
+ options: generateFocusOptions(dimensions) // Dynamic based on dimensions
222
+ }]
223
+ })
224
+
225
+ // 2. Analysis perspectives (multi-select, max 4)
226
+ const perspectives = request_user_input({
227
+ questions: [{
228
+ header: "分析视角",
229
+ id: "perspectives",
230
+ question: "Select analysis perspectives (single = focused, multi = broader coverage):",
231
+ options: [
232
+ { label: "Technical", description: "Implementation patterns, code structure, technical feasibility" },
233
+ { label: "Architectural", description: "System design, scalability, component interactions" },
234
+ { label: "Security", description: "Vulnerabilities, authentication, access control" }
235
+ ]
236
+ }]
237
+ })
238
+
239
+ // 3. Analysis depth (single-select, unless --depth already set)
240
+ // Quick: surface level | Standard: moderate depth | Deep: comprehensive
241
+ }
242
+ ```
243
+
244
+ ##### Step 1.3: Initialize discussion.md
245
+
246
+ ```javascript
247
+ const discussionMd = `# Analysis Discussion
248
+
249
+ **Session ID**: ${sessionId}
250
+ **Topic**: ${topic}
251
+ **Started**: ${getUtc8ISOString()}
252
+ **Dimensions**: ${dimensions.join(', ')}
253
+ **Depth**: ${analysisDepth}
254
+
255
+ ## Table of Contents
256
+ <!-- TOC: Auto-updated after each round/phase. Links to major sections. -->
257
+ - [Analysis Context](#analysis-context)
258
+ - [Current Understanding](#current-understanding)
259
+ - [Discussion Timeline](#discussion-timeline)
260
+ - [Decision Trail](#decision-trail)
261
+
262
+ ## Current Understanding
263
+ <!-- REPLACEABLE BLOCK: Overwrite (not append) after each round with latest consolidated understanding.
264
+ Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state. -->
265
+
266
+ > To be populated after exploration.
267
+
268
+ ## Analysis Context
269
+ - Focus areas: ${focusAreas.join(', ')}
270
+ - Perspectives: ${selectedPerspectives.map(p => p.name).join(', ')}
271
+ - Depth: ${analysisDepth}
272
+
273
+ ## Initial Questions
274
+ ${generateInitialQuestions(topic, dimensions).map(q => `- ${q}`).join('\n')}
275
+
276
+ ## Initial Decisions
277
+ > Record why these dimensions and focus areas were selected.
278
+
279
+ ---
280
+
281
+ ## Discussion Timeline
282
+
283
+ > Rounds will be appended below as analysis progresses.
284
+ > Each round MUST include a Decision Log section for any decisions made.
285
+
286
+ ---
287
+
288
+ ## Decision Trail
289
+
290
+ > Consolidated critical decisions across all rounds (populated in Phase 4).
291
+ `
292
+ Write(`${sessionFolder}/discussion.md`, discussionMd)
293
+ ```
294
+
295
+ **Success Criteria**:
296
+ - Session folder created with discussion.md initialized
297
+ - Analysis dimensions identified
298
+ - User preferences captured (focus, perspectives, depth)
299
+ - **Initial decisions recorded**: Dimension selection rationale, excluded dimensions with reasons, user preference intent
300
+
301
+ ### Phase 2: Exploration
302
+
303
+ **Objective**: Gather codebase context and execute analysis to build understanding. All exploration done inline — no agent delegation.
304
+
305
+ ##### Step 2.1: Detect Codebase & Explore
306
+
307
+ Search the codebase directly using available tools:
308
+
309
+ ```javascript
310
+ const hasCodebase = Bash(`
311
+ test -f package.json && echo "nodejs" ||
312
+ test -f go.mod && echo "golang" ||
313
+ test -f Cargo.toml && echo "rust" ||
314
+ test -f pyproject.toml && echo "python" ||
315
+ test -f pom.xml && echo "java" ||
316
+ test -d src && echo "generic" ||
317
+ echo "none"
318
+ `).trim()
319
+
320
+ if (hasCodebase !== 'none') {
321
+ // 1. Read project metadata (if exists)
322
+ // - Run `ccw spec load --category exploration` (load project specs)
323
+ // - Run `ccw spec load --category debug` (known issues and root-cause notes)
324
+ // - .workflow/specs/*.md (project conventions)
325
+
326
+ // 2. Search codebase for relevant content
327
+ // Use: Grep, Glob, Read, or mcp__ace-tool__search_context
328
+ // Search based on topic keywords and identified dimensions
329
+ // Focus on:
330
+ // - Modules/components related to the topic
331
+ // - Existing patterns and code structure
332
+ // - Integration points and constraints
333
+ // - Relevant configuration and dependencies
334
+
335
+ // 3. Write findings
336
+ Write(`${sessionFolder}/exploration-codebase.json`, JSON.stringify({
337
+ project_type: hasCodebase,
338
+ relevant_files: [...], // [{path, relevance, summary}]
339
+ patterns: [...], // [{pattern, files, description}]
340
+ constraints: [...], // Architectural constraints found
341
+ integration_points: [...], // [{location, description}]
342
+ key_findings: [...], // Main insights from code search
343
+ _metadata: { timestamp: getUtc8ISOString(), exploration_scope: '...' }
344
+ }, null, 2))
345
+ }
346
+ ```
347
+
348
+ ##### Step 2.2: Multi-Perspective Analysis (if selected)
349
+
350
+ Analyze the topic from each selected perspective. All analysis done inline by the AI.
351
+
352
+ **Single perspective** (default):
353
+
354
+ ```javascript
355
+ // Analyze comprehensively across all identified dimensions
356
+ // Use exploration-codebase.json as context
357
+ // Focus on: patterns, anti-patterns, potential issues, opportunities
358
+
359
+ const findings = {
360
+ session_id: sessionId,
361
+ timestamp: getUtc8ISOString(),
362
+ topic: topic,
363
+ dimensions: dimensions,
364
+ sources: [...], // [{type, file, summary}]
365
+ key_findings: [...], // Main insights
366
+ discussion_points: [...], // Questions for user engagement
367
+ open_questions: [...] // Unresolved questions
368
+ }
369
+ Write(`${sessionFolder}/explorations.json`, JSON.stringify(findings, null, 2))
370
+ ```
371
+
372
+ **Multi-perspective** (2-4 perspectives, serial):
373
+
374
+ ```javascript
375
+ // Analyze each perspective sequentially
376
+ // For each perspective:
377
+ // 1. Focus search/analysis on that perspective's concern area
378
+ // 2. Generate perspective-specific insights
379
+ // 3. Write individual findings
380
+
381
+ selectedPerspectives.forEach(perspective => {
382
+ // Analyze from this perspective's angle
383
+ // Use exploration-codebase.json + dimension focus
384
+ // Write to explorations/{perspective.name}.json
385
+ Write(`${sessionFolder}/explorations/${perspective.name}.json`, JSON.stringify({
386
+ perspective: perspective.name,
387
+ relevant_files: [...],
388
+ patterns: [...],
389
+ key_findings: [...],
390
+ perspective_insights: [...],
391
+ open_questions: [...],
392
+ _metadata: { timestamp: getUtc8ISOString() }
393
+ }, null, 2))
394
+ })
395
+ ```
396
+
397
+ ##### Step 2.3: Aggregate Findings
398
+
399
+ ```javascript
400
+ // Single perspective → explorations.json already written
401
+ // Multi-perspective → synthesize into perspectives.json
402
+
403
+ if (selectedPerspectives.length > 1) {
404
+ const synthesis = {
405
+ session_id: sessionId,
406
+ timestamp: getUtc8ISOString(),
407
+ topic: topic,
408
+ dimensions: dimensions,
409
+
410
+ // Individual perspective findings
411
+ perspectives: selectedPerspectives.map(p => ({
412
+ name: p.name,
413
+ findings: readJson(`${sessionFolder}/explorations/${p.name}.json`).key_findings,
414
+ insights: readJson(`${sessionFolder}/explorations/${p.name}.json`).perspective_insights,
415
+ questions: readJson(`${sessionFolder}/explorations/${p.name}.json`).open_questions
416
+ })),
417
+
418
+ // Cross-perspective synthesis
419
+ synthesis: {
420
+ convergent_themes: [...], // What all perspectives agree on
421
+ conflicting_views: [...], // Where perspectives differ
422
+ unique_contributions: [...] // Insights unique to specific perspectives
423
+ },
424
+
425
+ aggregated_findings: [...], // Main insights across all perspectives
426
+ discussion_points: [...], // Questions for user engagement
427
+ open_questions: [...] // Unresolved questions
428
+ }
429
+ Write(`${sessionFolder}/perspectives.json`, JSON.stringify(synthesis, null, 2))
430
+ }
431
+ ```
432
+
433
+ ##### Step 2.4: Update discussion.md
434
+
435
+ Append Round 1 with exploration results:
436
+
437
+ **Single perspective round 1**:
438
+ - Sources analyzed (files, patterns)
439
+ - Key findings with evidence
440
+ - Discussion points for user
441
+ - Open questions
442
+
443
+ **Multi-perspective round 1**:
444
+ - Per-perspective summary (brief)
445
+ - Synthesis section:
446
+ - Convergent themes (what all perspectives agree on)
447
+ - Conflicting views (where perspectives differ)
448
+ - Unique contributions (insights from specific perspectives)
449
+ - Discussion points
450
+ - Open questions
451
+
452
+ ##### Step 2.5: Initial Intent Coverage Check
453
+
454
+ Perform the FIRST intent coverage check before entering Phase 3:
455
+
456
+ ```javascript
457
+ // Re-read original user intent / analysis context from discussion.md header
458
+ // Check each intent item against Round 1 findings
459
+ // Append to discussion.md:
460
+
461
+ appendToDiscussion(`
462
+ #### Initial Intent Coverage Check (Post-Exploration)
463
+ ${originalIntents.map((intent, i) => {
464
+ const status = assessCoverage(intent, explorationFindings)
465
+ return `- ${status.icon} Intent ${i+1}: ${intent} — ${status.detail}`
466
+ }).join('\n')}
467
+
468
+ > 接下来的讨论将重点关注未覆盖 (❌) 和进行中 (🔄) 的意图。
469
+ `)
470
+
471
+ // Present to user at beginning of Phase 3 for early course correction
472
+ ```
473
+
474
+ **Success Criteria**:
475
+ - exploration-codebase.json created with codebase context (if codebase exists)
476
+ - explorations.json (single) or perspectives.json (multi) created with findings
477
+ - discussion.md updated with Round 1 results
478
+ - **Initial Intent Coverage Check** completed — early drift detection before interactive rounds
479
+ - Ready for interactive discussion
480
+ - **Key findings recorded** with evidence references and confidence levels
481
+ - **Exploration decisions recorded** (why certain perspectives/search strategies were chosen)
482
+
483
+ ### Phase 3: Interactive Discussion
484
+
485
+ **Objective**: Iteratively refine understanding through multi-round user-guided discussion cycles.
486
+
487
+ **Max Rounds**: 5 discussion rounds (can exit earlier if user indicates analysis is complete)
488
+
489
+ ##### Step 3.1: Current Understanding Summary & Present Findings
490
+
491
+ **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
492
+ - Generate 1-2 sentence recap of established consensus and last round's direction
493
+ - Example: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
494
+ - Purpose: Reset context, prevent cognitive overload, make incremental progress visible
495
+
496
+ Display current understanding and gather user direction:
497
+
498
+ ```javascript
499
+ // Round >= 2: Display Current Understanding Summary first
500
+ if (round >= 2) {
501
+ // Generate 1-2 sentence recap from previous round's narrative synthesis
502
+ // Display before presenting new findings
503
+ }
504
+
505
+ // Display current findings summary from explorations.json or perspectives.json
506
+ // Show key points, discussion points, open questions
507
+
508
+ if (!autoYes) {
509
+ const feedback = request_user_input({
510
+ questions: [{
511
+ header: "分析方向",
512
+ id: "direction",
513
+ question: `Analysis round ${round}: Feedback on current findings?`,
514
+ options: [
515
+ { label: "Deepen(Recommended)", description: "Analysis direction is correct, investigate deeper" },
516
+ { label: "Adjust Direction", description: "Different understanding or focus needed" },
517
+ { label: "Analysis Complete", description: "Sufficient information obtained, proceed to synthesis" }
518
+ ]
519
+ }]
520
+ })
521
+ }
522
+ ```
523
+
524
+ ##### Step 3.2: Process User Response
525
+
526
+ **Recording Checkpoint**: Regardless of which option the user selects, the following MUST be recorded to discussion.md:
527
+ - User's original choice and expression
528
+ - Impact of this choice on analysis direction
529
+ - If direction changed, record a full Decision Record
530
+
531
+ **Deepen** continue analysis in current direction:
532
+ ```javascript
533
+ // Generate deepen direction options dynamically:
534
+ // - 2-3 context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions
535
+ // - 1-2 heuristic options that break current frame:
536
+ // e.g., "compare with best practices in [related domain]",
537
+ // "analyze under extreme load scenarios",
538
+ // "review from security audit perspective",
539
+ // "explore simpler architectural alternatives"
540
+ // request_user_input with generated options (single-select)
541
+ // Execute selected direction via inline search tools
542
+ // Merge new findings into explorations.json
543
+ // Record: Which assumptions were confirmed, specific angles for deeper exploration
544
+ ```
545
+
546
+ **Agree & Suggest** user provides specific next step:
547
+ ```javascript
548
+ // Ask user for their specific direction (free text input)
549
+ const userSuggestion = request_user_input({
550
+ questions: [{
551
+ header: "你的方向",
552
+ id: "your_direction",
553
+ question: "请描述您希望下一步深入的方向:",
554
+ options: [
555
+ { label: "Code Details", description: "Deeper into implementation specifics" },
556
+ { label: "Architecture", description: "Broader structural analysis" }
557
+ ]
558
+ }]
559
+ })
560
+ // Execute user's specific direction via inline search tools
561
+ // Record: User-driven exploration rationale and findings
562
+ ```
563
+
564
+ **Adjust Direction** — new focus area:
565
+ ```javascript
566
+ // Ask user for adjusted focus
567
+ const adjustedFocus = request_user_input({
568
+ questions: [{
569
+ header: "新焦点",
570
+ id: "new_focus",
571
+ question: "What should the new analysis focus be?",
572
+ options: [
573
+ { label: "Code Details", description: "Deeper into implementation specifics" },
574
+ { label: "Architecture", description: "Broader structural analysis" },
575
+ { label: "Best Practices", description: "Industry standards and recommendations" }
576
+ ]
577
+ }]
578
+ })
579
+
580
+ // Analyze from adjusted perspective using inline search
581
+ // Compare new insights with prior analysis
582
+ // Identify what was missed and why
583
+ // Update explorations.json with adjusted findings
584
+ // Record Decision: Trigger reason for direction adjustment, old vs new direction, expected impact
585
+ ```
586
+
587
+ **Specific Questions** — answer directly:
588
+ ```javascript
589
+ // Capture user questions via request_user_input
590
+ // Answer each question based on codebase search and analysis
591
+ // Provide evidence and file references
592
+ // Rate confidence for each answer (high/medium/low)
593
+ // Document Q&A in discussion.md
594
+ // Record: Knowledge gaps revealed by the question, new understanding from the answer
595
+ ```
596
+
597
+ **Analysis Complete** — exit loop, proceed to Phase 4.
598
+ ```javascript
599
+ // Record: Why concluding at this round (sufficient information / scope fully focused / user satisfied)
600
+ ```
601
+
602
+ ##### Step 3.3: Document Each Round
603
+
604
+ Update discussion.md with results from each discussion round:
605
+
606
+ **Append** to Discussion Timeline:
607
+
608
+ | Section | Content |
609
+ |---------|---------|
610
+ | User Direction | Action taken (deepen/adjust/suggest/questions) and focus area |
611
+ | Decision Log | Decisions made this round using Decision Record format (with rejected alternatives) |
612
+ | Key Findings | Findings using Key Finding Record format (with confidence + hypothesis impact) |
613
+ | Analysis Results | Detailed insights, evidence with file references |
614
+ | Corrected Assumptions | Important wrong→right transformations with explanation |
615
+ | Open Items | Remaining questions or areas for future investigation |
616
+ | **Narrative Synthesis** | Round-end summary connecting this round to overall understanding evolution |
617
+
618
+ **Replace** (not append) these sections:
619
+
620
+ | Section | Update Rule |
621
+ |---------|-------------|
622
+ | `## Current Understanding` | Overwrite with latest consolidated understanding. Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state — NOT cumulative history |
623
+ | `## Table of Contents` | Update links to include new Round N sections and any new headings |
624
+
625
+ **Round Narrative Synthesis** (append after each round update):
626
+ ```markdown
627
+ ### Round N: Narrative Synthesis
628
+ **起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
629
+ **关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
630
+ **决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
631
+ **当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
632
+ **遗留问题**: [remaining questions driving next round]
633
+ ```
634
+
635
+ **Documentation Standards**:
636
+ - Clear timestamps for each round
637
+ - Evidence-based findings with file references and confidence levels
638
+ - Explicit tracking of assumption corrections
639
+ - Organized by analysis dimension
640
+ - Narrative synthesis linking rounds into coherent understanding evolution
641
+
642
+ ##### Step 3.4: Intent Drift Check (every round ≥ 2, building on Phase 2 initial check)
643
+
644
+ Re-read "User Intent" / "Analysis Context" from discussion.md header. Compare against the Initial Intent Coverage Check from Phase 2. For each original intent item, check updated coverage status:
645
+
646
+ ```markdown
647
+ #### Intent Coverage Check
648
+ - ✅ Intent 1: [addressed in Round N]
649
+ - 🔄 Intent 2: [in-progress, current focus]
650
+ - ⚠️ Intent 3: [implicitly absorbed by X — needs explicit confirmation]
651
+ - ❌ Intent 4: [not yet discussed]
652
+ ```
653
+
654
+ - If any item is "implicitly absorbed" (⚠️), note it explicitly in discussion.md — absorbed ≠ addressed
655
+ - If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
656
+
657
+ **Success Criteria**:
658
+ - User feedback processed for each round
659
+ - discussion.md updated with all discussion rounds
660
+ - Assumptions documented and corrected
661
+ - Exit condition reached (user selects complete or max rounds)
662
+ - **All decision points recorded** with Decision Record format
663
+ - **Direction changes documented** with before/after comparison and rationale
664
+
665
+ ### Phase 4: Synthesis & Conclusion
666
+
667
+ **Objective**: Consolidate insights from all discussion rounds, generate conclusions and recommendations.
668
+
669
+ ##### Step 4.0: Intent Coverage Verification (MANDATORY before synthesis)
670
+
671
+ Re-read all original user intent / analysis context items from discussion.md header. For EACH item, determine coverage status:
672
+
673
+ - **✅ Addressed**: Explicitly discussed and concluded with clear design/recommendation
674
+ - **🔀 Transformed**: Original intent evolved into a different solution — document the transformation chain
675
+ - **⚠️ Absorbed**: Implicitly covered by a broader solution — flag for explicit confirmation
676
+ - **❌ Missed**: Not discussed — MUST be either addressed now or explicitly listed as out-of-scope with reason
677
+
678
+ Write "Intent Coverage Matrix" to discussion.md:
679
+
680
+ ```markdown
681
+ ### Intent Coverage Matrix
682
+ | # | Original Intent | Status | Where Addressed | Notes |
683
+ |---|----------------|--------|-----------------|-------|
684
+ | 1 | [intent text] | ✅ Addressed | Round N, Conclusion #M | |
685
+ | 2 | [intent text] | 🔀 Transformed | Round N → Round M | Original: X → Final: Y |
686
+ | 3 | [intent text] | ❌ Missed | — | Reason for omission |
687
+ ```
688
+
689
+ **Gate**: If any item is ❌ Missed, MUST either:
690
+ - (a) Add a dedicated discussion round to address it before continuing, OR
691
+ - (b) Explicitly confirm with user that it is intentionally deferred
692
+
693
+ ##### Step 4.1: Consolidate Insights
694
+
695
+ ```javascript
696
+ const conclusions = {
697
+ session_id: sessionId,
698
+ topic: topic,
699
+ completed: getUtc8ISOString(),
700
+ total_rounds: roundCount,
701
+ summary: '...', // Executive summary
702
+ key_conclusions: [ // Main conclusions
703
+ { point: '...', evidence: '...', confidence: 'high|medium|low' }
704
+ ],
705
+ recommendations: [ // Actionable recommendations
706
+ {
707
+ action: '...', // What to do (imperative verb + target)
708
+ rationale: '...', // Why this matters
709
+ priority: 'high|medium|low',
710
+ evidence_refs: ['file:line', ...], // Supporting evidence locations
711
+ steps: [ // Granular sub-steps for execution
712
+ { description: '...', target: 'file/module', verification: 'how to verify done' }
713
+ ],
714
+ review_status: 'accepted|modified|rejected|pending' // Set during Phase 4 review
715
+ }
716
+ ],
717
+ open_questions: [...], // Unresolved questions
718
+ follow_up_suggestions: [ // Next steps
719
+ { type: 'issue|task|research', summary: '...' }
720
+ ],
721
+ decision_trail: [ // Consolidated decisions from all phases
722
+ { round: 1, decision: '...', context: '...', options_considered: [...], chosen: '...', rejected_reasons: '...', reason: '...', impact: '...' }
723
+ ],
724
+ narrative_trail: [ // From Step 3.3 Narrative Synthesis
725
+ { round: 1, starting_point: '...', key_progress: '...', hypothesis_impact: '...', updated_understanding: '...', remaining_questions: '...' }
726
+ ],
727
+ intent_coverage: [ // From Step 4.0
728
+ { intent: '...', status: 'addressed|transformed|absorbed|missed', where_addressed: '...', notes: '...' }
729
+ ]
730
+ }
731
+ Write(`${sessionFolder}/conclusions.json`, JSON.stringify(conclusions, null, 2))
732
+ ```
733
+
734
+ ##### Step 4.2: Final discussion.md Update
735
+
736
+ Append conclusions section and finalize:
737
+
738
+ **Synthesis & Conclusions Section**:
739
+ - **Executive Summary**: Overview of analysis findings
740
+ - **Key Conclusions**: Ranked by confidence level with supporting evidence
741
+ - **Recommendations**: Prioritized action items with rationale
742
+ - **Remaining Open Questions**: Unresolved items for future work
743
+
744
+ **Current Understanding (Final) Section**:
745
+
746
+ | Subsection | Content |
747
+ |------------|---------|
748
+ | What We Established | Confirmed points and validated findings |
749
+ | What Was Clarified | Important corrections (~~wrong→right~~) |
750
+ | Key Insights | Valuable learnings for future reference |
751
+
752
+ **Decision Trail Section**:
753
+
754
+ | Subsection | Content |
755
+ |------------|---------|
756
+ | Critical Decisions | Pivotal decisions that shaped the analysis outcome |
757
+ | Direction Changes | Timeline of scope/focus adjustments with rationale |
758
+ | Trade-offs Made | Key trade-offs and why certain paths were chosen |
759
+
760
+ **Session Statistics**: Total discussion rounds, key findings count, dimensions covered, artifacts generated, **decision count**.
761
+
762
+ ##### Step 4.3: Interactive Recommendation Review (skip in auto mode)
763
+
764
+ Walk through each recommendation one-by-one for user confirmation before proceeding:
765
+
766
+ ```javascript
767
+ // Order recommendations by priority: high → medium → low
768
+ const sortedRecs = conclusions.recommendations.sort(byPriority)
769
+
770
+ for (const [index, rec] of sortedRecs.entries()) {
771
+ // 1. Present recommendation details
772
+ // Display: action, rationale, priority, steps[] (numbered sub-steps with target + verification)
773
+
774
+ // 2. Gather user review
775
+ const review = request_user_input({
776
+ questions: [{
777
+ header: `建议#${index + 1}`,
778
+ id: `rec_${index + 1}`,
779
+ question: `Recommendation #${index + 1}: "${rec.action}" (${rec.priority} priority, ${rec.steps.length} steps). Your decision:`,
780
+ options: [
781
+ { label: "Accept(Recommended)", description: "Accept this recommendation as-is" },
782
+ { label: "Modify", description: "Adjust scope, steps, or priority" },
783
+ { label: "Reject", description: "Remove this recommendation" }
784
+ ]
785
+ }]
786
+ })
787
+
788
+ // 3. Process review decision
789
+ // Accept → rec.review_status = "accepted"
790
+ // Modifygather modification via free text → update rec → rec.review_status = "modified"
791
+ // Reject → gather reason → rec.review_status = "rejected"
792
+ // Accept All Remaining mark all remaining as "accepted", break loop
793
+
794
+ // 4. Record review decision to discussion.md Decision Log
795
+ // 5. Update conclusions.json
796
+ }
797
+
798
+ // Display review summary:
799
+ // Accepted: N | Modified: N | Rejected: N
800
+ // Only accepted/modified recommendations proceed to next step
801
+ ```
802
+
803
+ **Review Summary Format** (append to discussion.md):
804
+ ```markdown
805
+ ### Recommendation Review Summary
806
+ | # | Action | Priority | Steps | Review Status | Notes |
807
+ |---|--------|----------|-------|---------------|-------|
808
+ | 1 | [action] | high | 3 | ✅ Accepted | |
809
+ | 2 | [action] | medium | 2 | ✏️ Modified | [modification notes] |
810
+ | 3 | [action] | low | 1 | Rejected | [reason] |
811
+ ```
812
+
813
+ ##### Step 4.4: Post-Completion Options
814
+
815
+ **Complexity Assessment** — determine available options:
816
+
817
+ ```javascript
818
+ // Assess recommendation complexity to decide available options
819
+ const recs = conclusions.recommendations || []
820
+ const complexity = assessComplexity(recs)
821
+
822
+ function assessComplexity(recs) {
823
+ if (recs.length === 0) return 'none'
824
+ if (recs.length <= 2 && recs.every(r => r.priority === 'low')) return 'simple'
825
+ if (recs.length >= 3 || recs.some(r => r.priority === 'high')) return 'complex'
826
+ return 'moderate' // 1-2 medium-priority recommendations
827
+ }
828
+
829
+ // Complexity → available options mapping:
830
+ // none: Done | Create Issue | Export Report
831
+ // simple: Done | Create Issue | Export Report
832
+ // moderate: Generate Plan | Create Issue | Export Report | Done
833
+ // complex: Generate Plan | Create Issue | Export Report | Done
834
+ ```
835
+
836
+ ```javascript
837
+ if (!autoYes) {
838
+ const options = buildOptionsForComplexity(complexity)
839
+ request_user_input({
840
+ questions: [{
841
+ header: "下一步",
842
+ id: "next_step",
843
+ question: `Analysis complete (${recs.length} recommendations, complexity: ${complexity}). Next step:`,
844
+ options: options
845
+ }]
846
+ })
847
+ } else {
848
+ // Auto mode: generate plan only for moderate/complex, skip for simple/none
849
+ if (complexity === 'complex' || complexity === 'moderate') {
850
+ // → Phase 5 (plan generation only, NO code modifications)
851
+ } else {
852
+ // Done (conclusions.json is sufficient output)
853
+ }
854
+ }
855
+ ```
856
+
857
+ **Options by Complexity**:
858
+
859
+ | Complexity | Available Options | Rationale |
860
+ |------------|-------------------|-----------|
861
+ | `none` | Done, Create Issue, Export Report | No actionable recommendations |
862
+ | `simple` | Done, Create Issue, Export Report | 1-2 low-priority items don't warrant formal task JSON |
863
+ | `moderate` | Generate Plan, Create Issue, Export Report, Done | Task structure helpful for downstream execution |
864
+ | `complex` | Generate Plan, Create Issue, Export Report, Done | Full plan generation justified |
865
+
866
+ | Selection | Action |
867
+ |-----------|--------|
868
+ | Generate Plan | Jump to Phase 5 (plan generation only, NO code modifications) |
869
+ | Create Issue | `Skill(skill="issue:new", args="...")` (only reviewed recs) |
870
+ | Export Report | Copy discussion.md + conclusions.json to user-specified location |
871
+ | Done | Display artifact paths, end |
872
+
873
+ **Success Criteria**:
874
+ - conclusions.json created with complete synthesis
875
+ - discussion.md finalized with conclusions and decision trail
876
+ - **Intent Coverage Matrix** verified all original intents accounted for (no ❌ Missed without explicit user deferral)
877
+ - User offered meaningful next step options
878
+ - **Complete decision trail** documented and traceable from initial scoping to final conclusions
879
+
880
+ ### Phase 5: Plan Generation (Optional — NO code modifications)
881
+
882
+ **Objective**: Generate structured plan checklist from analysis recommendations. **This phase produces plans only — it does NOT modify any source code.**
883
+
884
+ **Trigger**: User selects "Generate Plan" in Phase 4. In auto mode, triggered only for `moderate`/`complex` recommendations.
885
+
886
+ ```javascript
887
+ const recs = conclusions.recommendations || []
888
+
889
+ // Build plan checklist from all accepted/modified recommendations
890
+ const planChecklist = recs
891
+ .filter(r => r.review_status !== 'rejected')
892
+ .map((rec, index) => {
893
+ const files = rec.evidence_refs
894
+ ?.filter(ref => ref.includes(':'))
895
+ .map(ref => ref.split(':')[0]) || []
896
+
897
+ return `### ${index + 1}. ${rec.action}
898
+ - **Priority**: ${rec.priority}
899
+ - **Rationale**: ${rec.rationale}
900
+ - **Target files**: ${files.join(', ') || 'TBD'}
901
+ - **Evidence**: ${rec.evidence_refs?.join(', ') || 'N/A'}
902
+ - [ ] Ready for execution`
903
+ }).join('\n\n')
904
+
905
+ // Append plan checklist to discussion.md
906
+ appendToDiscussion(`
907
+ ## Plan Checklist
908
+
909
+ > **This is a plan only — no code was modified.**
910
+ > To execute, use: \`$csv-wave-pipeline "<requirement summary>"\`
911
+
912
+ - **Recommendations**: ${recs.length}
913
+ - **Generated**: ${getUtc8ISOString()}
914
+
915
+ ${planChecklist}
916
+
917
+ ---
918
+
919
+ ### Next Step: Execute
920
+
921
+ Run \`$csv-wave-pipeline\` to execute these recommendations as wave-based batch tasks:
922
+
923
+ \`\`\`bash
924
+ $csv-wave-pipeline "${topic}"
925
+ \`\`\`
926
+ `)
927
+ ```
928
+
929
+ **Characteristics**:
930
+ - Plan checklist appended directly to `discussion.md`
931
+ - **No code modifications** plan output only
932
+ - Reminds user to use `$csv-wave-pipeline` for execution
933
+
934
+ **Success Criteria**:
935
+ - Plan checklist in discussion.md with all accepted recommendations
936
+ - User reminded about `$csv-wave-pipeline` for execution
937
+ - **No source code modified** strictly plan output
938
+
939
+ ## Output Structure
940
+
941
+ ```
942
+ {projectRoot}/.workflow/.analysis/ANL-{slug}-{date}/
943
+ ├── discussion.md # Evolution of understanding & discussions
944
+ ├── exploration-codebase.json # Phase 2: Codebase context
945
+ ├── explorations/ # Phase 2: Multi-perspective explorations (if selected)
946
+ ├── technical.json
947
+ │ ├── architectural.json
948
+ └── ...
949
+ ├── explorations.json # Phase 2: Single perspective aggregated findings
950
+ ├── perspectives.json # Phase 2: Multi-perspective findings with synthesis
951
+ └── conclusions.json # Phase 4: Final synthesis with recommendations
952
+ ```
953
+
954
+ > **Phase 5** appends a plan checklist to `discussion.md`. No additional files are generated.
955
+
956
+ | File | Phase | Description |
957
+ |------|-------|-------------|
958
+ | `discussion.md` | 1-5 | Session metadata → discussion timeline → conclusions. Plan checklist appended here (simple path). |
959
+ | `exploration-codebase.json` | 2 | Codebase context: relevant files, patterns, constraints |
960
+ | `explorations/*.json` | 2 | Per-perspective exploration results (multi only) |
961
+ | `explorations.json` | 2 | Single perspective aggregated findings |
962
+ | `perspectives.json` | 2 | Multi-perspective findings with cross-perspective synthesis |
963
+ | `conclusions.json` | 4 | Final synthesis: conclusions, recommendations, open questions |
964
+
965
+ ## Analysis Dimensions Reference
966
+
967
+ Dimensions guide the scope and focus of analysis:
968
+
969
+ | Dimension | Keywords | Description |
970
+ |-----------|----------|-------------|
971
+ | architecture | 架构, architecture, design, structure, 设计, pattern | System design, component interactions, design patterns |
972
+ | implementation | 实现, implement, code, coding, 代码, logic | Code patterns, implementation details, algorithms |
973
+ | performance | 性能, performance, optimize, bottleneck, 优化, speed | Bottlenecks, optimization opportunities, resource usage |
974
+ | security | 安全, security, auth, permission, 权限, vulnerability | Vulnerabilities, authentication, access control |
975
+ | concept | 概念, concept, theory, principle, 原理, understand | Foundational ideas, principles, theory |
976
+ | comparison | 比较, compare, vs, difference, 区别, versus | Comparing solutions, evaluating alternatives |
977
+ | decision | 决策, decision, choice, tradeoff, 选择, trade-off | Trade-offs, impact analysis, decision rationale |
978
+
979
+ ## Analysis Perspectives
980
+
981
+ Optional multi-perspective analysis (single perspective is default, max 4):
982
+
983
+ | Perspective | Focus | Best For |
984
+ |------------|-------|----------|
985
+ | **Technical** | Implementation patterns, code structure, technical feasibility | Understanding how and technical details |
986
+ | **Architectural** | System design, scalability, component interactions | Understanding structure and organization |
987
+ | **Security** | Security patterns, vulnerabilities, access control | Identifying security risks |
988
+ | **Performance** | Bottlenecks, optimization, resource utilization | Finding performance issues |
989
+
990
+ **Selection**: User can multi-select up to 4 perspectives in Phase 1, or default to single comprehensive view.
991
+
992
+ ### Analysis Depth Levels
993
+
994
+ | Depth | Scope | Description |
995
+ |-------|-------|-------------|
996
+ | Quick | Surface level understanding | Fast overview, minimal exploration |
997
+ | Standard | Moderate depth with good coverage | Balanced analysis (default) |
998
+ | Deep | Comprehensive detailed analysis | Thorough multi-round investigation |
999
+
1000
+ ## Dimension-Direction Mapping
1001
+
1002
+ When user selects focus areas, generate directions dynamically from detected dimensions:
1003
+
1004
+ | Dimension | Possible Directions |
1005
+ |-----------|-------------------|
1006
+ | architecture | System Design, Component Interactions, Technology Choices, Integration Points, Design Patterns, Scalability Strategy |
1007
+ | implementation | Code Structure, Implementation Details, Code Patterns, Error Handling, Testing Approach, Algorithm Analysis |
1008
+ | performance | Performance Bottlenecks, Optimization Opportunities, Resource Utilization, Caching Strategy, Concurrency Issues |
1009
+ | security | Security Vulnerabilities, Authentication/Authorization, Access Control, Data Protection, Input Validation |
1010
+ | concept | Conceptual Foundation, Core Mechanisms, Fundamental Patterns, Theory & Principles, Trade-offs & Reasoning |
1011
+ | comparison | Solution Comparison, Pros & Cons Analysis, Technology Evaluation, Approach Differences |
1012
+ | decision | Decision Criteria, Trade-off Analysis, Risk Assessment, Impact Analysis, Implementation Implications |
1013
+
1014
+ **Implementation**: Present 2-3 top dimension-related directions, allow user to multi-select and add custom directions.
1015
+
1016
+ ## Consolidation Rules
1017
+
1018
+ When updating "Current Understanding" in discussion.md:
1019
+
1020
+ | Rule | Description |
1021
+ |------|-------------|
1022
+ | Promote confirmed insights | Move validated findings to "What We Established" |
1023
+ | Track corrections | Keep important wrong→right transformations |
1024
+ | Focus on current state | What do we know NOW, not the journey |
1025
+ | Avoid timeline repetition | Don't copy discussion details into consolidated section |
1026
+ | Preserve key learnings | Keep insights valuable for future reference |
1027
+
1028
+ **Example**:
1029
+
1030
+ Bad (cluttered):
1031
+ ```markdown
1032
+ ## Current Understanding
1033
+ In round 1 we discussed X, then in round 2 user said Y...
1034
+ ```
1035
+
1036
+ Good (consolidated):
1037
+ ```markdown
1038
+ ## Current Understanding
1039
+
1040
+ ### What We Established
1041
+ - The authentication flow uses JWT with refresh tokens
1042
+ - Rate limiting is implemented at API gateway level
1043
+
1044
+ ### What Was Clarified
1045
+ - ~~Assumed Redis for sessions~~ → Actually uses database-backed sessions
1046
+
1047
+ ### Key Insights
1048
+ - Current architecture supports horizontal scaling
1049
+ ```
1050
+
1051
+ ## Templates
1052
+
1053
+ ### discussion.md Structure
1054
+
1055
+ The discussion.md file evolves through the analysis:
1056
+
1057
+ - **Header**: Session ID, topic, start time, identified dimensions
1058
+ - **Analysis Context**: Focus areas, perspectives, depth level
1059
+ - **Initial Questions**: Key questions to guide the analysis
1060
+ - **Initial Decisions**: Why these dimensions and focus areas were selected
1061
+ - **Discussion Timeline**: Round-by-round findings with narrative synthesis
1062
+ - Round 1: Initial Understanding + Exploration Results + **Initial Decision Log** + **Narrative Synthesis**
1063
+ - Round 2-N: Current Understanding Summary + User feedback + direction adjustments + new insights + **Decision Log** + **Key Findings** + **Narrative Synthesis**
1064
+ - **Decision Trail**: Consolidated critical decisions across all rounds
1065
+ - **Synthesis & Conclusions**: Summary, key conclusions, recommendations
1066
+ - **Current Understanding (Final)**: Consolidated insights
1067
+ - **Session Statistics**: Rounds completed, findings count, artifacts generated, decision count
1068
+
1069
+ ### Round Documentation Pattern
1070
+
1071
+ Each discussion round follows a consistent structure:
1072
+
1073
+ ```markdown
1074
+ ### Round N - [Deepen|Adjust|Suggest|Q&A] (timestamp)
1075
+
1076
+ #### User Input
1077
+ What the user indicated they wanted to focus on
1078
+
1079
+ #### Decision Log
1080
+ > **Decision**: [Description of direction/scope/approach decision made this round]
1081
+ > - **Context**: [What triggered this decision]
1082
+ > - **Options considered**: [Alternatives evaluated]
1083
+ > - **Chosen**: [Selected approach] — **Reason**: [Rationale]
1084
+ > - **Rejected**: [Why other options were discarded]
1085
+ > - **Impact**: [Effect on analysis direction/conclusions]
1086
+
1087
+ #### Key Findings
1088
+ > **Finding**: [Content]
1089
+ > - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
1090
+ > - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
1091
+ > - **Scope**: [What areas this affects]
1092
+
1093
+ #### Analysis Results
1094
+ Detailed findings from this round's analysis
1095
+ - Finding 1 (evidence: file:line)
1096
+ - Finding 2 (evidence: file:line)
1097
+
1098
+ #### Corrected Assumptions
1099
+ - ~~Previous assumption~~ → Corrected understanding
1100
+ - Reason: Why the assumption was wrong
1101
+
1102
+ #### Open Items
1103
+ Remaining questions or areas for investigation
1104
+
1105
+ #### Narrative Synthesis
1106
+ **起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
1107
+ **关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
1108
+ **决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]
1109
+ **当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
1110
+ **遗留问题**: [remaining questions driving next round]
1111
+ ```
1112
+
1113
+ ## Error Handling
1114
+
1115
+ | Situation | Action | Recovery |
1116
+ |-----------|--------|----------|
1117
+ | No codebase detected | Normal flow, pure topic analysis | Proceed without exploration-codebase.json |
1118
+ | Codebase search fails | Continue with available context | Note limitation in discussion.md |
1119
+ | No relevant findings | Broaden search keywords | Ask user for clarification |
1120
+ | User timeout in discussion | Save state, show resume command | Use `--continue` to resume |
1121
+ | Max rounds reached (5) | Force synthesis phase | Highlight remaining questions in conclusions |
1122
+ | Session folder conflict | Append timestamp suffix | Create unique folder and continue |
1123
+ | Plan generation: no recommendations | No plan to generate | Inform user, suggest lite-plan |
1124
+
1125
+ ## Best Practices
1126
+
1127
+ ### Core Principles
1128
+
1129
+ 1. **No code modifications**: This skill is strictly read-only and plan-only. Phase 5 generates plan checklists in `discussion.md` but does NOT modify source code. Use `$csv-wave-pipeline` for execution.
1130
+
1131
+ ### Before Starting Analysis
1132
+
1133
+ 1. **Clear Topic Definition**: Detailed topics lead to better dimension identification
1134
+ 2. **User Context**: Understanding focus preferences helps scope the analysis
1135
+ 3. **Perspective Selection**: Choose 2-4 perspectives for complex topics, single for focused queries
1136
+ 4. **Scope Understanding**: Being clear about depth expectations sets correct analysis intensity
1137
+
1138
+ ### During Analysis
1139
+
1140
+ 1. **Review Findings**: Check exploration results before proceeding to discussion
1141
+ 2. **Document Assumptions**: Track what you think is true for correction later
1142
+ 3. **Use Continue Mode**: Resume sessions to build on previous findings rather than starting over
1143
+ 4. **Embrace Corrections**: Track wrong→right transformations as valuable learnings
1144
+ 5. **Iterate Thoughtfully**: Each discussion round should meaningfully refine understanding
1145
+ 6. **Record Decisions Immediately**: Never defer recording capture decisions as they happen using the Decision Record format. A decision not recorded in-the-moment is a decision lost
1146
+
1147
+ ### Documentation Practices
1148
+
1149
+ 1. **Evidence-Based**: Every conclusion should reference specific code or patterns
1150
+ 2. **Confidence Levels**: Indicate confidence (high/medium/low) for conclusions
1151
+ 3. **Timeline Clarity**: Use clear timestamps for traceability
1152
+ 4. **Evolution Tracking**: Document how understanding changed across rounds
1153
+ 5. **Action Items**: Generate specific, actionable recommendations
1154
+ 6. **Multi-Perspective Synthesis**: When using multiple perspectives, document convergent/conflicting themes
1155
+ 7. **Link Decisions to Outcomes**: When writing conclusions, explicitly reference which decisions led to which outcomes — this creates an auditable trail from initial scoping to final recommendations
1156
+
1157
+ ## When to Use
1158
+
1159
+ **Use analyze-with-file when:**
1160
+ - Exploring complex topics collaboratively with documented trail
1161
+ - Need multi-round iterative refinement of understanding
1162
+ - Decision-making requires exploring multiple perspectives
1163
+ - Building shared understanding before implementation
1164
+ - Want to document how understanding evolved
1165
+
1166
+ **Use Plan Generation (Phase 5) when:**
1167
+ - Analysis conclusions contain clear, actionable recommendations
1168
+ - Simple: 1-2 items inline plan checklist in discussion.md
1169
+ - Complex: 3+ recommendationsdetailed plan checklist
1170
+ - **Then execute via**: `$csv-wave-pipeline` for wave-based batch execution
1171
+
1172
+ **Consider alternatives when:**
1173
+ - Specific bug diagnosis needed → use `debug-with-file`
1174
+ - Generating new ideas/solutions → use `brainstorm-with-file`
1175
+ - Complex planning with parallel perspectives → use `collaborative-plan-with-file`
1176
+ - Ready to implement → use `lite-plan`
1177
+ - Requirement decomposition needed → use `req-plan-with-file`
1178
+
1179
+ ---
1180
+
1181
+ **Now execute the analyze-with-file workflow for topic**: $TOPIC