From d46406df4a2604326e75211d18687ae791c28789 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Sun, 1 Feb 2026 17:45:38 +0800 Subject: [PATCH] feat: Add CodexLens Manager Page with tabbed interface for managing CodexLens features feat: Implement ConflictTab component to display conflict resolution decisions in session detail feat: Create ImplPlanTab component to show implementation plan with modal viewer in session detail feat: Develop ReviewTab component to display review findings by dimension in session detail test: Add end-to-end tests for CodexLens Manager functionality including navigation, tab switching, and settings validation --- .claude/commands/ccw-debug.md | 104 +- .claude/commands/ccw.md | 147 +- .../commands/workflow/analyze-with-file.md | 1023 +++++-------- .../commands/workflow/brainstorm-with-file.md | 1349 +++++++---------- .codex/prompts/merge-plans-with-file.md | 530 ------- .../src/components/codexlens/AdvancedTab.tsx | 292 ++++ .../src/components/codexlens/GpuSelector.tsx | 293 ++++ .../src/components/codexlens/ModelCard.tsx | 231 +++ .../components/codexlens/ModelsTab.test.tsx | 396 +++++ .../src/components/codexlens/ModelsTab.tsx | 283 ++++ .../components/codexlens/OverviewTab.test.tsx | 280 ++++ .../src/components/codexlens/OverviewTab.tsx | 246 +++ .../components/codexlens/SettingsTab.test.tsx | 456 ++++++ .../src/components/codexlens/SettingsTab.tsx | 272 ++++ .../components/hook/HookQuickTemplates.tsx | 13 + .../issue/discovery/DiscoveryDetail.tsx | 74 +- .../issue/discovery/FindingList.tsx | 236 ++- .../components/issue/hub/DiscoveryPanel.tsx | 13 +- .../src/components/issue/hub/IssueDrawer.tsx | 238 +++ .../src/components/issue/hub/IssuesPanel.tsx | 148 +- .../src/components/issue/hub/QueuePanel.tsx | 49 +- .../components/issue/queue/ExecutionGroup.tsx | 58 +- .../components/issue/queue/QueueActions.tsx | 288 +++- .../src/components/issue/queue/QueueCard.tsx | 9 + .../components/issue/queue/SolutionDrawer.tsx | 212 +++ .../src/components/layout/Sidebar.tsx | 6 +- .../session-detail/context/AssetsCard.tsx | 143 ++ .../context/ConflictDetectionCard.tsx | 159 ++ .../context/DependenciesCard.tsx | 146 ++ .../context/ExplorationCollapsible.tsx | 56 + .../context/ExplorationsSection.tsx | 183 +++ .../session-detail/context/FieldRenderer.tsx | 143 ++ .../context/TestContextCard.tsx | 179 +++ .../session-detail/context/index.ts | 24 + .../session-detail/tasks/BulkActionButton.tsx | 46 + .../session-detail/tasks/TaskStatsBar.tsx | 94 ++ .../tasks/TaskStatusDropdown.tsx | 134 ++ .../components/session-detail/tasks/index.ts | 12 + .../src/components/shared/MarkdownModal.tsx | 245 +++ ccw/frontend/src/components/ui/index.ts | 3 + ccw/frontend/src/hooks/index.ts | 53 +- ccw/frontend/src/hooks/useCli.ts | 4 +- ccw/frontend/src/hooks/useCodexLens.test.tsx | 427 ++++++ ccw/frontend/src/hooks/useCodexLens.ts | 762 ++++++++++ ccw/frontend/src/hooks/useCommands.ts | 3 +- ccw/frontend/src/hooks/useIssues.ts | 51 +- ccw/frontend/src/hooks/useSkills.ts | 5 +- ccw/frontend/src/lib/api.ts | 758 ++++++++- ccw/frontend/src/locales/en/cli-hooks.json | 4 + ccw/frontend/src/locales/en/codexlens.json | 178 +++ ccw/frontend/src/locales/en/index.ts | 4 +- ccw/frontend/src/locales/en/issues.json | 42 +- ccw/frontend/src/locales/en/navigation.json | 1 + .../src/locales/en/session-detail.json | 113 +- ccw/frontend/src/locales/zh/cli-hooks.json | 4 + ccw/frontend/src/locales/zh/codexlens.json | 178 +++ ccw/frontend/src/locales/zh/common.json | 8 +- ccw/frontend/src/locales/zh/index.ts | 4 +- ccw/frontend/src/locales/zh/issues.json | 150 +- ccw/frontend/src/locales/zh/navigation.json | 1 + .../src/locales/zh/session-detail.json | 111 +- .../src/pages/CodexLensManagerPage.test.tsx | 364 +++++ .../src/pages/CodexLensManagerPage.tsx | 205 +++ ccw/frontend/src/pages/DiscoveryPage.tsx | 4 + ccw/frontend/src/pages/IssueHubPage.tsx | 195 ++- ccw/frontend/src/pages/SessionDetailPage.tsx | 43 +- ccw/frontend/src/pages/index.ts | 1 + .../src/pages/session-detail/ConflictTab.tsx | 176 +++ .../src/pages/session-detail/ContextTab.tsx | 39 +- .../src/pages/session-detail/ImplPlanTab.tsx | 113 ++ .../src/pages/session-detail/ReviewTab.tsx | 227 +++ .../src/pages/session-detail/SummaryTab.tsx | 152 +- .../src/pages/session-detail/TaskListTab.tsx | 201 ++- ccw/frontend/src/router.tsx | 6 + ccw/frontend/src/test/i18n.tsx | 156 ++ .../tests/e2e/codexlens-manager.spec.ts | 445 ++++++ ccw/src/commands/hook.ts | 74 +- ccw/src/core/routes/cli-routes.ts | 29 + ccw/src/core/routes/hooks-routes.ts | 170 +++ 79 files changed, 11819 insertions(+), 2455 deletions(-) delete mode 100644 .codex/prompts/merge-plans-with-file.md create mode 100644 ccw/frontend/src/components/codexlens/AdvancedTab.tsx create mode 100644 ccw/frontend/src/components/codexlens/GpuSelector.tsx create mode 100644 ccw/frontend/src/components/codexlens/ModelCard.tsx create mode 100644 ccw/frontend/src/components/codexlens/ModelsTab.test.tsx create mode 100644 ccw/frontend/src/components/codexlens/ModelsTab.tsx create mode 100644 ccw/frontend/src/components/codexlens/OverviewTab.test.tsx create mode 100644 ccw/frontend/src/components/codexlens/OverviewTab.tsx create mode 100644 ccw/frontend/src/components/codexlens/SettingsTab.test.tsx create mode 100644 ccw/frontend/src/components/codexlens/SettingsTab.tsx create mode 100644 ccw/frontend/src/components/issue/hub/IssueDrawer.tsx create mode 100644 ccw/frontend/src/components/issue/queue/SolutionDrawer.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/AssetsCard.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/ConflictDetectionCard.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/DependenciesCard.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/ExplorationCollapsible.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/ExplorationsSection.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/FieldRenderer.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/TestContextCard.tsx create mode 100644 ccw/frontend/src/components/session-detail/context/index.ts create mode 100644 ccw/frontend/src/components/session-detail/tasks/BulkActionButton.tsx create mode 100644 ccw/frontend/src/components/session-detail/tasks/TaskStatsBar.tsx create mode 100644 ccw/frontend/src/components/session-detail/tasks/TaskStatusDropdown.tsx create mode 100644 ccw/frontend/src/components/session-detail/tasks/index.ts create mode 100644 ccw/frontend/src/components/shared/MarkdownModal.tsx create mode 100644 ccw/frontend/src/hooks/useCodexLens.test.tsx create mode 100644 ccw/frontend/src/hooks/useCodexLens.ts create mode 100644 ccw/frontend/src/locales/en/codexlens.json create mode 100644 ccw/frontend/src/locales/zh/codexlens.json create mode 100644 ccw/frontend/src/pages/CodexLensManagerPage.test.tsx create mode 100644 ccw/frontend/src/pages/CodexLensManagerPage.tsx create mode 100644 ccw/frontend/src/pages/session-detail/ConflictTab.tsx create mode 100644 ccw/frontend/src/pages/session-detail/ImplPlanTab.tsx create mode 100644 ccw/frontend/src/pages/session-detail/ReviewTab.tsx create mode 100644 ccw/frontend/tests/e2e/codexlens-manager.spec.ts diff --git a/.claude/commands/ccw-debug.md b/.claude/commands/ccw-debug.md index 0dc418a2..241b9882 100644 --- a/.claude/commands/ccw-debug.md +++ b/.claude/commands/ccw-debug.md @@ -148,6 +148,8 @@ User Input โ†’ Quick Context Gather โ†’ ccw cli (Gemini/Qwen/Codex) // - Read error file if path provided // - Extract error patterns from description // - Identify likely affected files (basic grep) + + // Note: CLI mode does not generate status.json (lightweight) ``` 2. **Execute CLI Analysis** (Phase 3) @@ -299,6 +301,27 @@ User Input โ†’ Session Init โ†’ /workflow:debug-with-file flags: { hotfix, autoYes } } Write(`${sessionFolder}/mode-config.json`, JSON.stringify(modeConfig, null, 2)) + + // Initialize status.json for hook tracking + const state = { + session_id: sessionId, + mode: "debug", + status: "running", + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + bug_description: bug_description, + command_chain: [ + { index: 0, command: "Phase 1: Debug & Analysis", status: "running" }, + { index: 1, command: "Phase 2: Apply Fix from Debug Findings", status: "pending" }, + { index: 2, command: "Phase 3: Generate & Execute Tests", status: "pending" }, + { index: 3, command: "Phase 4: Generate Report", status: "pending" } + ], + current_index: 0 + } + Write(`${sessionFolder}/status.json`, JSON.stringify(state, null, 2)) + + // Output session ID for hook matching + console.log(`๐Ÿ“‹ Session Started: ${sessionId}`) ``` 2. **Start Debug** (Phase 3) @@ -373,12 +396,38 @@ User Input โ†’ Session Init โ†’ /workflow:test-fix-gen 1. **Session Initialization** (Phase 2) ```javascript + const sessionId = `CCWD-${bugSlug}-${dateStr}` + const sessionFolder = `.workflow/.ccw-debug/${sessionId}` + bash(`mkdir -p ${sessionFolder}`) + const modeConfig = { mode: "test", original_input: bug_description, timestamp: getUtc8ISOString(), flags: { hotfix, autoYes } } + Write(`${sessionFolder}/mode-config.json`, JSON.stringify(modeConfig, null, 2)) + + // Initialize status.json for hook tracking + const state = { + session_id: sessionId, + mode: "test", + status: "running", + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + bug_description: bug_description, + command_chain: [ + { index: 0, command: "Phase 1: Generate Tests", status: "running" }, + { index: 1, command: "Phase 2: Execute & Fix Tests", status: "pending" }, + { index: 2, command: "Phase 3: Final Validation", status: "pending" }, + { index: 3, command: "Phase 4: Generate Report", status: "pending" } + ], + current_index: 0 + } + Write(`${sessionFolder}/status.json`, JSON.stringify(state, null, 2)) + + // Output session ID for hook matching + console.log(`๐Ÿ“‹ Session Started: ${sessionId}`) ``` 2. **Generate Tests** (Phase 3) @@ -439,8 +488,32 @@ User Input โ†’ Session Init โ†’ Parallel execution: **Execution Steps**: -1. **Parallel Execution** (Phase 3) +1. **Session Initialization & Parallel Execution** (Phase 2-3) ```javascript + const sessionId = `CCWD-${bugSlug}-${dateStr}` + const sessionFolder = `.workflow/.ccw-debug/${sessionId}` + bash(`mkdir -p ${sessionFolder}`) + + // Initialize status.json for hook tracking + const state = { + session_id: sessionId, + mode: "bidirectional", + status: "running", + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + bug_description: bug_description, + command_chain: [ + { index: 0, command: "Phase 1: Parallel Debug & Test", status: "running" }, + { index: 1, command: "Phase 2: Merge Findings", status: "pending" }, + { index: 2, command: "Phase 3: Generate Report", status: "pending" } + ], + current_index: 0 + } + Write(`${sessionFolder}/status.json`, JSON.stringify(state, null, 2)) + + // Output session ID for hook matching + console.log(`๐Ÿ“‹ Session Started: ${sessionId}`) + // Start debug const debugTask = Skill(skill="workflow:debug-with-file", args=`"${bug_description}"`) @@ -579,18 +652,24 @@ Arguments: ### Session State Management +**Status JSON Location**: `.workflow/.ccw-debug/{session_id}/status.json` + +**Status JSON Structure**: ```json { "session_id": "CCWD-login-timeout-2025-01-27", - "mode": "debug|test|bidirectional", + "mode": "debug|test|bidirectional|cli", "status": "running|completed|failed|paused", - "phases": { - "phase_1": { "status": "completed", "timestamp": "..." }, - "phase_2": { "status": "in_progress", "timestamp": "..." }, - "phase_3": { "status": "pending" }, - "phase_4": { "status": "pending" }, - "phase_5": { "status": "pending" } - }, + "created_at": "2025-01-27T10:30:00Z", + "updated_at": "2025-01-27T10:35:00Z", + "bug_description": "User login timeout after 30 seconds", + "command_chain": [ + { "index": 0, "command": "Phase 1: Debug & Analysis", "status": "completed" }, + { "index": 1, "command": "Phase 2: Apply Fix from Debug Findings", "status": "in_progress" }, + { "index": 2, "command": "Phase 3: Generate & Execute Tests", "status": "pending" }, + { "index": 3, "command": "Phase 4: Generate Report", "status": "pending" } + ], + "current_index": 1, "sub_sessions": { "debug_session": "DBG-...", "test_session": "WFS-test-..." @@ -603,6 +682,13 @@ Arguments: } ``` +**Session ID Output**: When session starts, ccw-debug outputs: +``` +๐Ÿ“‹ Session Started: CCWD-login-timeout-2025-01-27 +``` + +This output is captured by hooks for status.json path matching. + --- ## Mode Selection Logic diff --git a/.claude/commands/ccw.md b/.claude/commands/ccw.md index 6d7564f8..fdb8aad2 100644 --- a/.claude/commands/ccw.md +++ b/.claude/commands/ccw.md @@ -327,49 +327,107 @@ async function getUserConfirmation(chain) { --- -### Phase 4: Setup TODO Tracking +### Phase 4: Setup TODO Tracking & Status File ```javascript -function setupTodoTracking(chain, workflow) { +function setupTodoTracking(chain, workflow, analysis) { + const sessionId = `ccw-${Date.now()}`; + const stateDir = `.workflow/.ccw/${sessionId}`; + Bash(`mkdir -p "${stateDir}"`); + const todos = chain.map((step, i) => ({ content: `CCW:${workflow}: [${i + 1}/${chain.length}] ${step.cmd}`, status: i === 0 ? 'in_progress' : 'pending', activeForm: `Executing ${step.cmd}` })); TodoWrite({ todos }); + + // Initialize status.json for hook tracking + const state = { + session_id: sessionId, + workflow: workflow, + status: 'running', + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + analysis: analysis, + command_chain: chain.map((step, idx) => ({ + index: idx, + command: step.cmd, + status: idx === 0 ? 'running' : 'pending' + })), + current_index: 0 + }; + + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); + + return { sessionId, stateDir, state }; } ``` -**Output**: `-> CCW:rapid: [1/3] /workflow:lite-plan | CCW:rapid: [2/3] /workflow:lite-execute | ...` +**Output**: +- TODO: `-> CCW:rapid: [1/3] /workflow:lite-plan | CCW:rapid: [2/3] /workflow:lite-execute | ...` +- Status File: `.workflow/.ccw/{session_id}/status.json` --- ### Phase 5: Execute Command Chain ```javascript -async function executeCommandChain(chain, workflow) { +async function executeCommandChain(chain, workflow, trackingState) { let previousResult = null; + const { sessionId, stateDir, state } = trackingState; for (let i = 0; i < chain.length; i++) { try { + // Update status: mark current as running + state.command_chain[i].status = 'running'; + state.current_index = i; + state.updated_at = new Date().toISOString(); + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); + const fullCommand = assembleCommand(chain[i], previousResult); const result = await Skill({ skill: fullCommand }); previousResult = { ...result, success: true }; + + // Update status: mark current as completed, next as running + state.command_chain[i].status = 'completed'; + if (i + 1 < chain.length) { + state.command_chain[i + 1].status = 'running'; + } + state.updated_at = new Date().toISOString(); + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); + updateTodoStatus(i, chain.length, workflow, 'completed'); } catch (error) { + // Update status on error + state.command_chain[i].status = 'failed'; + state.status = 'error'; + state.updated_at = new Date().toISOString(); + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); + const action = await handleError(chain[i], error, i); if (action === 'retry') { + state.command_chain[i].status = 'pending'; + state.status = 'running'; i--; // Retry } else if (action === 'abort') { + state.status = 'failed'; + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); return { success: false, error: error.message }; } // 'skip' - continue + state.status = 'running'; } } - return { success: true, completed: chain.length }; + // Mark workflow as completed + state.status = 'completed'; + state.updated_at = new Date().toISOString(); + Write(`${stateDir}/status.json`, JSON.stringify(state, null, 2)); + + return { success: true, completed: chain.length, sessionId }; } // Assemble full command with session/plan parameters @@ -434,16 +492,19 @@ Phase 3: User Confirmation (optional) |-- Show pipeline visualization +-- Allow adjustment | -Phase 4: Setup TODO Tracking - +-- Create todos with CCW prefix +Phase 4: Setup TODO Tracking & Status File + |-- Create todos with CCW prefix + +-- Initialize .workflow/.ccw/{session_id}/status.json | Phase 5: Execute Command Chain |-- For each command: + | |-- Update status.json (current=running) | |-- Assemble full command | |-- Execute via Skill + | |-- Update status.json (current=completed, next=running) | |-- Update TODO status | +-- Handle errors (retry/skip/abort) - +-- Return workflow result + +-- Mark status.json as completed ``` --- @@ -482,7 +543,9 @@ Phase 5: Execute Command Chain ## State Management -**TodoWrite-Based Tracking**: All execution state tracked via TodoWrite with `CCW:` prefix. +### Dual Tracking System + +**1. TodoWrite-Based Tracking** (UI Display): All execution state tracked via TodoWrite with `CCW:` prefix. ```javascript // Initial state @@ -500,7 +563,57 @@ todos = [ ]; ``` -**vs ccw-coordinator**: Extensive state.json with task_id, status transitions, hook callbacks. +**2. Status.json Tracking**: Persistent state file for workflow monitoring. + +**Location**: `.workflow/.ccw/{session_id}/status.json` + +**Structure**: +```json +{ + "session_id": "ccw-1706123456789", + "workflow": "rapid", + "status": "running|completed|failed|error", + "created_at": "2025-02-01T10:30:00Z", + "updated_at": "2025-02-01T10:35:00Z", + "analysis": { + "goal": "Add user authentication", + "scope": ["auth"], + "constraints": [], + "task_type": "feature", + "complexity": "medium" + }, + "command_chain": [ + { + "index": 0, + "command": "/workflow:lite-plan", + "status": "completed" + }, + { + "index": 1, + "command": "/workflow:lite-execute", + "status": "running" + }, + { + "index": 2, + "command": "/workflow:test-cycle-execute", + "status": "pending" + } + ], + "current_index": 1 +} +``` + +**Status Values**: +- `running`: Workflow executing commands +- `completed`: All commands finished +- `failed`: User aborted or unrecoverable error +- `error`: Command execution failed (during error handling) + +**Command Status Values**: +- `pending`: Not started +- `running`: Currently executing +- `completed`: Successfully finished +- `failed`: Execution failed --- @@ -527,20 +640,6 @@ todos = [ --- -## Type Comparison: ccw vs ccw-coordinator - -| Aspect | ccw | ccw-coordinator | -|--------|-----|-----------------| -| **Type** | Main process (Skill) | External CLI (ccw cli + hook callbacks) | -| **Execution** | Synchronous blocking | Async background with hook completion | -| **Workflow** | Auto intent-based selection | Manual chain building | -| **Intent Analysis** | 5-phase clarity check | 3-phase requirement analysis | -| **State** | TodoWrite only (in-memory) | state.json + checkpoint/resume | -| **Error Handling** | Retry/skip/abort (interactive) | Retry/skip/abort (via AskUser) | -| **Use Case** | Auto workflow for any task | Manual orchestration, large chains | - ---- - ## Usage ```bash diff --git a/.claude/commands/workflow/analyze-with-file.md b/.claude/commands/workflow/analyze-with-file.md index f51be9dc..68a3eb3a 100644 --- a/.claude/commands/workflow/analyze-with-file.md +++ b/.claude/commands/workflow/analyze-with-file.md @@ -9,256 +9,190 @@ allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles. -# Workflow Analyze-With-File Command (/workflow:analyze-with-file) +# Workflow Analyze Command + +## Quick Start + +```bash +# Basic usage +/workflow:analyze-with-file "ๅฆ‚ไฝ•ไผ˜ๅŒ–่ฟ™ไธช้กน็›ฎ็š„่ฎค่ฏๆžถๆž„" + +# With options +/workflow:analyze-with-file --continue "่ฎค่ฏๆžถๆž„" # Continue existing session +/workflow:analyze-with-file -y "ๆ€ง่ƒฝ็“ถ้ขˆๅˆ†ๆž" # Auto mode +``` + +**Context Source**: cli-explore-agent + Gemini/Codex analysis +**Output Directory**: `.workflow/.analysis/{session-id}/` +**Core Innovation**: Documented discussion timeline with evolving understanding + +## Output Artifacts + +### Phase 1: Topic Understanding + +| Artifact | Description | +|----------|-------------| +| `discussion.md` | Evolution of understanding & discussions (initialized) | +| Session variables | Dimensions, focus areas, analysis depth | + +### Phase 2: CLI Exploration + +| Artifact | Description | +|----------|-------------| +| `exploration-codebase.json` | Codebase context from cli-explore-agent | +| `explorations.json` | Aggregated CLI findings (Gemini/Codex) | +| Updated `discussion.md` | Round 1 with exploration results | + +### Phase 3: Interactive Discussion + +| Artifact | Description | +|----------|-------------| +| Updated `discussion.md` | Round 2-N with user feedback and insights | +| Corrected assumptions | Tracked in discussion timeline | + +### Phase 4: Synthesis & Conclusion + +| Artifact | Description | +|----------|-------------| +| `conclusions.json` | Final synthesis with recommendations | +| Final `discussion.md` | โญ Complete analysis with conclusions | ## Overview -Interactive collaborative analysis workflow with **documented discussion process**. Records understanding evolution, facilitates multi-round Q&A, and uses CLI tools (Gemini/Codex) for deep exploration. +Interactive collaborative analysis workflow with **documented discussion process**. Records understanding evolution, facilitates multi-round Q&A, and uses CLI tools for deep exploration. **Core workflow**: Topic โ†’ Explore โ†’ Discuss โ†’ Document โ†’ Refine โ†’ Conclude -**Key features**: -- **discussion.md**: Timeline of discussions and understanding evolution -- **Multi-round Q&A**: Iterative clarification with user -- **CLI-assisted exploration**: Gemini/Codex for codebase and concept analysis -- **Consolidated insights**: Synthesizes discussions into actionable conclusions -- **Flexible continuation**: Resume analysis sessions to build on previous work - -## Usage - -```bash -/workflow:analyze-with-file [FLAGS] - -# Flags --y, --yes Skip confirmations, use recommended settings --c, --continue Continue existing session (auto-detected if exists) - -# Arguments - Analysis topic, question, or concept to explore (required) - -# Examples -/workflow:analyze-with-file "ๅฆ‚ไฝ•ไผ˜ๅŒ–่ฟ™ไธช้กน็›ฎ็š„่ฎค่ฏๆžถๆž„" -/workflow:analyze-with-file --continue "่ฎค่ฏๆžถๆž„" # Continue existing session -/workflow:analyze-with-file -y "ๆ€ง่ƒฝ็“ถ้ขˆๅˆ†ๆž" # Auto mode +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ INTERACTIVE ANALYSIS WORKFLOW โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ โ”‚ +โ”‚ Phase 1: Topic Understanding โ”‚ +โ”‚ โ”œโ”€ Parse topic/question โ”‚ +โ”‚ โ”œโ”€ Identify analysis dimensions (architecture, performance, etc.) โ”‚ +โ”‚ โ”œโ”€ Initial scoping with user โ”‚ +โ”‚ โ””โ”€ Initialize discussion.md โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 2: CLI Exploration โ”‚ +โ”‚ โ”œโ”€ cli-explore-agent: Codebase context (FIRST) โ”‚ +โ”‚ โ”œโ”€ Gemini/Codex: Deep analysis (AFTER exploration) โ”‚ +โ”‚ โ”œโ”€ Aggregate findings โ”‚ +โ”‚ โ””โ”€ Update discussion.md with Round 1 โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 3: Interactive Discussion (Multi-Round) โ”‚ +โ”‚ โ”œโ”€ Present exploration findings โ”‚ +โ”‚ โ”œโ”€ Facilitate Q&A with user โ”‚ +โ”‚ โ”œโ”€ Capture user insights and corrections โ”‚ +โ”‚ โ”œโ”€ Actions: Deepen | Adjust direction | Answer questions โ”‚ +โ”‚ โ”œโ”€ Update discussion.md with each round โ”‚ +โ”‚ โ””โ”€ Repeat until clarity achieved (max 5 rounds) โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 4: Synthesis & Conclusion โ”‚ +โ”‚ โ”œโ”€ Consolidate all insights โ”‚ +โ”‚ โ”œโ”€ Generate conclusions with recommendations โ”‚ +โ”‚ โ”œโ”€ Update discussion.md with final synthesis โ”‚ +โ”‚ โ””โ”€ Offer follow-up options (issue/task/report) โ”‚ +โ”‚ โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` -## Execution Process +## Output Structure ``` -Session Detection: - โ”œโ”€ Check if analysis session exists for topic - โ”œโ”€ EXISTS + discussion.md exists โ†’ Continue mode - โ””โ”€ NOT_FOUND โ†’ New session mode - -Phase 1: Topic Understanding - โ”œโ”€ Parse topic/question - โ”œโ”€ Identify analysis dimensions (architecture, implementation, concept, etc.) - โ”œโ”€ Initial scoping with user (AskUserQuestion) - โ””โ”€ Document initial understanding in discussion.md - -Phase 2: CLI Exploration (Parallel) - โ”œโ”€ Launch cli-explore-agent for codebase context - โ”œโ”€ Use Gemini/Codex for deep analysis - โ””โ”€ Aggregate findings into exploration summary - -Phase 3: Interactive Discussion (Multi-Round) - โ”œโ”€ Present exploration findings - โ”œโ”€ Facilitate Q&A with user (AskUserQuestion) - โ”œโ”€ Capture user insights and requirements - โ”œโ”€ Update discussion.md with each round - โ””โ”€ Repeat until user is satisfied or clarity achieved - -Phase 4: Synthesis & Conclusion - โ”œโ”€ Consolidate all insights - โ”œโ”€ Update discussion.md with conclusions - โ”œโ”€ Generate actionable recommendations - โ””โ”€ Optional: Create follow-up tasks or issues - -Output: - โ”œโ”€ .workflow/.analysis/{slug}-{date}/discussion.md (evolving document) - โ”œโ”€ .workflow/.analysis/{slug}-{date}/explorations.json (CLI findings) - โ””โ”€ .workflow/.analysis/{slug}-{date}/conclusions.json (final synthesis) +.workflow/.analysis/ANL-{slug}-{date}/ +โ”œโ”€โ”€ discussion.md # โญ Evolution of understanding & discussions +โ”œโ”€โ”€ exploration-codebase.json # Phase 2: Codebase context +โ”œโ”€โ”€ explorations.json # Phase 2: Aggregated CLI findings +โ””โ”€โ”€ conclusions.json # Phase 4: Final synthesis ``` ## Implementation -### Session Setup & Mode Detection +### Session Initialization -```javascript -const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() +**Objective**: Create session context and directory structure for analysis. -const topicSlug = topic_or_question.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40) -const dateStr = getUtc8ISOString().substring(0, 10) +**Required Actions**: +1. Extract topic/question from `$ARGUMENTS` +2. Generate session ID: `ANL-{slug}-{date}` + - slug: lowercase, alphanumeric + Chinese, max 40 chars + - date: YYYY-MM-DD (UTC+8) +3. Define session folder: `.workflow/.analysis/{session-id}` +4. Parse command options: + - `-c` or `--continue` for session continuation + - `-y` or `--yes` for auto-approval mode +5. Auto-detect mode: If session folder + discussion.md exist โ†’ continue mode +6. Create directory structure: `{session-folder}/` -const sessionId = `ANL-${topicSlug}-${dateStr}` -const sessionFolder = `.workflow/.analysis/${sessionId}` -const discussionPath = `${sessionFolder}/discussion.md` -const explorationsPath = `${sessionFolder}/explorations.json` -const conclusionsPath = `${sessionFolder}/conclusions.json` - -// Auto-detect mode -const sessionExists = fs.existsSync(sessionFolder) -const hasDiscussion = sessionExists && fs.existsSync(discussionPath) -const forcesContinue = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c') - -const mode = (hasDiscussion || forcesContinue) ? 'continue' : 'new' - -if (!sessionExists) { - bash(`mkdir -p ${sessionFolder}`) -} -``` - ---- +**Session Variables**: +- `sessionId`: Unique session identifier +- `sessionFolder`: Base directory for all artifacts +- `autoMode`: Boolean for auto-confirmation +- `mode`: new | continue ### Phase 1: Topic Understanding -**Step 1.1: Parse Topic & Identify Dimensions** +**Objective**: Analyze topic, identify dimensions, gather user input, initialize discussion.md. -```javascript -// Analyze topic to determine analysis dimensions -const ANALYSIS_DIMENSIONS = { - architecture: ['ๆžถๆž„', 'architecture', 'design', 'structure', '่ฎพ่ฎก'], - implementation: ['ๅฎž็Žฐ', 'implement', 'code', 'coding', 'ไปฃ็ '], - performance: ['ๆ€ง่ƒฝ', 'performance', 'optimize', 'bottleneck', 'ไผ˜ๅŒ–'], - security: ['ๅฎ‰ๅ…จ', 'security', 'auth', 'permission', 'ๆƒ้™'], - concept: ['ๆฆ‚ๅฟต', 'concept', 'theory', 'principle', 'ๅŽŸ็†'], - comparison: ['ๆฏ”่พƒ', 'compare', 'vs', 'difference', 'ๅŒบๅˆซ'], - decision: ['ๅ†ณ็ญ–', 'decision', 'choice', 'tradeoff', '้€‰ๆ‹ฉ'] -} +**Prerequisites**: +- Session initialized with valid sessionId and sessionFolder +- Topic/question available from $ARGUMENTS -function identifyDimensions(topic) { - const text = topic.toLowerCase() - const matched = [] +**Workflow Steps**: - for (const [dimension, keywords] of Object.entries(ANALYSIS_DIMENSIONS)) { - if (keywords.some(k => text.includes(k))) { - matched.push(dimension) - } - } +1. **Parse Topic & Identify Dimensions** + - Match topic keywords against ANALYSIS_DIMENSIONS + - Identify relevant dimensions: architecture, implementation, performance, security, concept, comparison, decision + - Default to "general" if no match - return matched.length > 0 ? matched : ['general'] -} +2. **Initial Scoping** (if new session + not auto mode) + - **Focus**: Multi-select from code implementation, architecture design, best practices, problem diagnosis + - **Depth**: Single-select from Quick Overview (10-15min) / Standard Analysis (30-60min) / Deep Dive (1-2hr) -const dimensions = identifyDimensions(topic_or_question) -``` +3. **Initialize discussion.md** + - Create discussion.md with session metadata + - Add user context: focus areas, analysis depth + - Add initial understanding: dimensions, scope, key questions + - Create empty sections for discussion timeline -**Step 1.2: Initial Scoping (New Session Only)** - -```javascript -const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y') - -if (mode === 'new' && !autoYes) { - // Ask user to scope the analysis - AskUserQuestion({ - questions: [ - { - question: `ๅˆ†ๆž่Œƒๅ›ด: "${topic_or_question}"\n\nๆ‚จๆƒณ้‡็‚นๅ…ณๆณจๅ“ชไบ›ๆ–น้ข?`, - header: "Focus", - multiSelect: true, - options: [ - { label: "ไปฃ็ ๅฎž็Žฐ", description: "ๅˆ†ๆž็Žฐๆœ‰ไปฃ็ ๅฎž็Žฐ" }, - { label: "ๆžถๆž„่ฎพ่ฎก", description: "ๆžถๆž„ๅฑ‚้ข็š„ๅˆ†ๆž" }, - { label: "ๆœ€ไฝณๅฎž่ทต", description: "่กŒไธšๆœ€ไฝณๅฎž่ทตๅฏนๆฏ”" }, - { label: "้—ฎ้ข˜่ฏŠๆ–ญ", description: "่ฏ†ๅˆซๆฝœๅœจ้—ฎ้ข˜" } - ] - }, - { - question: "ๅˆ†ๆžๆทฑๅบฆ?", - header: "Depth", - multiSelect: false, - options: [ - { label: "Quick Overview", description: "ๅฟซ้€Ÿๆฆ‚่งˆ (10-15ๅˆ†้’Ÿ)" }, - { label: "Standard Analysis", description: "ๆ ‡ๅ‡†ๅˆ†ๆž (30-60ๅˆ†้’Ÿ)" }, - { label: "Deep Dive", description: "ๆทฑๅบฆๅˆ†ๆž (1-2ๅฐๆ—ถ)" } - ] - } - ] - }) -} -``` - -**Step 1.3: Create/Update discussion.md** - -For new session: -```markdown -# Analysis Discussion - -**Session ID**: ${sessionId} -**Topic**: ${topic_or_question} -**Started**: ${getUtc8ISOString()} -**Dimensions**: ${dimensions.join(', ')} - ---- - -## User Context - -**Focus Areas**: ${userFocusAreas.join(', ')} -**Analysis Depth**: ${analysisDepth} - ---- - -## Discussion Timeline - -### Round 1 - Initial Understanding (${timestamp}) - -#### Topic Analysis - -Based on the topic "${topic_or_question}": - -- **Primary dimensions**: ${dimensions.join(', ')} -- **Initial scope**: ${initialScope} -- **Key questions to explore**: - - ${question1} - - ${question2} - - ${question3} - -#### Next Steps - -- Launch CLI exploration for codebase context -- Gather external insights via Gemini -- Prepare discussion points for user - ---- - -## Current Understanding - -${initialUnderstanding} -``` - -For continue session, append: -```markdown -### Round ${n} - Continuation (${timestamp}) - -#### Previous Context - -Resuming analysis based on prior discussion. - -#### New Focus - -${newFocusFromUser} -``` - ---- +**Success Criteria**: +- Session folder created with discussion.md initialized +- Analysis dimensions identified +- User preferences captured (focus, depth) ### Phase 2: CLI Exploration -**โš ๏ธ CRITICAL - EXPLORATION PRIORITY**: -- **cli-explore-agent FIRST**: Always use cli-explore-agent as primary exploration method -- **CLI calls AFTER**: Use Gemini/other CLI tools only after cli-explore-agent provides context -- **Sequential execution**: cli-explore-agent โ†’ CLI deep analysis (not parallel) -- Minimize output: No processing until 100% results available +**Objective**: Gather codebase context, then execute deep analysis via CLI tools. -**Step 2.1: Primary Exploration via cli-explore-agent** +**Prerequisites**: +- Phase 1 completed successfully +- discussion.md initialized +- Dimensions identified +**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 '{}'` + - Execute searches based on topic keywords + - Read: `.workflow/project-tech.json` if exists + - **Output**: `{sessionFolder}/exploration-codebase.json` + - relevant_files: [{path, relevance, rationale}] + - patterns: [] + - key_findings: [] + - questions_for_user: [] + - **Purpose**: Enrich CLI prompts with codebase context + +**Agent Call Example**: ```javascript -// โš ๏ธ PRIORITY: cli-explore-agent is the PRIMARY exploration method -// MUST complete before any CLI calls - -const codebaseExploration = await Task( - subagent_type="cli-explore-agent", - run_in_background=false, - description=`Explore codebase: ${topicSlug}`, - prompt=` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: `Explore codebase: ${topicSlug}`, + prompt: ` ## Analysis Context Topic: ${topic_or_question} Dimensions: ${dimensions.join(', ')} @@ -277,28 +211,28 @@ Write findings to: ${sessionFolder}/exploration-codebase.json Schema: { - "relevant_files": [{path, relevance, rationale}], + "relevant_files": [{"path": "...", "relevance": "high|medium|low", "rationale": "..."}], "patterns": [], "key_findings": [], "questions_for_user": [], "_metadata": { "exploration_type": "codebase", "timestamp": "..." } } ` -) - -// Read exploration results for CLI context enrichment -const explorationResults = Read(`${sessionFolder}/exploration-codebase.json`) +}) ``` -**Step 2.2: CLI Deep Analysis (Using Exploration Context)** +2. **CLI Deep Analysis** (โš ๏ธ AFTER exploration) + - Launch Gemini CLI with analysis mode + - **Shared context**: Include exploration-codebase.json findings in prompt + - **Execution**: Bash with run_in_background: true, wait for results + - **Output**: Analysis findings with insights and discussion points +**CLI Call Example**: ```javascript -// Gemini CLI for deep analysis - AFTER cli-explore-agent completes -// โš ๏ธ CRITICAL: Must wait for CLI completion before aggregating Bash({ command: `ccw cli -p " PURPOSE: Analyze topic '${topic_or_question}' from ${dimensions.join(', ')} perspectives -Success criteria: Actionable insights with clear reasoning +Success: Actionable insights with clear reasoning PRIOR EXPLORATION CONTEXT: - Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')} @@ -325,453 +259,194 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} " --tool gemini --mode analysis`, run_in_background: true }) + +// โš ๏ธ STOP POINT: Wait for hook callback to receive results before continuing ``` -**โš ๏ธ STOP POINT**: After launching CLI call, stop output immediately. Wait for hook callback to receive results before continuing to Step 2.3. +3. **Aggregate Findings** + - Consolidate codebase and CLI findings + - Extract key findings, discussion points, open questions + - Write to explorations.json -**Step 2.3: Aggregate Findings** +4. **Update discussion.md** + - Append Round 1 section with exploration results + - Include sources analyzed, key findings, discussion points, open questions -```javascript -// After explorations complete, aggregate into explorations.json -const explorations = { - session_id: sessionId, - timestamp: getUtc8ISOString(), - topic: topic_or_question, - dimensions: dimensions, - sources: [ - { type: "codebase", file: "exploration-codebase.json" }, - { type: "gemini", summary: geminiOutput } - ], - key_findings: [...], - discussion_points: [...], - open_questions: [...] -} +**explorations.json Schema**: +- `session_id`: Session identifier +- `timestamp`: Exploration completion time +- `topic`: Original topic/question +- `dimensions[]`: Analysis dimensions +- `sources[]`: {type, file/summary} +- `key_findings[]`: Main insights +- `discussion_points[]`: Questions for user +- `open_questions[]`: Unresolved questions -Write(explorationsPath, JSON.stringify(explorations, null, 2)) -``` +**Success Criteria**: +- exploration-codebase.json created with codebase context +- explorations.json created with aggregated findings +- discussion.md updated with Round 1 results +- All CLI calls completed successfully -**Step 2.4: Update discussion.md** +### Phase 3: Interactive Discussion -```markdown -#### Exploration Results (${timestamp}) +**Objective**: Iteratively refine understanding through user-guided discussion cycles. -**Sources Analyzed**: -${sources.map(s => `- ${s.type}: ${s.summary}`).join('\n')} +**Prerequisites**: +- Phase 2 completed successfully +- explorations.json contains initial findings +- discussion.md has Round 1 results -**Key Findings**: -${keyFindings.map((f, i) => `${i+1}. ${f}`).join('\n')} +**Workflow Steps**: -**Points for Discussion**: -${discussionPoints.map((p, i) => `${i+1}. ${p}`).join('\n')} +1. **Present Findings** + - Display current findings from explorations.json + - Show key points for user input -**Open Questions**: -${openQuestions.map((q, i) => `- ${q}`).join('\n')} -``` +2. **Gather User Feedback** (AskUserQuestion) + - **Question**: Feedback on current analysis + - **Options** (single-select): + - **ๅŒๆ„๏ผŒ็ปง็ปญๆทฑๅ…ฅ**: Analysis direction correct, deepen exploration + - **้œ€่ฆ่ฐƒๆ•ดๆ–นๅ‘**: Different understanding or focus + - **ๅˆ†ๆžๅฎŒๆˆ**: Sufficient information obtained + - **ๆœ‰ๅ…ทไฝ“้—ฎ้ข˜**: Specific questions to ask ---- +3. **Process User Response** -### Phase 3: Interactive Discussion (Multi-Round) + **Agree, Deepen**: + - Continue analysis in current direction + - Use CLI for deeper exploration -**Step 3.1: Present Findings & Gather Feedback** + **Adjust Direction**: + - AskUserQuestion for adjusted focus (code details / architecture / best practices) + - Launch new CLI exploration with adjusted scope -```javascript -// Maximum discussion rounds -const MAX_ROUNDS = 5 -let roundNumber = 1 -let discussionComplete = false + **Specific Questions**: + - Capture user questions + - Use CLI or direct analysis to answer + - Document Q&A in discussion.md -while (!discussionComplete && roundNumber <= MAX_ROUNDS) { - // Display current findings - console.log(` -## Discussion Round ${roundNumber} + **Complete**: + - Exit discussion loop, proceed to Phase 4 -${currentFindings} +4. **Update discussion.md** + - Append Round N section with: + - User input summary + - Direction adjustment (if any) + - User questions & answers (if any) + - Updated understanding + - Corrected assumptions + - New insights -### Key Points for Your Input -${discussionPoints.map((p, i) => `${i+1}. ${p}`).join('\n')} -`) +5. **Repeat or Converge** + - Continue loop (max 5 rounds) or exit to Phase 4 - // Gather user input - const userResponse = AskUserQuestion({ - questions: [ - { - question: "ๅฏนไปฅไธŠๅˆ†ๆžๆœ‰ไป€ไนˆ็œ‹ๆณ•ๆˆ–่กฅๅ……?", - header: "Feedback", - multiSelect: false, - options: [ - { label: "ๅŒๆ„๏ผŒ็ปง็ปญๆทฑๅ…ฅ", description: "ๅˆ†ๆžๆ–นๅ‘ๆญฃ็กฎ๏ผŒ็ปง็ปญๆŽข็ดข" }, - { label: "้œ€่ฆ่ฐƒๆ•ดๆ–นๅ‘", description: "ๆˆ‘ๆœ‰ไธๅŒ็š„็†่งฃๆˆ–้‡็‚น" }, - { label: "ๅˆ†ๆžๅฎŒๆˆ", description: "ๅทฒ่Žทๅพ—่ถณๅคŸไฟกๆฏ" }, - { label: "ๆœ‰ๅ…ทไฝ“้—ฎ้ข˜", description: "ๆˆ‘ๆƒณ้—ฎไธ€ไบ›ๅ…ทไฝ“้—ฎ้ข˜" } - ] - } - ] - }) +**Discussion Actions**: - // Process user response - switch (userResponse.feedback) { - case "ๅŒๆ„๏ผŒ็ปง็ปญๆทฑๅ…ฅ": - // Deepen analysis in current direction - await deepenAnalysis() - break - case "้œ€่ฆ่ฐƒๆ•ดๆ–นๅ‘": - // Get user's adjusted focus - const adjustment = AskUserQuestion({ - questions: [{ - question: "่ฏท่ฏดๆ˜Žๆ‚จๅธŒๆœ›่ฐƒๆ•ด็š„ๆ–นๅ‘ๆˆ–้‡็‚น:", - header: "Direction", - multiSelect: false, - options: [ - { label: "ๆ›ดๅคšไปฃ็ ็ป†่Š‚", description: "ๆทฑๅ…ฅไปฃ็ ๅฎž็Žฐ" }, - { label: "ๆ›ดๅคšๆžถๆž„่ง†่ง’", description: "ๅ…ณๆณจๆ•ดไฝ“่ฎพ่ฎก" }, - { label: "ๆ›ดๅคšๅฎž่ทตๅฏนๆฏ”", description: "ๅฏนๆฏ”ๆœ€ไฝณๅฎž่ทต" } - ] - }] - }) - await adjustAnalysisDirection(adjustment) - break - case "ๅˆ†ๆžๅฎŒๆˆ": - discussionComplete = true - break - case "ๆœ‰ๅ…ทไฝ“้—ฎ้ข˜": - // Let user ask specific questions, then answer - await handleUserQuestions() - break - } +| User Choice | Action | Tool | Description | +|-------------|--------|------|-------------| +| Deepen | Continue current direction | Gemini CLI | Deeper analysis in same focus | +| Adjust | Change analysis angle | Selected CLI | New exploration with adjusted scope | +| Questions | Answer specific questions | CLI or analysis | Address user inquiries | +| Complete | Exit discussion loop | - | Proceed to synthesis | - // Update discussion.md with this round - updateDiscussionDocument(roundNumber, userResponse, findings) - roundNumber++ -} -``` - -**Step 3.2: Document Each Round** - -Append to discussion.md: -```markdown -### Round ${n} - Discussion (${timestamp}) - -#### User Input - -${userInputSummary} - -${userResponse === 'adjustment' ? ` -**Direction Adjustment**: ${adjustmentDetails} -` : ''} - -${userResponse === 'questions' ? ` -**User Questions**: -${userQuestions.map((q, i) => `${i+1}. ${q}`).join('\n')} - -**Answers**: -${answers.map((a, i) => `${i+1}. ${a}`).join('\n')} -` : ''} - -#### Updated Understanding - -Based on user feedback: -- ${insight1} -- ${insight2} - -#### Corrected Assumptions - -${corrections.length > 0 ? corrections.map(c => ` -- ~~${c.wrong}~~ โ†’ ${c.corrected} - - Reason: ${c.reason} -`).join('\n') : 'None'} - -#### New Insights - -${newInsights.map(i => `- ${i}`).join('\n')} -``` - ---- +**Success Criteria**: +- User feedback processed for each round +- discussion.md updated with all discussion rounds +- Assumptions corrected and documented +- Exit condition reached (user selects "ๅฎŒๆˆ" or max rounds) ### Phase 4: Synthesis & Conclusion -**Step 4.1: Consolidate Insights** - -```javascript -const conclusions = { - session_id: sessionId, - topic: topic_or_question, - completed: getUtc8ISOString(), - total_rounds: roundNumber, - - summary: "...", - - key_conclusions: [ - { point: "...", evidence: "...", confidence: "high|medium|low" } - ], - - recommendations: [ - { action: "...", rationale: "...", priority: "high|medium|low" } - ], - - open_questions: [...], - - follow_up_suggestions: [ - { type: "issue", summary: "..." }, - { type: "task", summary: "..." } - ] -} - -Write(conclusionsPath, JSON.stringify(conclusions, null, 2)) -``` - -**Step 4.2: Final discussion.md Update** - -```markdown ---- - -## Conclusions (${timestamp}) - -### Summary - -${summaryParagraph} - -### Key Conclusions - -${conclusions.key_conclusions.map((c, i) => ` -${i+1}. **${c.point}** (Confidence: ${c.confidence}) - - Evidence: ${c.evidence} -`).join('\n')} - -### Recommendations - -${conclusions.recommendations.map((r, i) => ` -${i+1}. **${r.action}** (Priority: ${r.priority}) - - Rationale: ${r.rationale} -`).join('\n')} - -### Remaining Questions - -${conclusions.open_questions.map(q => `- ${q}`).join('\n')} - ---- - -## Current Understanding (Final) - -### What We Established - -${establishedPoints.map(p => `- ${p}`).join('\n')} - -### What Was Clarified/Corrected - -${corrections.map(c => `- ~~${c.original}~~ โ†’ ${c.corrected}`).join('\n')} - -### Key Insights - -${keyInsights.map(i => `- ${i}`).join('\n')} - ---- - -## Session Statistics - -- **Total Rounds**: ${totalRounds} -- **Duration**: ${duration} -- **Sources Used**: ${sources.join(', ')} -- **Artifacts Generated**: discussion.md, explorations.json, conclusions.json -``` - -**Step 4.3: Post-Completion Options** - -```javascript -AskUserQuestion({ - questions: [{ - question: "ๅˆ†ๆžๅฎŒๆˆใ€‚ๆ˜ฏๅฆ้œ€่ฆๅŽ็ปญๆ“ไฝœ?", - header: "Next Steps", - multiSelect: true, - options: [ - { label: "ๅˆ›ๅปบIssue", description: "ๅฐ†็ป“่ฎบ่ฝฌไธบๅฏๆ‰ง่กŒ็š„Issue" }, - { label: "็”ŸๆˆไปปๅŠก", description: "ๅˆ›ๅปบๅฎžๆ–ฝไปปๅŠก" }, - { label: "ๅฏผๅ‡บๆŠฅๅ‘Š", description: "็”Ÿๆˆ็‹ฌ็ซ‹็š„ๅˆ†ๆžๆŠฅๅ‘Š" }, - { label: "ๅฎŒๆˆ", description: "ไธ้œ€่ฆๅŽ็ปญๆ“ไฝœ" } - ] - }] -}) - -// Handle selections -if (selection.includes("ๅˆ›ๅปบIssue")) { - Skill(skill="issue:new", args=`${topic_or_question} - ๅˆ†ๆž็ป“่ฎบๅฎžๆ–ฝ`) -} -if (selection.includes("็”ŸๆˆไปปๅŠก")) { - Skill(skill="workflow:lite-plan", args=`ๅฎžๆ–ฝๅˆ†ๆž็ป“่ฎบ: ${summary}`) -} -if (selection.includes("ๅฏผๅ‡บๆŠฅๅ‘Š")) { - exportAnalysisReport(sessionFolder) -} -``` - ---- - -## Session Folder Structure - -``` -.workflow/.analysis/ANL-{slug}-{date}/ -โ”œโ”€โ”€ discussion.md # Evolution of understanding & discussions -โ”œโ”€โ”€ explorations.json # CLI exploration findings -โ”œโ”€โ”€ conclusions.json # Final synthesis -โ””โ”€โ”€ exploration-*.json # Individual exploration results (optional) -``` - -## Discussion Document Template - -```markdown -# Analysis Discussion - -**Session ID**: ANL-xxx-2025-01-25 -**Topic**: [topic or question] -**Started**: 2025-01-25T10:00:00+08:00 -**Dimensions**: [architecture, implementation, ...] - ---- - -## User Context - -**Focus Areas**: [user-selected focus] -**Analysis Depth**: [quick|standard|deep] - ---- - -## Discussion Timeline - -### Round 1 - Initial Understanding (2025-01-25 10:00) - -#### Topic Analysis -... - -#### Exploration Results -... - -### Round 2 - Discussion (2025-01-25 10:15) - -#### User Input -... - -#### Updated Understanding -... - -#### Corrected Assumptions -- ~~[wrong]~~ โ†’ [corrected] - -### Round 3 - Deep Dive (2025-01-25 10:30) -... - ---- - -## Conclusions (2025-01-25 11:00) - -### Summary -... - -### Key Conclusions -... - -### Recommendations -... - ---- - -## Current Understanding (Final) - -### What We Established -- [confirmed points] - -### What Was Clarified/Corrected -- ~~[original assumption]~~ โ†’ [corrected understanding] - -### Key Insights -- [insights gained] - ---- - -## Session Statistics - -- **Total Rounds**: 3 -- **Duration**: 1 hour -- **Sources Used**: codebase exploration, Gemini analysis -- **Artifacts Generated**: discussion.md, explorations.json, conclusions.json -``` - -## Iteration Flow - -``` -First Call (/workflow:analyze-with-file "topic"): - โ”œโ”€ No session exists โ†’ New mode - โ”œโ”€ Identify analysis dimensions - โ”œโ”€ Scope with user (unless --yes) - โ”œโ”€ Create discussion.md with initial understanding - โ”œโ”€ Launch CLI explorations - โ””โ”€ Enter discussion loop - -Continue Call (/workflow:analyze-with-file --continue "topic"): - โ”œโ”€ Session exists โ†’ Continue mode - โ”œโ”€ Load discussion.md - โ”œโ”€ Resume from last round - โ””โ”€ Continue discussion loop - -Discussion Loop: - โ”œโ”€ Present current findings - โ”œโ”€ Gather user feedback (AskUserQuestion) - โ”œโ”€ Process response: - โ”‚ โ”œโ”€ Agree โ†’ Deepen analysis - โ”‚ โ”œโ”€ Adjust โ†’ Change direction - โ”‚ โ”œโ”€ Question โ†’ Answer then continue - โ”‚ โ””โ”€ Complete โ†’ Exit loop - โ”œโ”€ Update discussion.md - โ””โ”€ Repeat until complete or max rounds - -Completion: - โ”œโ”€ Generate conclusions.json - โ”œโ”€ Update discussion.md with final synthesis - โ””โ”€ Offer follow-up options (issue, task, report) -``` - -## CLI Integration Points - -### 1. Codebase Exploration (cli-explore-agent) - -**Purpose**: Gather relevant code context - -**When**: Topic involves implementation or architecture analysis - -### 2. Gemini Deep Analysis - -**Purpose**: Conceptual analysis, pattern identification, best practices - -**Prompt Pattern**: -``` -PURPOSE: Analyze topic + identify insights -TASK: Explore dimensions + generate discussion points -CONTEXT: Codebase + topic -EXPECTED: Structured analysis + questions -``` - -### 3. Follow-up CLI Calls - -**Purpose**: Deepen specific areas based on user feedback - -**Dynamic invocation** based on discussion direction - -## Consolidation Rules +**Objective**: Consolidate insights, generate conclusions, offer next steps. + +**Prerequisites**: +- Phase 3 completed successfully +- Multiple rounds of discussion documented +- User ready to conclude + +**Workflow Steps**: + +1. **Consolidate Insights** + - Extract all findings from discussion timeline + - **Key conclusions**: Main points with evidence and confidence levels (high/medium/low) + - **Recommendations**: Action items with rationale and priority (high/medium/low) + - **Open questions**: Remaining unresolved questions + - **Follow-up suggestions**: Issue/task creation suggestions + - Write to conclusions.json + +2. **Final discussion.md Update** + - Append conclusions section: + - **Summary**: High-level overview + - **Key Conclusions**: Ranked with evidence and confidence + - **Recommendations**: Prioritized action items + - **Remaining Questions**: Unresolved items + - Update "Current Understanding (Final)": + - **What We Established**: Confirmed points + - **What Was Clarified/Corrected**: Important corrections + - **Key Insights**: Valuable learnings + - Add session statistics: rounds, duration, sources, artifacts + +3. **Post-Completion Options** (AskUserQuestion) + - **ๅˆ›ๅปบIssue**: Launch issue:new with conclusions + - **็”ŸๆˆไปปๅŠก**: Launch workflow:lite-plan for implementation + - **ๅฏผๅ‡บๆŠฅๅ‘Š**: Generate standalone analysis report + - **ๅฎŒๆˆ**: No further action + +**conclusions.json Schema**: +- `session_id`: Session identifier +- `topic`: Original topic/question +- `completed`: Completion timestamp +- `total_rounds`: Number of discussion rounds +- `summary`: Executive summary +- `key_conclusions[]`: {point, evidence, confidence} +- `recommendations[]`: {action, rationale, priority} +- `open_questions[]`: Unresolved questions +- `follow_up_suggestions[]`: {type, summary} + +**Success Criteria**: +- conclusions.json created with final synthesis +- discussion.md finalized with conclusions +- User offered next step options +- Session complete + +## Configuration + +### Analysis Dimensions + +Dimensions matched against topic keywords to identify focus areas: + +| Dimension | Keywords | +|-----------|----------| +| architecture | ๆžถๆž„, architecture, design, structure, ่ฎพ่ฎก | +| implementation | ๅฎž็Žฐ, implement, code, coding, ไปฃ็  | +| performance | ๆ€ง่ƒฝ, performance, optimize, bottleneck, ไผ˜ๅŒ– | +| security | ๅฎ‰ๅ…จ, security, auth, permission, ๆƒ้™ | +| concept | ๆฆ‚ๅฟต, concept, theory, principle, ๅŽŸ็† | +| comparison | ๆฏ”่พƒ, compare, vs, difference, ๅŒบๅˆซ | +| decision | ๅ†ณ็ญ–, decision, choice, tradeoff, ้€‰ๆ‹ฉ | + +### Consolidation Rules When updating "Current Understanding": -1. **Promote confirmed insights**: Move validated findings to "What We Established" -2. **Track corrections**: Keep important wrongโ†’right transformations -3. **Focus on current state**: What do we know NOW -4. **Avoid timeline repetition**: Don't copy discussion details -5. **Preserve key learnings**: Keep insights valuable for future reference +| Rule | Description | +|------|-------------| +| Promote confirmed insights | Move validated findings to "What We Established" | +| Track corrections | Keep important wrongโ†’right transformations | +| Focus on current state | What do we know NOW | +| Avoid timeline repetition | Don't copy discussion details | +| Preserve key learnings | Keep insights valuable for future reference | -**Bad (cluttered)**: +**Example**: + +โŒ **Bad (cluttered)**: ```markdown ## Current Understanding - -In round 1 we discussed X, then in round 2 user said Y, and we explored Z... +In round 1 we discussed X, then in round 2 user said Y... ``` -**Good (consolidated)**: +โœ… **Good (consolidated)**: ```markdown ## Current Understanding @@ -784,36 +459,86 @@ In round 1 we discussed X, then in round 2 user said Y, and we explored Z... ### Key Insights - Current architecture supports horizontal scaling -- Security audit recommended before production ``` ## Error Handling -| Situation | Action | -|-----------|--------| -| CLI exploration fails | Continue with available context, note limitation | +| Error | Resolution | +|-------|------------| +| cli-explore-agent fails | Continue with available context, note limitation | +| CLI timeout | Retry with shorter prompt, or skip perspective | | User timeout in discussion | Save state, show resume command | | Max rounds reached | Force synthesis, offer continuation option | | No relevant findings | Broaden search, ask user for clarification | | Session folder conflict | Append timestamp suffix | | Gemini unavailable | Fallback to Codex or manual analysis | +## Best Practices + +1. **Clear Topic Definition**: Detailed topics โ†’ better dimension identification +2. **Review discussion.md**: Check understanding evolution before conclusions +3. **Embrace Corrections**: Track wrongโ†’right transformations as learnings +4. **Document Evolution**: discussion.md captures full thinking process +5. **Use Continue Mode**: Resume sessions to build on previous analysis + +## Templates + +### Discussion Document Structure + +**discussion.md** contains: +- **Header**: Session metadata (ID, topic, started, dimensions) +- **User Context**: Focus areas, analysis depth +- **Discussion Timeline**: Round-by-round findings + - Round 1: Initial Understanding + Exploration Results + - Round 2-N: User feedback, adjusted understanding, corrections, new insights +- **Conclusions**: Summary, key conclusions, recommendations +- **Current Understanding (Final)**: Consolidated insights +- **Session Statistics**: Rounds, duration, sources, artifacts + +Example sections: + +```markdown +### Round 2 - Discussion (timestamp) + +#### User Input +User agrees with current direction, wants deeper code analysis + +#### Updated Understanding +- Identified session management uses database-backed approach +- Rate limiting applied at gateway, not application level + +#### Corrected Assumptions +- ~~Assumed Redis for sessions~~ โ†’ Database-backed sessions + - Reason: User clarified architecture decision + +#### New Insights +- Current design allows horizontal scaling without session affinity +``` ## Usage Recommendations -Use `/workflow:analyze-with-file` when: +**Use `/workflow:analyze-with-file` when:** - Exploring a complex topic collaboratively - Need documented discussion trail - Decision-making requires multiple perspectives - Want to iterate on understanding with user input - Building shared understanding before implementation -Use `/workflow:debug-with-file` when: +**Use `/workflow:debug-with-file` when:** - Diagnosing specific bugs - Need hypothesis-driven investigation - Focus on evidence and verification -Use `/workflow:lite-plan` when: +**Use `/workflow:brainstorm-with-file` when:** +- Generating new ideas or solutions +- Need creative exploration +- Want divergent thinking before convergence + +**Use `/workflow:lite-plan` when:** - Ready to implement (past analysis phase) - Need structured task breakdown - Focus on execution planning + +--- + +**Now execute analyze-with-file for**: $ARGUMENTS diff --git a/.claude/commands/workflow/brainstorm-with-file.md b/.claude/commands/workflow/brainstorm-with-file.md index ac2fc992..5f193058 100644 --- a/.claude/commands/workflow/brainstorm-with-file.md +++ b/.claude/commands/workflow/brainstorm-with-file.md @@ -7,9 +7,56 @@ allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob ## Auto Mode -When `--yes` or `-y`: Auto-confirm decisions, use balanced exploration across all perspectives. +When `--yes` or `-y`: Auto-confirm decisions, use recommended roles, balanced exploration mode. -# Workflow Brainstorm-With-File Command +# Workflow Brainstorm Command + +## Quick Start + +```bash +# Basic usage +/workflow:brainstorm-with-file "ๅฆ‚ไฝ•้‡ๆ–ฐ่ฎพ่ฎก็”จๆˆท้€š็Ÿฅ็ณป็ปŸ" + +# With options +/workflow:brainstorm-with-file --continue "้€š็Ÿฅ็ณป็ปŸ" # Continue existing +/workflow:brainstorm-with-file -y -m creative "ๅˆ›ๆ–ฐ็š„AI่พ…ๅŠฉๅŠŸ่ƒฝ" # Creative auto mode +/workflow:brainstorm-with-file -m structured "ไผ˜ๅŒ–็ผ“ๅญ˜็ญ–็•ฅ" # Goal-oriented mode +``` + +**Context Source**: cli-explore-agent + Multi-CLI perspectives (Gemini/Codex/Claude or Professional Roles) +**Output Directory**: `.workflow/.brainstorm/{session-id}/` +**Core Innovation**: Diverge-Converge cycles with documented thought evolution + +## Output Artifacts + +### Phase 1: Seed Understanding + +| Artifact | Description | +|----------|-------------| +| `brainstorm.md` | Complete thought evolution timeline (initialized) | +| Session variables | Dimensions, roles, exploration vectors | + +### 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 @@ -17,200 +64,133 @@ Interactive brainstorming workflow with **multi-CLI collaboration** and **docume **Core workflow**: Seed Idea โ†’ Expand โ†’ Multi-CLI Discuss โ†’ Synthesize โ†’ Refine โ†’ Crystallize -**Key features**: -- **brainstorm.md**: Complete thought evolution timeline -- **Multi-CLI collaboration**: Gemini (creative), Codex (pragmatic), Claude (systematic) perspectives -- **Idea expansion**: Progressive questioning and exploration -- **Diverge-Converge cycles**: Generate options then focus on best paths -- **Synthesis**: Merge multiple perspectives into coherent solutions - -## Usage - -```bash -/workflow:brainstorm-with-file [FLAGS] - -# Flags --y, --yes Skip confirmations, use recommended settings --c, --continue Continue existing session (auto-detected if exists) --m, --mode Brainstorm mode: creative (divergent) | structured (goal-oriented) - -# Arguments - Initial idea, problem, or topic to brainstorm (required) - -# Examples -/workflow:brainstorm-with-file "ๅฆ‚ไฝ•้‡ๆ–ฐ่ฎพ่ฎก็”จๆˆท้€š็Ÿฅ็ณป็ปŸ" -/workflow:brainstorm-with-file --continue "้€š็Ÿฅ็ณป็ปŸ" # Continue existing -/workflow:brainstorm-with-file -y -m creative "ๅˆ›ๆ–ฐ็š„AI่พ…ๅŠฉๅŠŸ่ƒฝ" # Creative auto mode -/workflow:brainstorm-with-file -m structured "ไผ˜ๅŒ–็ผ“ๅญ˜็ญ–็•ฅ" # Goal-oriented mode +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ INTERACTIVE BRAINSTORMING WORKFLOW โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ โ”‚ +โ”‚ Phase 1: Seed Understanding โ”‚ +โ”‚ โ”œโ”€ Parse initial idea/topic โ”‚ +โ”‚ โ”œโ”€ Identify dimensions (technical, UX, business, etc.) โ”‚ +โ”‚ โ”œโ”€ Select roles (professional or simple perspectives) โ”‚ +โ”‚ โ”œโ”€ Initial scoping questions โ”‚ +โ”‚ โ”œโ”€ Expand into exploration vectors โ”‚ +โ”‚ โ””โ”€ Initialize brainstorm.md โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 2: Divergent Exploration โ”‚ +โ”‚ โ”œโ”€ cli-explore-agent: Codebase context (FIRST) โ”‚ +โ”‚ โ”œโ”€ Multi-CLI Perspectives (AFTER exploration) โ”‚ +โ”‚ โ”‚ โ”œโ”€ Creative (Gemini): Innovation, cross-domain โ”‚ +โ”‚ โ”‚ โ”œโ”€ Pragmatic (Codex): Implementation, feasibility โ”‚ +โ”‚ โ”‚ โ””โ”€ Systematic (Claude): Architecture, structure โ”‚ +โ”‚ โ””โ”€ Aggregate diverse viewpoints โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 3: Interactive Refinement (Multi-Round) โ”‚ +โ”‚ โ”œโ”€ Present multi-perspective findings โ”‚ +โ”‚ โ”œโ”€ User selects promising directions โ”‚ +โ”‚ โ”œโ”€ Actions: Deep dive | Generate more | Challenge | Merge โ”‚ +โ”‚ โ”œโ”€ Update brainstorm.md with evolution โ”‚ +โ”‚ โ””โ”€ Repeat diverge-converge cycles (max 6 rounds) โ”‚ +โ”‚ โ”‚ +โ”‚ Phase 4: Convergence & Crystallization โ”‚ +โ”‚ โ”œโ”€ Synthesize best ideas โ”‚ +โ”‚ โ”œโ”€ Resolve conflicts between perspectives โ”‚ +โ”‚ โ”œโ”€ Generate actionable conclusions โ”‚ +โ”‚ โ”œโ”€ Offer next steps (plan/issue/analyze/export) โ”‚ +โ”‚ โ””โ”€ Final brainstorm.md update โ”‚ +โ”‚ โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` -## Execution Process +## Output Structure ``` -Session Detection: - โ”œโ”€ Check if brainstorm session exists for topic - โ”œโ”€ EXISTS + brainstorm.md exists โ†’ Continue mode - โ””โ”€ NOT_FOUND โ†’ New session mode - -Phase 1: Seed Understanding - โ”œโ”€ Parse initial idea/topic - โ”œโ”€ Identify brainstorm dimensions (technical, UX, business, etc.) - โ”œโ”€ Initial scoping questions (AskUserQuestion) - โ”œโ”€ Expand seed into exploration vectors - โ””โ”€ Document in brainstorm.md - -Phase 2: Divergent Exploration (Multi-CLI Parallel) - โ”œโ”€ Gemini CLI: Creative/innovative perspectives - โ”œโ”€ Codex CLI: Pragmatic/implementation perspectives - โ”œโ”€ Claude CLI: Systematic/architectural perspectives - โ””โ”€ Aggregate diverse viewpoints - -Phase 3: Interactive Refinement (Multi-Round) - โ”œโ”€ Present multi-perspective findings - โ”œโ”€ User selects promising directions - โ”œโ”€ Deep dive on selected paths - โ”œโ”€ Challenge assumptions (devil's advocate) - โ”œโ”€ Update brainstorm.md with evolution - โ””โ”€ Repeat diverge-converge cycles - -Phase 4: Convergence & Crystallization - โ”œโ”€ Synthesize best ideas - โ”œโ”€ Resolve conflicts between perspectives - โ”œโ”€ Formulate actionable conclusions - โ”œโ”€ Generate next steps or implementation plan - โ””โ”€ Final brainstorm.md update - -Output: - โ”œโ”€ .workflow/.brainstorm/{slug}-{date}/brainstorm.md (thought evolution) - โ”œโ”€ .workflow/.brainstorm/{slug}-{date}/perspectives.json (CLI findings) - โ”œโ”€ .workflow/.brainstorm/{slug}-{date}/synthesis.json (final ideas) - โ””โ”€ .workflow/.brainstorm/{slug}-{date}/ideas/ (individual idea deep-dives) +.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 Setup & Mode Detection +### Session Initialization -```javascript -const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() +**Objective**: Create session context and directory structure for brainstorming. -const topicSlug = idea_or_topic.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').substring(0, 40) -const dateStr = getUtc8ISOString().substring(0, 10) +**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) +3. Define session folder: `.workflow/.brainstorm/{session-id}` +4. Parse command options: + - `-c` or `--continue` for session continuation + - `-m` or `--mode` for brainstorm mode (creative/structured/balanced) + - `-y` or `--yes` for auto-approval mode +5. Auto-detect mode: If session folder + brainstorm.md exist โ†’ continue mode +6. Create directory structure: `{session-folder}/ideas/` -const sessionId = `BS-${topicSlug}-${dateStr}` -const sessionFolder = `.workflow/.brainstorm/${sessionId}` -const brainstormPath = `${sessionFolder}/brainstorm.md` -const perspectivesPath = `${sessionFolder}/perspectives.json` -const synthesisPath = `${sessionFolder}/synthesis.json` -const ideasFolder = `${sessionFolder}/ideas` - -// Auto-detect mode -const sessionExists = fs.existsSync(sessionFolder) -const hasBrainstorm = sessionExists && fs.existsSync(brainstormPath) -const forcesContinue = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c') - -const mode = (hasBrainstorm || forcesContinue) ? 'continue' : 'new' - -// Brainstorm mode -const brainstormMode = $ARGUMENTS.includes('--mode') - ? $ARGUMENTS.match(/--mode\s+(creative|structured)/)?.[1] || 'balanced' - : 'balanced' - -if (!sessionExists) { - bash(`mkdir -p ${sessionFolder}/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 ### Phase 1: Seed Understanding -**Step 1.1: Parse Seed & Identify Dimensions** +**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 + - 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) + - **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 technical, UX, innovation, feasibility + - **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 -// See Configuration section for BRAINSTORM_DIMENSIONS definition - -function identifyDimensions(topic) { - const text = topic.toLowerCase() - const matched = [] - - for (const [dimension, keywords] of Object.entries(BRAINSTORM_DIMENSIONS)) { - if (keywords.some(k => text.includes(k))) { - matched.push(dimension) - } - } - - // Default dimensions based on mode - if (matched.length === 0) { - return brainstormMode === 'creative' - ? ['innovation', 'ux', 'technical'] - : ['technical', 'feasibility', 'business'] - } - - return matched -} - -const dimensions = identifyDimensions(idea_or_topic) -``` - -**Step 1.2: Initial Scoping Questions** - -```javascript -const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y') - -if (mode === 'new' && !autoYes) { - AskUserQuestion({ - questions: [ - { - question: `ๅคด่„‘้ฃŽๆšดไธป้ข˜: "${idea_or_topic}"\n\nๆ‚จๅธŒๆœ›ๆŽข็ดขๅ“ชไบ›ๆ–นๅ‘?`, - header: "ๆ–นๅ‘", - multiSelect: true, - options: [ - { label: "ๆŠ€ๆœฏๆ–นๆกˆ", description: "ๆŽข็ดขๆŠ€ๆœฏๅฎž็Žฐๅฏ่ƒฝๆ€ง" }, - { label: "็”จๆˆทไฝ“้ชŒ", description: "ไปŽ็”จๆˆท่ง’ๅบฆๅ‡บๅ‘" }, - { label: "ๅˆ›ๆ–ฐ็ช็ ด", description: "ๅฏปๆ‰พ้žๅธธ่ง„่งฃๅ†ณๆ–นๆกˆ" }, - { label: "ๅฏ่กŒๆ€ง่ฏ„ไผฐ", description: "่ฏ„ไผฐๅฎž้™…่ฝๅœฐๅฏ่ƒฝ" } - ] - }, - { - question: "ๅคด่„‘้ฃŽๆšดๆทฑๅบฆ?", - header: "ๆทฑๅบฆ", - multiSelect: false, - options: [ - { label: "ๅฟซ้€Ÿๅ‘ๆ•ฃ", description: "ๅนฟๅบฆไผ˜ๅ…ˆ๏ผŒๅฟซ้€Ÿ็”Ÿๆˆๅคšไธชๆƒณๆณ• (15-20ๅˆ†้’Ÿ)" }, - { label: "ๅนณ่กกๆŽข็ดข", description: "ๆทฑๅบฆๅ’Œๅนฟๅบฆๅนณ่กก (30-60ๅˆ†้’Ÿ)" }, - { label: "ๆทฑๅบฆๆŒ–ๆŽ˜", description: "ๆทฑๅ…ฅๆŽข็ดขๅฐ‘ๆ•ฐๆ ธๅฟƒๆƒณๆณ• (1-2ๅฐๆ—ถ)" } - ] - }, - { - question: "ๆ˜ฏๅฆๆœ‰ไปปไฝ•็บฆๆŸๆˆ–ๅฟ…้กป่€ƒ่™‘็š„ๅ› ็ด ?", - header: "็บฆๆŸ", - multiSelect: true, - options: [ - { label: "็Žฐๆœ‰ๆžถๆž„", description: "้œ€่ฆไธŽ็Žฐๆœ‰็ณป็ปŸๅ…ผๅฎน" }, - { label: "ๆ—ถ้—ด้™ๅˆถ", description: "ๆœ‰ๅฎžๆ–ฝๆ—ถ้—ด็บฆๆŸ" }, - { label: "่ต„ๆบ้™ๅˆถ", description: "ๅผ€ๅ‘่ต„ๆบๆœ‰้™" }, - { label: "ๆ— ็บฆๆŸ", description: "ๅฎŒๅ…จๅผ€ๆ”พๆŽข็ดข" } - ] - } - ] - }) -} -``` - -**Step 1.3: Expand Seed into Exploration Vectors** - -```javascript -// Generate exploration vectors from seed idea -const expansionPrompt = ` -Given the initial idea: "${idea_or_topic}" +Bash({ + command: `ccw cli -p " +Given the initial idea: '${idea_or_topic}' User focus areas: ${userFocusAreas.join(', ')} Constraints: ${constraints.join(', ')} Generate 5-7 exploration vectors (questions/directions) to expand this idea: - 1. Core question: What is the fundamental problem/opportunity? 2. User perspective: Who benefits and how? 3. Technical angle: What enables this technically? @@ -220,46 +200,56 @@ Generate 5-7 exploration vectors (questions/directions) to expand this idea: 7. Integration: How does this fit with existing systems/processes? Output as structured exploration vectors for multi-perspective analysis. -` - -// โš ๏ธ CRITICAL: Must wait for CLI completion - do NOT proceed until result received -const expansionResult = await Bash({ - command: `ccw cli -p "${expansionPrompt}" --tool gemini --mode analysis --model gemini-2.5-flash`, +" --tool gemini --mode analysis --model gemini-2.5-flash`, run_in_background: false }) - -const explorationVectors = parseExpansionResult(expansionResult) ``` -**Step 1.4: Create brainstorm.md** +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 -See **Templates** section for complete brainstorm.md structure. Initialize with: -- Session metadata -- Initial context (user focus, depth, constraints) -- Seed expansion (original idea + exploration vectors) -- 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 (cli-explore-agent + Multi-CLI) +**Objective**: Gather codebase context, then execute multi-perspective analysis in parallel. -**โš ๏ธ CRITICAL - EXPLORATION PRIORITY**: -- **cli-explore-agent FIRST**: Always use cli-explore-agent as primary exploration method -- **Multi-CLI AFTER**: Use Gemini/Codex/Claude only after cli-explore-agent provides context -- **Sequential execution**: cli-explore-agent โ†’ Multi-CLI perspectives (not all parallel) -- Minimize output: No processing until 100% results available +**Prerequisites**: +- Phase 1 completed successfully +- Roles selected and stored +- brainstorm.md initialized -**Step 2.1: Primary Exploration via cli-explore-agent** +**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 -// โš ๏ธ PRIORITY: cli-explore-agent is the PRIMARY exploration method -// MUST complete before any CLI calls - -const codebaseExploration = await Task( - subagent_type="cli-explore-agent", - run_in_background=false, - description=`Explore codebase for brainstorm: ${topicSlug}`, - prompt=` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: `Explore codebase for brainstorm: ${topicSlug}`, + prompt: ` ## Brainstorm Context Topic: ${idea_or_topic} Dimensions: ${dimensions.join(', ')} @@ -282,7 +272,7 @@ Write findings to: ${sessionFolder}/exploration-codebase.json Schema: { - "relevant_files": [{path, relevance, rationale}], + "relevant_files": [{"path": "...", "relevance": "high|medium|low", "rationale": "..."}], "existing_patterns": [], "architecture_constraints": [], "integration_points": [], @@ -290,268 +280,195 @@ Schema: "_metadata": { "exploration_type": "brainstorm-codebase", "timestamp": "..." } } ` -) +}) -// Read exploration results for CLI context enrichment -const explorationResults = Read(`${sessionFolder}/exploration-codebase.json`) -``` - -**Step 2.2: Multi-CLI Perspectives (Using Exploration Context)** +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): ```javascript -// ============================================ -// Perspective Configuration (Data-Driven) -// ============================================ -const PERSPECTIVES = { - creative: { - tool: 'gemini', - focus: 'generate innovative, unconventional ideas', - success: '5+ unique creative solutions that push boundaries', - tasks: [ - 'Build on existing patterns found - how can they be extended creatively?', - 'Think beyond obvious solutions - what would be surprising/delightful?', - 'Explore cross-domain inspiration (what can we learn from other industries?)', - 'Challenge assumptions - what if the opposite were true?', - 'Generate "moonshot" ideas alongside practical ones' - ], - expected: [ - '5+ creative ideas with brief descriptions', - 'Each idea rated: novelty (1-5), potential impact (1-5)', - 'Key assumptions challenged', - 'Cross-domain inspirations', - 'One "crazy" idea that might just work' - ], - constraints: mode => mode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely' - }, - - pragmatic: { - tool: 'codex', - focus: 'focus on implementation reality', - success: 'Actionable approaches with clear implementation paths', - tasks: [ - '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' - ], - expected: [ - '3-5 practical implementation approaches', - 'Each rated: effort (1-5), risk (1-5), reuse potential (1-5)', - 'Technical dependencies identified', - 'Quick wins vs long-term solutions', - 'Recommended starting point' - ], - constraints: () => 'Focus on what can actually be built with current tech stack' - }, - - systematic: { - tool: 'claude', - focus: 'architectural and structural thinking', - success: 'Well-structured solution framework with clear tradeoffs', - tasks: [ - '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' - ], - expected: [ - 'Problem decomposition diagram (text)', - '2-3 architectural approaches with tradeoffs', - 'Dependency mapping', - 'Scalability assessment', - 'Recommended architecture pattern', - 'Risk matrix' - ], - constraints: () => 'Consider existing system architecture' - } -} - -// ============================================ -// Shared Context Builder -// ============================================ -const buildExplorationContext = (results) => ` +// Build shared context from exploration results +const explorationContext = ` PRIOR EXPLORATION CONTEXT (from cli-explore-agent): -- Key files: ${results.relevant_files.slice(0,5).map(f => f.path).join(', ')} -- Existing patterns: ${results.existing_patterns.slice(0,3).join(', ')} -- Architecture constraints: ${results.architecture_constraints.slice(0,3).join(', ')} -- Integration points: ${results.integration_points.slice(0,3).join(', ')}` +- 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(', ')}` -// ============================================ -// Universal CLI Prompt Template -// ============================================ -const buildCLIPrompt = (perspective, config) => ` -PURPOSE: ${perspective.charAt(0).toUpperCase() + perspective.slice(1)} brainstorming for '${idea_or_topic}' - ${config.focus} -Success: ${config.success} +// Launch 3 CLI calls in parallel (single message, multiple Bash calls) +Bash({ + command: `ccw cli -p " +PURPOSE: Creative brainstorming for '${idea_or_topic}' - generate innovative ideas +Success: 5+ unique creative solutions that push boundaries -${buildExplorationContext(explorationResults)} +${explorationContext} TASK: -${config.tasks.map(t => `โ€ข ${t}`).join('\n')} +โ€ข 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 MODE: analysis - CONTEXT: @**/* | Topic: ${idea_or_topic} -Exploration vectors: ${explorationVectors.map(v => v.title).join(', ')} +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`, + run_in_background: true +}) -EXPECTED: -${config.expected.map(e => `- ${e}`).join('\n')} +Bash({ + command: `ccw cli -p " +PURPOSE: Pragmatic brainstorming for '${idea_or_topic}' - focus on implementation reality +Success: Actionable approaches with clear implementation paths -CONSTRAINTS: ${config.constraints(brainstormMode)}` +${explorationContext} -// ============================================ -// Launch Multi-CLI (Parallel) -// ============================================ -const cliPromises = Object.entries(PERSPECTIVES).map(([name, config]) => - Bash({ - command: `ccw cli -p "${buildCLIPrompt(name, config)}" --tool ${config.tool} --mode analysis`, - run_in_background: true - }) -) +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 -// โš ๏ธ CRITICAL: Must wait for ALL results - do NOT proceed until all CLIs complete -await Promise.all(cliPromises) +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**: After launching CLI calls, stop output immediately. Wait for hook callback to receive results before continuing to Step 2.3. +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) + - Write to perspectives.json -**Step 2.3: Aggregate Multi-Perspective Findings** +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 + +### Phase 3: Interactive Refinement + +**Objective**: Iteratively refine ideas through user-guided exploration cycles. + +**Prerequisites**: +- Phase 2 completed successfully +- perspectives.json contains initial ideas +- brainstorm.md has Round 2 findings + +**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) + - **Question 1**: Which ideas to explore (multi-select from top ideas) + - **Question 2**: Next step (single-select): + - **ๆทฑๅ…ฅๆŽข็ดข**: Deep dive on selected ideas + - **็ปง็ปญๅ‘ๆ•ฃ**: Generate more ideas + - **ๆŒ‘ๆˆ˜้ชŒ่ฏ**: Devil's advocate challenge + - **ๅˆๅนถ็ปผๅˆ**: Merge multiple ideas + - **ๅ‡†ๅค‡ๆ”ถๆ•›**: Begin convergence (exit loop) + +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` + + **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**: ```javascript -const perspectives = { - session_id: sessionId, - timestamp: getUtc8ISOString(), - topic: idea_or_topic, - - creative: { - source: 'gemini', - ideas: [...], - insights: [...], - challenges: [...] - }, - - pragmatic: { - source: 'codex', - approaches: [...], - blockers: [...], - recommendations: [...] - }, - - systematic: { - source: 'claude', - decomposition: [...], - patterns: [...], - tradeoffs: [...] - }, - - synthesis: { - convergent_themes: [], - conflicting_views: [], - unique_contributions: [] - } -} - -Write(perspectivesPath, JSON.stringify(perspectives, null, 2)) -``` - -**Step 2.4: Update brainstorm.md with Perspectives** - -Append to brainstorm.md the Round 2 multi-perspective exploration findings (see Templates section for format). - ---- - -### Phase 3: Interactive Refinement (Multi-Round) - -**Step 3.1: Present & Select Directions** - -```javascript -const MAX_ROUNDS = 6 -let roundNumber = 3 // After initial exploration -let brainstormComplete = false - -while (!brainstormComplete && roundNumber <= MAX_ROUNDS) { - - // Present current state - console.log(` -## Brainstorm Round ${roundNumber} - -### Top Ideas So Far - -${topIdeas.map((idea, i) => ` -${i+1}. **${idea.title}** (${idea.source}) - ${idea.brief} - - Novelty: ${'โญ'.repeat(idea.novelty)} | Feasibility: ${'โœ…'.repeat(idea.feasibility)} -`).join('\n')} - -### Open Questions -${openQuestions.map((q, i) => `${i+1}. ${q}`).join('\n')} -`) - - // Gather user direction - const userDirection = AskUserQuestion({ - questions: [ - { - question: "ๅ“ชไบ›ๆƒณๆณ•ๅ€ผๅพ—ๆทฑๅ…ฅๆŽข็ดข?", - header: "้€‰ๆ‹ฉ", - multiSelect: true, - options: topIdeas.slice(0, 4).map(idea => ({ - label: idea.title, - description: idea.brief - })) - }, - { - question: "ไธ‹ไธ€ๆญฅ?", - header: "ๆ–นๅ‘", - multiSelect: false, - options: [ - { label: "ๆทฑๅ…ฅๆŽข็ดข", description: "ๆทฑๅ…ฅๅˆ†ๆž้€‰ไธญ็š„ๆƒณๆณ•" }, - { label: "็ปง็ปญๅ‘ๆ•ฃ", description: "็”Ÿๆˆๆ›ดๅคšๆ–ฐๆƒณๆณ•" }, - { label: "ๆŒ‘ๆˆ˜้ชŒ่ฏ", description: "Devil's advocate - ๆŒ‘ๆˆ˜ๅฝ“ๅ‰ๆƒณๆณ•" }, - { label: "ๅˆๅนถ็ปผๅˆ", description: "ๅฐ่ฏ•ๅˆๅนถๅคšไธชๆƒณๆณ•" }, - { label: "ๅ‡†ๅค‡ๆ”ถๆ•›", description: "ๅผ€ๅง‹ๆ•ด็†ๆœ€็ปˆ็ป“่ฎบ" } - ] - } - ] - }) - - // Process based on direction - switch (userDirection.direction) { - case "ๆทฑๅ…ฅๆŽข็ดข": - await deepDiveIdeas(userDirection.selectedIdeas) - break - case "็ปง็ปญๅ‘ๆ•ฃ": - await generateMoreIdeas() - break - case "ๆŒ‘ๆˆ˜้ชŒ่ฏ": - await devilsAdvocate(topIdeas) - break - case "ๅˆๅนถ็ปผๅˆ": - await mergeIdeas(userDirection.selectedIdeas) - break - case "ๅ‡†ๅค‡ๆ”ถๆ•›": - brainstormComplete = true - break - } - - // Update brainstorm.md - updateBrainstormDocument(roundNumber, userDirection, findings) - roundNumber++ -} -``` - -**Step 3.2: Deep Dive on Selected Ideas** - -```javascript -async function deepDiveIdeas(selectedIdeas) { - for (const idea of selectedIdeas) { - const ideaPath = `${ideasFolder}/${idea.slug}.md` - - // โš ๏ธ CRITICAL: Must wait for CLI completion before saving results - await Bash({ - command: `ccw cli -p " +Bash({ + command: `ccw cli -p " PURPOSE: Deep dive analysis on idea '${idea.title}' Success: Comprehensive understanding with actionable next steps @@ -580,21 +497,14 @@ EXPECTED: CONSTRAINTS: Focus on actionability " --tool gemini --mode analysis`, - run_in_background: false - }) - - Write(ideaPath, deepDiveContent) - } -} + run_in_background: false +}) ``` -**Step 3.3: Devil's Advocate Challenge** - +**2. Devil's Advocate Challenge**: ```javascript -async function devilsAdvocate(ideas) { - // โš ๏ธ CRITICAL: Must wait for CLI completion before returning results - const challengeResult = await Bash({ - command: `ccw cli -p " +Bash({ + command: `ccw cli -p " PURPOSE: Devil's advocate - rigorously challenge these brainstorm ideas Success: Uncover hidden weaknesses and strengthen viable ideas @@ -620,22 +530,14 @@ EXPECTED: CONSTRAINTS: Be genuinely critical, not just contrarian " --tool codex --mode analysis`, - run_in_background: false - }) - - return challengeResult -} + run_in_background: false +}) ``` -**Step 3.4: Merge & Synthesize Ideas** - +**3. Merge Multiple Ideas**: ```javascript -async function mergeIdeas(ideaIds) { - const selectedIdeas = ideas.filter(i => ideaIds.includes(i.id)) - - // โš ๏ธ CRITICAL: Must wait for CLI completion before processing merge result - const mergeResult = await Bash({ - command: `ccw cli -p " +Bash({ + command: `ccw cli -p " PURPOSE: Synthesize multiple ideas into unified concept Success: Coherent merged idea that captures best elements @@ -665,390 +567,183 @@ EXPECTED: CONSTRAINTS: Don't force incompatible ideas together " --tool gemini --mode analysis`, - run_in_background: false - }) - - const mergedIdea = parseMergeResult(mergeResult) - ideas.push(mergedIdea) - - return mergedIdea -} + run_in_background: false +}) ``` -**Step 3.5: Document Each Round** - -Append each round's findings to brainstorm.md (see Templates section for format). - ---- +**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) ### Phase 4: Convergence & Crystallization -**Step 4.1: Final Synthesis** +**Objective**: Synthesize final ideas, generate conclusions, offer next steps. -```javascript -const synthesis = { - session_id: sessionId, - topic: idea_or_topic, - completed: getUtc8ISOString(), - total_rounds: roundNumber, +**Prerequisites**: +- Phase 3 completed successfully +- Multiple rounds of refinement documented +- User ready to converge - top_ideas: ideas.filter(i => i.status === 'active').sort((a,b) => b.score - a.score).slice(0, 5).map(idea => ({ - title: idea.title, - description: idea.description, - source_perspective: idea.source, - score: idea.score, - novelty: idea.novelty, - feasibility: idea.feasibility, - key_strengths: idea.strengths, - main_challenges: idea.challenges, - next_steps: idea.nextSteps - })), +**Workflow Steps**: - parked_ideas: ideas.filter(i => i.status === 'parked').map(idea => ({ - title: idea.title, - reason_parked: idea.parkReason, - potential_future_trigger: idea.futureTrigger - })), +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 + - **Recommendations**: Primary recommendation, alternatives, not recommended + - **Follow-up**: Implementation/research/validation summaries + - Write to synthesis.json - key_insights: keyInsights, +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 - recommendations: { - primary: primaryRecommendation, - alternatives: alternativeApproaches, - not_recommended: notRecommended - }, +3. **Post-Completion Options** (AskUserQuestion) + - **ๅˆ›ๅปบๅฎžๆ–ฝ่ฎกๅˆ’**: Launch workflow:plan with top idea + - **ๅˆ›ๅปบIssue**: Launch issue:new for top 3 ideas + - **ๆทฑๅ…ฅๅˆ†ๆž**: Launch workflow:analyze-with-file for top idea + - **ๅฏผๅ‡บๅˆ†ไบซ**: Generate shareable report + - **ๅฎŒๆˆ**: No further action - follow_up: [ - { type: 'implementation', summary: '...' }, - { type: 'research', summary: '...' }, - { type: 'validation', summary: '...' } - ] -} +**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 -Write(synthesisPath, JSON.stringify(synthesis, null, 2)) -``` - -**Step 4.2: Final brainstorm.md Update** - -Update brainstorm.md with synthesis & conclusions (see Templates section for format). - -**Step 4.3: Post-Completion Options** - -```javascript -AskUserQuestion({ - questions: [{ - question: "ๅคด่„‘้ฃŽๆšดๅฎŒๆˆใ€‚ๆ˜ฏๅฆ้œ€่ฆๅŽ็ปญๆ“ไฝœ?", - header: "ๅŽ็ปญ", - multiSelect: true, - options: [ - { label: "ๅˆ›ๅปบๅฎžๆ–ฝ่ฎกๅˆ’", description: "ๅฐ†ๆœ€ไฝณๆƒณๆณ•่ฝฌไธบๅฎžๆ–ฝ่ฎกๅˆ’" }, - { label: "ๅˆ›ๅปบIssue", description: "ๅฐ†ๆƒณๆณ•่ฝฌไธบๅฏ่ฟฝ่ธช็š„Issue" }, - { label: "ๆทฑๅ…ฅๅˆ†ๆž", description: "ๅฏนๆŸไธชๆƒณๆณ•่ฟ›่กŒๆทฑๅบฆๆŠ€ๆœฏๅˆ†ๆž" }, - { label: "ๅฏผๅ‡บๅˆ†ไบซ", description: "็”Ÿๆˆๅฏๅˆ†ไบซ็š„ๆŠฅๅ‘Š" }, - { label: "ๅฎŒๆˆ", description: "ไธ้œ€่ฆๅŽ็ปญๆ“ไฝœ" } - ] - }] -}) - -// Handle selections -if (selection.includes("ๅˆ›ๅปบๅฎžๆ–ฝ่ฎกๅˆ’")) { - const topIdea = synthesis.top_ideas[0] - Skill(skill="workflow:plan", args=`ๅฎžๆ–ฝ: ${topIdea.title} - ${topIdea.description}`) -} -if (selection.includes("ๅˆ›ๅปบIssue")) { - for (const idea of synthesis.top_ideas.slice(0, 3)) { - Skill(skill="issue:new", args=`${idea.title}: ${idea.next_steps[0]}`) - } -} -if (selection.includes("ๆทฑๅ…ฅๅˆ†ๆž")) { - Skill(skill="workflow:analyze-with-file", args=synthesis.top_ideas[0].title) -} -if (selection.includes("ๅฏผๅ‡บๅˆ†ไบซ")) { - exportBrainstormReport(sessionFolder) -} -``` - ---- +**Success Criteria**: +- synthesis.json created with final synthesis +- brainstorm.md finalized with conclusions +- User offered next step options +- Session complete ## Configuration ### Brainstorm Dimensions -```javascript -const BRAINSTORM_DIMENSIONS = { - technical: ['ๆŠ€ๆœฏ', 'technical', 'implementation', 'code', 'ๅฎž็Žฐ', 'architecture'], - ux: ['็”จๆˆท', 'user', 'experience', 'UX', 'UI', 'ไฝ“้ชŒ', 'interaction'], - business: ['ไธšๅŠก', 'business', 'value', 'ROI', 'ไปทๅ€ผ', 'market'], - innovation: ['ๅˆ›ๆ–ฐ', 'innovation', 'novel', 'creative', 'ๆ–ฐ้ข–'], - feasibility: ['ๅฏ่กŒ', 'feasible', 'practical', 'realistic', 'ๅฎž้™…'], - scalability: ['ๆ‰ฉๅฑ•', 'scale', 'growth', 'performance', 'ๆ€ง่ƒฝ'], - security: ['ๅฎ‰ๅ…จ', 'security', 'risk', 'protection', '้ฃŽ้™ฉ'] -} -``` +Dimensions matched against topic keywords to identify focus areas: -### Multi-CLI Collaboration Strategy +| Dimension | Keywords | +|-----------|----------| +| technical | ๆŠ€ๆœฏ, technical, implementation, code, ๅฎž็Žฐ, architecture | +| ux | ็”จๆˆท, user, experience, UX, UI, ไฝ“้ชŒ, interaction | +| business | ไธšๅŠก, business, value, ROI, ไปทๅ€ผ, market | +| innovation | ๅˆ›ๆ–ฐ, innovation, novel, creative, ๆ–ฐ้ข– | +| feasibility | ๅฏ่กŒ, feasible, practical, realistic, ๅฎž้™… | +| scalability | ๆ‰ฉๅฑ•, scale, growth, performance, ๆ€ง่ƒฝ | +| security | ๅฎ‰ๅ…จ, security, risk, protection, ้ฃŽ้™ฉ | -**Perspective Roles** +### Role Selection -| CLI | Role | Focus | Best For | -|-----|------|-------|----------| -| Gemini | Creative | Innovation, cross-domain | Generating novel ideas | -| Codex | Pragmatic | Implementation, feasibility | Reality-checking ideas | -| Claude | Systematic | Architecture, structure | Organizing solutions | +**Professional Roles** (recommended based on topic keywords): -**Collaboration Patterns** +| Role | CLI Tool | Focus Area | Keywords | +|------|----------|------------|----------| +| system-architect | Claude | Architecture, patterns | ๆžถๆž„, architecture, system, ็ณป็ปŸ, design pattern | +| product-manager | Gemini | Business value, roadmap | ไบงๅ“, product, feature, ๅŠŸ่ƒฝ, roadmap | +| ui-designer | Gemini | Visual design, interaction | UI, ็•Œ้ข, interface, visual, ่ง†่ง‰ | +| ux-expert | Codex | User research, usability | UX, ไฝ“้ชŒ, experience, user, ็”จๆˆท | +| data-architect | Claude | Data modeling, storage | ๆ•ฐๆฎ, data, database, ๅญ˜ๅ‚จ, storage | +| test-strategist | Codex | Quality, testing | ๆต‹่ฏ•, test, quality, ่ดจ้‡, QA | +| subject-matter-expert | Gemini | Domain knowledge | ้ข†ๅŸŸ, domain, industry, ่กŒไธš, expert | +| product-owner | Codex | Priority, scope | ไผ˜ๅ…ˆ, priority, scope, ่Œƒๅ›ด, backlog | +| scrum-master | Gemini | Process, collaboration | ๆ•ๆท, agile, scrum, sprint, ่ฟญไปฃ | -1. **Parallel Divergence**: All CLIs explore simultaneously from different angles -2. **Sequential Deep-Dive**: One CLI expands, others critique/refine -3. **Debate Mode**: CLIs argue for/against specific approaches -4. **Synthesis Mode**: Combine insights from all perspectives +**Simple Perspectives** (fallback): -**When to Use Each Pattern** +| 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 | -- **New topic**: Parallel Divergence โ†’ get diverse initial ideas -- **Promising idea**: Sequential Deep-Dive โ†’ thorough exploration -- **Controversial approach**: Debate Mode โ†’ uncover hidden issues -- **Ready to decide**: Synthesis Mode โ†’ create actionable conclusion +**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 -### Error Handling +### Collaboration Patterns -| Situation | Action | -|-----------|--------| -| CLI timeout | Retry with shorter prompt, or continue without that perspective | -| No good ideas | Reframe the problem, adjust constraints, try different angles | -| User disengaged | Summarize progress, offer break point with resume option | -| Perspectives conflict | Present as tradeoff, let user decide direction | +| 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 | Resolution | +|-------|------------| +| cli-explore-agent fails | Continue with empty exploration context | +| CLI timeout | Retry with shorter prompt, or skip perspective | +| No good ideas | Reframe problem, adjust constraints, try new angles | +| User disengaged | Summarize progress, offer break point with resume | +| Perspectives conflict | Present as tradeoff, let user decide | | 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. **Review brainstorm.md**: Check thought evolution before final decisions +3. **Embrace Conflicts**: Perspective conflicts often reveal important tradeoffs +4. **Document Evolution**: brainstorm.md captures full thinking process for team review +5. **Use Continue Mode**: Resume sessions to build on previous exploration ## Templates -### Session Folder Structure - -``` -.workflow/.brainstorm/BS-{slug}-{date}/ -โ”œโ”€โ”€ brainstorm.md # Complete thought evolution -โ”œโ”€โ”€ perspectives.json # Multi-CLI perspective findings -โ”œโ”€โ”€ synthesis.json # Final synthesis -โ””โ”€โ”€ ideas/ # Individual idea deep-dives - โ”œโ”€โ”€ idea-1.md - โ”œโ”€โ”€ idea-2.md - โ””โ”€โ”€ merged-idea-1.md -``` - -### Brainstorm Document Template - -```markdown -# Brainstorm Session - -**Session ID**: BS-xxx-YYYY-MM-DD -**Topic**: [idea or topic] -**Started**: YYYY-MM-DDTHH:mm:ss+08:00 -**Mode**: creative | structured | balanced -**Dimensions**: [technical, ux, innovation, ...] - ---- - -## Initial Context - -**User Focus**: [selected focus areas] -**Depth**: [quick|balanced|deep] -**Constraints**: [if any] - ---- - -## Seed Expansion - -### Original Idea -> [the initial idea] - -### Exploration Vectors - -#### Vector 1: [title] -**Question**: [question] -**Angle**: [angle] -**Potential**: [potential] - -[... more vectors ...] - ---- - -## Thought Evolution Timeline - -### Round 1 - Seed Understanding (timestamp) - -#### Initial Parsing -- **Core concept**: [concept] -- **Problem space**: [space] -- **Opportunity**: [opportunity] - -#### Key Questions to Explore -1. [question 1] -2. [question 2] -... - ---- - -### Round 2 - Multi-Perspective Exploration (timestamp) - -#### Creative Perspective (Gemini) - -**Top Creative Ideas**: -1. **[Title]** โญ Novelty: X/5 | Impact: Y/5 - [description] - -**Challenged Assumptions**: -- ~~[assumption]~~ โ†’ Consider: [alternative] - -**Cross-Domain Inspirations**: -- [inspiration] - ---- - -#### Pragmatic Perspective (Codex) - -**Implementation Approaches**: -1. **[Title]** | Effort: X/5 | Risk: Y/5 - [description] - - Quick win: [win] - - Dependencies: [deps] - -**Technical Blockers**: -- โš ๏ธ [blocker] - ---- - -#### Systematic Perspective (Claude) - -**Problem Decomposition**: -[decomposition] - -**Architectural Options**: -1. **[Pattern]** - - Pros: [pros] - - Cons: [cons] - - Best for: [context] - ---- - -#### Perspective Synthesis - -**Convergent Themes** (all perspectives agree): -- โœ… [theme] - -**Conflicting Views** (need resolution): -- ๐Ÿ”„ [topic] - - Creative: [view] - - Pragmatic: [view] - - Systematic: [view] - -**Unique Contributions**: -- ๐Ÿ’ก [source] [insight] - ---- - -### Round 3+ - [Round Type] (timestamp) - -[Round-specific content: deep-dive, challenge, merge, etc.] - ---- - -## Synthesis & Conclusions (timestamp) - -### Executive Summary - -[summary] - -### Top Ideas (Final Ranking) - -#### 1. [Title] โญ Score: X/10 - -**Description**: [description] - -**Why This Idea**: -- โœ… [strength] - -**Main Challenges**: -- โš ๏ธ [challenge] - -**Recommended Next Steps**: -1. [step] -2. [step] - ---- - -[... more ideas ...] - -### Primary Recommendation - -> [recommendation] - -**Rationale**: [rationale] - -**Quick Start Path**: -1. [step] -2. [step] -3. [step] - -### Alternative Approaches - -1. **[Title]** - - When to consider: [when] - - Tradeoff: [tradeoff] - -### Ideas Parked for Future - -- **[Title]** (Parked: [reason]) - - Revisit when: [trigger] - ---- - -## Key Insights - -### Process Discoveries - -- ๐Ÿ’ก [discovery] - -### Assumptions Challenged - -- ~~[original]~~ โ†’ [updated] - -### Unexpected Connections - -- ๐Ÿ”— [connection] - ---- - -## Current Understanding (Final) - -### Problem Reframed - -[reframed problem] - -### Solution Space Mapped - -[solution space] - -### Decision Framework - -When to choose each approach: -[framework] - ---- - -## Session Statistics - -- **Total Rounds**: [n] -- **Ideas Generated**: [n] -- **Ideas Survived**: [n] -- **Perspectives Used**: Gemini (creative), Codex (pragmatic), Claude (systematic) -- **Duration**: [duration] -- **Artifacts**: brainstorm.md, perspectives.json, synthesis.json, [n] idea deep-dives -``` - ---- +### 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 @@ -1069,3 +764,7 @@ When to choose each approach: - Direction is already clear - Ready to move from ideas to execution - Need implementation breakdown + +--- + +**Now execute brainstorm-with-file for**: $ARGUMENTS diff --git a/.codex/prompts/merge-plans-with-file.md b/.codex/prompts/merge-plans-with-file.md deleted file mode 100644 index 4d70fc49..00000000 --- a/.codex/prompts/merge-plans-with-file.md +++ /dev/null @@ -1,530 +0,0 @@ ---- -description: Merge multiple planning/brainstorm/analysis outputs, resolve conflicts, and synthesize unified plan. Multi-team input aggregation and plan crystallization -argument-hint: "PATTERN=\"\" [--rule=consensus|priority|hierarchy] [--output=] [--auto] [--verbose]" ---- - -# Codex Merge-Plans-With-File Prompt - -## Overview - -Plan aggregation and conflict resolution workflow. Takes multiple planning artifacts (brainstorm conclusions, analysis recommendations, quick-plans, implementation plans) and synthesizes them into a unified, conflict-resolved execution plan. - -**Core workflow**: Load Sources โ†’ Parse Plans โ†’ Conflict Analysis โ†’ Arbitration โ†’ Unified Plan - -**Key features**: -- **Multi-Source Support**: brainstorm, analysis, quick-plan, IMPL_PLAN, task JSONs -- **Conflict Detection**: Identify contradictions across all input plans -- **Resolution Rules**: consensus, priority-based, or hierarchical resolution -- **Unified Synthesis**: Single authoritative plan from multiple perspectives -- **Decision Tracking**: Full audit trail of conflicts and resolutions - -## Target Pattern - -**$PATTERN** - -- `--rule`: Conflict resolution (consensus | priority | hierarchy) - consensus by default -- `--output`: Output directory (default: .workflow/.merged/{pattern}) -- `--auto`: Auto-resolve conflicts using rule, skip confirmations -- `--verbose`: Include detailed conflict analysis - -## Execution Process - -``` -Phase 1: Discovery & Loading - โ”œโ”€ Search for artifacts matching pattern - โ”œโ”€ Load synthesis.json, conclusions.json, IMPL_PLAN.md, task JSONs - โ”œโ”€ Parse into normalized task structure - โ””โ”€ Validate completeness - -Phase 2: Plan Normalization - โ”œโ”€ Convert all formats to common task representation - โ”œโ”€ Extract: tasks, dependencies, effort, risks - โ”œโ”€ Identify scope and boundaries - โ””โ”€ Aggregate recommendations - -Phase 3: Conflict Detection (Parallel) - โ”œโ”€ Architecture conflicts: different design approaches - โ”œโ”€ Task conflicts: overlapping or duplicated tasks - โ”œโ”€ Effort conflicts: different estimates - โ”œโ”€ Risk conflicts: different risk assessments - โ”œโ”€ Scope conflicts: different feature sets - โ””โ”€ Generate conflict matrix - -Phase 4: Conflict Resolution - โ”œโ”€ Analyze source rationale for each conflict - โ”œโ”€ Apply resolution rule (consensus / priority / hierarchy) - โ”œโ”€ Escalate unresolvable conflicts to user (unless --auto) - โ”œโ”€ Document decision rationale - โ””โ”€ Generate resolutions.json - -Phase 5: Plan Synthesis - โ”œโ”€ Merge task lists (deduplicate, combine insights) - โ”œโ”€ Integrate dependencies - โ”œโ”€ Consolidate effort and risk estimates - โ”œโ”€ Generate execution sequence - โ””โ”€ Output unified-plan.json - -Output: - โ”œโ”€ .workflow/.merged/{sessionId}/merge.md (process log) - โ”œโ”€ .workflow/.merged/{sessionId}/source-index.json (input sources) - โ”œโ”€ .workflow/.merged/{sessionId}/conflicts.json (conflict matrix) - โ”œโ”€ .workflow/.merged/{sessionId}/resolutions.json (decisions) - โ”œโ”€ .workflow/.merged/{sessionId}/unified-plan.json (for execution) - โ””โ”€ .workflow/.merged/{sessionId}/unified-plan.md (human-readable) -``` - -## Implementation Details - -### Phase 1: Discover & Load Sources - -```javascript -const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString() - -const mergeSlug = "$PATTERN".toLowerCase() - .replace(/[*?]/g, '-') - .replace(/[^a-z0-9\u4e00-\u9fa5-]+/g, '-') - .substring(0, 30) -const sessionId = `MERGE-${mergeSlug}-${getUtc8ISOString().substring(0, 10)}` -const sessionFolder = `.workflow/.merged/${sessionId}` - -bash(`mkdir -p ${sessionFolder}`) - -// Search paths for matching artifacts -const searchPaths = [ - `.workflow/.brainstorm/*${$PATTERN}*/synthesis.json`, - `.workflow/.analysis/*${$PATTERN}*/conclusions.json`, - `.workflow/.planning/*${$PATTERN}*/synthesis.json`, - `.workflow/.plan/*${$PATTERN}*IMPL_PLAN.md`, - `.workflow/**/*${$PATTERN}*.json` -] - -// Load and validate each source -const sourcePlans = [] -for (const pattern of searchPaths) { - const matches = glob(pattern) - for (const path of matches) { - const plan = loadAndParsePlan(path) - if (plan?.tasks?.length > 0) { - sourcePlans.push({ path, type: inferType(path), plan }) - } - } -} -``` - -### Phase 2: Normalize Plans - -Convert all source formats to common structure: - -```javascript -const normalizedPlans = sourcePlans.map((src, idx) => ({ - index: idx, - source: src.path, - type: src.type, - - metadata: { - title: src.plan.title || `Plan ${idx + 1}`, - topic: src.plan.topic, - complexity: src.plan.complexity_level || 'unknown' - }, - - tasks: src.plan.tasks.map(task => ({ - id: `T${idx}-${task.id || task.title.substring(0, 20)}`, - title: task.title, - description: task.description, - type: task.type || inferTaskType(task), - priority: task.priority || 'normal', - - effort: { estimated: task.effort_estimate, from_plan: idx }, - risk: { level: task.risk_level || 'medium', from_plan: idx }, - dependencies: task.dependencies || [], - - source_plan_index: idx - })) -})) -``` - -### Phase 3: Parallel Conflict Detection - -Launch parallel agents to detect and analyze conflicts: - -```javascript -// Parallel conflict detection with CLI agents -const conflictPromises = [] - -// Agent 1: Detect effort and task conflicts -conflictPromises.push( - Bash({ - command: `ccw cli -p " -PURPOSE: Detect effort conflicts and task duplicates across multiple plans -Success: Complete identification of conflicting estimates and duplicate tasks - -TASK: -โ€ข Identify tasks with significantly different effort estimates (>50% variance) -โ€ข Detect duplicate/similar tasks across plans -โ€ข Analyze effort estimation reasoning -โ€ข Suggest resolution for each conflict - -MODE: analysis - -CONTEXT: -- Plan 1: ${JSON.stringify(normalizedPlans[0]?.tasks?.slice(0,3) || [], null, 2)} -- Plan 2: ${JSON.stringify(normalizedPlans[1]?.tasks?.slice(0,3) || [], null, 2)} -- [Additional plans...] - -EXPECTED: -- Effort conflicts detected (task name, estimate in each plan, variance %) -- Duplicate task analysis (similar tasks, scope differences) -- Resolution recommendation for each conflict -- Confidence level for each detection - -CONSTRAINTS: Focus on significant conflicts (>30% effort variance) -" --tool gemini --mode analysis`, - run_in_background: true - }) -) - -// Agent 2: Analyze architecture and scope conflicts -conflictPromises.push( - Bash({ - command: \`ccw cli -p " -PURPOSE: Analyze architecture and scope conflicts across plans -Success: Clear identification of design approach differences and scope gaps - -TASK: -โ€ข Identify different architectural approaches in plans -โ€ข Detect scope differences (features included/excluded) -โ€ข Analyze design philosophy conflicts -โ€ข Suggest approach to reconcile different visions - -MODE: analysis - -CONTEXT: -- Plan 1 architecture: \${normalizedPlans[0]?.metadata?.complexity || 'unknown'} -- Plan 2 architecture: \${normalizedPlans[1]?.metadata?.complexity || 'unknown'} -- Different design approaches detected: \${JSON.stringify(['approach1', 'approach2'])} - -EXPECTED: -- Architecture conflicts identified (approach names and trade-offs) -- Scope conflicts (features/components in plan A but not B, vice versa) -- Design philosophy alignment/misalignment -- Recommendation for unified approach -- Pros/cons of each architectural approach - -CONSTRAINTS: Consider both perspectives objectively -" --tool codex --mode analysis\`, - run_in_background: true - }) -) - -// Agent 3: Analyze risk assessment conflicts -conflictPromises.push( - Bash({ - command: \`ccw cli -p " -PURPOSE: Analyze risk assessment conflicts across plans -Success: Unified risk assessment with conflict resolution - -TASK: -โ€ข Identify tasks/areas with significantly different risk ratings -โ€ข Analyze risk assessment reasoning -โ€ข Detect missing risks in some plans -โ€ข Propose unified risk assessment - -MODE: analysis - -CONTEXT: -- Risk areas with disagreement: [list areas] -- Plan 1 risk ratings: [risk matrix] -- Plan 2 risk ratings: [risk matrix] - -EXPECTED: -- Risk conflicts identified (area, plan A rating, plan B rating) -- Explanation of why assessments differ -- Missing risks analysis (important in one plan but not others) -- Unified risk rating recommendation -- Confidence level for each assessment - -CONSTRAINTS: Be realistic in risk assessment, not pessimistic -" --tool claude --mode analysis\`, - run_in_background: true - }) -) - -// Agent 4: Synthesize conflicts into resolution strategy -conflictPromises.push( - Bash({ - command: \`ccw cli -p " -PURPOSE: Synthesize all conflicts into unified resolution strategy -Success: Clear path to merge plans with informed trade-off decisions - -TASK: -โ€ข Analyze all detected conflicts holistically -โ€ข Identify which conflicts are critical vs. non-critical -โ€ข Propose resolution for each conflict type -โ€ข Suggest unified approach that honors valid insights from all plans - -MODE: analysis - -CONTEXT: -- Total conflicts detected: [number] -- Conflict types: effort, architecture, scope, risk -- Resolution rule: \${resolutionRule} -- Plan importance: \${normalizedPlans.map(p => p.metadata.title).join(', ')} - -EXPECTED: -- Conflict priority ranking (critical, important, minor) -- Recommended resolution for each conflict -- Rationale for each recommendation -- Potential issues with proposed resolution -- Fallback options if recommendation not accepted -- Overall merge strategy and sequencing - -CONSTRAINTS: Aim for solution that maximizes learning from all perspectives -" --tool gemini --mode analysis\`, - run_in_background: true - }) -) - -// Wait for all conflict detection agents to complete -const [effortConflicts, archConflicts, riskConflicts, resolutionStrategy] = - await Promise.all(conflictPromises) - -// Parse and consolidate all conflict findings -const allConflicts = { - effort: parseEffortConflicts(effortConflicts), - architecture: parseArchConflicts(archConflicts), - risk: parseRiskConflicts(riskConflicts), - strategy: parseResolutionStrategy(resolutionStrategy), - timestamp: getUtc8ISOString() -} - -Write(\`\${sessionFolder}/conflicts.json\`, JSON.stringify(allConflicts, null, 2)) -``` - -**Conflict Detection Workflow**: - -| Agent | Conflict Type | Focus | Output | -|-------|--------------|--------|--------| -| Gemini | Effort & Tasks | Duplicate detection, estimate variance | Conflicts with variance %, resolution suggestions | -| Codex | Architecture & Scope | Design approach differences | Design conflicts, scope gaps, recommendations | -| Claude | Risk Assessment | Risk rating disagreements | Risk conflicts, missing risks, unified assessment | -| Gemini | Resolution Strategy | Holistic synthesis | Priority ranking, resolution path, trade-offs | - -### Phase 4: Resolve Conflicts - -**Rule: Consensus (default)** -- Use median/average of conflicting estimates -- Merge scope differences -- Document minority viewpoints - -**Rule: Priority** -- First plan has highest authority -- Later plans supplement but don't override - -**Rule: Hierarchy** -- User ranks plan importance -- Higher-ranked plan wins conflicts - -```javascript -const resolutions = {} - -if (rule === 'consensus') { - for (const conflict of conflicts.effort) { - resolutions[conflict.task] = { - resolved: calculateMedian(conflict.estimates), - method: 'consensus-median', - rationale: 'Used median of all estimates' - } - } -} else if (rule === 'priority') { - for (const conflict of conflicts.effort) { - const primary = conflict.estimates[0] // First plan - resolutions[conflict.task] = { - resolved: primary.value, - method: 'priority-based', - rationale: `Selected from plan ${primary.from_plan} (highest priority)` - } - } -} else if (rule === 'hierarchy') { - // Request user ranking if not --auto - const ranking = getUserPlanRanking(normalizedPlans) - // Apply hierarchy-based resolution -} - -Write(`${sessionFolder}/resolutions.json`, JSON.stringify(resolutions, null, 2)) -``` - -### Phase 5: Generate Unified Plan - -```javascript -const unifiedPlan = { - session_id: sessionId, - merge_timestamp: getUtc8ISOString(), - - summary: { - total_source_plans: sourcePlans.length, - original_tasks: allTasks.length, - merged_tasks: deduplicatedTasks.length, - conflicts_resolved: Object.keys(resolutions).length, - resolution_rule: rule - }, - - tasks: deduplicatedTasks.map(task => ({ - id: task.id, - title: task.title, - description: task.description, - effort: task.resolved_effort, - risk: task.resolved_risk, - dependencies: task.merged_dependencies, - source_plans: task.contributing_plans - })), - - execution_sequence: topologicalSort(tasks), - critical_path: identifyCriticalPath(tasks), - - risks: aggregateRisks(tasks), - success_criteria: aggregateCriteria(tasks) -} - -Write(`${sessionFolder}/unified-plan.json`, JSON.stringify(unifiedPlan, null, 2)) -``` - -### Phase 6: Generate Human-Readable Plan - -```markdown -# Merged Planning Session - -**Session ID**: ${sessionId} -**Pattern**: $PATTERN -**Created**: ${timestamp} - ---- - -## Merge Summary - -**Source Plans**: ${summary.total_source_plans} -**Original Tasks**: ${summary.original_tasks} -**Merged Tasks**: ${summary.merged_tasks} -**Conflicts Resolved**: ${summary.conflicts_resolved} -**Resolution Method**: ${summary.resolution_rule} - ---- - -## Unified Task List - -${tasks.map((task, i) => ` -${i+1}. **${task.id}: ${task.title}** - - Effort: ${task.effort} - - Risk: ${task.risk} - - From plans: ${task.source_plans.join(', ')} -`).join('\n')} - ---- - -## Execution Sequence - -**Critical Path**: ${critical_path.join(' โ†’ ')} - ---- - -## Conflict Resolution Report - -${Object.entries(resolutions).map(([key, res]) => ` -- **${key}**: ${res.rationale} -`).join('\n')} - ---- - -## Next Steps - -**Execute**: -\`\`\` -/workflow:unified-execute-with-file -p ${sessionFolder}/unified-plan.json -\`\`\` -``` - -## Session Folder Structure - -``` -.workflow/.merged/{sessionId}/ -โ”œโ”€โ”€ merge.md # Process log -โ”œโ”€โ”€ source-index.json # All input sources -โ”œโ”€โ”€ conflicts.json # Detected conflicts -โ”œโ”€โ”€ resolutions.json # How resolved -โ”œโ”€โ”€ unified-plan.json # Merged plan (for execution) -โ””โ”€โ”€ unified-plan.md # Human-readable -``` - -## Resolution Rules Comparison - -| Rule | Method | Best For | Tradeoff | -|------|--------|----------|----------| -| **Consensus** | Median/average | Similar-quality inputs | May miss extremes | -| **Priority** | First wins | Clear authority order | Discards alternatives | -| **Hierarchy** | User-ranked | Mixed stakeholders | Needs user input | - -## Input Format Support - -| Source Type | Detection Pattern | Parsing | -|-------------|-------------------|---------| -| Brainstorm | `.brainstorm/*/synthesis.json` | Top ideas โ†’ tasks | -| Analysis | `.analysis/*/conclusions.json` | Recommendations โ†’ tasks | -| Quick-Plan | `.planning/*/synthesis.json` | Direct task list | -| IMPL_PLAN | `*IMPL_PLAN.md` | Markdown โ†’ tasks | -| Task JSON | `*.json` with `tasks` | Direct mapping | - -## Error Handling - -| Situation | Action | -|-----------|--------| -| No plans found | List available plans, suggest search terms | -| Incompatible format | Skip, continue with others | -| Circular dependencies | Alert user, suggest manual review | -| Unresolvable conflict | Require user decision (unless --auto) | - -## Integration Flow - -``` -Brainstorm Sessions / Analyses / Plans - โ”‚ - โ”œโ”€ synthesis.json (session 1) - โ”œโ”€ conclusions.json (session 2) - โ”œโ”€ synthesis.json (session 3) - โ”‚ - โ–ผ -merge-plans-with-file - โ”‚ - โ”œโ”€ unified-plan.json - โ”‚ - โ–ผ -unified-execute-with-file - โ”‚ - โ–ผ -Implementation -``` - -## Usage Patterns - -**Pattern 1: Merge all auth-related plans** -``` -PATTERN="authentication" --rule=consensus --auto -โ†’ Finds all auth plans -โ†’ Merges with consensus method -``` - -**Pattern 2: Prioritized merge** -``` -PATTERN="payment" --rule=priority -โ†’ First plan has authority -โ†’ Others supplement -``` - -**Pattern 3: Team input merge** -``` -PATTERN="feature-*" --rule=hierarchy -โ†’ Asks for plan ranking -โ†’ Applies hierarchy resolution -``` - ---- - -**Now execute merge-plans-with-file for pattern**: $PATTERN diff --git a/ccw/frontend/src/components/codexlens/AdvancedTab.tsx b/ccw/frontend/src/components/codexlens/AdvancedTab.tsx new file mode 100644 index 00000000..23e0a798 --- /dev/null +++ b/ccw/frontend/src/components/codexlens/AdvancedTab.tsx @@ -0,0 +1,292 @@ +// ======================================== +// CodexLens Advanced Tab +// ======================================== +// Advanced settings including .env editor and ignore patterns + +import { useState, useEffect } from 'react'; +import { useIntl } from 'react-intl'; +import { Save, RefreshCw, AlertTriangle, FileCode } from 'lucide-react'; +import { Card } from '@/components/ui/Card'; +import { Textarea } from '@/components/ui/Textarea'; +import { Button } from '@/components/ui/Button'; +import { Label } from '@/components/ui/Label'; +import { Badge } from '@/components/ui/Badge'; +import { useCodexLensEnv, useUpdateCodexLensEnv } from '@/hooks'; +import { useNotifications } from '@/hooks'; +import { cn } from '@/lib/utils'; + +interface AdvancedTabProps { + enabled?: boolean; +} + +interface FormErrors { + env?: string; +} + +export function AdvancedTab({ enabled = true }: AdvancedTabProps) { + const { formatMessage } = useIntl(); + const { success, error: showError } = useNotifications(); + + const { + raw, + env, + settings, + isLoading: isLoadingEnv, + refetch, + } = useCodexLensEnv({ enabled }); + + const { updateEnv, isUpdating } = useUpdateCodexLensEnv(); + + // Form state + const [envInput, setEnvInput] = useState(''); + const [errors, setErrors] = useState({}); + const [hasChanges, setHasChanges] = useState(false); + const [showWarning, setShowWarning] = useState(false); + + // Initialize form from env + useEffect(() => { + if (raw !== undefined) { + setEnvInput(raw); + setErrors({}); + setHasChanges(false); + setShowWarning(false); + } + }, [raw]); + + const handleEnvChange = (value: string) => { + setEnvInput(value); + // Check if there are changes + if (raw !== undefined) { + setHasChanges(value !== raw); + setShowWarning(value !== raw); + } + if (errors.env) { + setErrors((prev) => ({ ...prev, env: undefined })); + } + }; + + const parseEnvVariables = (text: string): Record => { + const envObj: Record = {}; + const lines = text.split('\n'); + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#') && trimmed.includes('=')) { + const [key, ...valParts] = trimmed.split('='); + const val = valParts.join('='); + if (key) { + envObj[key.trim()] = val.trim(); + } + } + } + return envObj; + }; + + const validateForm = (): boolean => { + const newErrors: FormErrors = {}; + const parsed = parseEnvVariables(envInput); + + // Check for invalid variable names + const invalidKeys = Object.keys(parsed).filter( + (key) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key) + ); + + if (invalidKeys.length > 0) { + newErrors.env = formatMessage( + { id: 'codexlens.advanced.validation.invalidKeys' }, + { keys: invalidKeys.join(', ') } + ); + } + + setErrors(newErrors); + return Object.keys(newErrors).length === 0; + }; + + const handleSave = async () => { + if (!validateForm()) { + return; + } + + try { + const parsed = parseEnvVariables(envInput); + const result = await updateEnv({ env: parsed }); + + if (result.success) { + success( + formatMessage({ id: 'codexlens.advanced.saveSuccess' }), + result.message || formatMessage({ id: 'codexlens.advanced.envUpdated' }) + ); + refetch(); + setShowWarning(false); + } else { + showError( + formatMessage({ id: 'codexlens.advanced.saveFailed' }), + result.message || formatMessage({ id: 'codexlens.advanced.saveError' }) + ); + } + } catch (err) { + showError( + formatMessage({ id: 'codexlens.advanced.saveFailed' }), + err instanceof Error ? err.message : formatMessage({ id: 'codexlens.advanced.unknownError' }) + ); + } + }; + + const handleReset = () => { + if (raw !== undefined) { + setEnvInput(raw); + setErrors({}); + setHasChanges(false); + setShowWarning(false); + } + }; + + const isLoading = isLoadingEnv; + + // Get current env variables as array for display + const currentEnvVars = env + ? Object.entries(env).map(([key, value]) => ({ key, value })) + : []; + + // Get settings variables + const settingsVars = settings + ? Object.entries(settings).map(([key, value]) => ({ key, value })) + : []; + + return ( +
+ {/* Sensitivity Warning Card */} + {showWarning && ( + +
+ +
+

+ {formatMessage({ id: 'codexlens.advanced.warningTitle' })} +

+

+ {formatMessage({ id: 'codexlens.advanced.warningMessage' })} +

+
+
+
+ )} + + {/* Current Variables Summary */} + {(currentEnvVars.length > 0 || settingsVars.length > 0) && ( + +

+ {formatMessage({ id: 'codexlens.advanced.currentVars' })} +

+
+ {settingsVars.length > 0 && ( +
+

+ {formatMessage({ id: 'codexlens.advanced.settingsVars' })} +

+
+ {settingsVars.map(({ key }) => ( + + {key} + + ))} +
+
+ )} + {currentEnvVars.length > 0 && ( +
+

+ {formatMessage({ id: 'codexlens.advanced.customVars' })} +

+
+ {currentEnvVars.map(({ key }) => ( + + {key} + + ))} +
+
+ )} +
+
+ )} + + {/* Environment Variables Editor */} + +
+
+ +

+ {formatMessage({ id: 'codexlens.advanced.envEditor' })} +

+
+ + {formatMessage({ id: 'codexlens.advanced.envFile' })}: .env + +
+ +
+ {/* Env Textarea */} +
+ +