claude-code-workflow 7.2.11 → 7.2.13

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 (30) hide show
  1. package/.claude/agents/workflow-research-agent.md +112 -0
  2. package/.claude/commands/workflow/analyze-with-file.md +185 -60
  3. package/.claude/commands/workflow-tune.md +811 -0
  4. package/.claude/skills/workflow-lite-execute/SKILL.md +106 -14
  5. package/.claude/skills/workflow-lite-plan/SKILL.md +34 -72
  6. package/.claude/skills/workflow-lite-test-review/SKILL.md +39 -26
  7. package/package.json +1 -1
  8. package/.claude/commands/ddd/auto.md +0 -359
  9. package/.claude/commands/ddd/doc-generate.md +0 -222
  10. package/.claude/commands/ddd/doc-refresh.md +0 -218
  11. package/.claude/commands/ddd/execute.md +0 -416
  12. package/.claude/commands/ddd/index-build.md +0 -212
  13. package/.claude/commands/ddd/plan.md +0 -611
  14. package/.claude/commands/ddd/scan.md +0 -365
  15. package/.claude/commands/ddd/sync.md +0 -353
  16. package/.claude/commands/ddd/update.md +0 -160
  17. package/.claude/commands/idaw/add.md +0 -287
  18. package/.claude/commands/idaw/resume.md +0 -442
  19. package/.claude/commands/idaw/run-coordinate.md +0 -648
  20. package/.claude/commands/idaw/run.md +0 -539
  21. package/.claude/commands/idaw/status.md +0 -182
  22. package/.claude/skills/workflow-tune/SKILL.md +0 -487
  23. package/.claude/skills/workflow-tune/phases/01-setup.md +0 -548
  24. package/.claude/skills/workflow-tune/phases/02-step-execute.md +0 -197
  25. package/.claude/skills/workflow-tune/phases/03-step-analyze.md +0 -386
  26. package/.claude/skills/workflow-tune/phases/04-synthesize.md +0 -257
  27. package/.claude/skills/workflow-tune/phases/05-optimize-report.md +0 -246
  28. package/.claude/skills/workflow-tune/specs/workflow-eval-criteria.md +0 -57
  29. package/.claude/skills/workflow-tune/templates/step-analysis-prompt.md +0 -88
  30. package/.claude/skills/workflow-tune/templates/synthesis-prompt.md +0 -90
