claude-code-workflow 7.2.29 → 7.2.30

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 (124) hide show
  1. package/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json +2 -2
  2. package/.ccw/workflows/cli-templates/schemas/task-schema.json +14 -7
  3. package/.claude/agents/action-planning-agent.md +7 -4
  4. package/.claude/agents/cli-explore-agent.md +77 -63
  5. package/.claude/agents/cli-lite-planning-agent.md +11 -10
  6. package/.claude/agents/issue-plan-agent.md +421 -426
  7. package/.claude/commands/workflow/spec/setup.md +1 -1
  8. package/.claude/skills/ccw-chain/SKILL.md +119 -0
  9. package/.claude/skills/ccw-chain/chains/ccw-cycle.json +21 -0
  10. package/.claude/skills/ccw-chain/chains/ccw-exploration.json +47 -0
  11. package/.claude/skills/ccw-chain/chains/ccw-issue.json +33 -0
  12. package/.claude/skills/ccw-chain/chains/ccw-lightweight.json +57 -0
  13. package/.claude/skills/ccw-chain/chains/ccw-main.json +52 -0
  14. package/.claude/skills/ccw-chain/chains/ccw-standard.json +39 -0
  15. package/.claude/skills/ccw-chain/chains/ccw-team.json +10 -0
  16. package/.claude/skills/ccw-chain/chains/ccw-with-file.json +31 -0
  17. package/.claude/skills/ccw-chain/phases/analyze-with-file.md +788 -0
  18. package/.claude/skills/ccw-chain/phases/brainstorm/SKILL.md +408 -0
  19. package/.claude/skills/ccw-chain/phases/brainstorm/phases/01-mode-routing.md +207 -0
  20. package/.claude/skills/ccw-chain/phases/brainstorm/phases/02-artifacts.md +567 -0
  21. package/.claude/skills/ccw-chain/phases/brainstorm/phases/03-role-analysis.md +748 -0
  22. package/.claude/skills/ccw-chain/phases/brainstorm/phases/04-synthesis.md +827 -0
  23. package/.claude/skills/ccw-chain/phases/brainstorm-with-file.md +482 -0
  24. package/.claude/skills/ccw-chain/phases/collaborative-plan-with-file.md +639 -0
  25. package/.claude/skills/ccw-chain/phases/debug-with-file.md +656 -0
  26. package/.claude/skills/ccw-chain/phases/integration-test-cycle.md +936 -0
  27. package/.claude/skills/ccw-chain/phases/issue-convert-to-plan.md +720 -0
  28. package/.claude/skills/ccw-chain/phases/issue-discover.md +483 -0
  29. package/.claude/skills/ccw-chain/phases/issue-execute.md +629 -0
  30. package/.claude/skills/ccw-chain/phases/issue-from-brainstorm.md +382 -0
  31. package/.claude/skills/ccw-chain/phases/issue-plan.md +343 -0
  32. package/.claude/skills/ccw-chain/phases/issue-queue.md +464 -0
  33. package/.claude/skills/ccw-chain/phases/refactor-cycle.md +852 -0
  34. package/.claude/skills/ccw-chain/phases/review-cycle/SKILL.md +132 -0
  35. package/.claude/skills/ccw-chain/phases/review-cycle/phases/review-fix.md +760 -0
  36. package/.claude/skills/ccw-chain/phases/review-cycle/phases/review-module.md +764 -0
  37. package/.claude/skills/ccw-chain/phases/review-cycle/phases/review-session.md +775 -0
  38. package/.claude/skills/ccw-chain/phases/roadmap-with-file.md +544 -0
  39. package/.claude/skills/ccw-chain/phases/spec-generator/SKILL.md +338 -0
  40. package/.claude/skills/ccw-chain/phases/spec-generator/phases/01-5-requirement-clarification.md +404 -0
  41. package/.claude/skills/ccw-chain/phases/spec-generator/phases/01-discovery.md +257 -0
  42. package/.claude/skills/ccw-chain/phases/spec-generator/phases/02-product-brief.md +274 -0
  43. package/.claude/skills/ccw-chain/phases/spec-generator/phases/03-requirements.md +184 -0
  44. package/.claude/skills/ccw-chain/phases/spec-generator/phases/04-architecture.md +248 -0
  45. package/.claude/skills/ccw-chain/phases/spec-generator/phases/05-epics-stories.md +178 -0
  46. package/.claude/skills/ccw-chain/phases/spec-generator/phases/06-5-auto-fix.md +144 -0
  47. package/.claude/skills/ccw-chain/phases/spec-generator/phases/06-readiness-check.md +480 -0
  48. package/.claude/skills/ccw-chain/phases/team-planex.md +123 -0
  49. package/.claude/skills/ccw-chain/phases/ui-design-explore-auto.md +678 -0
  50. package/.claude/skills/ccw-chain/phases/unified-execute-with-file.md +870 -0
  51. package/.claude/skills/ccw-chain/phases/workflow-execute/SKILL.md +625 -0
  52. package/.claude/skills/ccw-chain/phases/workflow-execute/phases/06-review.md +215 -0
  53. package/.claude/skills/ccw-chain/phases/workflow-lite-plan.md +616 -0
  54. package/.claude/skills/ccw-chain/phases/workflow-multi-cli-plan.md +424 -0
  55. package/.claude/skills/ccw-chain/phases/workflow-plan/SKILL.md +466 -0
  56. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/01-session-discovery.md +99 -0
  57. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/02-context-gathering.md +338 -0
  58. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/03-conflict-resolution.md +422 -0
  59. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/04-task-generation.md +440 -0
  60. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/05-plan-verify.md +395 -0
  61. package/.claude/skills/ccw-chain/phases/workflow-plan/phases/06-replan.md +594 -0
  62. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/SKILL.md +527 -0
  63. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/01-session-discovery.md +57 -0
  64. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/02-context-gathering.md +407 -0
  65. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/03-test-coverage-analysis.md +172 -0
  66. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/04-conflict-resolution.md +426 -0
  67. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/05-tdd-task-generation.md +473 -0
  68. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/06-tdd-structure-validation.md +189 -0
  69. package/.claude/skills/ccw-chain/phases/workflow-tdd-plan/phases/07-tdd-verify.md +635 -0
  70. package/.claude/skills/ccw-chain/phases/workflow-test-fix/SKILL.md +482 -0
  71. package/.claude/skills/ccw-chain/phases/workflow-test-fix/phases/01-session-start.md +60 -0
  72. package/.claude/skills/ccw-chain/phases/workflow-test-fix/phases/02-test-context-gather.md +493 -0
  73. package/.claude/skills/ccw-chain/phases/workflow-test-fix/phases/03-test-concept-enhanced.md +150 -0
  74. package/.claude/skills/ccw-chain/phases/workflow-test-fix/phases/04-test-task-generate.md +346 -0
  75. package/.claude/skills/ccw-chain/phases/workflow-test-fix/phases/05-test-cycle-execute.md +538 -0
  76. package/.claude/skills/ccw-chain/specs/auto-mode.md +47 -0
  77. package/.claude/skills/ccw-chain/specs/intent-patterns.md +60 -0
  78. package/.claude/skills/chain-loader/SKILL.md +78 -0
  79. package/.claude/skills/chain-loader/phases/01-analyze-skill.md +53 -0
  80. package/.claude/skills/chain-loader/phases/02-design-graph.md +73 -0
  81. package/.claude/skills/chain-loader/phases/03-generate-validate.md +75 -0
  82. package/.claude/skills/chain-loader/specs/chain-schema.md +99 -0
  83. package/.claude/skills/chain-loader/specs/design-patterns.md +99 -0
  84. package/.claude/skills/chain-loader/templates/chain-json.md +63 -0
  85. package/.claude/skills/review-cycle/phases/review-module.md +764 -764
  86. package/.claude/skills/review-cycle/phases/review-session.md +775 -775
  87. package/.claude/skills/workflow-multi-cli-plan/SKILL.md +2 -2
  88. package/.claude/skills/workflow-plan/phases/03-conflict-resolution.md +422 -422
  89. package/.claude/skills/workflow-plan/phases/05-plan-verify.md +395 -395
  90. package/.claude/skills/workflow-tdd-plan/phases/02-context-gathering.md +407 -407
  91. package/.claude/skills/workflow-tdd-plan/phases/04-conflict-resolution.md +426 -426
  92. package/.claude/skills/workflow-test-fix/phases/02-test-context-gather.md +493 -493
  93. package/README.md +14 -0
  94. package/ccw/dist/core/routes/litellm-api-routes.d.ts.map +1 -1
  95. package/ccw/dist/core/routes/litellm-api-routes.js +0 -23
  96. package/ccw/dist/core/routes/litellm-api-routes.js.map +1 -1
  97. package/ccw/dist/tools/chain-loader.d.ts +10 -0
  98. package/ccw/dist/tools/chain-loader.d.ts.map +1 -0
  99. package/ccw/dist/tools/chain-loader.js +642 -0
  100. package/ccw/dist/tools/chain-loader.js.map +1 -0
  101. package/ccw/dist/tools/index.d.ts.map +1 -1
  102. package/ccw/dist/tools/index.js +2 -0
  103. package/ccw/dist/tools/index.js.map +1 -1
  104. package/ccw/dist/tools/json-builder.js +20 -0
  105. package/ccw/dist/tools/json-builder.js.map +1 -1
  106. package/ccw/dist/types/chain-types.d.ts +72 -0
  107. package/ccw/dist/types/chain-types.d.ts.map +1 -0
  108. package/ccw/dist/types/chain-types.js +5 -0
  109. package/ccw/dist/types/chain-types.js.map +1 -0
  110. package/ccw/scripts/prepublish-clean.mjs +0 -1
  111. package/package.json +1 -3
  112. package/ccw-litellm/README.md +0 -180
  113. package/ccw-litellm/pyproject.toml +0 -35
  114. package/ccw-litellm/src/ccw_litellm/__init__.py +0 -47
  115. package/ccw-litellm/src/ccw_litellm/cli.py +0 -108
  116. package/ccw-litellm/src/ccw_litellm/clients/__init__.py +0 -12
  117. package/ccw-litellm/src/ccw_litellm/clients/litellm_embedder.py +0 -270
  118. package/ccw-litellm/src/ccw_litellm/clients/litellm_llm.py +0 -198
  119. package/ccw-litellm/src/ccw_litellm/config/__init__.py +0 -22
  120. package/ccw-litellm/src/ccw_litellm/config/loader.py +0 -343
  121. package/ccw-litellm/src/ccw_litellm/config/models.py +0 -162
  122. package/ccw-litellm/src/ccw_litellm/interfaces/__init__.py +0 -14
  123. package/ccw-litellm/src/ccw_litellm/interfaces/embedder.py +0 -52
  124. package/ccw-litellm/src/ccw_litellm/interfaces/llm.py +0 -45
