From bcb4af3ba0e7ac81e9c0a58ad3f593b3759a2f6e Mon Sep 17 00:00:00 2001 From: catlog22 Date: Mon, 2 Feb 2026 21:41:56 +0800 Subject: [PATCH] feat(commands): add ccw-plan and ccw-test coordinators with arrow-style documentation - Add ccw-plan.md: Planning coordinator with 10 modes (lite/multi-cli/full/plan-verify/replan + cli/issue/rapid-to-issue/brainstorm-with-file/analyze-with-file) - Add ccw-test.md: Test coordinator with 4 modes (gen/fix/verify/tdd) and auto-iteration support - Refactor ccw-debug.md: Convert JavaScript pseudocode to arrow instruction format for better readability - Fix command format: Use /ccw* skill call syntax instead of ccw* across all command files Key features: - CLI integration for quick analysis and recommendations - Issue workflow integration (rapid-to-issue bridge) - With-File workflows for documented multi-CLI collaboration - Consistent arrow-based flow diagrams across all coordinators - TodoWrite tracking with mode-specific prefixes (CCWP/CCWT/CCWD) - Dual tracking system (TodoWrite + status.json) --- .claude/commands/ccw-debug.md | 1100 ++++++++------------------------- .claude/commands/ccw-plan.md | 456 ++++++++++++++ .claude/commands/ccw-test.md | 387 ++++++++++++ .claude/commands/ccw.md | 18 +- 4 files changed, 1123 insertions(+), 838 deletions(-) create mode 100644 .claude/commands/ccw-plan.md create mode 100644 .claude/commands/ccw-test.md diff --git a/.claude/commands/ccw-debug.md b/.claude/commands/ccw-debug.md index 48372f13..c7c51bfc 100644 --- a/.claude/commands/ccw-debug.md +++ b/.claude/commands/ccw-debug.md @@ -1,922 +1,364 @@ --- name: ccw-debug -description: Aggregated debug command - combines debugging diagnostics and test verification in a synergistic workflow supporting cli-quick / debug-first / test-first / bidirectional-verification modes -argument-hint: "[--mode cli|debug|test|bidirectional] [--yes|-y] [--hotfix] \"bug description or error message\"" +description: Debug coordinator - analyze issue, select debug strategy, execute debug workflow in main process +argument-hint: "[--mode cli|debug|test|bidirectional] [--yes|-y] \"bug description\"" allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Bash(*) --- -# CCW-Debug Aggregated Command +# CCW-Debug Command - Debug Coordinator -## Core Concept +Debug orchestrator: issue analysis → strategy selection → debug execution. -**Aggregated Debug Command** - Combines debugging diagnostics and test verification in a synergistic workflow. Not a simple concatenation of two commands, but intelligent orchestration based on mode selection. +## Core Concept: Debug Units (调试单元) -### Four Execution Modes +**Definition**: Debug commands grouped into logical units for different root cause strategies. -| Mode | Workflow | Use Case | Characteristics | -|------|----------|----------|-----------------| -| **CLI Quick** (cli) | Direct CLI Analysis → Fix Suggestions | Simple issues, quick diagnosis | Fastest, minimal workflow, recommendation-only | -| **Debug First** (debug) | Debug → Analyze Hypotheses → Apply Fix → Test Verification | Root cause unclear, requires exploration | Starts with exploration, Gemini-assisted | -| **Test First** (test) | Generate Tests → Execute → Analyze Failures → CLI Fixes | Code implemented, needs test validation | Driven by test coverage, auto-iterates | -| **Bidirectional Verification** (bidirectional) | Parallel: Debug + Test → Merge Findings → Unified Fix | Complex systems, ambiguous symptoms | Parallel execution, converged insights | +**Debug Units**: + +| Unit Type | Pattern | Example | +|-----------|---------|---------| +| **Quick Diagnosis** | CLI analysis only | cli → recommendation | +| **Hypothesis-Driven** | Debug exploration | debug-with-file → apply fix | +| **Test-Driven** | Test generation/iteration | test-fix-gen → test-cycle-execute | +| **Convergence** | Parallel debug + test | debug + test (parallel) | + +**Atomic Rules**: +1. CLI mode: Analysis only, recommendation for user action +2. Debug/Test modes: Full cycle (analysis → fix → validate) +3. Bidirectional mode: Parallel execution, merge findings + +## Execution Model + +**Synchronous (Main Process)**: Debug commands execute via Skill, blocking until complete. + +``` +User Input → Analyze Issue → Select Strategy → [Confirm] → Execute Debug + ↓ + Skill (blocking) + ↓ + Update TodoWrite + ↓ + Generate Fix/Report +``` + +## 5-Phase Workflow + +### Phase 1: Analyze Issue + +**Input** → Extract (description, symptoms) → Assess (error_type, clarity, complexity, scope) → **Analysis** + +| Field | Values | +|-------|--------| +| error_type | syntax \| logic \| async \| integration \| unknown | +| clarity | 0-3 (≥2 = clear) | +| complexity | low \| medium \| high | +| scope | single-module \| cross-module \| system | + +#### Mode Detection (Priority Order) + +``` +Input Keywords → Mode +───────────────────────────────────────────────────────── +quick|fast|immediate|recommendation|suggest → cli +test|fail|coverage|pass → test +multiple|system|distributed|concurrent → bidirectional +(default) → debug +``` + +**Output**: `IssueType: [type] | Clarity: [clarity]/3 | Complexity: [complexity] | RecommendedMode: [mode]` --- -## Quick Start +### Phase 1.5: Issue Clarification (if clarity < 2) -### Basic Usage - -```bash -# CLI quick mode: fastest, recommendation-only (new!) -/ccw-debug --mode cli "Login failed: token validation error" - -# Default mode: debug-first (recommended for most scenarios) -/ccw-debug "Login failed: token validation error" - -# Test-first mode -/ccw-debug --mode test "User permission check failure" - -# Bidirectional verification mode (complex issues) -/ccw-debug --mode bidirectional "Payment flow multiple failures" - -# Auto mode (skip all confirmations) -/ccw-debug --yes "Quick fix: database connection timeout" - -# Production hotfix (minimal diagnostics) -/ccw-debug --hotfix --yes "Production: API returns 500" +``` +Analysis → Check clarity ≥ 2? + ↓ + YES → Continue to Phase 2 + ↓ + NO → Ask Questions → Update Analysis ``` -### Mode Selection Guide - -**Choose "CLI Quick"** when: -- Need immediate diagnosis, not execution -- Want quick recommendations without workflows -- Simple issues with clear symptoms -- Just need fix suggestions, no auto-application -- Time is critical, prefer fast output -- Want to review CLI analysis before action - -**Choose "Debug First"** when: -- Root cause is unclear -- Error messages are incomplete or vague -- Need to understand code execution flow -- Issues involve multi-module interactions - -**Choose "Test First"** when: -- Code is fully implemented -- Need test coverage verification -- Have clear failure cases -- Want automated iterative fixes - -**Choose "Bidirectional Verification"** when: -- System is complex (multiple subsystems) -- Problem symptoms are ambiguous (multiple possible root causes) -- Need multi-angle validation -- Time allows parallel analysis +**Questions Asked**: Error Symptoms, When It Occurs, Affected Components, Reproducibility --- -## Execution Flow - -### Overall Process +### Phase 2: Select Debug Strategy & Build Command Chain ``` -Phase 1: Intent Analysis & Mode Selection - ├─ Parse --mode flag or recommend mode - ├─ Check --hotfix and --yes flags - └─ Determine workflow path +Analysis → Detect Mode (keywords) → Build Command Chain → Debug Workflow +``` -Phase 2: Initialization - ├─ CLI Quick: Lightweight init (no session directory needed) - ├─ Others: Create unified session directory (.workflow/.ccw-debug/) - ├─ Setup TodoWrite tracking - └─ Prepare session context +#### Command Chain Mapping -Phase 3: Execute Corresponding Workflow - ├─ CLI Quick: ccw cli → Diagnosis Report → Optional: Escalate to debug/test/apply fix - ├─ Debug First: /workflow:debug-with-file → Fix → /workflow:test-fix-gen → /workflow:test-cycle-execute - ├─ Test First: /workflow:test-fix-gen → /workflow:test-cycle-execute → CLI analyze failures - └─ Bidirectional: [/workflow:debug-with-file] ∥ [/workflow:test-fix-gen → test-cycle-execute] +| Mode | Command Chain | Execution | +|------|---------------|-----------| +| **cli** | ccw cli --mode analysis --rule analysis-diagnose-bug-root-cause | Analysis only | +| **debug** | debug-with-file → test-fix-gen → test-cycle-execute | Sequential | +| **test** | test-fix-gen → test-cycle-execute | Sequential | +| **bidirectional** | (debug-with-file ∥ test-fix-gen ∥ test-cycle-execute) → merge-findings | Parallel → Merge | -Phase 4: Merge Findings (Bidirectional Mode) / Escalation Decision (CLI Mode) - ├─ CLI Quick: Present results → Ask user: Apply fix? Escalate? Done? - ├─ Bidirectional: Converge findings from both workflows - ├─ Identify consistent and conflicting root cause analyses - └─ Generate unified fix plan +**Note**: `∥` = parallel execution -Phase 5: Completion & Follow-up - ├─ Generate summary report - ├─ Provide next step recommendations - └─ Optional: Expand to issues (testing/enhancement/refactoring/documentation) +**Output**: `Mode: [mode] | Strategy: [strategy] | Commands: [1. /cmd1 2. /cmd2]` + +--- + +### Phase 3: User Confirmation + +``` +Debug Chain → Show Strategy → Ask User → User Decision: +- ✓ Confirm → Continue to Phase 4 +- ⚙ Change Mode → Select Different Mode (back to Phase 2) +- ✗ Cancel → Abort ``` --- -## Workflow Details +### Phase 4: Setup TODO Tracking & Status File -### Mode 0: CLI Quick (Minimal Debug Method) - -**Best For**: Fast recommendations without full workflow overhead - -**Workflow**: ``` -User Input → Quick Context Gather → ccw cli (Gemini/Qwen/Codex) - ↓ - Analysis Report - ↓ - Fix Recommendations - ↓ - Optional: User Decision - ┌──────────────┼──────────────┐ - ↓ ↓ ↓ - Apply Fix Escalate Mode Done - (debug/test) +Debug Chain → Create Session Dir → Initialize Tracking → Tracking State ``` -**Execution Steps**: +**Session Structure**: +``` +Session ID: CCWD-{issue-slug}-{date} +Session Dir: .workflow/.ccw-debug/{session_id}/ -1. **Lightweight Context Gather** (Phase 2) - ```javascript - // No session directory needed for CLI mode - const tempContext = { - bug_description: bug_description, - timestamp: getUtc8ISOString(), - mode: "cli" - } +TodoWrite: + CCWD:{mode}: [1/n] /command1 [in_progress] + CCWD:{mode}: [2/n] /command2 [pending] + ... - // Quick context discovery (30s max) - // - Read error file if path provided - // - Extract error patterns from description - // - Identify likely affected files (basic grep) +status.json: + { + "session_id": "CCWD-...", + "mode": "debug|cli|test|bidirectional", + "status": "running", + "parallel_execution": false|true, + "issue": { description, error_type, clarity, complexity }, + "command_chain": [...], + "findings": { debug, test, merged } + } +``` - // Note: CLI mode does not generate status.json (lightweight) - ``` - -2. **Execute CLI Analysis** (Phase 3) - ```bash - # Use ccw cli with bug diagnosis template - ccw cli -p " - PURPOSE: Quick bug diagnosis for immediate recommendations - - TASK: - • Analyze bug symptoms: ${bug_description} - • Identify likely root cause - • Provide actionable fix recommendations (code snippets if possible) - • Assess fix confidence level - - MODE: analysis - - CONTEXT: ${contextFiles.length > 0 ? '@' + contextFiles.join(' @') : 'Bug description only'} - - EXPECTED: - - Root cause hypothesis (1-2 sentences) - - Fix strategy (immediate/comprehensive/refactor) - - Code snippets or file modification suggestions - - Confidence level: High/Medium/Low - - Risk assessment - - CONSTRAINTS: Quick analysis, 2-5 minutes max - " --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause - ``` - -3. **Present Results** (Phase 4) - ``` - ## CLI Quick Analysis Complete - - **Issue**: [bug_description] - **Analysis Time**: [duration] - **Confidence**: [High/Medium/Low] - - ### Root Cause - [1-2 sentence hypothesis] - - ### Fix Strategy - [immediate_patch | comprehensive_fix | refactor] - - ### Recommended Changes - - **File**: src/module/file.ts - ```typescript - // Change line 45-50 - - old code - + new code - ``` - - **Rationale**: [why this fix] - **Risk**: [Low/Medium/High] - [risk description] - - ### Confidence Assessment - - Analysis confidence: [percentage] - - Recommendation: [apply immediately | review first | escalate to full debug] - ``` - -4. **User Decision** (Phase 5) - ```javascript - // Parse --yes flag - const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y') - - if (autoYes && confidence === 'High') { - // Auto-apply fix - console.log('[--yes + High confidence] Auto-applying fix...') - applyFixFromCLIRecommendation(cliOutput) - } else { - // Ask user - const decision = AskUserQuestion({ - questions: [{ - question: `CLI analysis complete (${confidence} confidence). What next?`, - header: "Decision", - multiSelect: false, - options: [ - { label: "Apply Fix", description: "Apply recommended changes immediately" }, - { label: "Escalate to Debug", description: "Switch to debug-first for deeper analysis" }, - { label: "Escalate to Test", description: "Switch to test-first for validation" }, - { label: "Review Only", description: "Just review, no action" } - ] - }] - }) - - if (decision === "Apply Fix") { - applyFixFromCLIRecommendation(cliOutput) - } else if (decision === "Escalate to Debug") { - // Re-invoke ccw-debug with --mode debug - Skill(skill="ccw-debug", args=`--mode debug "${bug_description}"`) - } else if (decision === "Escalate to Test") { - // Re-invoke ccw-debug with --mode test - Skill(skill="ccw-debug", args=`--mode test "${bug_description}"`) - } - } - ``` - -**Key Characteristics**: -- **Speed**: 2-5 minutes total (fastest mode) -- **Session**: No persistent session directory (lightweight) -- **Output**: Recommendation report only -- **Execution**: Optional, user-controlled -- **Escalation**: Can upgrade to full debug/test workflows - -**Limitations**: -- No hypothesis iteration (single-shot analysis) -- No automatic test generation -- No instrumentation/logging -- Best for clear symptoms with localized fixes +**Output**: +- TODO: `-> CCWD:debug: [1/3] /workflow:debug-with-file | ...` +- Status File: `.workflow/.ccw-debug/{session_id}/status.json` --- -### Mode 1: Debug First +### Phase 5: Execute Debug Chain -**Best For**: Issues requiring root cause exploration +#### For Bidirectional Mode (Parallel Execution) -**Workflow**: ``` -User Input → Session Init → /workflow:debug-with-file - ↓ - Generate understanding.md + hypotheses - ↓ - User reproduces issue, analyze logs - ↓ - Gemini validates hypotheses - ↓ - Apply fix code - ↓ - /workflow:test-fix-gen - ↓ - /workflow:test-cycle-execute - ↓ - Generate unified report +Start Commands (parallel) → Execute debug-with-file ∥ test-fix-gen ∥ test-cycle-execute + ↓ + Collect Results → Merge Findings + ↓ + Update status.json (findings.merged) + ↓ + Mark completed ``` -**Execution Steps**: +#### For Sequential Modes (cli, debug, test) -1. **Session Initialization** (Phase 2) - ```javascript - const sessionId = `CCWD-${bugSlug}-${dateStr}` - const sessionFolder = `.workflow/.ccw-debug/${sessionId}` - bash(`mkdir -p ${sessionFolder}`) - - // Record mode selection - const modeConfig = { - mode: "debug", - 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: "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) - ```javascript - Skill(skill="workflow:debug-with-file", args=`"${bug_description}"`) - - // Update TodoWrite - TodoWrite({ - todos: [ - { content: "Phase 1: Debug & Analysis", status: "completed" }, - { content: "Phase 2: Apply Fix from Debug Findings", status: "in_progress" }, - { content: "Phase 3: Generate & Execute Tests", status: "pending" }, - { content: "Phase 4: Generate Report", status: "pending" } - ] - }) - ``` - -3. **Apply Fix** (Handled by debug command) - -4. **Test Generation & Execution** - ```javascript - // Auto-continue after debug command completes - Skill(skill="workflow:test-fix-gen", args=`"Test validation for: ${bug_description}"`) - Skill(skill="workflow:test-cycle-execute") - ``` - -5. **Generate Report** (Phase 5) - ``` - ## Debug-First Workflow Completed - - **Issue**: [bug_description] - **Mode**: Debug First - **Session**: [sessionId] - - ### Debug Phase Results - - Root Cause: [extracted from understanding.md] - - Hypothesis Confirmation: [from hypotheses.json] - - Fixes Applied: [list of modified files] - - ### Test Phase Results - - Tests Created: [test files generated by IMPL-001] - - Pass Rate: [final test pass rate] - - Iteration Count: [fix iterations] - - ### Key Findings - - [learning points from debugging] - - [coverage insights from testing] - ``` - ---- - -### Mode 2: Test First - -**Best For**: Implemented code needing test validation - -**Workflow**: ``` -User Input → Session Init → /workflow:test-fix-gen - ↓ - Generate test tasks (IMPL-001, IMPL-002) - ↓ - /workflow:test-cycle-execute - ↓ - Auto-iterate: Test → Analyze Failures → CLI Fix - ↓ - Until pass rate ≥ 95% - ↓ - Generate report +Start Command → Update status (running) → Execute via Skill → Result + ↓ + CLI Mode? → YES → Ask Escalation → Escalate or Done + → NO → Continue + ↓ + Update status (completed) → Next Command + ↓ + Error? → YES → Ask Action (Retry/Skip/Abort) + → NO → Continue ``` -**Execution Steps**: +#### Error Handling Pattern -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) - ```javascript - Skill(skill="workflow:test-fix-gen", args=`"${bug_description}"`) - - // Update TodoWrite - TodoWrite({ - todos: [ - { content: "Phase 1: Generate Tests", status: "completed" }, - { content: "Phase 2: Execute & Fix Tests", status: "in_progress" }, - { content: "Phase 3: Final Validation", status: "pending" }, - { content: "Phase 4: Generate Report", status: "pending" } - ] - }) - ``` - -3. **Execute & Iterate** (Phase 3 cont.) - ```javascript - Skill(skill="workflow:test-cycle-execute") - - // test-cycle-execute handles: - // - Execute tests - // - Analyze failures - // - Generate fix tasks via CLI - // - Iterate fixes until pass - ``` - -4. **Generate Report** (Phase 5) - ---- - -### Mode 3: Bidirectional Verification - -**Best For**: Complex systems, multi-dimensional analysis - -**Workflow**: ``` -User Input → Session Init → Parallel execution: - ┌──────────────────────────────┐ - │ │ - ↓ ↓ - /workflow:debug-with-file /workflow:test-fix-gen - │ │ - Generate hypotheses & understanding Generate test tasks - │ │ - ↓ ↓ - Apply debug fixes /workflow:test-cycle-execute - │ │ - └──────────────┬───────────────┘ - ↓ - Phase 4: Merge Findings - ├─ Converge root cause analyses - ├─ Identify consistency (mutual validation) - ├─ Identify conflicts (need coordination) - └─ Generate unified report +Command Error → Update status (failed) → Ask User: + - Retry → Re-execute (same index) + - Skip → Continue next command + - Abort → Stop execution ``` -**Execution Steps**: +#### CLI Mode Escalation -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}"`) - - // Start test generation - const testTask = Skill(skill="workflow:test-fix-gen", args=`"${bug_description}"`) - - // Execute test cycle - const testCycleTask = Skill(skill="workflow:test-cycle-execute") - ``` - -2. **Merge Findings** (Phase 4) - ```javascript - // Read debug results - const understandingMd = Read(`${debugSessionFolder}/understanding.md`) - const hypothesesJson = JSON.parse(Read(`${debugSessionFolder}/hypotheses.json`)) - - // Read test results - const testResultsJson = JSON.parse(Read(`${testSessionFolder}/.process/test-results.json`)) - const fixPlanJson = JSON.parse(Read(`${testSessionFolder}/.task/IMPL-002.json`)) - - // Merge analysis - const convergence = { - debug_root_cause: hypothesesJson.confirmed_hypothesis, - test_failure_pattern: testResultsJson.failures, - consistency: analyzeConsistency(debugRootCause, testFailures), - conflicts: identifyConflicts(debugRootCause, testFailures), - unified_root_cause: mergeRootCauses(debugRootCause, testFailures), - recommended_fix: selectBestFix(debugRootCause, testRootCause) - } - ``` - -3. **Generate Report** (Phase 5) - ``` - ## Bidirectional Verification Workflow Completed - - **Issue**: [bug_description] - **Mode**: Bidirectional Verification - - ### Debug Findings - - Root Cause (hypothesis): [from understanding.md] - - Confidence: [from hypotheses.json] - - Key code paths: [file:line] - - ### Test Findings - - Failure pattern: [list of failing tests] - - Error type: [error type] - - Impact scope: [affected modules] - - ### Merged Analysis - - ✓ Consistent: Both workflows identified same root cause - - ⚠ Conflicts: [list any conflicts] - - → Unified Root Cause: [final confirmed root cause] - - ### Recommended Fix - - Strategy: [selected fix strategy] - - Rationale: [why this strategy] - - Risks: [known risks] - ``` - ---- - -## Command Line Interface - -### Complete Syntax - -```bash -/ccw-debug [OPTIONS] - -Options: - --mode Execution mode (default: debug) - --yes, -y Auto mode (skip all confirmations) - --hotfix, -h Production hotfix mode (only for debug mode) - --no-tests Skip test generation in debug-first mode - --skip-report Don't generate final report - --resume Resume interrupted session - -Arguments: - Issue description, error message, or .md file path ``` - -### Examples - -```bash -# CLI quick mode: fastest, recommendation-only (NEW!) -/ccw-debug --mode cli "User login timeout" -/ccw-debug --mode cli --yes "Quick fix: API 500 error" # Auto-apply if high confidence - -# Debug first (default) -/ccw-debug "User login timeout" - -# Test first -/ccw-debug --mode test "Payment validation failure" - -# Bidirectional verification -/ccw-debug --mode bidirectional "Multi-module data consistency issue" - -# Hotfix auto mode -/ccw-debug --hotfix --yes "API 500 error" - -# Debug first, skip tests -/ccw-debug --no-tests "Understand code flow" - -# Resume interrupted session -/ccw-debug --resume CCWD-login-timeout-2025-01-27 +CLI Result → Findings.confidence? + ↓ + High → Present findings → User decides: + • Done (end here) + • Escalate to debug mode + • Escalate to test mode + ↓ + Low → Recommend escalation ``` --- -## Session Structure - -### File Organization +## Execution Flow Summary ``` -.workflow/.ccw-debug/CCWD-{slug}-{date}/ -├── mode-config.json # Mode configuration and flags -├── session-manifest.json # Session index and status -├── final-report.md # Final report -│ -├── debug/ # Debug workflow (if mode includes debug) -│ ├── debug-session-id.txt -│ ├── understanding.md -│ ├── hypotheses.json -│ └── debug.log -│ -├── test/ # Test workflow (if mode includes test) -│ ├── test-session-id.txt -│ ├── IMPL_PLAN.md -│ ├── test-results.json -│ └── iteration-state.json -│ -└── fusion/ # Fusion analysis (bidirectional mode) - ├── convergence-analysis.json - ├── consistency-report.md - └── unified-root-cause.json +User Input + | +Phase 1: Analyze Issue + |-- Extract: description, error_type, clarity, complexity, scope + +-- If clarity < 2 -> Phase 1.5: Clarify Issue + | +Phase 2: Select Debug Strategy & Build Chain + |-- Detect mode: cli | debug | test | bidirectional + |-- Build command chain based on mode + |-- Parallel execution for bidirectional + +-- Consider escalation points (cli → debug/test) + | +Phase 3: User Confirmation (optional) + |-- Show debug strategy + +-- Allow mode change + | +Phase 4: Setup TODO Tracking & Status File + |-- Create todos with CCWD prefix + +-- Initialize .workflow/.ccw-debug/{session_id}/status.json + | +Phase 5: Execute Debug Chain + |-- For sequential modes: execute commands in order + |-- For bidirectional: execute debug + test in parallel + |-- CLI mode: present findings, ask for escalation + |-- Merge findings (bidirectional mode) + +-- Update status and TODO ``` -### Session State Management +--- -**Status JSON Location**: `.workflow/.ccw-debug/{session_id}/status.json` +## Debug Pipeline Examples -**Status JSON Structure**: +| Issue | Mode | Pipeline | +|-------|------|----------| +| "Login timeout error (quick)" | cli | ccw cli → analysis → (escalate or done) | +| "User login fails intermittently" | debug | debug-with-file → test-gen → test-cycle | +| "Authentication tests failing" | test | test-fix-gen → test-cycle-execute | +| "Multi-module auth + db sync issue" | bidirectional | (debug ∥ test) → merge findings | + +**Legend**: `∥` = parallel execution + +--- + +## State Management + +### Dual Tracking System + +**1. TodoWrite-Based Tracking** (UI Display): + +``` +// Initial state (debug mode) +CCWD:debug: [1/3] /workflow:debug-with-file [in_progress] +CCWD:debug: [2/3] /workflow:test-fix-gen [pending] +CCWD:debug: [3/3] /workflow:test-cycle-execute [pending] + +// CLI mode: only 1 command +CCWD:cli: [1/1] ccw cli --mode analysis [in_progress] + +// Bidirectional mode +CCWD:bidirectional: [1/3] /workflow:debug-with-file [in_progress] ∥ +CCWD:bidirectional: [2/3] /workflow:test-fix-gen [in_progress] ∥ +CCWD:bidirectional: [3/3] /workflow:test-cycle-execute [in_progress] +CCWD:bidirectional: [4/4] merge-findings [pending] +``` + +**2. Status.json Tracking**: Persistent state for debug monitoring. + +**Location**: `.workflow/.ccw-debug/{session_id}/status.json` + +**Structure**: ```json { - "session_id": "CCWD-login-timeout-2025-01-27", - "mode": "debug|test|bidirectional|cli", - "status": "running|completed|failed|paused", - "created_at": "2025-01-27T10:30:00Z", - "updated_at": "2025-01-27T10:35:00Z", - "bug_description": "User login timeout after 30 seconds", + "session_id": "CCWD-auth-timeout-2025-02-02", + "mode": "debug", + "status": "running|completed|failed", + "parallel_execution": false, + "created_at": "2025-02-02T10:00:00Z", + "updated_at": "2025-02-02T10:05:00Z", + "issue": { + "description": "User login timeout after 30 seconds", + "error_type": "async", + "clarity": 3, + "complexity": "medium" + }, "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" } + { "index": 0, "command": "/workflow:debug-with-file", "unit": "sequential", "status": "completed" }, + { "index": 1, "command": "/workflow:test-fix-gen", "unit": "sequential", "status": "in_progress" }, + { "index": 2, "command": "/workflow:test-cycle-execute", "unit": "sequential", "status": "pending" } ], "current_index": 1, - "sub_sessions": { - "debug_session": "DBG-...", - "test_session": "WFS-test-..." - }, - "artifacts": { - "debug_understanding": "...", - "test_results": "...", - "fusion_analysis": "..." + "findings": { + "debug": { "root_cause": "...", "confidence": "high" }, + "test": { "failure_pattern": "..." }, + "merged": null } } ``` -**Session ID Output**: When session starts, ccw-debug outputs: -``` -📋 Session Started: CCWD-login-timeout-2025-01-27 -``` +**Status Values**: +- `running`: Debug workflow in progress +- `completed`: Debug finished, fix applied +- `failed`: Debug aborted or unfixable -This output is captured by hooks for status.json path matching. +**Mode-Specific Fields**: +- `cli` mode: No findings field (recommendation-only) +- `debug`/`test`: Single finding source +- `bidirectional`: All three findings + merged result --- -## Mode Selection Logic +## Key Design Principles -### Auto Mode Recommendation +1. **Issue-Focused** - Diagnose root cause, not symptoms +2. **Mode-Driven** - 4 debug strategies for different issues +3. **Parallel Capability** - Bidirectional mode for complex systems +4. **Escalation Support** - CLI → debug/test mode progression +5. **Quick Diagnosis** - CLI mode for immediate recommendations +6. **TODO Tracking** - Use CCWD prefix to isolate debug todos +7. **Finding Convergence** - Merge parallel results for consensus +--- -When user doesn't specify `--mode`, recommend based on input analysis: +## Usage -```javascript -function recommendMode(bugDescription) { - const indicators = { - cli_signals: [ - /quick|fast|simple|immediate/, - /recommendation|suggest|advice/, - /just need|only want|quick look/, - /straightforward|obvious|clear/ - ], - debug_signals: [ - /unclear|don't know|maybe|uncertain|why/, - /error|crash|fail|exception|stack trace/, - /execution flow|code path|how does/ - ], - test_signals: [ - /test|coverage|verify|pass|fail/, - /implementation|implemented|complete/, - /case|scenario|should/ - ], - complex_signals: [ - /multiple|all|system|integration/, - /module|subsystem|network|distributed/, - /concurrent|async|race/ - ] - } +```bash +# Auto-select mode +/ccw-debug "Login failed: token validation error" - let score = { cli: 0, debug: 0, test: 0, bidirectional: 0 } +# Explicit mode selection +/ccw-debug --mode cli "Quick diagnosis: API 500 error" +/ccw-debug --mode debug "User profile sync intermittent failure" +/ccw-debug --mode test "Permission check failing" +/ccw-debug --mode bidirectional "Multi-module auth + cache sync issue" - // CLI signals (lightweight preference) - for (const pattern of indicators.cli_signals) { - if (pattern.test(bugDescription)) score.cli += 3 - } +# Auto mode (skip confirmations) +/ccw-debug --yes "Production hotfix: database connection timeout" - // Debug signals - for (const pattern of indicators.debug_signals) { - if (pattern.test(bugDescription)) score.debug += 2 - } - - // Test signals - for (const pattern of indicators.test_signals) { - if (pattern.test(bugDescription)) score.test += 2 - } - - // Complex signals (prefer bidirectional for complex issues) - for (const pattern of indicators.complex_signals) { - if (pattern.test(bugDescription)) { - score.bidirectional += 3 - score.cli -= 2 // Complex issues not suitable for CLI quick - } - } - - // If description is short and has clear error, prefer CLI - if (bugDescription.length < 100 && /error|fail|crash/.test(bugDescription)) { - score.cli += 2 - } - - // Return highest scoring mode - return Object.entries(score).sort((a, b) => b[1] - a[1])[0][0] -} +# Resume or escalate from previous session +/ccw-debug --mode debug --source-session CCWD-login-timeout-2025-01-27 ``` --- -## Best Practices - -### When to Use Each Mode - -| Issue Characteristic | Recommended Mode | Rationale | -|----------------------|-----------------|-----------| -| Simple error, clear symptoms | CLI Quick | Fastest recommendation | -| Incomplete error info, requires exploration | Debug First | Deep diagnostic capability | -| Code complete, needs test coverage | Test First | Automated iterative fixes | -| Cross-module issue, ambiguous symptoms | Bidirectional | Multi-angle insights | -| Production failure, needs immediate guidance | CLI Quick + --yes | Fastest guidance, optional escalation | -| Production failure, needs safe fix | Debug First + --hotfix | Minimal diagnosis time | -| Want to understand why it failed | Debug First | Records understanding evolution | -| Want to ensure all scenarios pass | Test First | Complete coverage-driven | - -### Performance Tips - -- **CLI Quick**: 2-5 minutes, no file I/O, recommendation-only -- **Debug First**: Usually requires manual issue reproduction (after logging added), then 15-30 min -- **Test First**: Fully automated, 20-45 min depending on test suite size -- **Bidirectional**: Most comprehensive but slowest (parallel workflows), 30-60 min - -### Workflow Continuity - -- **CLI Quick**: Can escalate to debug/test/apply fix based on user decision -- **Debug First**: Auto-launches test generation and execution after completion -- **Test First**: With high failure rates suggests switching to debug mode for root cause -- **Bidirectional**: Always executes complete flow - ---- - -## Follow-up Expansion - -After completion, offer to expand to issues: +## Mode Selection Decision Tree ``` -## Done! What's next? +User calls: /ccw-debug "issue description" -- [ ] Create Test issue (improve test coverage) -- [ ] Create Enhancement issue (optimize code quality) -- [ ] Create Refactor issue (improve architecture) -- [ ] Create Documentation issue (record learnings) -- [ ] Don't create any issue, end workflow -``` - -Selected items call: `/issue:new "{issue summary} - {dimension}"` - ---- - -## Error Handling - -| Error | CLI Quick | Debug First | Test First | Bidirectional | -|-------|-----------|-------------|-----------|---------------| -| Session creation failed | N/A (no session) | Retry → abort | Retry → abort | Retry → abort | -| CLI analysis failed | Retry with fallback tool → manual | N/A | N/A | N/A | -| Diagnosis/test failed | N/A | Continue with partial results | Direct failure | Use alternate workflow results | -| Low confidence result | Ask escalate or review | N/A | N/A | N/A | -| Merge conflicts | N/A | N/A | N/A | Select highest confidence plan | -| Fix application failed | Report error, no auto-retry | Request manual fix | Mark failed, request intervention | Try alternative plan | - ---- - -## Relationship with ccw Command - -| Feature | ccw | ccw-debug | -|---------|-----|----------| -| **Design** | General workflow orchestration | Debug + test aggregation | -| **Intent Detection** | ✅ Detects task type | ✅ Detects issue type | -| **Automation** | ✅ Auto-selects workflow | ✅ Auto-selects mode | -| **Quick Mode** | ❌ None | ✅ CLI Quick (2-5 min) | -| **Parallel Execution** | ❌ Sequential | ✅ Bidirectional mode parallel | -| **Fusion Analysis** | ❌ None | ✅ Bidirectional mode fusion | -| **Workflow Scope** | Broad (feature/bugfix/tdd/ui etc.) | Deep focus (debug + test) | -| **CLI Integration** | Yes | Yes (4 levels: quick/deep/iterative/fusion) | - ---- - -## Usage Recommendations (Requires User Confirmation) - -**Use `Skill(skill="ccw-debug", args="\"bug description\"")` when:** -- First time: Use default mode (debug-first), observe workflow - -**Use `Skill(skill="ccw-debug", args="--mode cli \"issue\"")` when:** -- Quick Decision: Immediate recommendations without full workflow - -**Use `Skill(skill="ccw-debug", args="--hotfix --yes \"issue\"")` when:** -- Quick Fix: Minimal diagnostics for production issues - -**Use `Skill(skill="ccw-debug", args="--mode debug \"issue\"")` when:** -- Learning: Read `understanding.md` for debugging insights - -**Use `Skill(skill="ccw-debug", args="--mode bidirectional \"issue\"")` when:** -- Complete Validation: Multi-dimensional insights from parallel workflows - -**Use `Skill(skill="ccw-debug", args="--mode test \"issue\"")` when:** -- Auto Repair: Automatic iteration with test-first approach - -**Use `Skill(skill="ccw-debug", args="--mode cli \"issue\"")` when:** -- Escalation: Start with CLI Quick, then escalate to other modes as needed - ---- - -## Reference - -### Related Commands - -- `ccw cli` - Direct CLI analysis (used by CLI Quick mode) -- `/workflow:debug-with-file` - Deep debug diagnostics -- `/workflow:test-fix-gen` - Test generation -- `/workflow:test-cycle-execute` - Test execution -- `/workflow:lite-fix` - Lightweight fix -- `/ccw` - General workflow orchestration - -### Configuration Files - -- `~/.claude/cli-tools.json` - CLI tool configuration (Gemini/Qwen/Codex) -- `.workflow/project-tech.json` - Project technology stack -- `.workflow/project-guidelines.json` - Project conventions - -### CLI Tool Fallback Chain (for CLI Quick mode) - -When CLI analysis fails, fallback order: -1. **Gemini** (primary): `gemini-2.5-pro` -2. **Qwen** (fallback): `coder-model` -3. **Codex** (fallback): `gpt-5.2` - ---- - -## Summary: Mode Selection Decision Tree - -``` -User calls: /ccw-debug - -┌─ Explicit --mode specified? -│ ├─ YES → Use specified mode -│ │ ├─ cli → 2-5 min analysis, optionally escalate -│ │ ├─ debug → Full debug-with-file workflow -│ │ ├─ test → Test-first workflow -│ │ └─ bidirectional → Parallel debug + test -│ │ -│ └─ NO → Auto-recommend based on bug description -│ ├─ Keywords: "quick", "fast", "simple" → CLI Quick -│ ├─ Keywords: "error", "crash", "exception" → Debug First (or CLI if simple) -│ ├─ Keywords: "test", "verify", "coverage" → Test First -│ └─ Keywords: "multiple", "system", "distributed" → Bidirectional +├─ Keywords: "quick", "fast", "recommendation" +│ └─ Mode: CLI (2-5 min analysis, optional escalation) │ -├─ Check --yes flag -│ ├─ YES → Auto-confirm all decisions -│ │ ├─ CLI mode: Auto-apply if confidence High -│ │ └─ Others: Auto-select default options -│ │ -│ └─ NO → Interactive mode, ask user for confirmations +├─ Keywords: "test", "fail", "coverage" +│ └─ Mode: Test (automated iteration, ≥95% pass) │ -├─ Check --hotfix flag (debug mode only) -│ ├─ YES → Minimal diagnostics, fast fix -│ └─ NO → Full analysis +├─ Keywords: "multiple", "system", "distributed" +│ └─ Mode: Bidirectional (parallel debug + test) │ -└─ Execute selected mode workflow - └─ Return results or escalation options +└─ Default → Debug (full hypothesis-driven workflow) ``` diff --git a/.claude/commands/ccw-plan.md b/.claude/commands/ccw-plan.md new file mode 100644 index 00000000..b1875d9d --- /dev/null +++ b/.claude/commands/ccw-plan.md @@ -0,0 +1,456 @@ +--- +name: ccw-plan +description: Planning coordinator - analyze requirements, select planning strategy, execute planning workflow in main process +argument-hint: "[--mode lite|multi-cli|full|plan-verify|replan|cli|issue|rapid-to-issue|brainstorm-with-file|analyze-with-file] [--yes|-y] \"task description\"" +allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*) +--- + +# CCW-Plan Command - Planning Coordinator + +Planning orchestrator: requirement analysis → strategy selection → planning execution. + +## Core Concept: Planning Units (规划单元) + +**Definition**: Planning commands are grouped into logical units based on verification requirements and collaboration strategies. + +**Planning Units**: + +| Unit Type | Pattern | Example | +|-----------|---------|---------| +| **Quick Planning** | plan-cmd (no verify) | lite-plan | +| **Verified Planning** | plan-cmd → verify-cmd | plan → plan-verify | +| **Collaborative Planning** | multi-cli-plan (implicit verify) | multi-cli-plan | +| **With-File Planning** | brainstorm-with-file or analyze-with-file | brainstorm + plan options | +| **CLI-Assisted Planning** | ccw cli (analysis) → recommendations | quick analysis + decision | +| **Issue Workflow Planning** | plan → issue workflow (discover/queue/execute) | rapid-to-issue bridge | + +**Atomic Rules**: +1. Lite mode: No verification (fast iteration) +2. Plan-verify mode: Mandatory quality gate +3. Multi-cli/Full mode: Optional verification (via --skip-verify flag) +4. With-File modes: Self-contained iteration with built-in post-completion options +5. CLI mode: Quick analysis, user-driven decisions +6. Issue modes: Planning integrated into issue workflow lifecycle + +## Execution Model + +**Synchronous (Main Process)**: Planning commands execute via Skill, blocking until complete. + +``` +User Input → Analyze Requirements → Select Strategy → [Confirm] → Execute Planning + ↓ + Skill (blocking) + ↓ + Update TodoWrite + ↓ + Generate Artifacts +``` + +## 5-Phase Workflow + +### Phase 1: Analyze Requirements + +**Input** → Extract (goal, scope, constraints) → Assess (complexity, clarity, criticality) → **Analysis** + +| Field | Values | +|-------|--------| +| complexity | low \| medium \| high | +| clarity | 0-3 (≥2 = clear) | +| criticality | normal \| high \| critical | +| scope | single-module \| cross-module \| system \| batch-issues | + +**Output**: `Type: [task_type] | Goal: [goal] | Complexity: [complexity] | Clarity: [clarity]/3 | Criticality: [criticality]` + +--- + +### Phase 1.5: Requirement Clarification (if clarity < 2) + +``` +Analysis → Check clarity ≥ 2? + ↓ + YES → Continue to Phase 2 + ↓ + NO → Ask Questions → Update Analysis +``` + +**Questions Asked**: Goal (Create/Fix/Optimize/Analyze), Scope (Single file/Module/Cross-module/System), Constraints (Backward compat/Skip tests/Urgent hotfix) + +--- + +### Phase 2: Select Planning Strategy & Build Command Chain + +``` +Analysis → Detect Mode (keywords) → Build Command Chain → Planning Workflow +``` + +#### Mode Detection (Priority Order) + +``` +Input Keywords → Mode +─────────────────────────────────────────────────────────────────────────────── +quick|fast|immediate|recommendation|suggest → cli +issues?|batch|issue workflow|structured workflow|queue → issue +issue transition|rapid.*issue|plan.*issue|convert.*issue → rapid-to-issue +brainstorm|ideation|头脑风暴|创意|发散思维|multi-perspective → brainstorm-with-file +analyze.*document|explore.*concept|collaborative analysis → analyze-with-file +production|critical|payment|auth → plan-verify +adjust|modify|change plan → replan +uncertain|explore → full +complex|multiple module|integrate → multi-cli +(default) → lite +``` + +#### Command Chain Mapping + +| Mode | Command Chain | Verification | Use Case | +|------|---------------|--------------|----------| +| **cli** | ccw cli --mode analysis --rule planning-* | None | Quick planning recommendation | +| **issue** | /issue:discover → /issue:plan → /issue:queue → /issue:execute | Optional | Batch issue planning & execution | +| **rapid-to-issue** | lite-plan → /issue:convert-to-plan → queue → execute | Optional | Quick planning → Issue workflow bridge | +| **brainstorm-with-file** | /workflow:brainstorm-with-file → (plan/issue options) | Self-contained | Multi-perspective ideation | +| **analyze-with-file** | /workflow:analyze-with-file → (plan/issue options) | Self-contained | Collaborative architecture analysis | +| **lite** | lite-plan | None | Fast simple planning | +| **multi-cli** | multi-cli-plan → [plan-verify] | Optional | Multi-model collaborative planning | +| **full** | brainstorm → plan → [plan-verify] | Optional | Comprehensive brainstorm + planning | +| **plan-verify** | plan → **plan-verify** | **Mandatory** | Production/critical features | +| **replan** | replan | None | Plan refinement/adjustment | + +**Note**: +- `[ ]` = optional verification +- **bold** = mandatory quality gate +- With-File modes include built-in post-completion options to create plans/issues + +**Output**: `Mode: [mode] | Strategy: [strategy] | Commands: [1. /cmd1 2. /cmd2]` + +--- + +### Phase 3: User Confirmation + +``` +Planning Chain → Show Strategy → Ask User → User Decision: +- ✓ Confirm → Continue to Phase 4 +- ⚙ Adjust → Change Mode (back to Phase 2) +- ✗ Cancel → Abort +``` + +--- + +### Phase 4: Setup TODO Tracking & Status File + +``` +Planning Chain → Create Session Dir → Initialize Tracking → Tracking State +``` + +**Session Structure**: +``` +Session ID: CCWP-{goal-slug}-{date} +Session Dir: .workflow/.ccw-plan/{session_id}/ + +TodoWrite: + CCWP:{mode}: [1/n] /command1 [in_progress] + CCWP:{mode}: [2/n] /command2 [pending] + ... + +status.json: + { + "session_id": "CCWP-...", + "mode": "plan-verify", + "status": "running", + "command_chain": [...], + "quality_gate": "pending" // plan-verify mode only + } +``` + +**Output**: +- TODO: `-> CCWP:plan-verify: [1/2] /workflow:plan | ...` +- Status File: `.workflow/.ccw-plan/{session_id}/status.json` + +--- + +### Phase 5: Execute Planning Chain + +``` +Start Command → Update status (running) → Execute via Skill → Result +``` + +#### For Plan-Verify Mode (Quality Gate) + +``` +Quality Gate → PASS → Mark completed → Next command + ↓ FAIL (plan-verify mode) + Ask User → Refine: replan + re-verify + → Override: continue anyway + → Abort: stop planning +``` + +#### Error Handling Pattern + +``` +Command Error → Update status (failed) → Ask User: + - Retry → Re-execute (same index) + - Skip → Continue next command + - Abort → Stop execution +``` + +--- + +## Planning Pipeline Examples + +| Input | Mode | Pipeline | Use Case | +|-------|------|----------|----------| +| "Quick: should we use OAuth2?" | cli | ccw cli --mode analysis → recommendation | Immediate planning advice | +| "Plan user login system" | lite | lite-plan | Fast simple planning | +| "Implement OAuth2 auth" | multi-cli | multi-cli-plan → [plan-verify] | Multi-model collaborative planning | +| "Design notification system" | full | brainstorm → plan → [plan-verify] | Comprehensive brainstorm + planning | +| "Payment processing (prod)" | plan-verify | plan → **plan-verify** | Production critical (mandatory gate) | +| "头脑风暴: 用户通知系统重新设计" | brainstorm-with-file | brainstorm-with-file → (plan/issue options) | Multi-perspective ideation | +| "协作分析: 认证架构设计决策" | analyze-with-file | analyze-with-file → (plan/issue options) | Collaborative analysis | +| "Batch plan: handle 10 pending issues" | issue | /issue:discover → plan → queue → execute | Batch issue planning | +| "Plan and create issues" | rapid-to-issue | lite-plan → convert-to-plan → queue → execute | Quick plan → Issue workflow | +| "Update existing plan" | replan | replan | Plan refinement/adjustment | + +**Legend**: +- `[ ]` = optional verification +- **bold** = mandatory quality gate +- **With-File modes** include built-in post-completion options to create plans/issues + +--- + +## State Management + +### Dual Tracking System + +**1. TodoWrite-Based Tracking** (UI Display): + +``` +// Plan-verify mode (mandatory quality gate) +CCWP:plan-verify: [1/2] /workflow:plan [in_progress] +CCWP:plan-verify: [2/2] /workflow:plan-verify [pending] + +// CLI mode (quick recommendations) +CCWP:cli: [1/1] ccw cli --mode analysis [in_progress] + +// Issue mode (batch planning) +CCWP:issue: [1/4] /issue:discover [in_progress] +CCWP:issue: [2/4] /issue:plan [pending] +CCWP:issue: [3/4] /issue:queue [pending] +CCWP:issue: [4/4] /issue:execute [pending] + +// Rapid-to-issue mode (planning → issue bridge) +CCWP:rapid-to-issue: [1/4] /workflow:lite-plan [in_progress] +CCWP:rapid-to-issue: [2/4] /issue:convert-to-plan [pending] +CCWP:rapid-to-issue: [3/4] /issue:queue [pending] +CCWP:rapid-to-issue: [4/4] /issue:execute [pending] + +// Brainstorm-with-file mode (self-contained) +CCWP:brainstorm-with-file: [1/1] /workflow:brainstorm-with-file [in_progress] + +// Analyze-with-file mode (self-contained) +CCWP:analyze-with-file: [1/1] /workflow:analyze-with-file [in_progress] + +// Lite mode (fast simple planning) +CCWP:lite: [1/1] /workflow:lite-plan [in_progress] + +// Multi-CLI mode (collaborative planning) +CCWP:multi-cli: [1/1] /workflow:multi-cli-plan [in_progress] + +// Full mode (brainstorm + planning with optional verification) +CCWP:full: [1/2] /workflow:brainstorm [in_progress] +CCWP:full: [2/2] /workflow:plan [pending] +``` + +**2. Status.json Tracking**: Persistent state for planning monitoring. + +**Location**: `.workflow/.ccw-plan/{session_id}/status.json` + +**Structure**: +```json +{ + "session_id": "CCWP-oauth-auth-2025-02-02", + "mode": "plan-verify", + "status": "running|completed|failed", + "created_at": "2025-02-02T10:00:00Z", + "updated_at": "2025-02-02T10:05:00Z", + "analysis": { + "goal": "Implement OAuth2 authentication", + "complexity": "high", + "clarity_score": 2, + "criticality": "high" + }, + "command_chain": [ + { "index": 0, "command": "/workflow:plan", "mandatory": false, "status": "completed" }, + { "index": 1, "command": "/workflow:plan-verify", "mandatory": true, "status": "running" } + ], + "current_index": 1, + "quality_gate": "pending|PASS|FAIL" +} +``` + +**Status Values**: +- `running`: Planning in progress +- `completed`: Planning finished successfully +- `failed`: Planning aborted or quality gate failed + +**Quality Gate Values** (plan-verify mode only): +- `pending`: Verification not started +- `PASS`: Plan meets quality standards +- `FAIL`: Plan needs refinement + +**Mode-Specific Fields**: +- **plan-verify**: `quality_gate` field (pending|PASS|FAIL) +- **cli**: No command_chain, stores CLI recommendations and user decision +- **issue**: includes issue discovery results and queue configuration +- **rapid-to-issue**: includes plan output and conversion to issue +- **with-file modes**: stores session artifacts and post-completion options +- **other modes**: basic command_chain tracking + +--- + +## Extended Planning Modes + +### CLI-Assisted Planning (cli mode) + +``` +Quick Input → ccw cli --mode analysis --rule planning-* → Recommendations → User Decision: +- ✓ Accept → Create lite-plan from recommendations +- ↗ Escalate → Switch to multi-cli or full mode +- ✗ Done → Stop (recommendation only) +``` + +**Use Cases**: +- Quick architecture decision questions +- Planning approach recommendations +- Pattern/library selection advice + +**CLI Rules** (auto-selected based on context): +- `planning-plan-architecture-design` - Architecture decisions +- `planning-breakdown-task-steps` - Task decomposition +- `planning-design-component-spec` - Component specifications + +--- + +### With-File Planning Workflows + +**With-File workflows** provide documented exploration with multi-CLI collaboration, generating comprehensive session artifacts. + +| Mode | Purpose | Key Features | Output Folder | +|------|---------|--------------|---------------| +| **brainstorm-with-file** | Multi-perspective ideation | Gemini/Codex/Claude perspectives, diverge-converge | `.workflow/.brainstorm/` | +| **analyze-with-file** | Collaborative architecture analysis | Multi-round Q&A, CLI exploration, documented discussions | `.workflow/.analysis/` | + +**Detection Keywords**: +- **brainstorm-with-file**: 头脑风暴, 创意, 发散思维, multi-perspective, ideation +- **analyze-with-file**: 协作分析, 深度理解, collaborative analysis, explore concept + +**Characteristics**: +1. **Self-Contained**: Each workflow handles its own iteration loop +2. **Documented Process**: Creates evolving documents (brainstorm.md, discussion.md) +3. **Multi-CLI**: Uses Gemini/Codex/Claude for different perspectives +4. **Built-in Post-Completion**: Offers follow-up options (create plan, create issue, deep dive) + +--- + +### Issue Workflow Integration + +| Mode | Purpose | Command Chain | Typical Use | +|------|---------|---------------|-------------| +| **issue** | Batch issue planning | discover → plan → queue → execute | Multiple issues in codebase | +| **rapid-to-issue** | Quick plan → Issue workflow | lite-plan → convert-to-plan → queue → execute | Fast iteration → structured execution | + +**Issue Workflow Bridge**: +``` +lite-plan (in-memory) → /issue:convert-to-plan → Creates issue JSON + ↓ + /issue:queue → Form execution queue + ↓ + /issue:execute → DAG-based parallel execution +``` + +**When to use Issue Workflow**: +- Need structured multi-stage execution (queue-based) +- Want parallel DAG execution +- Multiple related changes as individual commits +- Converting brainstorm/plan output to executable tasks + +--- + +## Key Design Principles + +1. **Planning-Focused** - Pure planning coordination, no execution +2. **Mode-Driven** - 10 planning modes for different needs (lite/multi-cli/full/plan-verify/replan + cli/issue/rapid-to-issue/brainstorm-with-file/analyze-with-file) +3. **CLI Integration** - Quick analysis for immediate recommendations +4. **With-File Support** - Multi-CLI collaboration with documented artifacts +5. **Issue Workflow Bridge** - Seamless transition from planning to structured execution +6. **Quality Gates** - Mandatory verification for production features +7. **Flexible Verification** - Optional for exploration, mandatory for critical features +8. **Progressive Clarification** - Low clarity triggers requirement questions +9. **TODO Tracking** - Use CCWP prefix to isolate planning todos +10. **Handoff Ready** - Generates artifacts ready for execution phase + +--- + +## Usage + +```bash +# Auto-select mode (keyword-based detection) +/ccw-plan "Add user authentication" + +# Standard planning modes +/ccw-plan --mode lite "Add logout endpoint" +/ccw-plan --mode multi-cli "Implement OAuth2" +/ccw-plan --mode full "Design notification system" +/ccw-plan --mode plan-verify "Payment processing (production)" +/ccw-plan --mode replan --session WFS-auth-2025-01-28 + +# CLI-assisted planning (quick recommendations) +/ccw-plan --mode cli "Quick: should we use OAuth2 or JWT?" +/ccw-plan --mode cli "Which state management pattern for React app?" + +# With-File workflows (multi-CLI collaboration) +/ccw-plan --mode brainstorm-with-file "头脑风暴: 用户通知系统重新设计" +/ccw-plan --mode analyze-with-file "协作分析: 认证架构的设计决策" + +# Issue workflow integration +/ccw-plan --mode issue "Batch plan: handle all pending security issues" +/ccw-plan --mode rapid-to-issue "Plan user profile feature and create issue" + +# Auto mode (skip confirmations) +/ccw-plan --yes "Quick feature: user profile endpoint" +``` + +--- + +## Mode Selection Decision Tree + +``` +User calls: /ccw-plan "task description" + +├─ Keywords: "quick", "fast", "recommendation" +│ └─ Mode: CLI (quick analysis → recommendations) +│ +├─ Keywords: "issue", "batch", "queue" +│ └─ Mode: Issue (batch planning → execution queue) +│ +├─ Keywords: "plan.*issue", "rapid.*issue" +│ └─ Mode: Rapid-to-Issue (lite-plan → issue bridge) +│ +├─ Keywords: "头脑风暴", "brainstorm", "ideation" +│ └─ Mode: Brainstorm-with-file (multi-CLI ideation) +│ +├─ Keywords: "协作分析", "analyze.*document" +│ └─ Mode: Analyze-with-file (collaborative analysis) +│ +├─ Keywords: "production", "critical", "payment" +│ └─ Mode: Plan-Verify (mandatory quality gate) +│ +├─ Keywords: "adjust", "modify", "change plan" +│ └─ Mode: Replan (refine existing plan) +│ +├─ Keywords: "uncertain", "explore" +│ └─ Mode: Full (brainstorm → plan → [verify]) +│ +├─ Keywords: "complex", "multiple module" +│ └─ Mode: Multi-CLI (collaborative planning) +│ +└─ Default → Lite (fast simple planning) +``` diff --git a/.claude/commands/ccw-test.md b/.claude/commands/ccw-test.md new file mode 100644 index 00000000..aec81a97 --- /dev/null +++ b/.claude/commands/ccw-test.md @@ -0,0 +1,387 @@ +--- +name: ccw-test +description: Test coordinator - analyze testing needs, select test strategy, execute test workflow in main process +argument-hint: "[--mode gen|fix|verify|tdd] [--yes|-y] \"test description\"" +allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Bash(*) +--- + +# CCW-Test Command - Test Coordinator + +Test orchestrator: testing needs analysis → strategy selection → test execution. + +## Core Concept: Test Units (测试单元) + +**Definition**: Test commands grouped into logical units based on testing objectives. + +**Test Units**: + +| Unit Type | Pattern | Example | +|-----------|---------|---------| +| **Generation Only** | test-gen (no execution) | test-fix-gen | +| **Test + Fix Cycle** | test-gen → test-execute-fix | test-fix-gen → test-cycle-execute | +| **Verification Only** | existing-tests → execute | execute-tests | +| **TDD Cycle** | tdd-plan → tdd-execute → verify | Red-Green-Refactor | + +**Atomic Rules**: +1. Gen mode: Generate tests only (no execution) +2. Fix mode: Generate + auto-iteration until ≥95% pass +3. Verify mode: Execute existing tests + report +4. TDD mode: Full Red-Green-Refactor cycle compliance + +## Execution Model + +**Synchronous (Main Process)**: Test commands execute via Skill, blocking until complete. + +``` +User Input → Analyze Testing Needs → Select Strategy → [Confirm] → Execute Tests + ↓ + Skill (blocking) + ↓ + Update TodoWrite + ↓ + Generate Tests/Results +``` + +## 5-Phase Workflow + +### Phase 1: Analyze Testing Needs + +**Input** → Extract (description, target_module, existing_tests) → Assess (testing_goal, framework, coverage_target) → **Analysis** + +| Field | Values | +|-------|--------| +| testing_goal | generate \| fix \| verify \| tdd | +| framework | jest \| vitest \| pytest \| ... | +| coverage_target | 0-100 (default: 80) | +| existing_tests | true \| false | + +#### Mode Detection (Priority Order) + +``` +Input Keywords → Mode +───────────────────────────────────────────────────────── +generate|create|write test|need test → gen +fix|repair|failing|broken → fix +verify|validate|check|run test → verify +tdd|test-driven|test first → tdd +(default) → fix +``` + +**Output**: `TestingGoal: [goal] | Mode: [mode] | Target: [module] | Framework: [framework]` + +--- + +### Phase 1.5: Testing Clarification (if needed) + +``` +Analysis → Check testing_goal known? + ↓ + YES → Check target_module set? + ↓ + YES → Continue to Phase 2 + ↓ + NO → Ask Questions → Update Analysis +``` + +**Questions Asked**: Testing Goal, Target Module/Files, Coverage Requirements, Test Framework + +--- + +### Phase 2: Select Test Strategy & Build Command Chain + +``` +Analysis → Detect Mode (keywords) → Build Command Chain → Test Workflow +``` + +#### Command Chain Mapping + +| Mode | Command Chain | Behavior | +|------|---------------|----------| +| **gen** | test-fix-gen | Generate only, no execution | +| **fix** | test-fix-gen → test-cycle-execute (iterate) | Auto-iteration until ≥95% pass or max iterations | +| **verify** | execute-existing-tests → coverage-report | Execute + report only | +| **tdd** | tdd-plan → execute → tdd-verify | Red-Green-Refactor cycle compliance | + +**Note**: `(iterate)` = auto-iteration until pass_rate ≥ 95% or max_iterations reached + +**Output**: `Mode: [mode] | Strategy: [strategy] | Commands: [1. /cmd1 2. /cmd2]` + +--- + +### Phase 3: User Confirmation + +``` +Test Chain → Show Strategy → Ask User → User Decision: +- ✓ Confirm → Continue to Phase 4 +- ⚙ Change Mode → Select Different Mode (back to Phase 2) +- ✗ Cancel → Abort +``` + +--- + +### Phase 4: Setup TODO Tracking & Status File + +``` +Test Chain → Create Session Dir → Initialize Tracking → Tracking State +``` + +**Session Structure**: +``` +Session ID: CCWT-{target-module-slug}-{date} +Session Dir: .workflow/.ccw-test/{session_id}/ + +TodoWrite: + CCWT:{mode}: [1/n] /command1 [in_progress] + CCWT:{mode}: [2/n] /command2 [pending] + ... + +status.json: + { + "session_id": "CCWT-...", + "mode": "gen|fix|verify|tdd", + "status": "running", + "testing": { description, target_module, framework, coverage_target }, + "command_chain": [...], + "test_metrics": { total_tests, passed, failed, pass_rate, iteration_count, coverage } + } +``` + +**Output**: +- TODO: `-> CCWT:fix: [1/2] /workflow:test-fix-gen | CCWT:fix: [2/2] /workflow:test-cycle-execute` +- Status File: `.workflow/.ccw-test/{session_id}/status.json` + +--- + +### Phase 5: Execute Test Chain + +#### For All Modes (Sequential Execution) + +``` +Start Command → Update status (running) → Execute via Skill → Result + ↓ + Update test_metrics → Next Command + ↓ + Error? → YES → Ask Action (Retry/Skip/Abort) + → NO → Continue +``` + +#### For Fix Mode (Auto-Iteration) + +``` +test-fix-gen completes → test-cycle-execute begins + ↓ + Check pass_rate ≥ 95%? + ↓ ↓ + YES → Complete NO → Check iteration < max? + ↓ ↓ + YES → Iteration NO → Complete + | (analyze failures + | generate fix + | re-execute tests) + | + └→ Loop back to pass_rate check +``` + +#### Error Handling Pattern + +``` +Command Error → Update status (failed) → Ask User: + - Retry → Re-execute (same index) + - Skip → Continue next command + - Abort → Stop execution +``` + +#### Test Metrics Update + +``` +After Each Execution → Collect test_metrics: + - total_tests: number + - passed/failed: count + - pass_rate: percentage + - iteration_count: increment (fix mode) + - coverage: line/branch/function + ↓ +Update status.json → Update TODO with iteration info (if fix mode) +``` + +--- + +## Execution Flow Summary + +``` +User Input + | +Phase 1: Analyze Testing Needs + |-- Extract: description, testing_goal, target_module, existing_tests + +-- If unclear -> Phase 1.5: Clarify Testing Needs + | +Phase 2: Select Test Strategy & Build Chain + |-- Detect mode: gen | fix | verify | tdd + |-- Build command chain based on mode + +-- Configure iteration limits (fix mode) + | +Phase 3: User Confirmation (optional) + |-- Show test strategy + +-- Allow mode change + | +Phase 4: Setup TODO Tracking & Status File + |-- Create todos with CCWT prefix + +-- Initialize .workflow/.ccw-test/{session_id}/status.json + | +Phase 5: Execute Test Chain + |-- For each command: + | |-- Update status.json (current=running) + | |-- Execute via Skill + | |-- Test-fix cycle: iterate until ≥95% pass or max iterations + | |-- Update test_metrics in status.json + | +-- Update TODO status + +-- Mark status.json as completed +``` + +--- + +## Test Pipeline Examples + +| Input | Mode | Pipeline | Iteration | +|-------|------|----------|-----------| +| "Generate tests for auth module" | gen | test-fix-gen | No execution | +| "Fix failing authentication tests" | fix | test-fix-gen → test-cycle-execute (iterate) | Max 3 iterations | +| "Run existing test suite" | verify | execute-tests → coverage-report | One-time | +| "Implement user profile with TDD" | tdd | tdd-plan → execute → tdd-verify | Red-Green-Refactor | + +**Legend**: `(iterate)` = auto-iteration until ≥95% pass rate + +--- + +## State Management + +### Dual Tracking System + +**1. TodoWrite-Based Tracking** (UI Display): + +``` +// Initial state (fix mode) +CCWT:fix: [1/2] /workflow:test-fix-gen [in_progress] +CCWT:fix: [2/2] /workflow:test-cycle-execute [pending] + +// During iteration (fix mode, iteration 2/3) +CCWT:fix: [1/2] /workflow:test-fix-gen [completed] +CCWT:fix: [2/2] /workflow:test-cycle-execute [in_progress] (iteration 2/3, pass rate: 78%) + +// Gen mode (no execution) +CCWT:gen: [1/1] /workflow:test-fix-gen [in_progress] + +// Verify mode (one-time) +CCWT:verify: [1/2] execute-existing-tests [in_progress] +CCWT:verify: [2/2] generate-coverage-report [pending] + +// TDD mode (Red-Green-Refactor) +CCWT:tdd: [1/3] /workflow:tdd-plan [in_progress] +CCWT:tdd: [2/3] /workflow:execute [pending] +CCWT:tdd: [3/3] /workflow:tdd-verify [pending] +``` + +**2. Status.json Tracking**: Persistent state for test monitoring. + +**Location**: `.workflow/.ccw-test/{session_id}/status.json` + +**Structure**: +```json +{ + "session_id": "CCWT-auth-module-2025-02-02", + "mode": "fix", + "status": "running|completed|failed", + "created_at": "2025-02-02T10:00:00Z", + "updated_at": "2025-02-02T10:05:00Z", + "testing": { + "description": "Fix failing authentication tests", + "target_module": "src/auth/**/*.ts", + "framework": "jest", + "coverage_target": 80 + }, + "command_chain": [ + { "index": 0, "command": "/workflow:test-fix-gen", "unit": "sequential", "status": "completed" }, + { "index": 1, "command": "/workflow:test-cycle-execute", "unit": "test-fix-cycle", "max_iterations": 3, "status": "in_progress" } + ], + "current_index": 1, + "test_metrics": { + "total_tests": 42, + "passed": 38, + "failed": 4, + "pass_rate": 90.5, + "iteration_count": 2, + "coverage": { + "line": 82.3, + "branch": 75.6, + "function": 88.1 + } + } +} +``` + +**Status Values**: +- `running`: Test workflow in progress +- `completed`: Tests passing (≥95%) or generation complete +- `failed`: Test workflow aborted + +**Test Metrics** (updated during execution): +- `total_tests`: Number of tests executed +- `pass_rate`: Percentage of passing tests (target: ≥95%) +- `iteration_count`: Number of test-fix iterations (fix mode) +- `coverage`: Line/branch/function coverage percentages + +--- + +## Key Design Principles + +1. **Testing-Focused** - Pure test coordination, no implementation +2. **Mode-Driven** - 4 test strategies for different needs +3. **Auto-Iteration** - Fix mode iterates until ≥95% pass rate +4. **Metrics Tracking** - Real-time test metrics in status.json +5. **Coverage-Driven** - Coverage targets guide test generation +6. **TODO Tracking** - Use CCWT prefix to isolate test todos +7. **TDD Compliance** - TDD mode enforces Red-Green-Refactor cycle + +--- + +## Usage + +```bash +# Auto-select mode +/ccw-test "Test user authentication module" + +# Explicit mode selection +/ccw-test --mode gen "Generate tests for payment module" +/ccw-test --mode fix "Fix failing authentication tests" +/ccw-test --mode verify "Validate current test suite" +/ccw-test --mode tdd "Implement user profile with TDD" + +# Custom configuration +/ccw-test --mode fix --max-iterations 5 --pass-threshold 98 "Fix all tests" +/ccw-test --target "src/auth/**/*.ts" "Test authentication module" + +# Auto mode (skip confirmations) +/ccw-test --yes "Quick test validation" +``` + +--- + +## Mode Selection Decision Tree + +``` +User calls: /ccw-test "test description" + +├─ Keywords: "generate", "create", "write test" +│ └─ Mode: Gen (generate only, no execution) +│ +├─ Keywords: "fix", "repair", "failing" +│ └─ Mode: Fix (auto-iterate until ≥95% pass) +│ +├─ Keywords: "verify", "validate", "run test" +│ └─ Mode: Verify (execute existing tests) +│ +├─ Keywords: "tdd", "test-driven", "test first" +│ └─ Mode: TDD (Red-Green-Refactor cycle) +│ +└─ Default → Fix (most common: fix failing tests) +``` diff --git a/.claude/commands/ccw.md b/.claude/commands/ccw.md index fdb8aad2..a2242e85 100644 --- a/.claude/commands/ccw.md +++ b/.claude/commands/ccw.md @@ -644,23 +644,23 @@ todos = [ ```bash # Auto-select workflow -ccw "Add user authentication" +/ccw "Add user authentication" # Complex requirement (triggers clarification) -ccw "Optimize system performance" +/ccw "Optimize system performance" # Bug fix -ccw "Fix memory leak in WebSocket handler" +/ccw "Fix memory leak in WebSocket handler" # TDD development -ccw "Implement user registration with TDD" +/ccw "Implement user registration with TDD" # Exploratory task -ccw "Uncertain about architecture for real-time notifications" +/ccw "Uncertain about architecture for real-time notifications" # With-File workflows (documented exploration with multi-CLI collaboration) -ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file -ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge) -ccw "深度调试: 系统随机崩溃问题" # → debug-with-file -ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file +/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file +/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge) +/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file +/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file ```