@@ -0,0 +1,112 @@
1
+ ---
2
+ name: workflow-research-agent
3
+ description: External research agent — web search for API details, design patterns, best practices, and technology validation. Returns structured markdown, does NOT write files.
4
+ tools: Read, WebSearch, WebFetch, Bash
5
+ ---
6
+
7
+ # External Research Agent
8
+
9
+ ## Role
10
+ You perform targeted external research using web search to gather API details, design patterns, architecture approaches, best practices, and technology evaluations. You synthesize findings into structured, actionable markdown for downstream analysis workflows.
11
+
12
+ Spawned by: analyze-with-file (Phase 2), brainstorm-with-file, or any workflow needing external context.
13
+
14
+ **CRITICAL**: Return structured markdown only. Do NOT write any files unless explicitly instructed in the prompt.
15
+
16
+ ## Process
17
+
18
+ 1. **Parse research objective** — Understand the topic, focus area, and what the caller needs
19
+ 2. **Plan queries** — Design 3-5 focused search queries targeting the objective
20
+ 3. **Execute searches** — Use `WebSearch` for general research, `WebFetch` for specific documentation pages
21
+ 4. **Cross-reference** — If codebase files are provided in prompt, `Read` them to ground research in actual code context
22
+ 5. **Synthesize findings** — Extract key insights, patterns, and recommendations from search results
23
+ 6. **Return structured output** — Markdown-formatted research findings
24
+
25
+ ## Research Modes
26
+
27
+ ### Detail Verification (default for analyze)
28
+ Focus: verify assumptions, check best practices, validate technology choices, confirm patterns.
29
+ Queries target: benchmarks, production postmortems, known issues, compatibility matrices, official docs.
30
+
31
+ ### API Research (for implementation planning)
32
+ Focus: concrete API details, library versions, integration patterns, configuration options.
33
+ Queries target: official documentation, API references, migration guides, changelog entries.
34
+
35
+ ### Design Research (for brainstorm/architecture)
36
+ Focus: design alternatives, architecture patterns, competitive analysis, UX patterns.
37
+ Queries target: design systems, pattern libraries, case studies, comparison articles.
38
+
39
+ ## Execution
40
+
41
+ ### Query Strategy
42
+ ```
43
+ 1. Parse topic → extract key technologies, patterns, concepts
44
+ 2. Generate 3-5 queries:
45
+ - Q1: "{technology} best practices {year}"
46
+ - Q2: "{pattern} vs {alternative} comparison"
47
+ - Q3: "{technology} known issues production"
48
+ - Q4: "{specific API/library} documentation {version}"
49
+ - Q5: "{domain} architecture patterns"
50
+ 3. Execute queries via WebSearch
51
+ 4. For promising results, WebFetch full content for detail extraction
52
+ 5. Synthesize across all sources
53
+ ```
54
+
55
+ ### Codebase Grounding
56
+ When the prompt includes `codebase_context` (file paths, patterns, tech stack):
57
+ - Read referenced files to understand actual usage
58
+ - Compare external best practices against current implementation
59
+ - Flag gaps between current code and recommended patterns
60
+
61
+ ## Output Format
62
+
63
+ Return structured markdown (do NOT write files):
64
+
65
+ ```markdown
66
+ ## Research: {topic}
67
+
68
+ ### Key Findings
69
+ - **{Finding 1}**: {detail} (confidence: HIGH|MEDIUM|LOW, source: {url_or_reference})
70
+ - **{Finding 2}**: {detail} (confidence: HIGH|MEDIUM|LOW, source: {url_or_reference})
71
+
72
+ ### Technology / API Details
73
+ - **{Library/API}**: version {X}, {key capabilities}
74
+ - Integration: {how to integrate}
75
+ - Caveats: {known issues or limitations}
76
+
77
+ ### Best Practices
78
+ - {Practice 1}: {rationale} (source: {reference})
79
+ - {Practice 2}: {rationale} (source: {reference})
80
+
81
+ ### Recommended Approach
82
+ {Prescriptive recommendation with rationale — "use X" not "consider X or Y" when evidence is strong}
83
+
84
+ ### Alternatives Considered
85
+ | Option | Pros | Cons | Verdict |
86
+ |--------|------|------|---------|
87
+ | {A} | ... | ... | Recommended / Viable / Avoid |
88
+
89
+ ### Pitfalls & Known Issues
90
+ - {Issue 1}: {mitigation} (source: {reference})
91
+
92
+ ### Codebase Gaps (if codebase_context provided)
93
+ - {Gap}: current code does {X}, best practice recommends {Y}
94
+
95
+ ### Sources
96
+ - {source title}: {url} — {key takeaway}
97
+ ```
98
+
99
+ ## Error Handling
100
+ - If WebSearch returns no results for a query: note "no results" and proceed with remaining queries
101
+ - If WebFetch fails for a URL: skip and note the intended lookup
102
+ - If all searches fail: return "research unavailable — proceed with codebase-only analysis" and list the queries that were attempted
103
+ - If codebase files referenced in prompt don't exist: proceed with external research only
104
+
105
+ ## Constraints
106
+ - Be prescriptive ("use X") not exploratory ("consider X or Y") when evidence is strong
107
+ - Assign confidence levels (HIGH/MEDIUM/LOW) to all findings
108
+ - Cite sources for claims — include URLs
109
+ - Keep output under 200 lines
110
+ - Do NOT write any files — return structured markdown only
111
+ - Do NOT fabricate URLs or sources — only cite actual search results
112
+ - Bash calls MUST use `run_in_background: false` (subagent cannot receive hook callbacks)
@@ -10,11 +10,11 @@ allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glo
10
10
  When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles.
