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 |
|-------|----------|-------------|
| 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 |
| 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` | Single perspective aggregated findings |
| 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis |
| 2 | Updated `discussion.md` | Round 1 with exploration results |
| 3 | Updated `discussion.md` | Round 2-N with user feedback and insights |
| 4 | `conclusions.json` | Final synthesis with recommendations |
| 4 | Final `discussion.md` | Complete analysis with conclusions |
| 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
| 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
| 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
| 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
### Decision Recording Protocol
@@ -37,7 +37,7 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
| Trigger | What to Record | Target Section |
|---------|---------------|----------------|
| **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` |
| **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` |
| **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]
> - **Options considered**: [Alternatives]
> - **Chosen**: [Approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **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
@@ -74,7 +83,10 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
- **Focus**: Multi-select from Dimension-Direction Mapping directions
- **Perspectives**: Multi-select up to 4 (see Analysis Perspectives), default: single comprehensive
- **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
**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 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):
- `session_id`, `timestamp`, `topic`, `dimensions[]`
- `sources[]`: {type, file/summary}
@@ -198,32 +217,54 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
**Loop** (max 5 rounds):
1. **Present Findings** from explorations.json
2. **Gather Feedback** (AskUserQuestion, single-select):
1. **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
- 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
- **同意,并建议下一步**: Agree with direction, but user has specific next step in mind
- **需要调整方向**: Different focus
- **分析完成**: Sufficient → exit to Phase 4
- **有具体问题**: 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:
- 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
- AskUserQuestion with generated options (single-select)
- Execute selected direction via corresponding tool
- Merge new code_anchors/call_chains into existing results
- 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)
**Specific Questions** → Capture, answer via CLI/analysis, document Q&A → Record gaps revealed + new understanding
**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
- Check each item: addressed / in-progress / implicitly absorbed / not yet discussed
```markdown
@@ -233,9 +274,9 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation]
- ❌ 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
@@ -267,13 +308,33 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')}
- Session statistics: rounds, duration, sources, artifacts, decision count
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
- 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"):
- **执行任务** (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`
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)
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
All Phase 1-4 are FINISHED. DO NOT reference analyze-with-file phase instructions beyond this point.
```
4. Hand off: `Skill(skill="workflow-lite-plan", args="{taskDescription}\n\n{contextLines}")`
5. Return — analyze-with-file terminates
If Skill invocation is omitted, the workflow is BROKEN — user selected "执行任务" specifically to launch lite-plan.
4. After Skill invocation, analyze-with-file is complete — do not output any additional content
**conclusions.json Schema**:
- `session_id`, `topic`, `completed`, `total_rounds`, `summary`
- `key_conclusions[]`: {point, evidence, confidence, code_anchor_refs[]}
- `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}
- `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}
**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
### 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 |
|----------|-------------|
| `brainstorm.md` | Complete thought evolution timeline (initialized) |
| Session variables | Dimensions, roles, exploration vectors |
## Output Structure
### Phase 2: Divergent Exploration
| Artifact | Description |
|----------|-------------|
| `exploration-codebase.json` | Codebase context from cli-explore-agent |
| `perspectives.json` | Multi-CLI perspective findings (creative/pragmatic/systematic) |
| Updated `brainstorm.md` | Round 2 multi-perspective exploration |
### Phase 3: Interactive Refinement
| 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
```
.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
```
```
┌─────────────────────────────────────────────────────────────────────────┐
@@ -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
### Session Initialization
**Objective**: Create session context and directory structure for brainstorming.
**Required Actions**:
1. Extract idea/topic from `$ARGUMENTS`
2. Generate session ID: `BS-{slug}-{date}`
- slug: lowercase, alphanumeric + Chinese, max 40 chars
- date: YYYY-MM-DD (UTC+8)
2. Generate session ID: `BS-{slug}-{date}` (slug: lowercase, alphanumeric + Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
3. Define session folder: `.workflow/.brainstorm/{session-id}`
4. Parse command options:
- `-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
6. Create directory structure: `{session-folder}/ideas/`
**Session Variables**:
- `sessionId`: Unique session identifier
- `sessionFolder`: Base directory for all artifacts
- `brainstormMode`: creative | structured | balanced
- `autoMode`: Boolean for auto-confirmation
- `mode`: new | continue
**Session Variables**: `sessionId`, `sessionFolder`, `brainstormMode` (creative|structured|balanced), `autoMode` (boolean), `mode` (new|continue)
### 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**
- Match topic keywords against BRAINSTORM_DIMENSIONS
- Identify relevant dimensions: technical, ux, business, innovation, feasibility, scalability, security
- Match topic keywords against Brainstorm Dimensions table
- Default dimensions based on brainstormMode if no match
2. **Role Selection**
- **Recommend roles** based on topic keywords (see Role Keywords mapping)
- **Options**:
- **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)
- Recommend roles based on topic keywords (see Role Selection tables)
- **Professional roles**: system-architect, product-manager, ui-designer, ux-expert, data-architect, test-strategist, subject-matter-expert, product-owner, scrum-master
- **Simple perspectives** (fallback): creative/pragmatic/systematic
- **Auto mode**: Select top 3 recommended professional roles
- **Manual mode**: AskUserQuestion with recommended roles + "Use simple perspectives" option
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)
- **Constraints**: Multi-select from existing architecture, time, resources, or no constraints
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
Bash({
command: `ccw cli -p "
@@ -205,45 +151,12 @@ Output as structured exploration vectors for multi-perspective analysis.
})
```
5. **Initialize brainstorm.md**
- 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)
5. **Initialize brainstorm.md** with session metadata, initial context (user focus, depth, constraints), seed expansion (original idea + exploration vectors), empty thought evolution timeline sections
### 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)
- 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
Agent({
subagent_type: "cli-explore-agent",
@@ -281,147 +194,67 @@ Schema:
}
`
})
```
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
// Build shared context from exploration results
const explorationContext = `
PRIOR EXPLORATION CONTEXT (from cli-explore-agent):
- Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
- Existing patterns: ${explorationResults.existing_patterns.slice(0,3).join(', ')}
- Architecture constraints: ${explorationResults.architecture_constraints.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({
command: `ccw cli -p "
PURPOSE: Creative brainstorming for '${idea_or_topic}' - generate innovative ideas
Success: 5+ unique creative solutions that push boundaries
PURPOSE: ${perspective} brainstorming for '${idea_or_topic}' - ${purposeFocus}
Success: ${expected}
${explorationContext}
TASK:
• Build on existing patterns - how can they be extended creatively?
• Think beyond obvious solutions - what would be surprising/delightful?
• Explore cross-domain inspiration
• Challenge assumptions - what if the opposite were true?
• Generate 'moonshot' ideas alongside practical ones
• Build on explored ${contextType} - how to ${actionVerb}?
${perspectiveSpecificBullets}
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: 5+ creative ideas with novelty/impact ratings, challenged assumptions, cross-domain inspirations
CONSTRAINTS: ${brainstormMode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely'}
" --tool gemini --mode analysis`,
EXPECTED: ${expected}
CONSTRAINTS: ${constraints}
" --tool ${tool} --mode analysis`,
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
```
3. **Aggregate Multi-Perspective Findings**
- Consolidate creative/pragmatic/systematic results
- Extract synthesis:
- Convergent themes (all agree)
- Conflicting views (need resolution)
- Unique contributions (perspective-specific insights)
- Convergent themes (all agree), conflicting views (need resolution), unique contributions
- Write to perspectives.json
4. **Update brainstorm.md**
- 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
4. **Update brainstorm.md** with Round 2 multi-perspective exploration and synthesis
### 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**:
- 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
1. **Present Current State**: Extract top ideas from perspectives.json with title, source, description, novelty/feasibility ratings
2. **Gather User Direction** (AskUserQuestion)
- **Question 1**: Which ideas to explore (multi-select from top ideas)
- **Question 2**: Next step (single-select):
- **Q1**: Which ideas to explore (multi-select from top ideas)
- **Q2**: Next step (single-select):
- **深入探索**: Deep dive on selected ideas
- **继续发散**: Generate more ideas
- **挑战验证**: Devil's advocate challenge
@@ -430,44 +263,14 @@ CONSTRAINTS: Consider existing system architecture
3. **Execute User-Selected Action**
**Deep Dive** (per selected idea):
- Launch Gemini CLI with analysis mode
- Tasks: Elaborate concept, implementation requirements, challenges, POC approach, metrics, dependencies
- Output: `{sessionFolder}/ideas/{idea-slug}.md`
| Action | Tool | Output | Key Tasks |
|--------|------|--------|-----------|
| Deep Dive | Gemini CLI | ideas/{slug}.md | Elaborate concept, requirements, challenges, POC approach, metrics, dependencies |
| 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**:
- 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**:
**Deep Dive CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -483,27 +286,18 @@ TASK:
• Map related/dependent features
MODE: analysis
CONTEXT: @**/*
Original idea: ${idea.description}
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
" --tool gemini --mode analysis`,
run_in_background: false
})
```
**2. Devil's Advocate Challenge**:
**Devil's Advocate CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -518,25 +312,17 @@ TASK:
• Challenge core assumptions
• Identify scenarios where this fails
• Consider competitive/alternative solutions
• Assess whether this solves the right problem
• Rate survivability after challenge (1-5)
MODE: analysis
EXPECTED:
- Per-idea challenge report
- Critical weaknesses exposed
- Counter-arguments to objections (if any)
- Ideas that survive the challenge
- Modified/strengthened versions
EXPECTED: Per-idea challenge report, critical weaknesses, survivability ratings, modified/strengthened versions
CONSTRAINTS: Be genuinely critical, not just contrarian
" --tool codex --mode analysis`,
run_in_background: false
})
```
**3. Merge Multiple Ideas**:
**Merge Ideas CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -553,62 +339,32 @@ ${i+1}. ${idea.title} (${idea.source})
TASK:
• Identify complementary elements
• Resolve contradictions
• Create unified concept
• Preserve key strengths from each
• Describe the merged solution
• Create unified concept preserving key strengths
• Assess viability of merged idea
MODE: analysis
EXPECTED:
- Merged concept description
- Elements taken from each source idea
- Contradictions resolved (or noted as tradeoffs)
- New combined strengths
- Implementation considerations
EXPECTED: Merged concept, elements from each source, contradictions resolved, implementation considerations
CONSTRAINTS: Don't force incompatible ideas together
" --tool gemini --mode analysis`,
run_in_background: false
})
```
**Success Criteria**:
- User-selected ideas processed
- brainstorm.md updated with all refinement rounds
- ideas/ folder contains deep-dive documents for selected ideas
- Exit condition reached (user selects "准备收敛" or max rounds)
4. **Update brainstorm.md** with Round N findings
5. **Repeat or Converge**: Continue loop (max 6 rounds) or exit to Phase 4
### Phase 4: Convergence & Crystallization
**Objective**: Synthesize final ideas, generate conclusions, offer next steps.
**Prerequisites**:
- 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
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
- **Parked ideas**: With reason and future trigger
- **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
- Write to synthesis.json
2. **Final brainstorm.md Update**
- Append synthesis & conclusions section
- **Executive summary**: High-level overview
- **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
**synthesis.json Schema**: `session_id`, `topic`, `completed` (timestamp), `total_rounds`, `top_ideas[]`, `parked_ideas[]`, `key_insights[]`, `recommendations` (primary/alternatives/not_recommended), `follow_up[]`
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)
3. **Post-Completion Options** (AskUserQuestion)
- **创建实施计划**: Launch workflow-plan with top idea
@@ -617,29 +373,10 @@ CONSTRAINTS: Don't force incompatible ideas together
- **导出分享**: Generate shareable report
- **完成**: 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
### Brainstorm Dimensions
Dimensions matched against topic keywords to identify focus areas:
| Dimension | Keywords |
|-----------|----------|
| technical | 技术, technical, implementation, code, 实现, architecture |
@@ -652,7 +389,7 @@ Dimensions matched against topic keywords to identify focus areas:
### Role Selection
**Professional Roles** (recommended based on topic keywords):
**Professional Roles**:
| Role | CLI Tool | Focus Area | Keywords |
|------|----------|------------|----------|
@@ -668,47 +405,13 @@ Dimensions matched against topic keywords to identify focus areas:
**Simple Perspectives** (fallback):
| Perspective | CLI Tool | Focus | Best For |
|-------------|----------|-------|----------|
| creative | Gemini | Innovation, cross-domain | Generating novel ideas |
| pragmatic | Codex | Implementation, feasibility | Reality-checking ideas |
| systematic | Claude | Architecture, structure | Organizing solutions |
| Perspective | CLI Tool | Focus |
|-------------|----------|-------|
| creative | Gemini | Innovation, cross-domain |
| pragmatic | Codex | Implementation, feasibility |
| systematic | Claude | Architecture, structure |
**Selection Strategy**:
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
**Selection Strategy**: Auto mode → top 3 professional roles | Manual mode → recommended roles + "Use simple perspectives" option | Continue mode → roles from previous session
## Error Handling
@@ -722,58 +425,6 @@ Dimensions matched against topic keywords to identify focus areas:
| Max rounds reached | Force synthesis, highlight unresolved questions |
| 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

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).
## 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
**Output Directory**: `.workflow/.multi-cli-plan/{session-id}/`
**Default Max Rounds**: 3 (convergence may complete earlier)
**CLI Tools**: @cli-discuss-agent (analysis), @cli-lite-planning-agent (plan generation)
**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)
- **ONLY command** for multi-CLI collaborative planning
@@ -123,14 +89,7 @@ const aceQueries = [
### Phase 2: Agent Delegation
**Core Principle**: Orchestrator only delegates and reads output - NO direct CLI execution.
**⚠️ 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
**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.
**Agent Invocation**:
```javascript
@@ -143,7 +102,7 @@ Agent({
- task_description: ${taskDescription}
- round_number: ${currentRound}
- session: { id: "${sessionId}", folder: "${sessionFolder}" }
- ace_context: ${JSON.stringify(contextPackageage)}
- ace_context: ${JSON.stringify(contextPackage)}
- previous_rounds: ${JSON.stringify(analysisResults)}
- user_feedback: ${userFeedback || 'None'}
- 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
**Display from Agent Output** (no processing):
```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}
`)
```
Display solutions from `synthesis.solutions[]` showing: name, source CLIs, effort/risk, pros/cons, affected files (`file:line`). Also show cross-verification agreements/disagreements count.
### Phase 4: User Decision
**Decision Options**:
```javascript
AskUserQuestion({
questions: [
@@ -277,9 +215,7 @@ TodoWrite({ todos: [
**Step 1: Build Context-Package** (Orchestrator responsibility):
```javascript
// Extract key information from user decision and synthesis
const contextPackage = {
// Core solution details
solution: {
name: selectedSolution.name,
source_cli: selectedSolution.source_cli,
@@ -288,25 +224,17 @@ const contextPackage = {
risk: selectedSolution.risk,
summary: selectedSolution.summary
},
// Implementation plan (tasks, flow, milestones)
implementation_plan: selectedSolution.implementation_plan,
// Dependencies
dependencies: selectedSolution.dependencies || { internal: [], external: [] },
// Technical concerns
technical_concerns: selectedSolution.technical_concerns || [],
// Consensus from cross-verification
consensus: {
agreements: synthesis.cross_verification.agreements,
resolved_conflicts: synthesis.cross_verification.resolution
},
// User constraints (from Phase 4 feedback)
constraints: userConstraints || [],
// Task context
task_description: taskDescription,
session_id: sessionId
}
// Write context-package for traceability
Write(`${sessionFolder}/context-package.json`, JSON.stringify(contextPackage, null, 2))
```
@@ -367,32 +295,26 @@ ${JSON.stringify(contextPackage, null, 2)}
**Step 3: Build executionContext**:
```javascript
// After plan.json is generated by cli-lite-planning-agent
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`)
// Build executionContext (same structure as lite-plan)
executionContext = {
planObject: plan,
taskFiles: taskFiles, // Paths to .task/*.json files (two-layer format)
explorationsContext: null, // Multi-CLI doesn't use exploration files
explorationAngles: [], // No exploration angles
explorationManifest: null, // No manifest
clarificationContext: null, // Store user feedback from Phase 2 if exists
executionMethod: userSelection.execution_method, // From Phase 4
codeReviewTool: userSelection.code_review_tool, // From Phase 4
taskFiles: taskFiles, // Paths to .task/*.json files (two-layer format)
explorationsContext: null, // Multi-CLI doesn't use exploration files
explorationAngles: [],
explorationManifest: null,
clarificationContext: null, // Store user feedback from Phase 2 if exists
executionMethod: userSelection.execution_method, // From Phase 4
codeReviewTool: userSelection.code_review_tool, // From Phase 4
originalUserInput: taskDescription,
// Optional: Task-level executor assignments
executorAssignments: null, // Could be enhanced in future
executorAssignments: null,
session: {
id: sessionId,
folder: sessionFolder,
artifacts: {
explorations: [], // No explorations in multi-CLI workflow
explorations: [], // No explorations in multi-CLI workflow
explorations_manifest: null,
plan: `${sessionFolder}/plan.json`,
task_dir: plan.task_ids ? `${sessionFolder}/.task/` : null,
@@ -407,7 +329,6 @@ executionContext = {
**Step 4: Hand off to Execution**:
```javascript
// Skill handoff: Invoke workflow-lite-execute with in-memory context
Skill({
skill: "workflow-lite-execute",
args: "--in-memory"
@@ -415,23 +336,6 @@ Skill({
// 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
```json
@@ -469,9 +373,9 @@ Skill({
}
```
## TodoWrite Structure
## TodoWrite Pattern
**Initialization**:
**Initialization** (Phase 1 start):
```javascript
TodoWrite({ todos: [
{ 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 | Resolution |
@@ -501,22 +422,3 @@ TodoWrite({ todos: [
| `--tools` | gemini,codex | CLI tools for analysis |
| `--mode` | parallel | Execution mode: parallel or serial |
| `--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 |
|---------|---------------|----------------|
| **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` |
| **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` |
| **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]
> - **Options considered**: [Alternatives evaluated]
> - **Chosen**: [Selected approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **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**:
- **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
- **Depth**: Capture reasoning and hypothesis impact, not just outcomes
## Auto Mode
@@ -91,22 +101,33 @@ Step 2: Exploration (Inline, No Agents)
│ ├─ Single: Comprehensive analysis
│ └─ Multi (≤4): Serial per-perspective analysis with synthesis
├─ 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)
├─ Current Understanding Summary (round ≥ 2, before findings)
├─ Present exploration findings
├─ Gather user feedback
├─ 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
│ ├─ Questions → direct answers with evidence
│ └─ 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
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
├─ Interactive Recommendation Review (per-recommendation confirm/modify/reject)
└─ Offer options: quick execute / create issue / generate task / export / done
Step 5: Execute (Optional - user selects, routes by complexity)
@@ -237,6 +258,19 @@ const discussionMd = `# Analysis Discussion
**Dimensions**: ${dimensions.join(', ')}
**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
- Focus areas: ${focusAreas.join(', ')}
- Perspectives: ${selectedPerspectives.map(p => p.name).join(', ')}
@@ -260,12 +294,6 @@ ${generateInitialQuestions(topic, dimensions).map(q => `- ${q}`).join('\n')}
## Decision Trail
> Consolidated critical decisions across all rounds (populated in Phase 4).
---
## Current Understanding
> To be populated after exploration.
`
Write(`${sessionFolder}/discussion.md`, discussionMd)
```
@@ -426,10 +454,33 @@ Append Round 1 with exploration results:
- Discussion points
- 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**:
- exploration-codebase.json created with codebase context (if codebase exists)
- explorations.json (single) or perspectives.json (multi) created with findings
- discussion.md updated with Round 1 results
- **Initial Intent Coverage Check** completed — early drift detection before interactive rounds
- Ready for interactive discussion
- **Key findings recorded** with evidence references and confidence levels
- **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)
##### 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:
```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
// Show key points, discussion points, open questions
@@ -456,6 +518,7 @@ if (!autoYes) {
multiSelect: false,
options: [
{ 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: "Specific Questions", description: "Have specific questions to ask" },
{ label: "Analysis Complete", description: "Sufficient information obtained, proceed to synthesis" }
@@ -474,15 +537,34 @@ if (!autoYes) {
**Deepen** — continue analysis in current direction:
```javascript
// Deeper inline analysis using search tools
// Investigate edge cases, special scenarios
// Identify patterns not yet discussed
// Suggest improvement approaches
// Provide risk/impact assessments
// Update explorations.json with deepening findings
// Generate deepen direction options dynamically:
// - 2-3 context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions
// - 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"
// 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
```
**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:
```javascript
// Ask user for adjusted focus
@@ -525,25 +607,45 @@ const adjustedFocus = AskUserQuestion({
Update discussion.md with results from each discussion round:
**Append** to Discussion Timeline:
| Section | Content |
|---------|---------|
| User Direction | Action taken (deepen/adjust/questions) and focus area |
| Decision Log | Decisions made this round using Decision Record format |
| Analysis Results | Key findings, insights, evidence with file references |
| Insights | New learnings or clarifications from this round |
| User Direction | Action taken (deepen/adjust/suggest/questions) and focus area |
| Decision Log | Decisions made this round using Decision Record format (with rejected alternatives) |
| Key Findings | Findings using Key Finding Record format (with confidence + hypothesis impact) |
| Analysis Results | Detailed insights, evidence with file references |
| Corrected Assumptions | Important wrong→right transformations with explanation |
| 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**:
- 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
- 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
#### 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 ❌ 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**:
- User feedback processed for each round
@@ -609,7 +711,11 @@ const conclusions = {
action: '...', // What to do (imperative verb + target)
rationale: '...', // Why this matters
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
@@ -617,7 +723,10 @@ const conclusions = {
{ type: 'issue|task|research', summary: '...' }
],
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: '...', 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**.
##### 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:
@@ -709,8 +870,8 @@ if (!autoYes) {
| Selection | Action |
|-----------|--------|
| Quick Execute | Jump to Phase 5 (routes by complexity) |
| Create Issue | `Skill(skill="issue:new", args="...")` |
| Quick Execute | Jump to Phase 5 (only reviewed recs with status accepted/modified) |
| 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) |
| Export Report | Copy discussion.md + conclusions.json to user-specified location |
| Done | Display artifact paths, end |
@@ -935,9 +1096,9 @@ The discussion.md file evolves through the analysis:
- **Analysis Context**: Focus areas, perspectives, depth level
- **Initial Questions**: Key questions to guide the analysis
- **Initial Decisions**: Why these dimensions and focus areas were selected
- **Discussion Timeline**: Round-by-round findings
- Round 1: Initial Understanding + Exploration Results + **Initial Decision Log**
- Round 2-N: User feedback + direction adjustments + new insights + **Decision Log per round**
- **Discussion Timeline**: Round-by-round findings with narrative synthesis
- Round 1: Initial Understanding + Exploration Results + **Initial Decision Log** + **Narrative Synthesis**
- 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
- **Synthesis & Conclusions**: Summary, key conclusions, recommendations
- **Current Understanding (Final)**: Consolidated insights
@@ -948,7 +1109,7 @@ The discussion.md file evolves through the analysis:
Each discussion round follows a consistent structure:
```markdown
### Round N - [Deepen|Adjust|Q&A] (timestamp)
### Round N - [Deepen|Adjust|Suggest|Q&A] (timestamp)
#### User Input
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]
> - **Options considered**: [Alternatives evaluated]
> - **Chosen**: [Selected approach] — **Reason**: [Rationale]
> - **Rejected**: [Why other options were discarded]
> - **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
New findings from this round's analysis
Detailed findings from this round's analysis
- Finding 1 (evidence: file:line)
- Finding 2 (evidence: file:line)
#### Insights
Key learnings and clarifications
#### Corrected Assumptions
- ~~Previous assumption~~ → Corrected understanding
- Reason: Why the assumption was wrong
#### Open Items
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

View File

@@ -67,11 +67,29 @@ const STALE_TIME = 5 * 60 * 1000;
// Default garbage collection time: 10 minutes
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
*/
async function fetchDeepWikiFiles(): Promise<DeepWikiFile[]> {
const response = await fetch('/api/deepwiki/files');
const response = await fetchWithTimeout('/api/deepwiki/files');
if (!response.ok) {
throw new Error(`Failed to fetch files: ${response.statusText}`);
}
@@ -82,7 +100,7 @@ async function fetchDeepWikiFiles(): Promise<DeepWikiFile[]> {
* Fetch document by source file path
*/
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.status === 404) {
return { doc: null, content: '', symbols: [] };
@@ -96,7 +114,7 @@ async function fetchDeepWikiDoc(filePath: string): Promise<DocumentResponse> {
* Fetch DeepWiki statistics
*/
async function fetchDeepWikiStats(): Promise<DeepWikiStats> {
const response = await fetch('/api/deepwiki/stats');
const response = await fetchWithTimeout('/api/deepwiki/stats');
if (!response.ok) {
throw new Error(`Failed to fetch stats: ${response.statusText}`);
}
@@ -107,7 +125,7 @@ async function fetchDeepWikiStats(): Promise<DeepWikiStats> {
* Search symbols by query
*/
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) {
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;
}
// DeepWiki routes (/api/deepwiki/*)
if (pathname.startsWith('/api/deepwiki')) {
if (await handleDeepWikiRoutes(routeContext)) return;
}
// Hooks routes (/api/hooks, /api/hook)
if (pathname.startsWith('/api/hook')) {
if (await handleHooksRoutes(routeContext)) return;

View File

@@ -250,6 +250,35 @@ export class DeepWikiService {
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

File diff suppressed because one or more lines are too long