Refactor multi-CLI planning documentation, enhance analyze-with-file skill, and implement timeout for DeepWiki API requests

- Updated SKILL.md for workflow-multi-cli-plan to streamline sections, clarify processes, and improve user decision points.
- Enhanced analyze-with-file skill to include hypothesis impact in key findings and refined recording principles for better documentation.
- Added fetchWithTimeout function to DeepWiki API calls to handle request timeouts, ensuring more robust error handling.
- Introduced new DeepWiki routes in server.ts to manage API requests effectively.
- Updated tsconfig.tsbuildinfo to reflect recent changes in the codebase structure.
This commit is contained in:
catlog22
2026-03-06 15:54:40 +08:00
parent 88149b6154
commit f2d4364c69
8 changed files with 477 additions and 639 deletions

View File

@@ -19,16 +19,16 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
| Phase | Artifact | Description | | Phase | Artifact | Description |
|-------|----------|-------------| |-------|----------|-------------|
| 1 | `discussion.md` | Evolution of understanding & discussions (initialized) | | 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata |
| 1 | Session variables | Dimensions, focus areas, analysis depth | | 1 | Session variables | Dimensions, focus areas, analysis depth |
| 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent | | 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent |
| 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) | | 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) |
| 2 | `explorations.json` | Single perspective aggregated findings | | 2 | `explorations.json` | Single perspective aggregated findings |
| 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis | | 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis |
| 2 | Updated `discussion.md` | Round 1 with exploration results | | 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
| 3 | Updated `discussion.md` | Round 2-N with user feedback and insights | | 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
| 4 | `conclusions.json` | Final synthesis with recommendations | | 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
| 4 | Final `discussion.md` | Complete analysis with conclusions | | 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
### Decision Recording Protocol ### Decision Recording Protocol
@@ -37,7 +37,7 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
| Trigger | What to Record | Target Section | | Trigger | What to Record | Target Section |
|---------|---------------|----------------| |---------|---------------|----------------|
| **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` | | **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` |
| **Key finding** | Content, impact scope, confidence level | `#### Key Findings` | | **Key finding** | Content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
| **Assumption change** | Old → new understanding, reason, impact | `#### Corrected Assumptions` | | **Assumption change** | Old → new understanding, reason, impact | `#### Corrected Assumptions` |
| **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` | | **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` |
| **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` | | **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` |
@@ -49,10 +49,19 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
> - **Context**: [Trigger] > - **Context**: [Trigger]
> - **Options considered**: [Alternatives] > - **Options considered**: [Alternatives]
> - **Chosen**: [Approach] — **Reason**: [Rationale] > - **Chosen**: [Approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **Impact**: [Effect on analysis] > - **Impact**: [Effect on analysis]
``` ```
**Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason), Traceability (later phases trace back) **Key Finding Record Format**:
```markdown
> **Finding**: [Content]
> - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
> - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
> - **Scope**: [What areas this affects]
```
**Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason+rejected), Traceability (later phases trace back), Depth (capture reasoning, not just outcomes)
## Implementation ## Implementation
@@ -74,7 +83,10 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
- **Focus**: Multi-select from Dimension-Direction Mapping directions - **Focus**: Multi-select from Dimension-Direction Mapping directions
- **Perspectives**: Multi-select up to 4 (see Analysis Perspectives), default: single comprehensive - **Perspectives**: Multi-select up to 4 (see Analysis Perspectives), default: single comprehensive
- **Depth**: Quick Overview (10-15min) / Standard (30-60min) / Deep Dive (1-2hr) - **Depth**: Quick Overview (10-15min) / Standard (30-60min) / Deep Dive (1-2hr)
3. **Initialize discussion.md** — Session metadata, user context, initial understanding, empty discussion timeline, initial dimension selection rationale 3. **Initialize discussion.md** — Structure includes:
- **Dynamic TOC** (top of file, updated after each round/phase): `## Table of Contents` with links to major sections
- **Current Understanding** (replaceable block, overwritten each round — NOT appended): `## Current Understanding` initialized as "To be populated after exploration"
- Session metadata, user context, initial questions, empty discussion timeline, initial dimension selection rationale
4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments 4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments
**Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded **Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded
@@ -178,6 +190,13 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
**Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions **Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions
**Step 5: Initial Intent Coverage Check** (FIRST check, before entering Phase 3):
- Re-read original "User Intent" / "Analysis Context" from discussion.md header
- Check each intent item against Round 1 findings: ✅ addressed / 🔄 in-progress / ❌ not yet touched
- Append initial Intent Coverage Check to discussion.md
- Present to user at beginning of Phase 3: "初始探索完成后,以下意图的覆盖情况:[list]。接下来的讨论将重点关注未覆盖的部分。"
- Purpose: Early course correction — catch drift before spending multiple interactive rounds
**explorations.json Schema** (single): **explorations.json Schema** (single):
- `session_id`, `timestamp`, `topic`, `dimensions[]` - `session_id`, `timestamp`, `topic`, `dimensions[]`
- `sources[]`: {type, file/summary} - `sources[]`: {type, file/summary}
@@ -198,32 +217,54 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
**Loop** (max 5 rounds): **Loop** (max 5 rounds):
1. **Present Findings** from explorations.json 1. **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
2. **Gather Feedback** (AskUserQuestion, single-select): - Generate 1-2 sentence recap: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
- Purpose: Reset context, prevent cognitive overload, make incremental progress visible
2. **Present Findings** from explorations.json
3. **Gather Feedback** (AskUserQuestion, single-select):
- **同意,继续深入**: Direction correct, deepen - **同意,继续深入**: Direction correct, deepen
- **同意,并建议下一步**: Agree with direction, but user has specific next step in mind
- **需要调整方向**: Different focus - **需要调整方向**: Different focus
- **分析完成**: Sufficient → exit to Phase 4 - **分析完成**: Sufficient → exit to Phase 4
- **有具体问题**: Specific questions - **有具体问题**: Specific questions
3. **Process Response** (always record user choice + impact to discussion.md): 4. **Process Response** (always record user choice + impact to discussion.md):
**Agree, Deepen** → Dynamically generate deepen directions from current analysis context: **Agree, Deepen** → Dynamically generate deepen directions from current analysis context:
- Extract 3-4 options from: unresolved questions in explorations.json, low-confidence findings, unexplored dimensions, user-highlighted areas - Extract 2-3 context-driven options from: unresolved questions in explorations.json, low-confidence findings, unexplored dimensions, user-highlighted areas
- Generate 1-2 heuristic options that break current frame: e.g., "compare with best practices in [related domain]", "analyze under extreme load scenarios", "review from security audit perspective", "explore simpler architectural alternatives"
- Each option specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope - Each option specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope
- AskUserQuestion with generated options (single-select) - AskUserQuestion with generated options (single-select)
- Execute selected direction via corresponding tool - Execute selected direction via corresponding tool
- Merge new code_anchors/call_chains into existing results - Merge new code_anchors/call_chains into existing results
- Record confirmed assumptions + deepen angle - Record confirmed assumptions + deepen angle
**Agree, Suggest Next Step** → AskUserQuestion (free text: "请描述您希望下一步深入的方向") → Execute user's specific direction via cli-explore-agent or CLI → Record user-driven exploration rationale
**Adjust Direction** → AskUserQuestion for new focus → new CLI exploration → Record Decision (old vs new direction, reason, impact) **Adjust Direction** → AskUserQuestion for new focus → new CLI exploration → Record Decision (old vs new direction, reason, impact)
**Specific Questions** → Capture, answer via CLI/analysis, document Q&A → Record gaps revealed + new understanding **Specific Questions** → Capture, answer via CLI/analysis, document Q&A → Record gaps revealed + new understanding
**Complete** → Exit loop → Record why concluding **Complete** → Exit loop → Record why concluding
4. **Update discussion.md** — Append Round N: user input, direction adjustment, Q&A, updated understanding, corrections, new insights 5. **Update discussion.md**:
- **Append** Round N: user input, direction adjustment, Q&A, corrections, new insights
- **Replace** `## Current Understanding` block with latest consolidated understanding (follow Consolidation Rules: promote confirmed, track corrections, focus on NOW)
- **Update** `## Table of Contents` with links to new Round N sections
5. **Intent Drift Check** (every round >= 2): 6. **Round Narrative Synthesis** (append to discussion.md after each round update):
```markdown
### Round N: Narrative Synthesis
**起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
**关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
**决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
**当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
**遗留问题**: [remaining questions driving next round]
```
7. **Intent Drift Check** (every round >= 2):
- Re-read original "User Intent" from discussion.md header - Re-read original "User Intent" from discussion.md header
- Check each item: addressed / in-progress / implicitly absorbed / not yet discussed - Check each item: addressed / in-progress / implicitly absorbed / not yet discussed
```markdown ```markdown
@@ -233,9 +274,9 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation] - ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation]
- ❌ Intent 4: [not yet discussed] - ❌ Intent 4: [not yet discussed]
``` ```
- If ❌ or ⚠️ after 3+ rounds → surface to user in next round - If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
**Success**: All rounds documented, assumptions corrected, all decisions recorded, direction changes with before/after **Success**: All rounds documented with narrative synthesis, assumptions corrected, all decisions recorded with rejection reasoning, direction changes with before/after
### Phase 4: Synthesis & Conclusion ### Phase 4: Synthesis & Conclusion
@@ -267,13 +308,33 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- Session statistics: rounds, duration, sources, artifacts, decision count - Session statistics: rounds, duration, sources, artifacts, decision count
4. **Display Conclusions Summary** — Present to user: 4. **Display Conclusions Summary** — Present to user:
- **Analysis Report**: summary, key conclusions (numbered, with confidence), recommendations (numbered, with priority + rationale) - **Analysis Report**: summary, key conclusions (numbered, with confidence), recommendations (numbered, with priority + rationale + steps)
- Open questions if any - Open questions if any
- Link to full report: `{sessionFolder}/discussion.md` - Link to full report: `{sessionFolder}/discussion.md`
5. **Post-Completion Options** (TERMINAL — analyze-with-file ends after selection): 5. **Interactive Recommendation Review** (skip in auto mode):
> **WORKFLOW BOUNDARY**: After selection, analyze-with-file is **COMPLETE**. If "执行任务" selected, workflow-lite-plan takes over exclusively. Walk through each recommendation one-by-one for user confirmation:
```
For each recommendation (ordered by priority high→medium→low):
1. Present: action, rationale, priority, steps[] (numbered sub-steps)
2. AskUserQuestion (single-select, header: "Rec #N"):
- **确认**: Accept as-is → review_status = "accepted"
- **修改**: User adjusts scope/steps → record modification → review_status = "modified"
- **删除**: Not needed → record reason → review_status = "rejected"
- **跳过逐条审议**: Accept all remaining as-is → break loop
3. Record review decision to discussion.md Decision Log
4. Update conclusions.json recommendation.review_status
```
**After review loop**: Display summary of reviewed recommendations:
- Accepted: N items | Modified: N items | Rejected: N items
- Only accepted/modified recommendations proceed to next step
6. **Post-Completion Options** (analyze-with-file transitions based on user selection):
> **WORKFLOW TRANSITION**: "执行任务" MUST invoke `Skill(skill="workflow-lite-plan")` — do NOT end without calling it.
AskUserQuestion (single-select, header: "Next Step"): AskUserQuestion (single-select, header: "Next Step"):
- **执行任务** (Recommended if high/medium priority recs exist): Launch workflow-lite-plan - **执行任务** (Recommended if high/medium priority recs exist): Launch workflow-lite-plan
@@ -286,24 +347,24 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- Create via pipe: `echo '<issue-json>' | ccw issue create` - Create via pipe: `echo '<issue-json>' | ccw issue create`
2. Display created issue IDs with next step hint: `/issue:plan <id>` 2. Display created issue IDs with next step hint: `/issue:plan <id>`
**Handle "执行任务"** (TERMINAL — analyze-with-file ends here, lite-plan takes over): **Handle "执行任务"** — MUST invoke Skill tool (do NOT just display a summary and stop):
1. Build `taskDescription` from high/medium priority recommendations (fallback: summary) 1. Build `taskDescription` from high/medium priority recommendations (fallback: summary)
2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json 2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json
3. Output session termination boundary: 3. **MANDATORY — Invoke Skill tool immediately** (this is the ONLY correct action, do NOT skip):
```javascript
Skill({ skill: "workflow-lite-plan", args: `${taskDescription}\n\n${contextLines}` })
``` ```
⛔ ANALYZE-WITH-FILE SESSION COMPLETE If Skill invocation is omitted, the workflow is BROKEN — user selected "执行任务" specifically to launch lite-plan.
All Phase 1-4 are FINISHED. DO NOT reference analyze-with-file phase instructions beyond this point. 4. After Skill invocation, analyze-with-file is complete — do not output any additional content
```
4. Hand off: `Skill(skill="workflow-lite-plan", args="{taskDescription}\n\n{contextLines}")`
5. Return — analyze-with-file terminates
**conclusions.json Schema**: **conclusions.json Schema**:
- `session_id`, `topic`, `completed`, `total_rounds`, `summary` - `session_id`, `topic`, `completed`, `total_rounds`, `summary`
- `key_conclusions[]`: {point, evidence, confidence, code_anchor_refs[]} - `key_conclusions[]`: {point, evidence, confidence, code_anchor_refs[]}
- `code_anchors[]`: {file, lines, snippet, significance} - `code_anchors[]`: {file, lines, snippet, significance}
- `recommendations[]`: {action, rationale, priority} - `recommendations[]`: {action, rationale, priority, steps[]: {description, target, verification}, review_status: accepted|modified|rejected|pending}
- `open_questions[]`, `follow_up_suggestions[]`: {type, summary} - `open_questions[]`, `follow_up_suggestions[]`: {type, summary}
- `decision_trail[]`: {round, decision, context, options_considered, chosen, reason, impact} - `decision_trail[]`: {round, decision, context, options_considered, chosen, rejected_reasons, reason, impact}
- `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions}
- `intent_coverage[]`: {intent, status, where_addressed, notes} - `intent_coverage[]`: {intent, status, where_addressed, notes}
**Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented **Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented

View File

@@ -29,40 +29,31 @@ When `--yes` or `-y`: Auto-confirm decisions, use recommended roles, balanced ex
## Output Artifacts ## Output Artifacts
### Phase 1: Seed Understanding | Phase | Artifact | Description |
|-------|----------|-------------|
| 1 | `brainstorm.md` | Complete thought evolution timeline (initialized) |
| 1 | Session variables | Dimensions, roles, exploration vectors |
| 2 | `exploration-codebase.json` | Codebase context from cli-explore-agent |
| 2 | `perspectives.json` | Multi-CLI perspective findings (creative/pragmatic/systematic) |
| 2 | Updated `brainstorm.md` | Round 2 multi-perspective exploration |
| 3 | `ideas/{idea-slug}.md` | Deep-dive analysis for selected ideas |
| 3 | Updated `brainstorm.md` | Round 3-6 refinement cycles |
| 4 | `synthesis.json` | Final synthesis with top ideas, recommendations |
| 4 | Final `brainstorm.md` | Complete thought evolution with conclusions |
| Artifact | Description | ## Output Structure
|----------|-------------|
| `brainstorm.md` | Complete thought evolution timeline (initialized) |
| Session variables | Dimensions, roles, exploration vectors |
### Phase 2: Divergent Exploration ```
.workflow/.brainstorm/BS-{slug}-{date}/
| Artifact | Description | ├── brainstorm.md # ⭐ Complete thought evolution timeline
|----------|-------------| ├── exploration-codebase.json # Phase 2: Codebase context
| `exploration-codebase.json` | Codebase context from cli-explore-agent | ├── perspectives.json # Phase 2: Multi-CLI findings
| `perspectives.json` | Multi-CLI perspective findings (creative/pragmatic/systematic) | ├── synthesis.json # Phase 4: Final synthesis
| Updated `brainstorm.md` | Round 2 multi-perspective exploration | └── ideas/ # Phase 3: Individual idea deep-dives
├── idea-1.md
### Phase 3: Interactive Refinement ├── idea-2.md
└── merged-idea-1.md
| Artifact | Description | ```
|----------|-------------|
| `ideas/{idea-slug}.md` | Deep-dive analysis for selected ideas |
| Updated `brainstorm.md` | Round 3-6 refinement cycles |
### Phase 4: Convergence & Crystallization
| Artifact | Description |
|----------|-------------|
| `synthesis.json` | Final synthesis with top ideas, recommendations |
| Final `brainstorm.md` | ⭐ Complete thought evolution with conclusions |
## Overview
Interactive brainstorming workflow with **multi-CLI collaboration** and **documented thought evolution**. Expands initial ideas through questioning, multi-perspective analysis, and iterative refinement.
**Core workflow**: Seed Idea → Expand → Multi-CLI Discuss → Synthesize → Refine → Crystallize
``` ```
┌─────────────────────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────────────────────┐
@@ -102,31 +93,12 @@ Interactive brainstorming workflow with **multi-CLI collaboration** and **docume
└─────────────────────────────────────────────────────────────────────────┘ └─────────────────────────────────────────────────────────────────────────┘
``` ```
## Output Structure
```
.workflow/.brainstorm/BS-{slug}-{date}/
├── brainstorm.md # ⭐ Complete thought evolution timeline
├── exploration-codebase.json # Phase 2: Codebase context
├── perspectives.json # Phase 2: Multi-CLI findings
├── synthesis.json # Phase 4: Final synthesis
└── ideas/ # Phase 3: Individual idea deep-dives
├── idea-1.md
├── idea-2.md
└── merged-idea-1.md
```
## Implementation ## Implementation
### Session Initialization ### Session Initialization
**Objective**: Create session context and directory structure for brainstorming.
**Required Actions**:
1. Extract idea/topic from `$ARGUMENTS` 1. Extract idea/topic from `$ARGUMENTS`
2. Generate session ID: `BS-{slug}-{date}` 2. Generate session ID: `BS-{slug}-{date}` (slug: lowercase, alphanumeric + Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
- slug: lowercase, alphanumeric + Chinese, max 40 chars
- date: YYYY-MM-DD (UTC+8)
3. Define session folder: `.workflow/.brainstorm/{session-id}` 3. Define session folder: `.workflow/.brainstorm/{session-id}`
4. Parse command options: 4. Parse command options:
- `-c` or `--continue` for session continuation - `-c` or `--continue` for session continuation
@@ -135,54 +107,28 @@ Interactive brainstorming workflow with **multi-CLI collaboration** and **docume
5. Auto-detect mode: If session folder + brainstorm.md exist → continue mode 5. Auto-detect mode: If session folder + brainstorm.md exist → continue mode
6. Create directory structure: `{session-folder}/ideas/` 6. Create directory structure: `{session-folder}/ideas/`
**Session Variables**: **Session Variables**: `sessionId`, `sessionFolder`, `brainstormMode` (creative|structured|balanced), `autoMode` (boolean), `mode` (new|continue)
- `sessionId`: Unique session identifier
- `sessionFolder`: Base directory for all artifacts
- `brainstormMode`: creative | structured | balanced
- `autoMode`: Boolean for auto-confirmation
- `mode`: new | continue
### Phase 1: Seed Understanding ### Phase 1: Seed Understanding
**Objective**: Analyze topic, select roles, gather user input, expand into exploration vectors.
**Prerequisites**:
- Session initialized with valid sessionId and sessionFolder
- Topic/idea available from $ARGUMENTS
**Workflow Steps**:
1. **Parse Seed & Identify Dimensions** 1. **Parse Seed & Identify Dimensions**
- Match topic keywords against BRAINSTORM_DIMENSIONS - Match topic keywords against Brainstorm Dimensions table
- Identify relevant dimensions: technical, ux, business, innovation, feasibility, scalability, security
- Default dimensions based on brainstormMode if no match - Default dimensions based on brainstormMode if no match
2. **Role Selection** 2. **Role Selection**
- **Recommend roles** based on topic keywords (see Role Keywords mapping) - Recommend roles based on topic keywords (see Role Selection tables)
- **Options**:
- **Professional roles**: system-architect, product-manager, ui-designer, ux-expert, data-architect, test-strategist, subject-matter-expert, product-owner, scrum-master - **Professional roles**: system-architect, product-manager, ui-designer, ux-expert, data-architect, test-strategist, subject-matter-expert, product-owner, scrum-master
- **Simple perspectives**: creative/pragmatic/systematic (fallback) - **Simple perspectives** (fallback): creative/pragmatic/systematic
- **Auto mode**: Select top 3 recommended professional roles - **Auto mode**: Select top 3 recommended professional roles
- **Manual mode**: AskUserQuestion with recommended roles + "Use simple perspectives" option - **Manual mode**: AskUserQuestion with recommended roles + "Use simple perspectives" option
3. **Initial Scoping Questions** (if new session + not auto mode) 3. **Initial Scoping Questions** (if new session + not auto mode)
- **Direction**: Multi-select from directions generated by detected dimensions (see Brainstorm Dimensions) - **Direction**: Multi-select from directions generated by detected dimensions
- **Depth**: Single-select from quick/balanced/deep (15-20min / 30-60min / 1-2hr) - **Depth**: Single-select from quick/balanced/deep (15-20min / 30-60min / 1-2hr)
- **Constraints**: Multi-select from existing architecture, time, resources, or no constraints - **Constraints**: Multi-select from existing architecture, time, resources, or no constraints
4. **Expand Seed into Exploration Vectors** 4. **Expand Seed into Exploration Vectors**
- Launch Gemini CLI with analysis mode
- Generate 5-7 exploration vectors:
- Core question: Fundamental problem/opportunity
- User perspective: Who benefits and how
- Technical angle: What enables this
- Alternative approaches: Other solutions
- Challenges: Potential blockers
- Innovation angle: 10x better approach
- Integration: Fit with existing systems
- Parse result into structured vectors
**CLI Call Example**:
```javascript ```javascript
Bash({ Bash({
command: `ccw cli -p " command: `ccw cli -p "
@@ -205,45 +151,12 @@ Output as structured exploration vectors for multi-perspective analysis.
}) })
``` ```
5. **Initialize brainstorm.md** 5. **Initialize brainstorm.md** with session metadata, initial context (user focus, depth, constraints), seed expansion (original idea + exploration vectors), empty thought evolution timeline sections
- Create brainstorm.md with session metadata
- Add initial context: user focus, depth, constraints
- Add seed expansion: original idea + exploration vectors
- Create empty sections for thought evolution timeline
**Success Criteria**:
- Session folder created with brainstorm.md initialized
- 1-3 roles selected (professional or simple perspectives)
- 5-7 exploration vectors generated
- User preferences captured (direction, depth, constraints)
### Phase 2: Divergent Exploration ### Phase 2: Divergent Exploration
**Objective**: Gather codebase context, then execute multi-perspective analysis in parallel.
**Prerequisites**:
- Phase 1 completed successfully
- Roles selected and stored
- brainstorm.md initialized
**Workflow Steps**:
1. **Primary Codebase Exploration via cli-explore-agent** (⚠️ FIRST) 1. **Primary Codebase Exploration via cli-explore-agent** (⚠️ FIRST)
- Agent type: `cli-explore-agent`
- Execution mode: synchronous (run_in_background: false)
- **Tasks**:
- Run: `ccw tool exec get_modules_by_depth '{}'`
- Search code related to topic keywords
- Read: `.workflow/project-tech.json` if exists
- **Output**: `{sessionFolder}/exploration-codebase.json`
- relevant_files: [{path, relevance, rationale}]
- existing_patterns: []
- architecture_constraints: []
- integration_points: []
- inspiration_sources: []
- **Purpose**: Enrich CLI prompts with codebase context
**Agent Call Example**:
```javascript ```javascript
Agent({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
@@ -281,147 +194,67 @@ Schema:
} }
` `
}) })
```
2. **Multi-CLI Perspective Analysis** (⚠️ AFTER exploration) 2. **Multi-CLI Perspective Analysis** (⚠️ AFTER exploration)
- Launch 3 CLI calls in parallel (Gemini/Codex/Claude)
- **Perspectives**:
- **Creative (Gemini)**: Innovation, cross-domain inspiration, challenge assumptions
- **Pragmatic (Codex)**: Implementation reality, feasibility, technical blockers
- **Systematic (Claude)**: Architecture, decomposition, scalability
- **Shared context**: Include exploration-codebase.json findings in prompts
- **Execution**: Bash with run_in_background: true, wait for all results
- **Output**: perspectives.json with creative/pragmatic/systematic sections
**Multi-CLI Call Example** (parallel execution): Build shared context from exploration results:
```javascript ```javascript
// Build shared context from exploration results
const explorationContext = ` const explorationContext = `
PRIOR EXPLORATION CONTEXT (from cli-explore-agent): PRIOR EXPLORATION CONTEXT (from cli-explore-agent):
- Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')} - Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
- Existing patterns: ${explorationResults.existing_patterns.slice(0,3).join(', ')} - Existing patterns: ${explorationResults.existing_patterns.slice(0,3).join(', ')}
- Architecture constraints: ${explorationResults.architecture_constraints.slice(0,3).join(', ')} - Architecture constraints: ${explorationResults.architecture_constraints.slice(0,3).join(', ')}
- Integration points: ${explorationResults.integration_points.slice(0,3).join(', ')}` - Integration points: ${explorationResults.integration_points.slice(0,3).join(', ')}`
```
// Launch 3 CLI calls in parallel (single message, multiple Bash calls) Launch 3 parallel CLI calls (`run_in_background: true` each), one per perspective:
| Perspective | Tool | PURPOSE | Key TASK bullets | EXPECTED | CONSTRAINTS |
|-------------|------|---------|-----------------|----------|-------------|
| Creative | gemini | Generate innovative ideas | Challenge assumptions, cross-domain inspiration, moonshot + practical ideas | 5+ creative ideas with novelty/impact ratings | structured mode: keep feasible |
| Pragmatic | codex | Implementation reality | Evaluate feasibility, estimate complexity, identify blockers, incremental approach | 3-5 practical approaches with effort/risk ratings | Current tech stack |
| Systematic | claude | Architectural thinking | Decompose problems, identify patterns, map dependencies, scalability | Problem decomposition, 2-3 approaches with tradeoffs | Existing architecture |
```javascript
// Each perspective uses this prompt structure (launch all 3 in parallel):
Bash({ Bash({
command: `ccw cli -p " command: `ccw cli -p "
PURPOSE: Creative brainstorming for '${idea_or_topic}' - generate innovative ideas PURPOSE: ${perspective} brainstorming for '${idea_or_topic}' - ${purposeFocus}
Success: 5+ unique creative solutions that push boundaries Success: ${expected}
${explorationContext} ${explorationContext}
TASK: TASK:
• Build on existing patterns - how can they be extended creatively? • Build on explored ${contextType} - how to ${actionVerb}?
• Think beyond obvious solutions - what would be surprising/delightful? ${perspectiveSpecificBullets}
• Explore cross-domain inspiration
• Challenge assumptions - what if the opposite were true?
• Generate 'moonshot' ideas alongside practical ones
MODE: analysis MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic} CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: 5+ creative ideas with novelty/impact ratings, challenged assumptions, cross-domain inspirations EXPECTED: ${expected}
CONSTRAINTS: ${brainstormMode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely'} CONSTRAINTS: ${constraints}
" --tool gemini --mode analysis`, " --tool ${tool} --mode analysis`,
run_in_background: true run_in_background: true
}) })
Bash({
command: `ccw cli -p "
PURPOSE: Pragmatic brainstorming for '${idea_or_topic}' - focus on implementation reality
Success: Actionable approaches with clear implementation paths
${explorationContext}
TASK:
• Build on explored codebase - how to integrate with existing patterns?
• Evaluate technical feasibility of core concept
• Identify existing patterns/libraries that could help
• Estimate implementation complexity
• Highlight potential technical blockers
• Suggest incremental implementation approach
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: 3-5 practical approaches with effort/risk ratings, dependencies, quick wins vs long-term
CONSTRAINTS: Focus on what can actually be built with current tech stack
" --tool codex --mode analysis`,
run_in_background: true
})
Bash({
command: `ccw cli -p "
PURPOSE: Systematic brainstorming for '${idea_or_topic}' - architectural thinking
Success: Well-structured solution framework with clear tradeoffs
${explorationContext}
TASK:
• Build on explored architecture - how to extend systematically?
• Decompose the problem into sub-problems
• Identify architectural patterns that apply
• Map dependencies and interactions
• Consider scalability implications
• Propose systematic solution structure
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: Problem decomposition, 2-3 architectural approaches with tradeoffs, scalability assessment
CONSTRAINTS: Consider existing system architecture
" --tool claude --mode analysis`,
run_in_background: true
})
// ⚠️ STOP POINT: Wait for hook callback to receive all results before continuing // ⚠️ STOP POINT: Wait for hook callback to receive all results before continuing
``` ```
3. **Aggregate Multi-Perspective Findings** 3. **Aggregate Multi-Perspective Findings**
- Consolidate creative/pragmatic/systematic results - Convergent themes (all agree), conflicting views (need resolution), unique contributions
- Extract synthesis:
- Convergent themes (all agree)
- Conflicting views (need resolution)
- Unique contributions (perspective-specific insights)
- Write to perspectives.json - Write to perspectives.json
4. **Update brainstorm.md** 4. **Update brainstorm.md** with Round 2 multi-perspective exploration and synthesis
- Append Round 2 section with multi-perspective exploration
- Include creative/pragmatic/systematic findings
- Add perspective synthesis
**CLI Prompt Template**:
- **PURPOSE**: Role brainstorming for topic - focus description
- **TASK**: Bullet list of specific actions
- **MODE**: analysis
- **CONTEXT**: @**/* | Topic + Exploration vectors + Codebase findings
- **EXPECTED**: Output format requirements
- **CONSTRAINTS**: Role-specific constraints
**Success Criteria**:
- exploration-codebase.json created with codebase context
- perspectives.json created with 3 perspective analyses
- brainstorm.md updated with Round 2 findings
- All CLI calls completed successfully
### Phase 3: Interactive Refinement ### Phase 3: Interactive Refinement
**Objective**: Iteratively refine ideas through user-guided exploration cycles. **Guideline**: Delegate complex tasks to agents (cli-explore-agent, code-developer, universal-executor) or CLI calls. Avoid direct analysis/execution in main process.
**Prerequisites**: 1. **Present Current State**: Extract top ideas from perspectives.json with title, source, description, novelty/feasibility ratings
- Phase 2 completed successfully
- perspectives.json contains initial ideas
- brainstorm.md has Round 2 findings
**Guideline**: For complex tasks (code analysis, implementation, POC creation), delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process.
**Workflow Steps**:
1. **Present Current State**
- Extract top ideas from perspectives.json
- Display with: title, source, brief description, novelty/feasibility ratings
- List open questions
2. **Gather User Direction** (AskUserQuestion) 2. **Gather User Direction** (AskUserQuestion)
- **Question 1**: Which ideas to explore (multi-select from top ideas) - **Q1**: Which ideas to explore (multi-select from top ideas)
- **Question 2**: Next step (single-select): - **Q2**: Next step (single-select):
- **深入探索**: Deep dive on selected ideas - **深入探索**: Deep dive on selected ideas
- **继续发散**: Generate more ideas - **继续发散**: Generate more ideas
- **挑战验证**: Devil's advocate challenge - **挑战验证**: Devil's advocate challenge
@@ -430,44 +263,14 @@ CONSTRAINTS: Consider existing system architecture
3. **Execute User-Selected Action** 3. **Execute User-Selected Action**
**Deep Dive** (per selected idea): | Action | Tool | Output | Key Tasks |
- Launch Gemini CLI with analysis mode |--------|------|--------|-----------|
- Tasks: Elaborate concept, implementation requirements, challenges, POC approach, metrics, dependencies | Deep Dive | Gemini CLI | ideas/{slug}.md | Elaborate concept, requirements, challenges, POC approach, metrics, dependencies |
- Output: `{sessionFolder}/ideas/{idea-slug}.md` | Generate More | Selected CLI | Updated perspectives.json | New angles from unexplored vectors |
| Challenge | Codex CLI | Challenge results | 3 objections per idea, challenge assumptions, failure scenarios, survivability (1-5) |
| Merge | Gemini CLI | ideas/merged-{slug}.md | Complementary elements, resolve contradictions, unified concept |
**Generate More Ideas**: **Deep Dive CLI Call**:
- Launch CLI with new angles from unexplored vectors
- Add results to perspectives.json
**Devil's Advocate Challenge**:
- Launch Codex CLI with analysis mode
- Tasks: Identify objections, challenge assumptions, failure scenarios, alternatives, survivability rating
- Return challenge results for idea strengthening
**Merge Ideas**:
- Launch Gemini CLI with analysis mode
- Tasks: Identify complementary elements, resolve contradictions, create unified concept
- Add merged idea to perspectives.json
4. **Update brainstorm.md**
- Append Round N section with findings
- Document user direction and action results
5. **Repeat or Converge**
- Continue loop (max 6 rounds) or exit to Phase 4
**Refinement Actions**:
| Action | Tool | Output | Description |
|--------|------|--------|-------------|
| Deep Dive | Gemini CLI | ideas/{slug}.md | Comprehensive idea analysis |
| Generate More | Selected CLI | Updated perspectives.json | Additional idea generation |
| Challenge | Codex CLI | Challenge results | Critical weaknesses exposed |
| Merge | Gemini CLI | Merged idea | Synthesized concept |
**CLI Call Examples for Refinement Actions**:
**1. Deep Dive on Selected Idea**:
```javascript ```javascript
Bash({ Bash({
command: `ccw cli -p " command: `ccw cli -p "
@@ -483,27 +286,18 @@ TASK:
• Map related/dependent features • Map related/dependent features
MODE: analysis MODE: analysis
CONTEXT: @**/* CONTEXT: @**/*
Original idea: ${idea.description} Original idea: ${idea.description}
Source perspective: ${idea.source} Source perspective: ${idea.source}
User interest reason: ${idea.userReason || 'Selected for exploration'}
EXPECTED:
- Detailed concept description
- Technical requirements list
- Risk/challenge matrix
- MVP definition
- Success criteria
- Recommendation: pursue/pivot/park
EXPECTED: Detailed concept, technical requirements, risk matrix, MVP definition, success criteria, recommendation (pursue/pivot/park)
CONSTRAINTS: Focus on actionability CONSTRAINTS: Focus on actionability
" --tool gemini --mode analysis`, " --tool gemini --mode analysis`,
run_in_background: false run_in_background: false
}) })
``` ```
**2. Devil's Advocate Challenge**: **Devil's Advocate CLI Call**:
```javascript ```javascript
Bash({ Bash({
command: `ccw cli -p " command: `ccw cli -p "
@@ -518,25 +312,17 @@ TASK:
• Challenge core assumptions • Challenge core assumptions
• Identify scenarios where this fails • Identify scenarios where this fails
• Consider competitive/alternative solutions • Consider competitive/alternative solutions
• Assess whether this solves the right problem
• Rate survivability after challenge (1-5) • Rate survivability after challenge (1-5)
MODE: analysis MODE: analysis
EXPECTED: Per-idea challenge report, critical weaknesses, survivability ratings, modified/strengthened versions
EXPECTED:
- Per-idea challenge report
- Critical weaknesses exposed
- Counter-arguments to objections (if any)
- Ideas that survive the challenge
- Modified/strengthened versions
CONSTRAINTS: Be genuinely critical, not just contrarian CONSTRAINTS: Be genuinely critical, not just contrarian
" --tool codex --mode analysis`, " --tool codex --mode analysis`,
run_in_background: false run_in_background: false
}) })
``` ```
**3. Merge Multiple Ideas**: **Merge Ideas CLI Call**:
```javascript ```javascript
Bash({ Bash({
command: `ccw cli -p " command: `ccw cli -p "
@@ -553,62 +339,32 @@ ${i+1}. ${idea.title} (${idea.source})
TASK: TASK:
• Identify complementary elements • Identify complementary elements
• Resolve contradictions • Resolve contradictions
• Create unified concept • Create unified concept preserving key strengths
• Preserve key strengths from each
• Describe the merged solution
• Assess viability of merged idea • Assess viability of merged idea
MODE: analysis MODE: analysis
EXPECTED: Merged concept, elements from each source, contradictions resolved, implementation considerations
EXPECTED:
- Merged concept description
- Elements taken from each source idea
- Contradictions resolved (or noted as tradeoffs)
- New combined strengths
- Implementation considerations
CONSTRAINTS: Don't force incompatible ideas together CONSTRAINTS: Don't force incompatible ideas together
" --tool gemini --mode analysis`, " --tool gemini --mode analysis`,
run_in_background: false run_in_background: false
}) })
``` ```
**Success Criteria**: 4. **Update brainstorm.md** with Round N findings
- User-selected ideas processed 5. **Repeat or Converge**: Continue loop (max 6 rounds) or exit to Phase 4
- brainstorm.md updated with all refinement rounds
- ideas/ folder contains deep-dive documents for selected ideas
- Exit condition reached (user selects "准备收敛" or max rounds)
### Phase 4: Convergence & Crystallization ### Phase 4: Convergence & Crystallization
**Objective**: Synthesize final ideas, generate conclusions, offer next steps. 1. **Generate Final Synthesis** → Write to synthesis.json
- **Top ideas**: Filter active, sort by score, top 5 with title, description, source_perspective, score, novelty, feasibility, strengths, challenges, next_steps
**Prerequisites**: - **Parked ideas**: With reason and future trigger
- Phase 3 completed successfully
- Multiple rounds of refinement documented
- User ready to converge
**Workflow Steps**:
1. **Generate Final Synthesis**
- Consolidate all ideas from perspectives.json and refinement rounds
- **Top ideas**: Filter active ideas, sort by score, take top 5
- Include: title, description, source_perspective, score, novelty, feasibility, strengths, challenges, next_steps
- **Parked ideas**: Ideas marked as parked with reason and future trigger
- **Key insights**: Process discoveries, challenged assumptions, unexpected connections - **Key insights**: Process discoveries, challenged assumptions, unexpected connections
- **Recommendations**: Primary recommendation, alternatives, not recommended - **Recommendations**: Primary, alternatives, not recommended
- **Follow-up**: Implementation/research/validation summaries - **Follow-up**: Implementation/research/validation summaries
- Write to synthesis.json
2. **Final brainstorm.md Update** **synthesis.json Schema**: `session_id`, `topic`, `completed` (timestamp), `total_rounds`, `top_ideas[]`, `parked_ideas[]`, `key_insights[]`, `recommendations` (primary/alternatives/not_recommended), `follow_up[]`
- Append synthesis & conclusions section
- **Executive summary**: High-level overview 2. **Final brainstorm.md Update**: Executive summary, top ideas ranked, primary recommendation with rationale, alternative approaches, parked ideas, key insights, session statistics (rounds, ideas generated/survived, duration)
- **Top ideas**: Ranked with descriptions, strengths, challenges, next steps
- **Primary recommendation**: Best path forward with rationale
- **Alternative approaches**: Other viable options with tradeoffs
- **Parked ideas**: Future considerations
- **Key insights**: Learnings from the process
- **Session statistics**: Rounds, ideas generated/survived, duration
3. **Post-Completion Options** (AskUserQuestion) 3. **Post-Completion Options** (AskUserQuestion)
- **创建实施计划**: Launch workflow-plan with top idea - **创建实施计划**: Launch workflow-plan with top idea
@@ -617,29 +373,10 @@ CONSTRAINTS: Don't force incompatible ideas together
- **导出分享**: Generate shareable report - **导出分享**: Generate shareable report
- **完成**: No further action - **完成**: No further action
**synthesis.json Schema**:
- `session_id`: Session identifier
- `topic`: Original idea/topic
- `completed`: Completion timestamp
- `total_rounds`: Number of refinement rounds
- `top_ideas[]`: Top 5 ranked ideas
- `parked_ideas[]`: Ideas parked for future
- `key_insights[]`: Process learnings
- `recommendations`: Primary/alternatives/not_recommended
- `follow_up[]`: Next step summaries
**Success Criteria**:
- synthesis.json created with final synthesis
- brainstorm.md finalized with conclusions
- User offered next step options
- Session complete
## Configuration ## Configuration
### Brainstorm Dimensions ### Brainstorm Dimensions
Dimensions matched against topic keywords to identify focus areas:
| Dimension | Keywords | | Dimension | Keywords |
|-----------|----------| |-----------|----------|
| technical | 技术, technical, implementation, code, 实现, architecture | | technical | 技术, technical, implementation, code, 实现, architecture |
@@ -652,7 +389,7 @@ Dimensions matched against topic keywords to identify focus areas:
### Role Selection ### Role Selection
**Professional Roles** (recommended based on topic keywords): **Professional Roles**:
| Role | CLI Tool | Focus Area | Keywords | | Role | CLI Tool | Focus Area | Keywords |
|------|----------|------------|----------| |------|----------|------------|----------|
@@ -668,47 +405,13 @@ Dimensions matched against topic keywords to identify focus areas:
**Simple Perspectives** (fallback): **Simple Perspectives** (fallback):
| Perspective | CLI Tool | Focus | Best For | | Perspective | CLI Tool | Focus |
|-------------|----------|-------|----------| |-------------|----------|-------|
| creative | Gemini | Innovation, cross-domain | Generating novel ideas | | creative | Gemini | Innovation, cross-domain |
| pragmatic | Codex | Implementation, feasibility | Reality-checking ideas | | pragmatic | Codex | Implementation, feasibility |
| systematic | Claude | Architecture, structure | Organizing solutions | | systematic | Claude | Architecture, structure |
**Selection Strategy**: **Selection Strategy**: Auto mode → top 3 professional roles | Manual mode → recommended roles + "Use simple perspectives" option | Continue mode → roles from previous session
1. **Auto mode** (`-y`): Choose top 3 recommended professional roles
2. **Manual mode**: Present recommended roles + "Use simple perspectives" option
3. **Continue mode**: Use roles from previous session
### Collaboration Patterns
| Pattern | Usage | Description |
|---------|-------|-------------|
| Parallel Divergence | New topic | All roles explore simultaneously from different angles |
| Sequential Deep-Dive | Promising idea | One role expands, others critique/refine |
| Debate Mode | Controversial approach | Roles argue for/against approaches |
| Synthesis Mode | Ready to decide | Combine insights into actionable conclusion |
### Context Overflow Protection
**Per-Role Limits**:
- Main analysis output: < 3000 words
- Sub-document (if any): < 2000 words each
- Maximum sub-documents: 5 per role
**Synthesis Protection**:
- If total analysis > 100KB, synthesis reads only main analysis files (not sub-documents)
- Large ideas automatically split into separate idea documents in ideas/ folder
**Recovery Steps**:
1. Check CLI logs for context overflow errors
2. Reduce scope: fewer roles or simpler topic
3. Use `--mode structured` for more focused output
4. Split complex topics into multiple sessions
**Prevention**:
- Start with 3 roles (default), increase if needed
- Use structured topic format: "GOAL: ... SCOPE: ... CONTEXT: ..."
- Review output sizes before final synthesis
## Error Handling ## Error Handling
@@ -722,58 +425,6 @@ Dimensions matched against topic keywords to identify focus areas:
| Max rounds reached | Force synthesis, highlight unresolved questions | | Max rounds reached | Force synthesis, highlight unresolved questions |
| All ideas fail challenge | Return to divergent phase with new constraints | | All ideas fail challenge | Return to divergent phase with new constraints |
## Best Practices
1. **Clear Topic Definition**: Detailed topics → better role selection and exploration
2. **Agent-First for Complex Tasks**: For code analysis, POC implementation, or technical validation during refinement, delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process
3. **Review brainstorm.md**: Check thought evolution before final decisions
4. **Embrace Conflicts**: Perspective conflicts often reveal important tradeoffs
5. **Document Evolution**: brainstorm.md captures full thinking process for team review
6. **Use Continue Mode**: Resume sessions to build on previous exploration
## Templates
### Brainstorm Document Structure
**brainstorm.md** contains:
- **Header**: Session metadata (ID, topic, started, mode, dimensions)
- **Initial Context**: User focus, depth, constraints
- **Seed Expansion**: Original idea + exploration vectors
- **Thought Evolution Timeline**: Round-by-round findings
- Round 1: Seed Understanding
- Round 2: Multi-Perspective Exploration (creative/pragmatic/systematic)
- Round 3-N: Interactive Refinement (deep-dive/challenge/merge)
- **Synthesis & Conclusions**: Executive summary, top ideas, recommendations
- **Session Statistics**: Rounds, ideas, duration, artifacts
See full markdown template in original file (lines 955-1161).
## Usage Recommendations (Requires User Confirmation)
**Use `Skill(skill="brainstorm", args="\"topic or question\"")` when:**
- Starting a new feature/product without clear direction
- Facing a complex problem with multiple possible solutions
- Need to explore alternatives before committing
- Want documented thinking process for team review
- Combining multiple stakeholder perspectives
**Use `Skill(skill="workflow:analyze-with-file", args="\"topic\"")` when:**
- Investigating existing code/system
- Need factual analysis over ideation
- Debugging or troubleshooting
- Understanding current state
**Use `Skill(skill="workflow-plan", args="\"task description\"")` when:**
- Complex planning requiring multiple perspectives
- Large scope needing parallel sub-domain analysis
- Want shared collaborative planning document
- Need structured task breakdown with agent coordination
**Use `Skill(skill="workflow-lite-plan", args="\"task description\"")` when:**
- Direction is already clear
- Ready to move from ideas to execution
- Need simple implementation breakdown
--- ---
**Now execute brainstorm-with-file for**: $ARGUMENTS **Now execute brainstorm-with-file for**: $ARGUMENTS

View File

@@ -10,46 +10,12 @@ allowed-tools: Skill, Agent, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash
When `workflowPreferences.autoYes` is true: Auto-approve plan, use recommended solution and execution method (Agent, Skip review). When `workflowPreferences.autoYes` is true: Auto-approve plan, use recommended solution and execution method (Agent, Skip review).
## Quick Start
```bash
# Basic usage
/workflow-multi-cli-plan "Implement user authentication"
# With options
/workflow-multi-cli-plan "Add dark mode support" --max-rounds=3
/workflow-multi-cli-plan "Refactor payment module" --tools=gemini,codex,claude
/workflow-multi-cli-plan "Fix memory leak" --mode=serial
```
**Context Source**: ACE semantic search + Multi-CLI analysis **Context Source**: ACE semantic search + Multi-CLI analysis
**Output Directory**: `.workflow/.multi-cli-plan/{session-id}/` **Output Directory**: `.workflow/.multi-cli-plan/{session-id}/`
**Default Max Rounds**: 3 (convergence may complete earlier) **Default Max Rounds**: 3 (convergence may complete earlier)
**CLI Tools**: @cli-discuss-agent (analysis), @cli-lite-planning-agent (plan generation) **CLI Tools**: @cli-discuss-agent (analysis), @cli-lite-planning-agent (plan generation)
**Execution**: Auto-hands off to workflow-lite-execute after plan approval **Execution**: Auto-hands off to workflow-lite-execute after plan approval
## What & Why
### Core Concept
Multi-CLI collaborative planning with **three-phase architecture**: ACE context gathering → Iterative multi-CLI discussion → Plan generation. Orchestrator delegates analysis to agents, only handles user decisions and session management.
**Process**:
- **Phase 1**: ACE semantic search gathers codebase context
- **Phase 2**: cli-discuss-agent orchestrates Gemini/Codex/Claude for cross-verified analysis
- **Phase 3-5**: User decision → Plan generation → Execution handoff
**vs Single-CLI Planning**:
- **Single**: One model perspective, potential blind spots
- **Multi-CLI**: Cross-verification catches inconsistencies, builds consensus on solutions
### Value Proposition
1. **Multi-Perspective Analysis**: Gemini + Codex + Claude analyze from different angles
2. **Cross-Verification**: Identify agreements/disagreements, build confidence
3. **User-Driven Decisions**: Every round ends with user decision point
4. **Iterative Convergence**: Progressive refinement until consensus reached
### Orchestrator Boundary (CRITICAL) ### Orchestrator Boundary (CRITICAL)
- **ONLY command** for multi-CLI collaborative planning - **ONLY command** for multi-CLI collaborative planning
@@ -123,14 +89,7 @@ const aceQueries = [
### Phase 2: Agent Delegation ### Phase 2: Agent Delegation
**Core Principle**: Orchestrator only delegates and reads output - NO direct CLI execution. **Core Principle**: Orchestrator only delegates and reads output NO direct CLI execution. CLI calls MUST use `Bash` with `run_in_background: true`, wait for hook callback, do NOT use `TaskOutput` polling.
**⚠️ CRITICAL - CLI EXECUTION REQUIREMENT**:
- **MUST** execute CLI calls via `Bash` with `run_in_background: true`
- **MUST** wait for hook callback to receive complete results
- **MUST NOT** proceed with next phase until CLI execution fully completes
- Do NOT use `TaskOutput` polling during CLI execution - wait passively for results
- Minimize scope: Proceed only when 100% result available
**Agent Invocation**: **Agent Invocation**:
```javascript ```javascript
@@ -143,7 +102,7 @@ Agent({
- task_description: ${taskDescription} - task_description: ${taskDescription}
- round_number: ${currentRound} - round_number: ${currentRound}
- session: { id: "${sessionId}", folder: "${sessionFolder}" } - session: { id: "${sessionId}", folder: "${sessionFolder}" }
- ace_context: ${JSON.stringify(contextPackageage)} - ace_context: ${JSON.stringify(contextPackage)}
- previous_rounds: ${JSON.stringify(analysisResults)} - previous_rounds: ${JSON.stringify(analysisResults)}
- user_feedback: ${userFeedback || 'None'} - user_feedback: ${userFeedback || 'None'}
- cli_config: { tools: ["gemini", "codex"], mode: "parallel", fallback_chain: ["gemini", "codex", "claude"] } - cli_config: { tools: ["gemini", "codex"], mode: "parallel", fallback_chain: ["gemini", "codex", "claude"] }
@@ -191,31 +150,10 @@ if (synthesis.convergence.recommendation === 'converged') {
### Phase 3: Present Options ### Phase 3: Present Options
**Display from Agent Output** (no processing): Display solutions from `synthesis.solutions[]` showing: name, source CLIs, effort/risk, pros/cons, affected files (`file:line`). Also show cross-verification agreements/disagreements count.
```javascript
console.log(`
## Solution Options
${synthesis.solutions.map((s, i) => `
**Option ${i+1}: ${s.name}**
Source: ${s.source_cli.join(' + ')}
Effort: ${s.effort} | Risk: ${s.risk}
Pros: ${s.pros.join(', ')}
Cons: ${s.cons.join(', ')}
Files: ${s.affected_files.slice(0,3).map(f => `${f.file}:${f.line}`).join(', ')}
`).join('\n')}
## Cross-Verification
Agreements: ${synthesis.cross_verification.agreements.length}
Disagreements: ${synthesis.cross_verification.disagreements.length}
`)
```
### Phase 4: User Decision ### Phase 4: User Decision
**Decision Options**:
```javascript ```javascript
AskUserQuestion({ AskUserQuestion({
questions: [ questions: [
@@ -277,9 +215,7 @@ TodoWrite({ todos: [
**Step 1: Build Context-Package** (Orchestrator responsibility): **Step 1: Build Context-Package** (Orchestrator responsibility):
```javascript ```javascript
// Extract key information from user decision and synthesis
const contextPackage = { const contextPackage = {
// Core solution details
solution: { solution: {
name: selectedSolution.name, name: selectedSolution.name,
source_cli: selectedSolution.source_cli, source_cli: selectedSolution.source_cli,
@@ -288,25 +224,17 @@ const contextPackage = {
risk: selectedSolution.risk, risk: selectedSolution.risk,
summary: selectedSolution.summary summary: selectedSolution.summary
}, },
// Implementation plan (tasks, flow, milestones)
implementation_plan: selectedSolution.implementation_plan, implementation_plan: selectedSolution.implementation_plan,
// Dependencies
dependencies: selectedSolution.dependencies || { internal: [], external: [] }, dependencies: selectedSolution.dependencies || { internal: [], external: [] },
// Technical concerns
technical_concerns: selectedSolution.technical_concerns || [], technical_concerns: selectedSolution.technical_concerns || [],
// Consensus from cross-verification
consensus: { consensus: {
agreements: synthesis.cross_verification.agreements, agreements: synthesis.cross_verification.agreements,
resolved_conflicts: synthesis.cross_verification.resolution resolved_conflicts: synthesis.cross_verification.resolution
}, },
// User constraints (from Phase 4 feedback)
constraints: userConstraints || [], constraints: userConstraints || [],
// Task context
task_description: taskDescription, task_description: taskDescription,
session_id: sessionId session_id: sessionId
} }
// Write context-package for traceability
Write(`${sessionFolder}/context-package.json`, JSON.stringify(contextPackage, null, 2)) Write(`${sessionFolder}/context-package.json`, JSON.stringify(contextPackage, null, 2))
``` ```
@@ -367,10 +295,7 @@ ${JSON.stringify(contextPackage, null, 2)}
**Step 3: Build executionContext**: **Step 3: Build executionContext**:
```javascript ```javascript
// After plan.json is generated by cli-lite-planning-agent
const plan = JSON.parse(Read(`${sessionFolder}/plan.json`)) const plan = JSON.parse(Read(`${sessionFolder}/plan.json`))
// Load task files from .task/ directory (two-layer format)
const taskFiles = plan.task_ids.map(id => `${sessionFolder}/.task/${id}.json`) const taskFiles = plan.task_ids.map(id => `${sessionFolder}/.task/${id}.json`)
// Build executionContext (same structure as lite-plan) // Build executionContext (same structure as lite-plan)
@@ -378,16 +303,13 @@ executionContext = {
planObject: plan, planObject: plan,
taskFiles: taskFiles, // Paths to .task/*.json files (two-layer format) taskFiles: taskFiles, // Paths to .task/*.json files (two-layer format)
explorationsContext: null, // Multi-CLI doesn't use exploration files explorationsContext: null, // Multi-CLI doesn't use exploration files
explorationAngles: [], // No exploration angles explorationAngles: [],
explorationManifest: null, // No manifest explorationManifest: null,
clarificationContext: null, // Store user feedback from Phase 2 if exists clarificationContext: null, // Store user feedback from Phase 2 if exists
executionMethod: userSelection.execution_method, // From Phase 4 executionMethod: userSelection.execution_method, // From Phase 4
codeReviewTool: userSelection.code_review_tool, // From Phase 4 codeReviewTool: userSelection.code_review_tool, // From Phase 4
originalUserInput: taskDescription, originalUserInput: taskDescription,
executorAssignments: null,
// Optional: Task-level executor assignments
executorAssignments: null, // Could be enhanced in future
session: { session: {
id: sessionId, id: sessionId,
folder: sessionFolder, folder: sessionFolder,
@@ -407,7 +329,6 @@ executionContext = {
**Step 4: Hand off to Execution**: **Step 4: Hand off to Execution**:
```javascript ```javascript
// Skill handoff: Invoke workflow-lite-execute with in-memory context
Skill({ Skill({
skill: "workflow-lite-execute", skill: "workflow-lite-execute",
args: "--in-memory" args: "--in-memory"
@@ -415,23 +336,6 @@ Skill({
// executionContext is passed via global variable to workflow-lite-execute (Mode 1: In-Memory Plan) // executionContext is passed via global variable to workflow-lite-execute (Mode 1: In-Memory Plan)
``` ```
## Output File Structure
```
.workflow/.multi-cli-plan/{MCP-task-slug-YYYY-MM-DD}/
├── session-state.json # Session tracking (orchestrator)
├── rounds/
│ ├── 1/synthesis.json # Round 1 analysis (cli-discuss-agent)
│ ├── 2/synthesis.json # Round 2 analysis (cli-discuss-agent)
│ └── .../
├── context-package.json # Extracted context for planning (orchestrator)
├── plan.json # Plan overview with task_ids[] (NO embedded tasks[])
└── .task/ # Independent task files
├── TASK-001.json # Task file following task-schema.json
├── TASK-002.json
└── ...
```
## synthesis.json Schema ## synthesis.json Schema
```json ```json
@@ -469,9 +373,9 @@ Skill({
} }
``` ```
## TodoWrite Structure ## TodoWrite Pattern
**Initialization**: **Initialization** (Phase 1 start):
```javascript ```javascript
TodoWrite({ todos: [ TodoWrite({ todos: [
{ content: "Phase 1: Context Gathering", status: "in_progress", activeForm: "Gathering context" }, { content: "Phase 1: Context Gathering", status: "in_progress", activeForm: "Gathering context" },
@@ -482,6 +386,23 @@ TodoWrite({ todos: [
]}) ]})
``` ```
## Output File Structure
```
.workflow/.multi-cli-plan/{MCP-task-slug-YYYY-MM-DD}/
├── session-state.json # Session tracking (orchestrator)
├── rounds/
│ ├── 1/synthesis.json # Round 1 analysis (cli-discuss-agent)
│ ├── 2/synthesis.json # Round 2 analysis (cli-discuss-agent)
│ └── .../
├── context-package.json # Extracted context for planning (orchestrator)
├── plan.json # Plan overview with task_ids[] (NO embedded tasks[])
└── .task/ # Independent task files
├── TASK-001.json # Task file following task-schema.json
├── TASK-002.json
└── ...
```
## Error Handling ## Error Handling
| Error | Resolution | | Error | Resolution |
@@ -501,22 +422,3 @@ TodoWrite({ todos: [
| `--tools` | gemini,codex | CLI tools for analysis | | `--tools` | gemini,codex | CLI tools for analysis |
| `--mode` | parallel | Execution mode: parallel or serial | | `--mode` | parallel | Execution mode: parallel or serial |
| `--auto-execute` | false | Auto-execute after approval | | `--auto-execute` | false | Auto-execute after approval |
## Related Commands
```bash
# Simpler single-round planning
/workflow-lite-plan "task description"
# Issue-driven discovery
/issue:discover-by-prompt "find issues"
# View session files
cat .workflow/.multi-cli-plan/{session-id}/plan.json
cat .workflow/.multi-cli-plan/{session-id}/rounds/1/synthesis.json
cat .workflow/.multi-cli-plan/{session-id}/context-package.json
```
## Next Phase
Auto-continue via `Skill({ skill: "workflow-lite-execute", args: "--in-memory" })` with executionContext.

View File

@@ -26,7 +26,7 @@ Interactive collaborative analysis workflow with **documented discussion process
| Trigger | What to Record | Target Section | | Trigger | What to Record | Target Section |
|---------|---------------|----------------| |---------|---------------|----------------|
| **Direction choice** | What was chosen, why, what alternatives were discarded | `#### Decision Log` | | **Direction choice** | What was chosen, why, what alternatives were discarded | `#### Decision Log` |
| **Key finding** | Finding content, impact scope, confidence level | `#### Key Findings` | | **Key finding** | Finding content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
| **Assumption change** | Old assumption → new understanding, reason, impact | `#### Corrected Assumptions` | | **Assumption change** | Old assumption → new understanding, reason, impact | `#### Corrected Assumptions` |
| **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` | | **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` |
| **Disagreement & trade-off** | Conflicting viewpoints, trade-off basis, final choice | `#### Decision Log` | | **Disagreement & trade-off** | Conflicting viewpoints, trade-off basis, final choice | `#### Decision Log` |
@@ -38,13 +38,23 @@ Interactive collaborative analysis workflow with **documented discussion process
> - **Context**: [What triggered this decision] > - **Context**: [What triggered this decision]
> - **Options considered**: [Alternatives evaluated] > - **Options considered**: [Alternatives evaluated]
> - **Chosen**: [Selected approach] — **Reason**: [Rationale] > - **Chosen**: [Selected approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **Impact**: [Effect on analysis direction/conclusions] > - **Impact**: [Effect on analysis direction/conclusions]
``` ```
**Key Finding Record Format**:
```markdown
> **Finding**: [Content]
> - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
> - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
> - **Scope**: [What areas this affects]
```
**Recording Principles**: **Recording Principles**:
- **Immediacy**: Record decisions as they happen, not at the end of a phase - **Immediacy**: Record decisions as they happen, not at the end of a phase
- **Completeness**: Capture context, options, chosen approach, and reason - **Completeness**: Capture context, options, chosen approach, reason, and rejected alternatives
- **Traceability**: Later phases must be able to trace back why a decision was made - **Traceability**: Later phases must be able to trace back why a decision was made
- **Depth**: Capture reasoning and hypothesis impact, not just outcomes
## Auto Mode ## Auto Mode
@@ -91,22 +101,33 @@ Step 2: Exploration (Inline, No Agents)
│ ├─ Single: Comprehensive analysis │ ├─ Single: Comprehensive analysis
│ └─ Multi (≤4): Serial per-perspective analysis with synthesis │ └─ Multi (≤4): Serial per-perspective analysis with synthesis
├─ Aggregate findings → explorations.json / perspectives.json ├─ Aggregate findings → explorations.json / perspectives.json
─ Update discussion.md with Round 1 ─ Update discussion.md with Round 1
│ ├─ Replace ## Current Understanding with initial findings
│ └─ Update ## Table of Contents
└─ Initial Intent Coverage Check (early drift detection)
Step 3: Interactive Discussion (Multi-Round, max 5) Step 3: Interactive Discussion (Multi-Round, max 5)
├─ Current Understanding Summary (round ≥ 2, before findings)
├─ Present exploration findings ├─ Present exploration findings
├─ Gather user feedback ├─ Gather user feedback
├─ Process response: ├─ Process response:
│ ├─ Deepen → deeper inline analysis in current direction │ ├─ Deepen → context-driven + heuristic options → deeper inline analysis
│ ├─ Agree & Suggest → user-directed exploration
│ ├─ Adjust → new inline analysis with adjusted focus │ ├─ Adjust → new inline analysis with adjusted focus
│ ├─ Questions → direct answers with evidence │ ├─ Questions → direct answers with evidence
│ └─ Complete → exit loop for synthesis │ └─ Complete → exit loop for synthesis
├─ Update discussion.md with each round ├─ Update discussion.md:
│ ├─ Append round details + Narrative Synthesis
│ ├─ Replace ## Current Understanding with latest state
│ └─ Update ## Table of Contents
├─ Intent Drift Check (round ≥ 2, building on Phase 2 initial check)
└─ Repeat until user selects complete or max rounds └─ Repeat until user selects complete or max rounds
Step 4: Synthesis & Conclusion Step 4: Synthesis & Conclusion
├─ Consolidate all insights → conclusions.json ├─ Intent Coverage Verification (mandatory gate)
├─ Consolidate all insights → conclusions.json (with steps[] per recommendation)
├─ Update discussion.md with final synthesis ├─ Update discussion.md with final synthesis
├─ Interactive Recommendation Review (per-recommendation confirm/modify/reject)
└─ Offer options: quick execute / create issue / generate task / export / done └─ Offer options: quick execute / create issue / generate task / export / done
Step 5: Execute (Optional - user selects, routes by complexity) Step 5: Execute (Optional - user selects, routes by complexity)
@@ -237,6 +258,19 @@ const discussionMd = `# Analysis Discussion
**Dimensions**: ${dimensions.join(', ')} **Dimensions**: ${dimensions.join(', ')}
**Depth**: ${analysisDepth} **Depth**: ${analysisDepth}
## Table of Contents
<!-- TOC: Auto-updated after each round/phase. Links to major sections. -->
- [Analysis Context](#analysis-context)
- [Current Understanding](#current-understanding)
- [Discussion Timeline](#discussion-timeline)
- [Decision Trail](#decision-trail)
## Current Understanding
<!-- REPLACEABLE BLOCK: Overwrite (not append) after each round with latest consolidated understanding.
Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state. -->
> To be populated after exploration.
## Analysis Context ## Analysis Context
- Focus areas: ${focusAreas.join(', ')} - Focus areas: ${focusAreas.join(', ')}
- Perspectives: ${selectedPerspectives.map(p => p.name).join(', ')} - Perspectives: ${selectedPerspectives.map(p => p.name).join(', ')}
@@ -260,12 +294,6 @@ ${generateInitialQuestions(topic, dimensions).map(q => `- ${q}`).join('\n')}
## Decision Trail ## Decision Trail
> Consolidated critical decisions across all rounds (populated in Phase 4). > Consolidated critical decisions across all rounds (populated in Phase 4).
---
## Current Understanding
> To be populated after exploration.
` `
Write(`${sessionFolder}/discussion.md`, discussionMd) Write(`${sessionFolder}/discussion.md`, discussionMd)
``` ```
@@ -426,10 +454,33 @@ Append Round 1 with exploration results:
- Discussion points - Discussion points
- Open questions - Open questions
##### Step 2.5: Initial Intent Coverage Check
Perform the FIRST intent coverage check before entering Phase 3:
```javascript
// Re-read original user intent / analysis context from discussion.md header
// Check each intent item against Round 1 findings
// Append to discussion.md:
appendToDiscussion(`
#### Initial Intent Coverage Check (Post-Exploration)
${originalIntents.map((intent, i) => {
const status = assessCoverage(intent, explorationFindings)
return `- ${status.icon} Intent ${i+1}: ${intent}${status.detail}`
}).join('\n')}
> 接下来的讨论将重点关注未覆盖 (❌) 和进行中 (🔄) 的意图。
`)
// Present to user at beginning of Phase 3 for early course correction
```
**Success Criteria**: **Success Criteria**:
- exploration-codebase.json created with codebase context (if codebase exists) - exploration-codebase.json created with codebase context (if codebase exists)
- explorations.json (single) or perspectives.json (multi) created with findings - explorations.json (single) or perspectives.json (multi) created with findings
- discussion.md updated with Round 1 results - discussion.md updated with Round 1 results
- **Initial Intent Coverage Check** completed — early drift detection before interactive rounds
- Ready for interactive discussion - Ready for interactive discussion
- **Key findings recorded** with evidence references and confidence levels - **Key findings recorded** with evidence references and confidence levels
- **Exploration decisions recorded** (why certain perspectives/search strategies were chosen) - **Exploration decisions recorded** (why certain perspectives/search strategies were chosen)
@@ -440,11 +491,22 @@ Append Round 1 with exploration results:
**Max Rounds**: 5 discussion rounds (can exit earlier if user indicates analysis is complete) **Max Rounds**: 5 discussion rounds (can exit earlier if user indicates analysis is complete)
##### Step 3.1: Present Findings & Gather Feedback ##### Step 3.1: Current Understanding Summary & Present Findings
**Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
- Generate 1-2 sentence recap of established consensus and last round's direction
- Example: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
- Purpose: Reset context, prevent cognitive overload, make incremental progress visible
Display current understanding and gather user direction: Display current understanding and gather user direction:
```javascript ```javascript
// Round >= 2: Display Current Understanding Summary first
if (round >= 2) {
// Generate 1-2 sentence recap from previous round's narrative synthesis
// Display before presenting new findings
}
// Display current findings summary from explorations.json or perspectives.json // Display current findings summary from explorations.json or perspectives.json
// Show key points, discussion points, open questions // Show key points, discussion points, open questions
@@ -456,6 +518,7 @@ if (!autoYes) {
multiSelect: false, multiSelect: false,
options: [ options: [
{ label: "Deepen", description: "Analysis direction is correct, investigate deeper" }, { label: "Deepen", description: "Analysis direction is correct, investigate deeper" },
{ label: "Agree & Suggest", description: "Agree with direction, but have specific next step in mind" },
{ label: "Adjust Direction", description: "Different understanding or focus needed" }, { label: "Adjust Direction", description: "Different understanding or focus needed" },
{ label: "Specific Questions", description: "Have specific questions to ask" }, { label: "Specific Questions", description: "Have specific questions to ask" },
{ label: "Analysis Complete", description: "Sufficient information obtained, proceed to synthesis" } { label: "Analysis Complete", description: "Sufficient information obtained, proceed to synthesis" }
@@ -474,15 +537,34 @@ if (!autoYes) {
**Deepen** — continue analysis in current direction: **Deepen** — continue analysis in current direction:
```javascript ```javascript
// Deeper inline analysis using search tools // Generate deepen direction options dynamically:
// Investigate edge cases, special scenarios // - 2-3 context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions
// Identify patterns not yet discussed // - 1-2 heuristic options that break current frame:
// Suggest improvement approaches // e.g., "compare with best practices in [related domain]",
// Provide risk/impact assessments // "analyze under extreme load scenarios",
// Update explorations.json with deepening findings // "review from security audit perspective",
// "explore simpler architectural alternatives"
// AskUserQuestion with generated options (single-select)
// Execute selected direction via inline search tools
// Merge new findings into explorations.json
// Record: Which assumptions were confirmed, specific angles for deeper exploration // Record: Which assumptions were confirmed, specific angles for deeper exploration
``` ```
**Agree & Suggest** — user provides specific next step:
```javascript
// Ask user for their specific direction (free text input)
const userSuggestion = AskUserQuestion({
questions: [{
question: "请描述您希望下一步深入的方向:",
header: "Your Direction",
multiSelect: false,
options: [/* user will select "Other" to type free text */]
}]
})
// Execute user's specific direction via inline search tools
// Record: User-driven exploration rationale and findings
```
**Adjust Direction** — new focus area: **Adjust Direction** — new focus area:
```javascript ```javascript
// Ask user for adjusted focus // Ask user for adjusted focus
@@ -525,25 +607,45 @@ const adjustedFocus = AskUserQuestion({
Update discussion.md with results from each discussion round: Update discussion.md with results from each discussion round:
**Append** to Discussion Timeline:
| Section | Content | | Section | Content |
|---------|---------| |---------|---------|
| User Direction | Action taken (deepen/adjust/questions) and focus area | | User Direction | Action taken (deepen/adjust/suggest/questions) and focus area |
| Decision Log | Decisions made this round using Decision Record format | | Decision Log | Decisions made this round using Decision Record format (with rejected alternatives) |
| Analysis Results | Key findings, insights, evidence with file references | | Key Findings | Findings using Key Finding Record format (with confidence + hypothesis impact) |
| Insights | New learnings or clarifications from this round | | Analysis Results | Detailed insights, evidence with file references |
| Corrected Assumptions | Important wrong→right transformations with explanation | | Corrected Assumptions | Important wrong→right transformations with explanation |
| Open Items | Remaining questions or areas for future investigation | | Open Items | Remaining questions or areas for future investigation |
| **Narrative Synthesis** | Round-end summary connecting this round to overall understanding evolution |
**Replace** (not append) these sections:
| Section | Update Rule |
|---------|-------------|
| `## Current Understanding` | Overwrite with latest consolidated understanding. Follow Consolidation Rules: promote confirmed insights, track corrections, focus on current state — NOT cumulative history |
| `## Table of Contents` | Update links to include new Round N sections and any new headings |
**Round Narrative Synthesis** (append after each round update):
```markdown
### Round N: Narrative Synthesis
**起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
**关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
**决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
**当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
**遗留问题**: [remaining questions driving next round]
```
**Documentation Standards**: **Documentation Standards**:
- Clear timestamps for each round - Clear timestamps for each round
- Evidence-based findings with file references - Evidence-based findings with file references and confidence levels
- Explicit tracking of assumption corrections - Explicit tracking of assumption corrections
- Organized by analysis dimension - Organized by analysis dimension
- Links between rounds showing understanding evolution - Narrative synthesis linking rounds into coherent understanding evolution
##### Step 3.4: Intent Drift Check (every round ≥ 2) ##### Step 3.4: Intent Drift Check (every round ≥ 2, building on Phase 2 initial check)
Re-read "User Intent" / "Analysis Context" from discussion.md header. For each original intent item, check coverage status: 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:
```markdown ```markdown
#### Intent Coverage Check #### Intent Coverage Check
@@ -554,7 +656,7 @@ Re-read "User Intent" / "Analysis Context" from discussion.md header. For each o
``` ```
- If any item is "implicitly absorbed" (⚠️), note it explicitly in discussion.md — absorbed ≠ addressed - If any item is "implicitly absorbed" (⚠️), note it explicitly in discussion.md — absorbed ≠ addressed
- If any item is ❌ after 3+ rounds, surface it to the user in the next round's presentation - If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
**Success Criteria**: **Success Criteria**:
- User feedback processed for each round - User feedback processed for each round
@@ -609,7 +711,11 @@ const conclusions = {
action: '...', // What to do (imperative verb + target) action: '...', // What to do (imperative verb + target)
rationale: '...', // Why this matters rationale: '...', // Why this matters
priority: 'high|medium|low', priority: 'high|medium|low',
evidence_refs: ['file:line', ...] // Supporting evidence locations evidence_refs: ['file:line', ...], // Supporting evidence locations
steps: [ // Granular sub-steps for execution
{ description: '...', target: 'file/module', verification: 'how to verify done' }
],
review_status: 'accepted|modified|rejected|pending' // Set during Phase 4 review
} }
], ],
open_questions: [...], // Unresolved questions open_questions: [...], // Unresolved questions
@@ -617,7 +723,10 @@ const conclusions = {
{ type: 'issue|task|research', summary: '...' } { type: 'issue|task|research', summary: '...' }
], ],
decision_trail: [ // Consolidated decisions from all phases decision_trail: [ // Consolidated decisions from all phases
{ round: 1, decision: '...', context: '...', options_considered: [...], chosen: '...', reason: '...', impact: '...' } { round: 1, decision: '...', context: '...', options_considered: [...], chosen: '...', rejected_reasons: '...', reason: '...', impact: '...' }
],
narrative_trail: [ // From Step 3.3 Narrative Synthesis
{ round: 1, starting_point: '...', key_progress: '...', hypothesis_impact: '...', updated_understanding: '...', remaining_questions: '...' }
], ],
intent_coverage: [ // From Step 4.0 intent_coverage: [ // From Step 4.0
{ intent: '...', status: 'addressed|transformed|absorbed|missed', where_addressed: '...', notes: '...' } { intent: '...', status: 'addressed|transformed|absorbed|missed', where_addressed: '...', notes: '...' }
@@ -654,7 +763,59 @@ Append conclusions section and finalize:
**Session Statistics**: Total discussion rounds, key findings count, dimensions covered, artifacts generated, **decision count**. **Session Statistics**: Total discussion rounds, key findings count, dimensions covered, artifacts generated, **decision count**.
##### Step 4.3: Post-Completion Options ##### Step 4.3: Interactive Recommendation Review (skip in auto mode)
Walk through each recommendation one-by-one for user confirmation before proceeding:
```javascript
// Order recommendations by priority: high → medium → low
const sortedRecs = conclusions.recommendations.sort(byPriority)
for (const [index, rec] of sortedRecs.entries()) {
// 1. Present recommendation details
// Display: action, rationale, priority, steps[] (numbered sub-steps with target + verification)
// 2. Gather user review
const review = AskUserQuestion({
questions: [{
question: `Recommendation #${index + 1}: "${rec.action}" (${rec.priority} priority, ${rec.steps.length} steps). Your decision:`,
header: `Rec #${index + 1}`,
multiSelect: false,
options: [
{ label: "Accept", description: "Accept this recommendation as-is" },
{ label: "Modify", description: "Adjust scope, steps, or priority" },
{ label: "Reject", description: "Remove this recommendation" },
{ label: "Accept All Remaining", description: "Skip review for remaining recommendations" }
]
}]
})
// 3. Process review decision
// Accept → rec.review_status = "accepted"
// Modify → gather modification via free text → update rec → rec.review_status = "modified"
// Reject → gather reason → rec.review_status = "rejected"
// Accept All Remaining → mark all remaining as "accepted", break loop
// 4. Record review decision to discussion.md Decision Log
// 5. Update conclusions.json
}
// Display review summary:
// Accepted: N | Modified: N | Rejected: N
// Only accepted/modified recommendations proceed to next step
```
**Review Summary Format** (append to discussion.md):
```markdown
### Recommendation Review Summary
| # | Action | Priority | Steps | Review Status | Notes |
|---|--------|----------|-------|---------------|-------|
| 1 | [action] | high | 3 | ✅ Accepted | |
| 2 | [action] | medium | 2 | ✏️ Modified | [modification notes] |
| 3 | [action] | low | 1 | ❌ Rejected | [reason] |
```
##### Step 4.4: Post-Completion Options
**Complexity Assessment** — determine whether .task/*.json generation is warranted: **Complexity Assessment** — determine whether .task/*.json generation is warranted:
@@ -709,8 +870,8 @@ if (!autoYes) {
| Selection | Action | | Selection | Action |
|-----------|--------| |-----------|--------|
| Quick Execute | Jump to Phase 5 (routes by complexity) | | Quick Execute | Jump to Phase 5 (only reviewed recs with status accepted/modified) |
| Create Issue | `Skill(skill="issue:new", args="...")` | | Create Issue | `Skill(skill="issue:new", args="...")` (only reviewed recs) |
| Generate Task | Jump to Phase 5 Step 5.1-5.2 only (generate .task/*.json, no execution) | | Generate Task | Jump to Phase 5 Step 5.1-5.2 only (generate .task/*.json, no execution) |
| Export Report | Copy discussion.md + conclusions.json to user-specified location | | Export Report | Copy discussion.md + conclusions.json to user-specified location |
| Done | Display artifact paths, end | | Done | Display artifact paths, end |
@@ -935,9 +1096,9 @@ The discussion.md file evolves through the analysis:
- **Analysis Context**: Focus areas, perspectives, depth level - **Analysis Context**: Focus areas, perspectives, depth level
- **Initial Questions**: Key questions to guide the analysis - **Initial Questions**: Key questions to guide the analysis
- **Initial Decisions**: Why these dimensions and focus areas were selected - **Initial Decisions**: Why these dimensions and focus areas were selected
- **Discussion Timeline**: Round-by-round findings - **Discussion Timeline**: Round-by-round findings with narrative synthesis
- Round 1: Initial Understanding + Exploration Results + **Initial Decision Log** - Round 1: Initial Understanding + Exploration Results + **Initial Decision Log** + **Narrative Synthesis**
- Round 2-N: User feedback + direction adjustments + new insights + **Decision Log per round** - Round 2-N: Current Understanding Summary + User feedback + direction adjustments + new insights + **Decision Log** + **Key Findings** + **Narrative Synthesis**
- **Decision Trail**: Consolidated critical decisions across all rounds - **Decision Trail**: Consolidated critical decisions across all rounds
- **Synthesis & Conclusions**: Summary, key conclusions, recommendations - **Synthesis & Conclusions**: Summary, key conclusions, recommendations
- **Current Understanding (Final)**: Consolidated insights - **Current Understanding (Final)**: Consolidated insights
@@ -948,7 +1109,7 @@ The discussion.md file evolves through the analysis:
Each discussion round follows a consistent structure: Each discussion round follows a consistent structure:
```markdown ```markdown
### Round N - [Deepen|Adjust|Q&A] (timestamp) ### Round N - [Deepen|Adjust|Suggest|Q&A] (timestamp)
#### User Input #### User Input
What the user indicated they wanted to focus on What the user indicated they wanted to focus on
@@ -958,22 +1119,33 @@ What the user indicated they wanted to focus on
> - **Context**: [What triggered this decision] > - **Context**: [What triggered this decision]
> - **Options considered**: [Alternatives evaluated] > - **Options considered**: [Alternatives evaluated]
> - **Chosen**: [Selected approach] — **Reason**: [Rationale] > - **Chosen**: [Selected approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **Impact**: [Effect on analysis direction/conclusions] > - **Impact**: [Effect on analysis direction/conclusions]
#### Key Findings
> **Finding**: [Content]
> - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
> - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
> - **Scope**: [What areas this affects]
#### Analysis Results #### Analysis Results
New findings from this round's analysis Detailed findings from this round's analysis
- Finding 1 (evidence: file:line) - Finding 1 (evidence: file:line)
- Finding 2 (evidence: file:line) - Finding 2 (evidence: file:line)
#### Insights
Key learnings and clarifications
#### Corrected Assumptions #### Corrected Assumptions
- ~~Previous assumption~~ → Corrected understanding - ~~Previous assumption~~ → Corrected understanding
- Reason: Why the assumption was wrong - Reason: Why the assumption was wrong
#### Open Items #### Open Items
Remaining questions or areas for investigation Remaining questions or areas for investigation
#### Narrative Synthesis
**起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
**关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
**决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
**当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
**遗留问题**: [remaining questions driving next round]
``` ```
## Error Handling ## Error Handling

View File

@@ -67,11 +67,29 @@ const STALE_TIME = 5 * 60 * 1000;
// Default garbage collection time: 10 minutes // Default garbage collection time: 10 minutes
const GC_TIME = 10 * 60 * 1000; const GC_TIME = 10 * 60 * 1000;
// Request timeout: 10 seconds
const REQUEST_TIMEOUT = 10 * 1000;
/**
* Fetch with timeout wrapper
*/
async function fetchWithTimeout(url: string, timeout: number = REQUEST_TIMEOUT): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response;
} finally {
clearTimeout(timeoutId);
}
}
/** /**
* Fetch list of documented files * Fetch list of documented files
*/ */
async function fetchDeepWikiFiles(): Promise<DeepWikiFile[]> { async function fetchDeepWikiFiles(): Promise<DeepWikiFile[]> {
const response = await fetch('/api/deepwiki/files'); const response = await fetchWithTimeout('/api/deepwiki/files');
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to fetch files: ${response.statusText}`); throw new Error(`Failed to fetch files: ${response.statusText}`);
} }
@@ -82,7 +100,7 @@ async function fetchDeepWikiFiles(): Promise<DeepWikiFile[]> {
* Fetch document by source file path * Fetch document by source file path
*/ */
async function fetchDeepWikiDoc(filePath: string): Promise<DocumentResponse> { async function fetchDeepWikiDoc(filePath: string): Promise<DocumentResponse> {
const response = await fetch(`/api/deepwiki/doc?path=${encodeURIComponent(filePath)}`); const response = await fetchWithTimeout(`/api/deepwiki/doc?path=${encodeURIComponent(filePath)}`);
if (!response.ok) { if (!response.ok) {
if (response.status === 404) { if (response.status === 404) {
return { doc: null, content: '', symbols: [] }; return { doc: null, content: '', symbols: [] };
@@ -96,7 +114,7 @@ async function fetchDeepWikiDoc(filePath: string): Promise<DocumentResponse> {
* Fetch DeepWiki statistics * Fetch DeepWiki statistics
*/ */
async function fetchDeepWikiStats(): Promise<DeepWikiStats> { async function fetchDeepWikiStats(): Promise<DeepWikiStats> {
const response = await fetch('/api/deepwiki/stats'); const response = await fetchWithTimeout('/api/deepwiki/stats');
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to fetch stats: ${response.statusText}`); throw new Error(`Failed to fetch stats: ${response.statusText}`);
} }
@@ -107,7 +125,7 @@ async function fetchDeepWikiStats(): Promise<DeepWikiStats> {
* Search symbols by query * Search symbols by query
*/ */
async function searchDeepWikiSymbols(query: string, limit = 50): Promise<DeepWikiSymbol[]> { async function searchDeepWikiSymbols(query: string, limit = 50): Promise<DeepWikiSymbol[]> {
const response = await fetch(`/api/deepwiki/search?q=${encodeURIComponent(query)}&limit=${limit}`); const response = await fetchWithTimeout(`/api/deepwiki/search?q=${encodeURIComponent(query)}&limit=${limit}`);
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to search symbols: ${response.statusText}`); throw new Error(`Failed to search symbols: ${response.statusText}`);
} }

View File

@@ -578,6 +578,11 @@ export async function startServer(options: ServerOptions = {}): Promise<http.Ser
if (await handleMcpRoutes(routeContext)) return; if (await handleMcpRoutes(routeContext)) return;
} }
// DeepWiki routes (/api/deepwiki/*)
if (pathname.startsWith('/api/deepwiki')) {
if (await handleDeepWikiRoutes(routeContext)) return;
}
// Hooks routes (/api/hooks, /api/hook) // Hooks routes (/api/hooks, /api/hook)
if (pathname.startsWith('/api/hook')) { if (pathname.startsWith('/api/hook')) {
if (await handleHooksRoutes(routeContext)) return; if (await handleHooksRoutes(routeContext)) return;

View File

@@ -250,6 +250,35 @@ export class DeepWikiService {
return []; return [];
} }
} }
/**
* Get storage statistics
* @returns Statistics object with counts
*/
public getStats(): { files: number; symbols: number; docs: number; filesNeedingDocs: number; dbPath: string } {
const db = this.getConnection();
if (!db) {
return { files: 0, symbols: 0, docs: 0, filesNeedingDocs: 0, dbPath: this.dbPath };
}
try {
const files = db.prepare('SELECT COUNT(*) as count FROM deepwiki_files').get() as { count: number };
const symbols = db.prepare('SELECT COUNT(*) as count FROM deepwiki_symbols').get() as { count: number };
const docs = db.prepare('SELECT COUNT(*) as count FROM deepwiki_docs').get() as { count: number };
const filesNeedingDocs = db.prepare('SELECT COUNT(*) as count FROM deepwiki_files WHERE docs_generated = 0').get() as { count: number };
return {
files: files?.count || 0,
symbols: symbols?.count || 0,
docs: docs?.count || 0,
filesNeedingDocs: filesNeedingDocs?.count || 0,
dbPath: this.dbPath
};
} catch (error) {
console.error('[DeepWiki] Error getting stats:', error);
return { files: 0, symbols: 0, docs: 0, filesNeedingDocs: 0, dbPath: this.dbPath };
}
}
} }
// Singleton instance // Singleton instance

File diff suppressed because one or more lines are too long