11
11
 
12
12
  <purpose>
13
- Interactive collaborative analysis workflow combining codebase exploration (cli-explore-agent) with CLI-assisted analysis (Gemini/Codex). Produces a documented discussion timeline with evolving understanding, decision trails, and actionable conclusions.
13
+ Interactive collaborative analysis workflow combining codebase exploration (cli-explore-agent), external research (workflow-research-agent), and CLI-assisted analysis (Gemini/Codex). Produces a documented discussion timeline with evolving understanding, decision trails, and actionable conclusions.
14
14
 
15
15
  Invoked when user needs deep, multi-perspective analysis of a topic or codebase question — e.g., architecture review, implementation analysis, concept exploration, or decision evaluation.
16
16
 
17
- Produces: `discussion.md` (evolving analysis document with TOC, rounds, narrative synthesis), `explorations.json`/`perspectives.json` (structured findings), `conclusions.json` (final synthesis with recommendations). All artifacts stored in `.workflow/.analysis/{session-id}/`.
17
+ Produces: `discussion.md` (evolving analysis document with TOC, rounds, narrative synthesis), `explorations.json`/`perspectives.json` (structured findings), `research.json` (external research findings), `conclusions.json` (final synthesis with recommendations). All artifacts stored in `.workflow/.analysis/{session-id}/`.
18
18
  </purpose>
19
19
 
20
20
  <conventions>
@@ -78,10 +78,11 @@ All `AskUserQuestion` calls MUST comply:
78
78
  |-------|----------|-------------|
79
79
  | 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata |
80
80
  | 1 | Session variables | Dimensions, focus areas, analysis depth |
81
- | 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent |
82
- | 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) |
83
- | 2 | `explorations.json` | Single perspective aggregated findings |
84
- | 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis |
81
+ | 2 | `exploration-codebase.json` | Shared Layer 1 discovery (files, modules, patterns) — always created |
82
+ | 2 | `explorations/*.json` | Per-perspective Layer 2-3 deep-dives (multi-perspective only, max 4) |
83
+ | 2 | `research.json` | External research findings (best practices, API details, known issues) — from workflow-research-agent |
84
+ | 2 | `explorations.json` | Single perspective aggregated findings (Layer 1 + CLI analysis + research) |
85
+ | 2 | `perspectives.json` | Multi-perspective findings (Layer 1 shared + per-perspective deep-dives + research) with synthesis |
85
86
  | 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
86
87
  | 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
87
88
  | 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
@@ -141,98 +142,179 @@ All `AskUserQuestion` calls MUST comply:
141
142
  <step name="cli_exploration">
142
143
  **Phase 2: Codebase exploration FIRST, then CLI analysis.**
143
144
 
144
- **Step 1: Codebase Exploration** (cli-explore-agent, parallel up to 6)
145
+ **Step 1: Codebase Exploration** (cli-explore-agent, 1 shared + N perspective-specific)
145
146
 
146
- - **Single**: General codebase analysis -> `{sessionFolder}/exploration-codebase.json`
147
- - **Multi-perspective**: Parallel per-perspective -> `{sessionFolder}/explorations/{perspective}.json`
148
- - **Common tasks**: `ccw tool exec get_modules_by_depth '{}'`, keyword searches, read `.workflow/project-tech.json`
147
+ Two-phase approach to avoid redundant file discovery:
148
+
149
+ **Phase A Shared Discovery** (1 agent, always runs):
150
+ One cli-explore-agent performs Layer 1 (breadth) for ALL perspectives -> `{sessionFolder}/exploration-codebase.json`
149
151
 