@@ -0,0 +1,788 @@
1
+ ---
2
+ name: analyze-with-file
3
+ description: Interactive collaborative analysis with documented discussions, CLI-assisted exploration, and evolving understanding
4
+ argument-hint: "[-y|--yes] [-c|--continue] \"topic or question\""
5
+ allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
6
+ ---
7
+
8
+ ## Auto Mode
9
+
10
+ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles.
11
+
12
+ <purpose>
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
+
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
+
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
+ </purpose>
19
+
20
+ <conventions>
21
+
22
+ ### AskUserQuestion Constraints
23
+
24
+ All `AskUserQuestion` calls MUST comply:
25
+ - **questions**: 1-4 questions per call
26
+ - **options**: 2-4 per question (system auto-adds "Other" for free-text input)
27
+ - **header**: max 12 characters
28
+ - **label**: 1-5 words per option
29
+
30
+ ### Decision Recording Protocol
31
+
32
+ **CRITICAL**: Record immediately when any of these occur:
33
+
34
+ | Trigger | What to Record | Target Section |
35
+ |---------|---------------|----------------|
36
+ | **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` |
37
+ | **Key finding** | Content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
38
+ | **Assumption change** | Old -> new understanding, reason, impact | `#### Corrected Assumptions` |
39
+ | **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` |
40
+ | **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` |
41
+ | **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` |
42
+ | **Technical solution proposed/validated/rejected** | Solution description, rationale, alternatives considered, status | `#### Technical Solutions` |
43
+
44
+ **Decision Record Format**:
45
+ ```markdown
46
+ > **Decision**: [Description]
47
+ > - **Context**: [Trigger]
48
+ > - **Options considered**: [Alternatives]
49
+ > - **Chosen**: [Approach] — **Reason**: [Rationale]
50
+ > - **Rejected**: [Why other options were discarded]
51
+ > - **Impact**: [Effect on analysis]
52
+ ```
53
+
54
+ **Key Finding Record Format**:
55
+ ```markdown
56
+ > **Finding**: [Content]
57
+ > - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
58
+ > - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
59
+ > - **Scope**: [What areas this affects]
60
+ ```
61
+
62
+ **Technical Solution Record Format**:
63
+ ```markdown
64
+ > **Solution**: [Description — what approach, pattern, or implementation]
65
+ > - **Status**: [Proposed / Validated / Rejected]
66
+ > - **Problem**: [What problem this solves]
67
+ > - **Rationale**: [Why this approach]
68
+ > - **Alternatives**: [Other options considered and why not chosen]
69
+ > - **Evidence**: [file:line or code anchor references]
70
+ > - **Next Action**: [Follow-up required or none]
71
+ ```
72
+
73
+ **Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason+rejected), Traceability (later phases trace back), Depth (capture reasoning, not just outcomes)
74
+
75
+ **Technical Solution Triggers** — record using Technical Solution Record Format when ANY of:
76
+ - An implementation approach is described with specific files/patterns/code changes
77
+ - Two or more alternatives are compared with trade-offs
78
+ - User confirms, modifies, or rejects a proposed approach
79
+ - A concrete code change strategy emerges (what to modify, how, why)
80
+
81
+ ### Output Artifacts
82
+
83
+ | Phase | Artifact | Description |
84
+ |-------|----------|-------------|
85
+ | 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata |
86
+ | 1 | Session variables | Dimensions, focus areas, analysis depth |
87
+ | 2 | `exploration-codebase.json` | Shared Layer 1 discovery (files, modules, patterns) — always created |
88
+ | 2 | `explorations/*.json` | Per-perspective Layer 2-3 deep-dives (multi-perspective only, max 4) |
89
+ | 2 | `research.json` | External research findings (best practices, API details, known issues) — from workflow-research-agent |
90
+ | 2 | `explorations.json` | Single perspective aggregated findings (Layer 1 + CLI analysis + research) |
91
+ | 2 | `perspectives.json` | Multi-perspective findings (Layer 1 shared + per-perspective deep-dives + research) with synthesis |
92
+ | 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
93
+ | 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
94
+ | 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
95
+ | 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
96
+
97
+ </conventions>
98
+
99
+ <process>
100
+
101
+ <step name="session_init" priority="first">
102
+ **Initialize session and create progress tracking.**
103
+
104
+ 1. Extract topic/question from `$ARGUMENTS`
105
+ 2. Generate session ID: `ANL-{slug}-{date}` (slug: lowercase alphanumeric+Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
106
+ 3. Define session folder: `.workflow/.analysis/{session-id}`
107
+ 4. Parse options: `-c`/`--continue` for continuation, `-y`/`--yes` for auto-approval
108
+ 5. Auto-detect: If session folder + discussion.md exist -> continue mode
109
+ 6. Create directory structure
110
+ 7. **Create Progress Tracking** (TodoWrite — MANDATORY):
111
+ ```
112
+ TodoWrite([
113
+ { id: "phase-1", title: "Phase 1: Topic Understanding", status: "in_progress" },
114
+ { id: "phase-2", title: "Phase 2: CLI Exploration", status: "pending" },
115
+ { id: "phase-3", title: "Phase 3: Interactive Discussion", status: "pending" },
116
+ { id: "phase-4", title: "Phase 4: Synthesis & Conclusion", status: "pending" },
117
+ { id: "next-step", title: "GATE: Post-Completion Next Step", status: "pending" }
118
+ ])
119
+ ```
120
+ - Update status to `"in_progress"` when entering each phase, `"completed"` when done
121
+ - **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"`
122
+
123
+ **Session Variables**: `sessionId`, `sessionFolder`, `autoMode` (boolean), `mode` (new|continue)
124
+ </step>
125
+
126
+ <step name="topic_understanding">
127
+ **Phase 1: Parse topic, identify dimensions, and capture user preferences.**
128
+
129
+ 1. **Parse Topic & Identify Dimensions** — Match keywords against Analysis Dimensions table (see Configuration)
130
+ 2. **Initial Scoping** (if new session + not auto mode) — use **single AskUserQuestion call with up to 3 questions**:
131
+ - Q1 **Focus** (multiSelect: true, header: "分析方向"): Top 3-4 directions from Dimension-Direction Mapping (options max 4)
132
+ - Q2 **Perspectives** (multiSelect: true, header: "分析视角"): Up to 4 from Analysis Perspectives table (options max 4), default: single comprehensive
133
+ - Q3 **Depth** (multiSelect: false, header: "分析深度"): Quick Overview / Standard / Deep Dive (3 options)
134
+ 3. **Initialize discussion.md** — Structure includes:
135
+ - **Dynamic TOC** (top of file, updated after each round/phase): `## Table of Contents` with links to major sections
136
+ - **Current Understanding** (replaceable block, overwritten each round — NOT appended): `## Current Understanding` initialized as "To be populated after exploration"
137
+ - Session metadata, user context, initial questions, empty discussion timeline, initial dimension selection rationale
138
+ 4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments
139
+
140
+ | Condition | Action |
141
+ |-----------|--------|
142
+ | Session folder + discussion.md created | Continue to Phase 2 |
143
+ | User provides no input (timeout) | Save state, show resume command `# (see code: E003)` |
144
+
145
+ **TodoWrite**: Update `phase-1` -> `"completed"`, `phase-2` -> `"in_progress"`
146
+ </step>
147
+
148
+ <step name="cli_exploration">
149
+ **Phase 2: Codebase exploration FIRST, then CLI analysis.**
150
+
151
+ **Step 1: Codebase Exploration** (cli-explore-agent, 1 shared + N perspective-specific)
152
+
153
+ Two-phase approach to avoid redundant file discovery:
154
+
155
+ **Phase A — Shared Discovery** (1 agent, always runs):
156
+ One cli-explore-agent performs Layer 1 (breadth) for ALL perspectives -> `{sessionFolder}/exploration-codebase.json`
157
+
158
+ ```javascript
159
+ // Shared Layer 1 discovery — runs ONCE regardless of perspective count
160
+ Agent({
161
+ subagent_type: "cli-explore-agent",
162
+ run_in_background: false,
163
+ description: `Discover codebase: ${topicSlug}`,
164
+ prompt: `
165
+ ## Analysis Context
166
+ Topic: ${topic_or_question}
167
+ Dimensions: ${dimensions.join(', ')}
168
+ Session: ${sessionFolder}
169
+
170
+ ## MANDATORY FIRST STEPS
171
+ 1. Run: ccw tool exec get_modules_by_depth '{}'
172
+ 2. Read: .workflow/project-tech.json (if exists)
173
+
174
+ ## Layer 1 — Module Discovery (Breadth ONLY)
175
+ - Search by topic keywords across ALL dimensions: ${dimensions.join(', ')}
176
+ - Identify ALL relevant files, map module boundaries and entry points
177
+ - Categorize files by dimension/perspective relevance
178
+ - Output: relevant_files[] with annotations + dimension tags, initial patterns[]
179
+
180
+ ## Output
181
+ Write to: ${sessionFolder}/exploration-codebase.json
182
+ Schema: {relevant_files: [{path, annotation, dimensions[]}], patterns[], module_map: {}, questions_for_user, _metadata}
183
+ `
184
+ })
185
+ ```
186
+
187
+ **Phase A2 — External Research** (parallel with Phase A, runs when topic involves technologies/patterns/APIs):
188
+
189
+ 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.
190
+
191
+ ```javascript
192
+ // External research — runs in PARALLEL with Phase A codebase exploration
193
+ // Skip if topic is purely internal codebase navigation
194
+ const needsResearch = dimensions.some(d =>
195
+ ['architecture', 'comparison', 'decision', 'performance', 'security'].includes(d)
196
+ ) || topic_or_question.match(/best practice|pattern|vs|compare|approach|standard|library|framework/i)
197
+
198
+ if (needsResearch) {
199
+ Agent({
200
+ subagent_type: "workflow-research-agent",
201
+ run_in_background: false,
202
+ description: `Research: ${topicSlug}`,
203
+ prompt: `
204
+ ## Research Objective
205
+ Topic: ${topic_or_question}
206
+ Mode: detail-verification
207
+ Dimensions: ${dimensions.join(', ')}
208
+
209
+ ## Focus
210
+ ${dimensions.includes('architecture') ? '- Architecture patterns and best practices for this domain' : ''}
211
+ ${dimensions.includes('performance') ? '- Performance benchmarks and optimization patterns' : ''}
212
+ ${dimensions.includes('security') ? '- Security best practices and known vulnerabilities' : ''}
213
+ ${dimensions.includes('comparison') ? '- Technology comparison and trade-off analysis' : ''}
214
+ ${dimensions.includes('decision') ? '- Decision frameworks and industry recommendations' : ''}
215
+ - Verify assumptions about technologies/patterns involved
216
+ - Known issues and pitfalls in this area
217
+ - Recommended approaches with evidence
218
+
219
+ ## Codebase Context (from Phase A if available)
220
+ Tech stack: ${techStack || 'detect from project files'}
221
+ Key patterns observed: ${sharedDiscovery?.patterns?.join(', ') || 'pending Phase A results'}
222
+
223
+ ## Output
224
+ Return structured markdown per your output format.
225
+ Do NOT write files.
226
+ `
227
+ })
228
+ // Parse research agent output → save to ${sessionFolder}/research.json
229
+ // Schema: {topic, mode, findings[], best_practices[], alternatives[], pitfalls[], sources[], _metadata}
230
+ }
231
+ ```
232
+
233
+ **Phase B — Perspective Deep-Dive** (PARALLEL, only for multi-perspective, max 4):
234
+ Each perspective agent receives shared Layer 1 results, performs only Layer 2-3 on its relevant subset.
235
+ Skip if single-perspective (single mode proceeds directly to Step 2 CLI analysis with Layer 1 results).
236
+
237
+ **CRITICAL — Parallel Execution**: Launch ALL perspective Agent() calls in the SAME response block so Claude Code executes them concurrently. Do NOT use a loop that waits for each agent before starting the next.
238
+
239
+ ```javascript
240
+ // Per-perspective Layer 2-3 — receives shared discovery, avoids re-scanning
241
+ // Only runs in multi-perspective mode
242
+ // PARALLEL: All Agent() calls MUST appear in ONE response — Claude Code runs them concurrently
243
+ const sharedDiscovery = readJSON(`${sessionFolder}/exploration-codebase.json`)
244
+
245
+ // Prepare per-perspective file lists
246
+ const perspectiveFileLists = Object.fromEntries(
247
+ selectedPerspectives.map(p => [
248
+ p.name,
249
+ sharedDiscovery.relevant_files.filter(f => f.dimensions.includes(p.dimension))
250
+ ])
251
+ )
252
+
253
+ // Launch ALL agents in a SINGLE response block (not sequentially):
254
+ // Agent({ ..perspective1.. }) ← call 1
255
+ // Agent({ ..perspective2.. }) ← call 2 (same response)
256
+ // Agent({ ..perspective3.. }) ← call 3 (same response)
257
+
258
+ // Each agent call follows this template:
259
+ Agent({
260
+ subagent_type: "cli-explore-agent",
261
+ run_in_background: false,
262
+ description: `Deep-dive: ${perspective.name}`,
263
+ prompt: `
264
+ ## Analysis Context
265
+ Topic: ${topic_or_question}
266
+ Perspective: ${perspective.name} - ${perspective.focus}
267
+ Session: ${sessionFolder}
268
+
269
+ ## SHARED DISCOVERY (Layer 1 already completed — DO NOT re-scan)
270
+ Relevant files for this perspective:
271
+ ${perspectiveFileLists[perspective.name].map(f => `- ${f.path}: ${f.annotation}`).join('\n')}
272
+ Patterns found: ${sharedDiscovery.patterns.join(', ')}
273
+
274
+ ## Layer 2 — Structure Tracing (Depth)
275
+ - From the relevant files above, pick top 3-5 key files for this perspective
276
+ - Trace call chains 2-3 levels deep
277
+ - Identify data flow paths and dependencies -> call_chains[], data_flows[]
278
+
279
+ ## Layer 3 — Code Anchor Extraction (Detail)
280
+ - Each key finding: extract code snippet (20-50 lines) with file:line
281
+ - Annotate WHY this matters for ${perspective.name} -> code_anchors[]
282
+
283
+ ## Output
284
+ Write to: ${sessionFolder}/explorations/${perspective.name}.json
285
+ Schema: {perspective, relevant_files, key_findings, code_anchors: [{file, lines, snippet, significance}], call_chains: [{entry, chain, files}], questions_for_user, _metadata}
286
+ `
287
+ })
288
+ ```
289
+
290
+ **Step 2: CLI Deep Analysis** (AFTER exploration, single-perspective ONLY)
291
+
292
+ - **Single-perspective**: CLI does Layer 2-3 depth analysis (explore agent only did Layer 1)
293
+ - **Multi-perspective**: SKIP this step — perspective agents in Step 1 Phase B already did Layer 2-3
294
+ - Execution: `Bash` with `run_in_background: true`
295
+
296
+ ```javascript
297
+ // ONLY for single-perspective mode — multi-perspective already has deep-dive agents
298
+ if (selectedPerspectives.length <= 1) {
299
+ const sharedDiscovery = readJSON(`${sessionFolder}/exploration-codebase.json`)
300
+ const explorationContext = `
301
+ PRIOR EXPLORATION (Layer 1 discovery):
302
+ - Key files: ${sharedDiscovery.relevant_files.slice(0,8).map(f => `${f.path} (${f.annotation})`).join(', ')}
303
+ - Patterns: ${sharedDiscovery.patterns.slice(0,5).join(', ')}
304
+ - Module map: ${JSON.stringify(sharedDiscovery.module_map || {})}`
305
+
306
+ Bash({
307
+ command: `ccw cli -p "
308
+ PURPOSE: Deep analysis of '${topic_or_question}' — build on prior file discovery
309
+ Success: Actionable insights with code evidence (anchors + call chains)
310
+
311
+ ${explorationContext}
312
+
313
+ TASK:
314
+ - From discovered files, trace call chains 2-3 levels deep for top 3-5 key files
315
+ - Extract code snippets (20-50 lines) for each key finding with file:line
316
+ - Identify patterns, anti-patterns, and potential issues with evidence
317
+ - Generate discussion points for user clarification
318
+
319
+ MODE: analysis
320
+ CONTEXT: @**/* | Topic: ${topic_or_question}
321
+ EXPECTED: Structured analysis with: key_findings[], code_anchors[{file,lines,snippet,significance}], call_chains[{entry,chain,files}], discussion_points[]
322
+ CONSTRAINTS: Focus on ${dimensions.join(', ')} | Do NOT re-discover files — use provided file list
323
+ " --tool gemini --mode analysis`,
324
+ run_in_background: true
325
+ })
326
+ // STOP: Wait for hook callback before continuing
327
+ }
328
+ ```
329
+
330
+ **Step 3: Aggregate Findings**
331
+ - Consolidate explorations + CLI results + research findings (if research.json exists)
332
+ - Merge research best_practices[] and pitfalls[] into discussion points
333
+ - Cross-reference: flag gaps where codebase patterns diverge from research best practices
334
+ - Multi: Extract synthesis (convergent themes, conflicting views, unique contributions)
335
+ - Write to `explorations.json` (single) or `perspectives.json` (multi)
336
+ - If research.json exists, add `external_research` section to explorations/perspectives with: key findings, best practices, codebase gaps
337
+
338
+ **Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions
339
+
340
+ **Step 5: Initial Intent Coverage Check** (FIRST check, before entering Phase 3):
341
+ - Re-read original "User Intent" / "Analysis Context" from discussion.md header
342
+ - Check each intent item against Round 1 findings: ✅ addressed / 🔄 in-progress / ❌ not yet touched
343
+ - Append initial Intent Coverage Check to discussion.md
344
+ - Present to user at beginning of Phase 3: "初始探索完成后,以下意图的覆盖情况:[list]。接下来的讨论将重点关注未覆盖的部分。"
345
+ - Purpose: Early course correction — catch drift before spending multiple interactive rounds
346
+
347
+ > All JSON schemas consolidated in `<schemas>` section below.
348
+
349
+ | Condition | Action |
350
+ |-----------|--------|
351
+ | Exploration + CLI artifacts created | Continue to Phase 3 |
352
+ | cli-explore-agent fails | Continue with available context, note limitation `# (see code: E001)` |
353
+ | CLI timeout | Retry with shorter prompt, or skip perspective `# (see code: E002)` |
354
+
355
+ **TodoWrite**: Update `phase-2` -> `"completed"`, `phase-3` -> `"in_progress"`
356
+ </step>
357
+
358
+ <step name="interactive_discussion">
359
+ **Phase 3: Interactive discussion loop with evolving understanding.**
360
+
361
+ **Guideline**: Delegate complex tasks to agents (cli-explore-agent) or CLI calls. Avoid direct analysis in main process.
362
+
363
+ **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:
364
+ ```javascript
365
+ // Build cumulative context from all prior explorations (Phase 2 + previous rounds)
366
+ const allFindings = readJSON(`${sessionFolder}/explorations.json`) // or perspectives.json
367
+ const priorContext = `
368
+ ## KNOWN FINDINGS (DO NOT re-discover)
369
+ - Established files: ${allFindings.sources.map(s => s.file).join(', ')}
370
+ - Key findings: ${allFindings.key_findings.join('; ')}
371
+ - Code anchors: ${allFindings.code_anchors.slice(0,5).map(a => `${a.file}:${a.lines}`).join(', ')}
372
+ - Call chains: ${allFindings.call_chains.slice(0,3).map(c => c.entry).join(', ')}
373
+ - Open questions: ${allFindings.open_questions.join('; ')}
374
+
375
+ ## NEW TASK: Focus ONLY on unexplored areas below.
376
+ `
377
+ ```
378
+
379
+ **Loop** (max 5 rounds):
380
+
381
+ 1. **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
382
+ - Generate 1-2 sentence recap: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
383
+ - Purpose: Reset context, prevent cognitive overload, make incremental progress visible
384
+
385
+ 2. **Present Findings** from explorations.json
386
+
387
+ 3. **Gather Feedback** (AskUserQuestion, single-select, header: "分析反馈"):
388
+ - **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
389
+ - **外部研究**: Need external research on specific technology/pattern/best practice (spawns workflow-research-agent)
390
+ - **调整方向**: Different focus or specific questions to address
391
+ - **分析完成**: Sufficient -> exit to Phase 4
392
+
393
+ 4. **Process Response** (always record user choice + impact to discussion.md):
394
+
395
+ **Record-Before-Continue Rule**: Each path below MUST write findings and discussion synthesis to `discussion.md` BEFORE proceeding to Step 5. Specifically, after agent/CLI returns results:
396
+ - Append the exploration results, reasoning, and any technical approaches discussed to the current round section
397
+ - Apply **Technical Solution Triggers** (see Decision Recording Protocol) — if triggered, record using Technical Solution Record Format
398
+ - **Ambiguity Check**: For each Technical Solution with Status `Proposed`, verify no unresolved alternatives remain. If a solution lists 2+ options without a chosen one (e.g., "A or B"), record as:
399
+ ```markdown
400
+ > **⚠️ Ambiguity**: [Solution] has [N] unresolved alternatives: [list]
401
+ > - **Needs**: [Decision criteria or exploration to resolve]
402
+ ```
403
+ Surface unresolved ambiguities to user in the next feedback round.
404
+ - Only THEN proceed to Step 5 for Current Understanding replacement and TOC update
405
+
406
+ **继续深入** -> Sub-question to choose direction (AskUserQuestion, single-select, header: "深入方向"):
407
+ - Dynamically generate **max 3** context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions, user-highlighted areas
408
+ - Add **1** heuristic option that breaks current frame (e.g., "compare with best practices", "review from security perspective", "explore simpler alternatives")
409
+ - Total: **max 4 options**. Each specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope
410
+ - **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option)
411
+ - Execute selected direction -> merge new code_anchors/call_chains into explorations.json -> **write exploration results, analysis reasoning, and any proposed approaches to discussion.md** -> record confirmed assumptions + deepen angle
412
+
413
+ **外部研究** -> Spawn workflow-research-agent for targeted research:
414
+ - AskUserQuestion (header: "研究主题", freetext via "Other"): What specific technology/pattern/approach needs external research?
415
+ - Spawn research agent with topic + current codebase context (from explorations.json)
416
+ - Merge research findings into explorations.json `external_research` section
417
+ - Update research.json with new findings (append, don't overwrite)
418
+ - Record research findings as Key Findings in discussion.md
419
+
420
+ **调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
421
+
422
+ **分析完成** -> Exit loop -> Record why concluding
423
+
424
+ 5. **Update discussion.md** (after Record-Before-Continue writes are done):
425
+ - **Replace** `## Current Understanding` block with latest consolidated understanding (follow Consolidation Rules)
426
+ - **Update** `## Table of Contents` with links to new Round N sections
427
+
428
+ 6. **Round Narrative Synthesis** (append to discussion.md after each round update):
429
+ ```markdown
430
+ ### Round N: Narrative Synthesis
431
+ **起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
432
+ **关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
433
+ **决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
434
+ **当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
435
+ **遗留问题**: [remaining questions driving next round]
436
+ ```
437
+
438
+ 7. **Intent Drift Check** (every round >= 2):
439
+ - Re-read original "User Intent" from discussion.md header
440
+ - Check each item: addressed / in-progress / implicitly absorbed / not yet discussed
441
+ ```markdown
442
+ #### Intent Coverage Check
443
+ - ✅ Intent 1: [addressed in Round N]
444
+ - 🔄 Intent 2: [in-progress]
445
+ - ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation]
446
+ - ❌ Intent 4: [not yet discussed]
447
+ ```
448
+ - If ❌ or ⚠️ items exist -> **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
449
+
450
+ | Condition | Action |
451
+ |-----------|--------|
452
+ | User selects "分析完成" | Exit loop, proceed to Phase 4 |
453
+ | Max rounds (5) reached | Force synthesis, offer continuation `# (see code: E004)` |
454
+ | User timeout | Save state, show resume command `# (see code: E003)` |
455
+
456
+ **TodoWrite**: Update `phase-3` -> `"completed"`, `phase-4` -> `"in_progress"`
457
+ </step>
458
+
459
+ <step name="synthesis_conclusion">
460
+ **Phase 4: Synthesize findings, verify intent coverage, and determine next steps.**
461
+
462
+ 1. **Intent Coverage Verification** (MANDATORY before synthesis):
463
+ - Check each original intent: ✅ Addressed / 🔀 Transformed / ⚠️ Absorbed / ❌ Missed
464
+ ```markdown
465
+ ### Intent Coverage Matrix
466
+ | # | Original Intent | Status | Where Addressed | Notes |
467
+ |---|----------------|--------|-----------------|-------|
468
+ | 1 | [intent] | ✅ Addressed | Round N, Conclusion #M | |
469
+ | 2 | [intent] | 🔀 Transformed | Round N -> M | Original: X -> Final: Y |
470
+ | 3 | [intent] | ❌ Missed | — | Reason |
471
+ ```
472
+ - **Gate**: ❌ Missed items must be either (a) addressed in additional round or (b) confirmed deferred by user
473
+ - Add `intent_coverage[]` to conclusions.json
474
+
475
+ 2. **Findings-to-Recommendations Traceability** (MANDATORY before consolidation):
476
+ - **Collect ALL actionable findings** from every round: key findings with actionable implications, technical solutions (proposed/validated), identified gaps (API-frontend gaps, missing features, design issues), corrected assumptions that imply fixes
477
+ - **Map each finding → disposition**:
478
+ | Disposition | Meaning |
479
+ |-------------|---------|
480
+ | `recommendation` | Converted to a numbered recommendation |
481
+ | `absorbed` | Covered by another recommendation (specify which) |
482
+ | `deferred` | Explicitly out-of-scope with reason |
483
+ | `informational` | Pure insight, no action needed |
484
+ - **Findings Coverage Matrix** (append to discussion.md):
485
+ ```markdown
486
+ ### Findings Coverage Matrix
487
+ | # | Finding (Round) | Disposition | Target |
488
+ |---|----------------|-------------|--------|
489
+ | 1 | [finding summary] (R1) | recommendation | Rec #1 |
490
+ | 2 | [finding summary] (R2) | absorbed | → Rec #1 |
491
+ | 3 | [finding summary] (R2) | deferred | Reason: [why] |
492
+ | 4 | [finding summary] (R1) | informational | — |
493
+ ```
494
+ - **Gate**: Findings with `disposition = null` (unmapped) MUST be either assigned a disposition or added as new recommendations. Do NOT proceed to step 3 with unmapped findings.
495
+ - Add `findings_coverage[]` to conclusions.json
496
+
497
+ 3. **Consolidate Insights**:
498
+ - Compile Decision Trail from all phases
499
+ - Key conclusions with evidence + confidence (high/medium/low)
500
+ - Recommendations with rationale + priority (high/medium/low) — **merge validated `technical_solutions[]` from explorations.json as high-priority recommendations** — **ensure all `disposition = recommendation` findings from step 2 are represented**
501
+ - **Solution Readiness Gate**: For each recommendation, check if all key choices are resolved. Flag `ambiguity_resolved: false` on any recommendation that still contains unresolved alternatives. Present unresolved items to user before proceeding to Step 4.
502
+ - Open questions, follow-up suggestions
503
+ - Decision summary linking conclusions back to decisions
504
+ - Write to conclusions.json
505
+
506
+ 4. **Final discussion.md Update**:
507
+ - **Conclusions**: Summary, ranked key conclusions, prioritized recommendations, remaining questions
508
+ - **Current Understanding (Final)**: What established, what clarified/corrected, key insights
509
+ - **Decision Trail**: Critical decisions, direction changes timeline, trade-offs
510
+ - **Findings Coverage Matrix**: From step 2 (already appended)
511
+ - Session statistics: rounds, duration, sources, artifacts, decision count
512
+
513
+ 5. **Display Conclusions Summary** — Present to user:
514
+ - **Analysis Report**: summary, key conclusions (numbered, with confidence), recommendations (numbered, with priority + rationale + steps)
515
+ - Open questions if any
516
+ - Link to full report: `{sessionFolder}/discussion.md`
517
+
518
+ 6. **Interactive Recommendation Review** (skip in auto mode):
519
+
520
+ Present all recommendations, then batch-confirm via **single AskUserQuestion call** (up to 4 questions):
521
+
522
+ ```
523
+ 1. Display all recommendations with numbering (action, rationale, priority, steps[])
524
+ 2. Single AskUserQuestion call — one question per recommendation (max 4, ordered by priority high->medium->low):
525
+ Each question (single-select, header: "建议#N"):
526
+ - **确认** (label: "确认", desc: "Accept as-is") -> review_status = "accepted"
527
+ - **修改** (label: "修改", desc: "Adjust scope/steps") -> review_status = "modified"
528
+ - **删除** (label: "删除", desc: "Not needed") -> review_status = "rejected"
529
+ 3. If >4 recommendations: batch in groups of 4 with additional AskUserQuestion calls
530
+ 4. For "修改" selections: follow up to capture modification details
531
+ 5. Record all review decisions to discussion.md Decision Log
532
+ 6. Update conclusions.json recommendation.review_status for each
533
+ ```
534
+
535
+ **After review**: Display summary of reviewed recommendations:
536
+ - Accepted: N items | Modified: N items | Rejected: N items
537
+ - Only accepted/modified recommendations proceed to next step
538
+
539
+ 7. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step.
540
+
541
+ **TodoWrite**: Update `phase-4` -> `"completed"`, `next-step` -> `"in_progress"`
542
+
543
+ > **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying conclusions (step 4) and recommendation review (step 5), you MUST immediately proceed here.
544
+
545
+ Call AskUserQuestion (single-select, header: "Next Step"):
546
+ - **执行任务** (Recommended if high/medium priority recs exist): "基于分析结论启动 workflow-lite-plan 制定执行计划"
547
+ - **产出Issue**: "将建议转化为 issue 进行跟踪管理"
548
+ - **完成**: "分析已足够,无需进一步操作"
549
+
550
+ **Handle user selection**:
551
+
552
+ **"执行任务"** -> Implementation Scoping + Skill invocation (MUST NOT just display summary and stop):
553
+
554
+ **Step A: Build Implementation Scope** — Transform recommendations into actionable specs:
555
+ ```javascript
556
+ // Filter to accepted/modified recommendations only
557
+ const actionableRecs = conclusions.recommendations
558
+ .filter(r => r.review_status === 'accepted' || r.review_status === 'modified')
559
+ .sort((a, b) => (a.priority === 'high' ? 0 : 1) - (b.priority === 'high' ? 0 : 1))
560
+
561
+ // Map each recommendation to implementation scope using code_anchors
562
+ const implScope = actionableRecs.map(rec => ({
563
+ objective: rec.action, // WHAT to do
564
+ rationale: rec.rationale, // WHY
565
+ priority: rec.priority,
566
+ target_files: rec.steps.flatMap(s => s.target ? [s.target] : [])
567
+ .concat((conclusions.code_anchors || [])
568
+ .filter(a => rec.action.includes(a.significance) || rec.steps.some(s => s.description.includes(a.file)))
569
+ .map(a => ({ path: a.file, lines: a.lines, context: a.significance }))),
570
+ acceptance_criteria: rec.steps.map(s => s.verification || s.description),
571
+ change_summary: rec.steps.map(s => `${s.target || 'TBD'}: ${s.description}`).join('; ')
572
+ }))
573
+ ```
574
+
575
+ **Step B: User Scope Confirmation** (skip in auto mode):
576
+ ```javascript
577
+ // Present implementation scope for confirmation
578
+ console.log(`## Implementation Scope (${implScope.length} items)`)
579
+ implScope.forEach((item, i) => {
580
+ console.log(`${i+1}. **${item.objective}** [${item.priority}]`)
581
+ console.log(` Files: ${item.target_files.map(f => typeof f === 'string' ? f : f.path).join(', ') || 'TBD by lite-plan'}`)
582
+ console.log(` Done when: ${item.acceptance_criteria.join(' + ')}`)
583
+ })
584
+
585
+ if (!autoMode) {
586
+ AskUserQuestion({
587
+ questions: [{
588
+ question: "Implementation scope correct? lite-plan will break these into concrete tasks.",
589
+ header: "Scope确认",
590
+ multiSelect: false,
591
+ options: [
592
+ { label: "确认执行", description: "Scope is clear, proceed to planning" },
593
+ { label: "调整范围", description: "Narrow or expand scope before planning" },
594
+ { label: "补充标准", description: "Add/refine acceptance criteria" }
595
+ ]
596
+ }]
597
+ })
598
+ // Handle "调整范围" / "补充标准" -> update implScope, re-confirm
599
+ }
600
+ ```
601
+
602
+ **Step C: Build Structured Handoff & Invoke Skill**:
603
+ ```javascript
604
+ // Structured handoff — lite-plan parses this as JSON block, not free text
605
+ const handoff = {
606
+ source: 'analyze-with-file',
607
+ session_id: sessionId,
608
+ session_folder: sessionFolder,
609
+ summary: conclusions.summary,
610
+ implementation_scope: implScope, // WHAT + acceptance criteria
611
+ code_anchors: (conclusions.code_anchors || []).slice(0, 10), // WHERE
612
+ key_files: explorationResults.relevant_files?.slice(0, 8) || [],
613
+ key_findings: conclusions.key_conclusions?.slice(0, 5) || [],
614
+ decision_context: conclusions.decision_trail?.slice(-3) || [] // recent decisions for context
615
+ }
616
+
617
+ const handoffBlock = `## Prior Analysis (${sessionId})
618
+
619
+ \`\`\`json:handoff-spec
620
+ ${JSON.stringify(handoff, null, 2)}
621
+ \`\`\`
622
+
623
+ ### Summary
624
+ ${conclusions.summary}
625
+
626
+ ### Implementation Scope
627
+ ${implScope.map((item, i) => `${i+1}. **${item.objective}** [${item.priority}]
628
+ - Files: ${item.target_files.map(f => typeof f === 'string' ? f : f.path).join(', ') || 'TBD'}
629
+ - Done when: ${item.acceptance_criteria.join('; ')}
630
+ - Changes: ${item.change_summary}`).join('\n')}`
631
+
632
+ Skill({ skill: "workflow-lite-plan", args: handoffBlock })
633
+ ```
634
+ If Skill invocation is omitted, the workflow is BROKEN.
635
+ 4. After Skill invocation, analyze-with-file is complete — do not output any additional content
636
+
637
+ **"产出Issue"** -> Convert recommendations to issues:
638
+ 1. For each recommendation in conclusions.recommendations (priority high/medium):
639
+ - Build issue JSON: `{title, context: rec.action + rec.rationale, priority: rec.priority == 'high' ? 2 : 3, source: 'discovery', labels: dimensions}`
640
+ - Create via pipe: `echo '<issue-json>' | ccw issue create`
641
+ 2. Display created issue IDs with next step hint: `/issue:plan <id>`
642
+
643
+ **"完成"** -> No further action needed.
644
+
645
+ **TodoWrite**: Update `next-step` -> `"completed"` after user selection is handled
646
+
647
+ > conclusions.json schema: see `<schemas>` section below.
648
+ </step>
649
+
650
+ </process>
651
+
652
+ <schemas>
653
+
654
+ **exploration-codebase.json** (shared Layer 1):
655
+ - `session_id`, `timestamp`, `topic`, `dimensions[]`
656
+ - `relevant_files[]`: {path, annotation, dimensions[]}
657
+ - `patterns[]`, `module_map`: {}
658
+ - `questions_for_user[]`, `_metadata`
659
+
660
+ **research.json** (external research findings):
661
+ - `topic`, `mode` (detail-verification|api-research|design-research), `timestamp`
662
+ - `findings[]`: {finding, detail, confidence, source_url}
663
+ - `best_practices[]`: {practice, rationale, source}
664
+ - `alternatives[]`: {option, pros, cons, verdict}
665
+ - `pitfalls[]`: {issue, mitigation, source}
666
+ - `codebase_gaps[]`: {gap, current_approach, recommended_approach}
667
+ - `sources[]`: {title, url, key_takeaway}
668
+ - `_metadata`: {queries_executed, results_found}
669
+
670
+ **explorations.json** (single — Layer 1 + CLI analysis + research merged):
671
+ - `session_id`, `timestamp`, `topic`, `dimensions[]`
672
+ - `sources[]`: {type, file/summary}
673
+ - `key_findings[]`, `code_anchors[]`: {file, lines, snippet, significance}
674
+ - `call_chains[]`: {entry, chain, files}
675
+ - `discussion_points[]`, `open_questions[]`
676
+ - `technical_solutions[]`: {round, solution, problem, rationale, alternatives, status: proposed|validated|rejected, evidence_refs[], next_action}
677
+ - `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
678
+
679
+ **perspectives.json** (multi — Layer 1 shared + per-perspective Layer 2-3 + research):
680
+ - `shared_discovery`: {relevant_files[], patterns[], module_map}
681
+ - `perspectives[]`: [{name, tool, findings, insights, questions, code_anchors[], call_chains[]}]
682
+ - `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
683
+ - `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
684
+
685
+ **conclusions.json**:
686
+ - `session_id`, `topic`, `completed`, `total_rounds`, `summary`
687
+ - `key_conclusions[]`: {point, evidence, confidence, code_anchor_refs[]}
688
+ - `code_anchors[]`: {file, lines, snippet, significance}
689
+ - `recommendations[]`: {action, rationale, priority, steps[]: {description, target, verification}, review_status: accepted|modified|rejected|pending}
690
+ - `implementation_scope[]`: {objective, rationale, priority, target_files[], acceptance_criteria[], change_summary} — built in Phase 4 "执行任务" Step A, only for accepted/modified recommendations
691
+ - `open_questions[]`, `follow_up_suggestions[]`: {type, summary}
692
+ - `decision_trail[]`: {round, decision, context, options_considered, chosen, rejected_reasons, reason, impact}
693
+ - `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions}
694
+ - `intent_coverage[]`: {intent, status, where_addressed, notes}
695
+ - `findings_coverage[]`: {finding, round, disposition: recommendation|absorbed|deferred|informational, target, reason}
696
+
697
+ </schemas>
698
+
699
+ <error_codes>
700
+
701
+ | Code | Severity | Description | Stage |
702
+ |------|----------|-------------|-------|
703
+ | E001 | error | cli-explore-agent fails — continue with available context, note limitation | cli_exploration |
704
+ | E002 | error | CLI timeout — retry with shorter prompt, or skip perspective | cli_exploration |
705
+ | E003 | error | User timeout — save state, show resume command | topic_understanding, interactive_discussion |
706
+ | E004 | warning | Max discussion rounds (5) reached — force synthesis, offer continuation | interactive_discussion |
707
+ | E005 | error | No relevant findings from exploration — broaden search, ask user for clarification | cli_exploration |
708
+ | E006 | warning | Session folder conflict — append timestamp suffix | session_init |
709
+ | E007 | error | Gemini unavailable — fallback to Codex or manual analysis | cli_exploration |
710
+ | E008 | warning | Research agent WebSearch failed — continue with codebase-only analysis, note limitation | cli_exploration |
711
+ | E009 | warning | Research findings conflict with codebase patterns — flag as codebase_gaps for user review | cli_exploration |
712
+
713
+ </error_codes>
714
+
715
+ <success_criteria>
716
+ - [ ] Session folder created with valid session ID
717
+ - [ ] Progress tracking (TodoWrite) initialized with all 5 items
718
+ - [ ] Dimensions identified and user preferences captured (Phase 1)
719
+ - [ ] discussion.md initialized with TOC, Current Understanding, metadata
720
+ - [ ] Codebase exploration completed with code_anchors and call_chains (Phase 2)
721
+ - [ ] External research executed if topic warrants it (architecture/comparison/decision/performance/security dimensions)
722
+ - [ ] Research findings merged into explorations/perspectives with codebase_gaps flagged
723
+ - [ ] CLI analysis executed and findings aggregated
724
+ - [ ] Initial Intent Coverage Check appended to discussion.md
725
+ - [ ] Interactive discussion rounds documented with narrative synthesis (Phase 3)
726
+ - [ ] Intent Drift Check performed each round >= 2
727
+ - [ ] All decisions recorded per Decision Recording Protocol
728
+ - [ ] Intent Coverage Matrix verified in Phase 4
729
+ - [ ] Findings Coverage Matrix completed — all actionable findings mapped to disposition (recommendation/absorbed/deferred/informational)
730
+ - [ ] conclusions.json created with key_conclusions, recommendations, decision_trail, findings_coverage
731
+ - [ ] discussion.md finalized with conclusions, Decision Trail, session statistics
732
+ - [ ] Recommendation review completed (non-auto mode)
733
+ - [ ] Next Step terminal gate executed — `next-step` todo is `"completed"`
734
+ </success_criteria>
735
+
736
+ <configuration>
737
+
738
+ ### Analysis Perspectives
739
+
740
+ | Perspective | Tool | Focus | Best For |
741
+ |------------|------|-------|----------|
742
+ | **Technical** | Gemini | Implementation, code patterns, feasibility | How + technical details |
743
+ | **Architectural** | Claude | System design, scalability, interactions | Structure + organization |
744
+ | **Business** | Codex | Value, ROI, stakeholder impact | Business implications |
745
+ | **Domain Expert** | Gemini | Domain patterns, best practices, standards | Industry knowledge |
746
+
747
+ User multi-selects up to 4 in Phase 1. Default: if dimensions >= 2, pre-select Technical + Architectural; if dimensions == 1, single comprehensive view.
748
+
749
+ ### Dimension-Direction Mapping
750
+
751
+ | Dimension | Possible Directions |
752
+ |-----------|-------------------|
753
+ | architecture | System Design, Component Interactions, Technology Choices, Integration Points, Design Patterns, Scalability |
754
+ | implementation | Code Structure, Details, Patterns, Error Handling, Testing, Algorithm Analysis |
755
+ | performance | Bottlenecks, Optimization, Resource Utilization, Caching, Concurrency |
756
+ | security | Vulnerabilities, Auth, Access Control, Data Protection, Input Validation |
757
+ | concept | Foundation, Core Mechanisms, Patterns, Theory, Trade-offs |
758
+ | comparison | Solution Comparison, Pros/Cons, Technology Evaluation, Approach Differences |
759
+ | decision | Criteria, Trade-off Analysis, Risk Assessment, Impact, Implementation Implications |
760
+
761
+ Present 2-3 top directions per dimension, allow multi-select + custom.
762
+
763
+ ### Analysis Dimensions
764
+
765
+ | Dimension | Keywords |
766
+ |-----------|----------|
767
+ | architecture | 架构, architecture, design, structure, 设计 |
768
+ | implementation | 实现, implement, code, coding, 代码 |
769
+ | performance | 性能, performance, optimize, bottleneck, 优化 |
770
+ | security | 安全, security, auth, permission, 权限 |
771
+ | concept | 概念, concept, theory, principle, 原理 |
772
+ | comparison | 比较, compare, vs, difference, 区别 |
773
+ | decision | 决策, decision, choice, tradeoff, 选择 |
774
+
775
+ ### Consolidation Rules
776
+
777
+ | Rule | Description |
778
+ |------|-------------|
779
+ | Promote confirmed insights | Move validated findings to "What We Established" |
780
+ | Track corrections | Keep important wrong->right transformations |
781
+ | Focus on current state | What do we know NOW |
782
+ | Avoid timeline repetition | Don't copy discussion details |
783
+ | Preserve key learnings | Keep insights valuable for future reference |
784
+
785
+ </configuration>
786
+ ---
787
+
788
+ **Now execute analyze-with-file for**: $ARGUMENTS