150
152
  ```javascript
151
- // Template for cli-explore-agent (single or per-perspective)
153
+ // Shared Layer 1 discovery runs ONCE regardless of perspective count
152
154
  Agent({
153
155
  subagent_type: "cli-explore-agent",
154
156
  run_in_background: false,
155
- description: `Explore codebase: ${topicSlug}`,
157
+ description: `Discover codebase: ${topicSlug}`,
156
158
  prompt: `
157
159
  ## Analysis Context
158
160
  Topic: ${topic_or_question}
159
161
  Dimensions: ${dimensions.join(', ')}
160
- // For multi-perspective, add: Perspective: ${perspective.name} - ${perspective.focus}
161
162
  Session: ${sessionFolder}
162
163
 
163
164
  ## MANDATORY FIRST STEPS
164
165
  1. Run: ccw tool exec get_modules_by_depth '{}'
165
166
  2. Read: .workflow/project-tech.json (if exists)
166
167
 
167
- ## Layered Exploration (MUST follow all 3 layers)
168
+ ## Layer 1 Module Discovery (Breadth ONLY)
169
+ - Search by topic keywords across ALL dimensions: ${dimensions.join(', ')}
170
+ - Identify ALL relevant files, map module boundaries and entry points
171
+ - Categorize files by dimension/perspective relevance
172
+ - Output: relevant_files[] with annotations + dimension tags, initial patterns[]
173
+
174
+ ## Output
175
+ Write to: ${sessionFolder}/exploration-codebase.json
176
+ Schema: {relevant_files: [{path, annotation, dimensions[]}], patterns[], module_map: {}, questions_for_user, _metadata}
177
+ `
178
+ })
179
+ ```
180
+
181
+ **Phase A2 — External Research** (parallel with Phase A, runs when topic involves technologies/patterns/APIs):
182
+
183
+ Determine if external research would add value — skip for purely internal codebase questions (e.g., "how does module X work"), run for topics involving technology choices, best practices, architecture patterns, API usage, or comparison with industry standards.
168
184
 
169
- ### Layer 1 — Module Discovery (Breadth)
170
- - Search by topic keywords, identify ALL relevant files
171
- - Map module boundaries and entry points -> relevant_files[] with annotations
185
+ ```javascript
186
+ // External research runs in PARALLEL with Phase A codebase exploration
187
+ // Skip if topic is purely internal codebase navigation
188
+ const needsResearch = dimensions.some(d =>
189
+ ['architecture', 'comparison', 'decision', 'performance', 'security'].includes(d)
190
+ ) || topic_or_question.match(/best practice|pattern|vs|compare|approach|standard|library|framework/i)
191
+
192
+ if (needsResearch) {
193
+ Agent({
194
+ subagent_type: "workflow-research-agent",
195
+ run_in_background: false,
196
+ description: `Research: ${topicSlug}`,
197
+ prompt: `
198
+ ## Research Objective
199
+ Topic: ${topic_or_question}
200
+ Mode: detail-verification
201
+ Dimensions: ${dimensions.join(', ')}
202
+
203
+ ## Focus
204
+ ${dimensions.includes('architecture') ? '- Architecture patterns and best practices for this domain' : ''}
205
+ ${dimensions.includes('performance') ? '- Performance benchmarks and optimization patterns' : ''}
206
+ ${dimensions.includes('security') ? '- Security best practices and known vulnerabilities' : ''}
207
+ ${dimensions.includes('comparison') ? '- Technology comparison and trade-off analysis' : ''}
208
+ ${dimensions.includes('decision') ? '- Decision frameworks and industry recommendations' : ''}
209
+ - Verify assumptions about technologies/patterns involved
210
+ - Known issues and pitfalls in this area
211
+ - Recommended approaches with evidence
212
+
213
+ ## Codebase Context (from Phase A if available)
214
+ Tech stack: ${techStack || 'detect from project files'}
215
+ Key patterns observed: ${sharedDiscovery?.patterns?.join(', ') || 'pending Phase A results'}
216
+
217
+ ## Output
218
+ Return structured markdown per your output format.
219
+ Do NOT write files.
220
+ `
221
+ })
222
+ // Parse research agent output → save to ${sessionFolder}/research.json
223
+ // Schema: {topic, mode, findings[], best_practices[], alternatives[], pitfalls[], sources[], _metadata}
224
+ }
225
+ ```
172
226
 
173
- ### Layer 2 Structure Tracing (Depth)
174
- - Top 3-5 key files: trace call chains 2-3 levels deep
227
+ **Phase BPerspective Deep-Dive** (parallel, only for multi-perspective, max 4):
228
+ Each perspective agent receives shared Layer 1 results, performs only Layer 2-3 on its relevant subset.
229
+ Skip if single-perspective (single mode proceeds directly to Step 2 CLI analysis with Layer 1 results).
230
+
231
+ ```javascript
232
+ // Per-perspective Layer 2-3 — receives shared discovery, avoids re-scanning
233
+ // Only runs in multi-perspective mode
234
+ const sharedDiscovery = readJSON(`${sessionFolder}/exploration-codebase.json`)
235
+ const perspectiveFiles = sharedDiscovery.relevant_files
236
+ .filter(f => f.dimensions.includes(perspective.dimension))
237
+
238
+ selectedPerspectives.forEach(perspective => {
239
+ Agent({
240
+ subagent_type: "cli-explore-agent",
241
+ run_in_background: false,
242
+ description: `Deep-dive: ${perspective.name}`,
243
+ prompt: `
244
+ ## Analysis Context
245
+ Topic: ${topic_or_question}
246
+ Perspective: ${perspective.name} - ${perspective.focus}
247
+ Session: ${sessionFolder}
248
+
249
+ ## SHARED DISCOVERY (Layer 1 already completed — DO NOT re-scan)
250
+ Relevant files for this perspective:
251
+ ${perspectiveFiles.map(f => `- ${f.path}: ${f.annotation}`).join('\n')}
252
+ Patterns found: ${sharedDiscovery.patterns.join(', ')}
253
+
254
+ ## Layer 2 — Structure Tracing (Depth)
255
+ - From the relevant files above, pick top 3-5 key files for this perspective
256
+ - Trace call chains 2-3 levels deep
175
257
  - Identify data flow paths and dependencies -> call_chains[], data_flows[]
176
258
 
177
- ### Layer 3 — Code Anchor Extraction (Detail)
259
+ ## Layer 3 — Code Anchor Extraction (Detail)
178
260
  - Each key finding: extract code snippet (20-50 lines) with file:line
179
- - Annotate WHY this matters -> code_anchors[]
261
+ - Annotate WHY this matters for ${perspective.name} -> code_anchors[]
180
262
 
181
263
  ## Output
182
- Write to: ${sessionFolder}/exploration-codebase.json
183
- // Multi-perspective: ${sessionFolder}/explorations/${perspective.name}.json
184
-
185
- Schema: {relevant_files, patterns, key_findings, code_anchors: [{file, lines, snippet, significance}], call_chains: [{entry, chain, files}], questions_for_user, _metadata}
264
+ Write to: ${sessionFolder}/explorations/${perspective.name}.json
265
+ Schema: {perspective, relevant_files, key_findings, code_anchors: [{file, lines, snippet, significance}], call_chains: [{entry, chain, files}], questions_for_user, _metadata}
186
266
  `
267
+ })
187
268
  })
188
269
  ```
189
270
 
190
- **Step 2: CLI Analysis** (AFTER exploration)
271
+ **Step 2: CLI Deep Analysis** (AFTER exploration, single-perspective ONLY)
191
272
 
192
- - **Single**: Comprehensive CLI analysis with exploration context
193
- - **Multi (up to 4)**: Parallel CLI calls per perspective
273
+ - **Single-perspective**: CLI does Layer 2-3 depth analysis (explore agent only did Layer 1)
274
+ - **Multi-perspective**: SKIP this step perspective agents in Step 1 Phase B already did Layer 2-3
194
275
  - Execution: `Bash` with `run_in_background: true`
195
276
 
196
277
  ```javascript
197
- // Build shared exploration context for CLI prompts
198
- const explorationContext = `
199
- PRIOR EXPLORATION CONTEXT:
200
- - Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
201
- - Patterns: ${explorationResults.patterns.slice(0,3).join(', ')}
202
- - Findings: ${explorationResults.key_findings.slice(0,3).join(', ')}
203
- - Code anchors:
204
- ${(explorationResults.code_anchors || []).slice(0,5).map(a => ` [${a.file}:${a.lines}] ${a.significance}\n \`\`\`\n ${a.snippet}\n \`\`\``).join('\n')}
205
- - Call chains: ${(explorationResults.call_chains || []).slice(0,3).map(c => `${c.entry} -> ${c.chain.join(' -> ')}`).join('; ')}`
206
-
207
- // Single perspective (for multi: loop selectedPerspectives with perspective.purpose/tasks/constraints)
208
- Bash({
209
- command: `ccw cli -p "
210
- PURPOSE: Analyze '${topic_or_question}' from ${dimensions.join(', ')} perspectives
211
- Success: Actionable insights with clear reasoning
278
+ // ONLY for single-perspective mode multi-perspective already has deep-dive agents
279
+ if (selectedPerspectives.length <= 1) {
280
+ const sharedDiscovery = readJSON(`${sessionFolder}/exploration-codebase.json`)
281
+ const explorationContext = `
282
+ PRIOR EXPLORATION (Layer 1 discovery):
283
+ - Key files: ${sharedDiscovery.relevant_files.slice(0,8).map(f => `${f.path} (${f.annotation})`).join(', ')}
284
+ - Patterns: ${sharedDiscovery.patterns.slice(0,5).join(', ')}
285
+ - Module map: ${JSON.stringify(sharedDiscovery.module_map || {})}`
286
+
287
+ Bash({
288
+ command: `ccw cli -p "
289
+ PURPOSE: Deep analysis of '${topic_or_question}' — build on prior file discovery
290
+ Success: Actionable insights with code evidence (anchors + call chains)
212
291
 
213
292
  ${explorationContext}
214
293
 
215
294
  TASK:
216
- - Build on exploration findings reference specific code anchors
217
- - Analyze common patterns and anti-patterns with code evidence
218
- - Highlight potential issues/opportunities with file:line references
295
+ - From discovered files, trace call chains 2-3 levels deep for top 3-5 key files
296
+ - Extract code snippets (20-50 lines) for each key finding with file:line
297
+ - Identify patterns, anti-patterns, and potential issues with evidence
219
298
  - Generate discussion points for user clarification
220
299
 
221
300
  MODE: analysis
222
301
  CONTEXT: @**/* | Topic: ${topic_or_question}
223
- EXPECTED: Structured analysis with sections, insights tied to evidence, questions, recommendations
224
- CONSTRAINTS: Focus on ${dimensions.join(', ')}
302
+ EXPECTED: Structured analysis with: key_findings[], code_anchors[{file,lines,snippet,significance}], call_chains[{entry,chain,files}], discussion_points[]
303
+ CONSTRAINTS: Focus on ${dimensions.join(', ')} | Do NOT re-discover files — use provided file list
225
304
  " --tool gemini --mode analysis`,
226
- run_in_background: true
227
- })
228
- // STOP: Wait for hook callback before continuing
229
- // Multi-perspective: Same pattern per perspective with perspective.purpose/tasks/constraints/tool
305
+ run_in_background: true
306
+ })
307
+ // STOP: Wait for hook callback before continuing
308
+ }
230
309
  ```
231
310
 
232
311
  **Step 3: Aggregate Findings**
233
- - Consolidate explorations + CLI results
312
+ - Consolidate explorations + CLI results + research findings (if research.json exists)
313
+ - Merge research best_practices[] and pitfalls[] into discussion points
314
+ - Cross-reference: flag gaps where codebase patterns diverge from research best practices
234
315
  - Multi: Extract synthesis (convergent themes, conflicting views, unique contributions)
235
316
  - Write to `explorations.json` (single) or `perspectives.json` (multi)
317
+ - If research.json exists, add `external_research` section to explorations/perspectives with: key findings, best practices, codebase gaps
236
318
 
237
319
  **Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions
238
320
 
@@ -243,18 +325,36 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
243
325
  - Present to user at beginning of Phase 3: "初始探索完成后,以下意图的覆盖情况:[list]。接下来的讨论将重点关注未覆盖的部分。"
244
326
  - Purpose: Early course correction — catch drift before spending multiple interactive rounds
245
327
 
246
- **explorations.json Schema** (single):
328
+ **exploration-codebase.json Schema** (shared Layer 1):
329
+ - `session_id`, `timestamp`, `topic`, `dimensions[]`
330
+ - `relevant_files[]`: {path, annotation, dimensions[]}
331
+ - `patterns[]`, `module_map`: {}
332
+ - `questions_for_user[]`, `_metadata`
333
+
334
+ **research.json Schema** (external research findings):
335
+ - `topic`, `mode` (detail-verification|api-research|design-research), `timestamp`
336
+ - `findings[]`: {finding, detail, confidence, source_url}
337
+ - `best_practices[]`: {practice, rationale, source}
338
+ - `alternatives[]`: {option, pros, cons, verdict}
339
+ - `pitfalls[]`: {issue, mitigation, source}
340
+ - `codebase_gaps[]`: {gap, current_approach, recommended_approach}
341
+ - `sources[]`: {title, url, key_takeaway}
342
+ - `_metadata`: {queries_executed, results_found}
343
+
344
+ **explorations.json Schema** (single — Layer 1 + CLI analysis + research merged):
247
345
  - `session_id`, `timestamp`, `topic`, `dimensions[]`
248
346
  - `sources[]`: {type, file/summary}
249
347
  - `key_findings[]`, `code_anchors[]`: {file, lines, snippet, significance}
250
348
  - `call_chains[]`: {entry, chain, files}
251
349
  - `discussion_points[]`, `open_questions[]`
252
350
  - `technical_solutions[]`: {round, solution, problem, rationale, alternatives, status: proposed|validated|rejected, evidence_refs[], next_action}
351
+ - `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
253
352
 
254
- **perspectives.json Schema** (multi — extends explorations.json):
255
- - `perspectives[]`: [{name, tool, findings, insights, questions}]
353
+ **perspectives.json Schema** (multi — Layer 1 shared + per-perspective Layer 2-3 + research):
354
+ - `shared_discovery`: {relevant_files[], patterns[], module_map}
355
+ - `perspectives[]`: [{name, tool, findings, insights, questions, code_anchors[], call_chains[]}]
356
+ - `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
256
357
  - `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
257
- - code_anchors/call_chains include `perspective` field
258
358
 
259
359
  | Condition | Action |
260
360
  |-----------|--------|
@@ -270,6 +370,22 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
270
370
 
271
371
  **Guideline**: Delegate complex tasks to agents (cli-explore-agent) or CLI calls. Avoid direct analysis in main process.
272
372
 
373
+ **Cumulative Context Rule**: Every agent/CLI call in Phase 3 MUST include a summary of ALL prior exploration results to avoid re-discovering known information. Build `priorContext` before each call:
374
+ ```javascript
375
+ // Build cumulative context from all prior explorations (Phase 2 + previous rounds)
376
+ const allFindings = readJSON(`${sessionFolder}/explorations.json`) // or perspectives.json
377
+ const priorContext = `
378
+ ## KNOWN FINDINGS (DO NOT re-discover)
379
+ - Established files: ${allFindings.sources.map(s => s.file).join(', ')}
380
+ - Key findings: ${allFindings.key_findings.join('; ')}
381
+ - Code anchors: ${allFindings.code_anchors.slice(0,5).map(a => `${a.file}:${a.lines}`).join(', ')}
382
+ - Call chains: ${allFindings.call_chains.slice(0,3).map(c => c.entry).join(', ')}
383
+ - Open questions: ${allFindings.open_questions.join('; ')}
384
+
385
+ ## NEW TASK: Focus ONLY on unexplored areas below.
386
+ `
387
+ ```
388
+
273
389
  **Loop** (max 5 rounds):
274
390
 
275
391
  1. **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
@@ -280,8 +396,8 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
280
396
 
281
397
  3. **Gather Feedback** (AskUserQuestion, single-select, header: "分析反馈"):
282
398
  - **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
399
+ - **外部研究**: Need external research on specific technology/pattern/best practice (spawns workflow-research-agent)
283
400
  - **调整方向**: Different focus or specific questions to address
284
- - **补充信息**: User has additional context, constraints, or corrections to provide
285
401
  - **分析完成**: Sufficient -> exit to Phase 4
286
402
 
287
403
  4. **Process Response** (always record user choice + impact to discussion.md):
@@ -293,9 +409,14 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
293
409
  - **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option)
294
410
  - Execute selected direction -> merge new code_anchors/call_chains -> record confirmed assumptions + deepen angle
295
411
 
296
- **调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
412
+ **外部研究** -> Spawn workflow-research-agent for targeted research:
413
+ - AskUserQuestion (header: "研究主题", freetext via "Other"): What specific technology/pattern/approach needs external research?
414
+ - Spawn research agent with topic + current codebase context (from explorations.json)
415
+ - Merge research findings into explorations.json `external_research` section
416
+ - Update research.json with new findings (append, don't overwrite)
417
+ - Record research findings as Key Findings in discussion.md
297
418
 
298
- **补充信息** -> Capture user input, integrate into context, answer questions via CLI/analysis if needed -> Record corrections/additions + updated understanding
419
+ **调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
299
420
 
300
421
  **分析完成** -> Exit loop -> Record why concluding
301
422
 
@@ -525,6 +646,8 @@ ${implScope.map((item, i) => `${i+1}. **${item.objective}** [${item.priority}]
525
646
  | E005 | error | No relevant findings from exploration — broaden search, ask user for clarification | cli_exploration |
526
647
  | E006 | warning | Session folder conflict — append timestamp suffix | session_init |
527
648
  | E007 | error | Gemini unavailable — fallback to Codex or manual analysis | cli_exploration |
649
+ | E008 | warning | Research agent WebSearch failed — continue with codebase-only analysis, note limitation | cli_exploration |
650
+ | E009 | warning | Research findings conflict with codebase patterns — flag as codebase_gaps for user review | cli_exploration |
528
651
 
529
652
  </error_codes>
530
653
 
@@ -534,6 +657,8 @@ ${implScope.map((item, i) => `${i+1}. **${item.objective}** [${item.priority}]
534
657
  - [ ] Dimensions identified and user preferences captured (Phase 1)
535
658
  - [ ] discussion.md initialized with TOC, Current Understanding, metadata
536
659
  - [ ] Codebase exploration completed with code_anchors and call_chains (Phase 2)
660
+ - [ ] External research executed if topic warrants it (architecture/comparison/decision/performance/security dimensions)
661
+ - [ ] Research findings merged into explorations/perspectives with codebase_gaps flagged
537
662
  - [ ] CLI analysis executed and findings aggregated
538
663
  - [ ] Initial Intent Coverage Check appended to discussion.md
539
664
  - [ ] Interactive discussion rounds documented with narrative synthesis (Phase 3)