From 09114f59c861e54533eb10adf9115b162b21bacc Mon Sep 17 00:00:00 2001 From: catlog22 Date: Sat, 29 Nov 2025 11:18:48 +0800 Subject: [PATCH] fix: Complete lite-fix command with diagnosis workflow and schemas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add lite-fix.md command based on lite-plan.md structure - Create diagnosis-json-schema.json for bug diagnosis results - Create fix-plan-json-schema.json for fix planning - Update intelligent-tools-strategy.md: simplify model selection, add 5min minimum timeout - Fix missing _metadata.diagnosis_index in agent prompt - Clarify --hotfix mode skip behavior 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .claude/commands/workflow/lite-fix.md | 1182 +++++++---------- .../schemas/diagnosis-json-schema.json | 234 ++++ .../schemas/fix-plan-json-schema.json | 273 ++++ .../workflows/intelligent-tools-strategy.md | 27 +- 4 files changed, 1011 insertions(+), 705 deletions(-) create mode 100644 .claude/workflows/cli-templates/schemas/diagnosis-json-schema.json create mode 100644 .claude/workflows/cli-templates/schemas/fix-plan-json-schema.json diff --git a/.claude/commands/workflow/lite-fix.md b/.claude/commands/workflow/lite-fix.md index 3cc2277f..709cf778 100644 --- a/.claude/commands/workflow/lite-fix.md +++ b/.claude/commands/workflow/lite-fix.md @@ -2,794 +2,598 @@ name: lite-fix description: Lightweight bug diagnosis and fix workflow with intelligent severity assessment and optional hotfix mode for production incidents argument-hint: "[--hotfix] \"bug description or issue reference\"" -allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*), Read(*), Bash(*) +allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*) --- # Workflow Lite-Fix Command (/workflow:lite-fix) ## Overview -Fast-track bug fixing workflow optimized for quick diagnosis, targeted fixes, and streamlined verification. Automatically adjusts process complexity based on impact assessment. +Intelligent lightweight bug fixing command with dynamic workflow adaptation based on severity assessment. Focuses on diagnosis phases (root cause analysis, impact assessment, fix planning, confirmation) and delegates execution to `/workflow:lite-execute`. **Core capabilities:** -- Rapid root cause diagnosis with intelligent code search -- Automatic severity assessment and adaptive workflow -- Fix strategy selection (immediate patch vs comprehensive refactor) -- Risk-aware verification (smoke tests to full suite) -- Optional hotfix mode for production incidents with branch management -- Automatic follow-up task generation for hotfixes +- Intelligent bug analysis with automatic severity detection +- Dynamic code diagnosis (cli-explore-agent) for root cause identification +- Interactive clarification after diagnosis to gather missing information +- Adaptive fix planning strategy (direct Claude vs cli-lite-planning-agent) based on complexity +- Two-step confirmation: fix-plan display -> multi-dimensional input collection +- Execution dispatch with complete context handoff to lite-execute ## Usage -### Command Syntax ```bash /workflow:lite-fix [FLAGS] # Flags ---hotfix, -h Production hotfix mode (creates hotfix branch, auto follow-up) +--hotfix, -h Production hotfix mode (minimal diagnosis, fast fix) # Arguments - Bug description or issue reference (required) -``` - -### Modes - -| Mode | Time Budget | Use Case | Workflow Characteristics | -|------|-------------|----------|--------------------------| -| **Default** | Auto-adapt (15min-4h) | All standard bugs | Intelligent severity assessment + adaptive process | -| **Hotfix** (`--hotfix`) | 15-30 min | Production outage | Minimal diagnosis + hotfix branch + auto follow-up | - -### Examples - -```bash -# Default mode: Automatically adjusts based on impact -/workflow:lite-fix "User avatar upload fails with 413 error" -/workflow:lite-fix "Shopping cart randomly loses items at checkout" - -# Hotfix mode: Production incident -/workflow:lite-fix --hotfix "Payment gateway 5xx errors" + Bug description, error message, or path to .md file (required) ``` ## Execution Process ``` -Input Parsing: - └─ Parse flags: --hotfix → hotfixMode = true | false +Phase 1: Bug Analysis & Diagnosis + |- Parse input (description, error message, or .md file) + |- Intelligent severity pre-assessment (Low/Medium/High/Critical) + |- Diagnosis decision (auto-detect or --hotfix flag) + |- Context protection: If file reading >=50k chars -> force cli-explore-agent + +- Decision: + |- needsDiagnosis=true -> Launch parallel cli-explore-agents (1-4 based on severity) + +- needsDiagnosis=false (hotfix) -> Skip directly to Phase 3 (Fix Planning) -Phase 1: Diagnosis & Root Cause Analysis - └─ Decision (confidence-based): - ├─ High confidence (specific error) → Direct grep search (5min) - ├─ Medium confidence → cli-explore-agent focused search (10-15min) - └─ Low confidence (vague) → cli-explore-agent broad search (20min) - └─ Hotfix mode: Minimal search (Read suspected file + git blame) +Phase 2: Clarification (optional) + |- Aggregate clarification_needs from all diagnosis angles + |- Deduplicate similar questions + +- Decision: + |- Has clarifications -> AskUserQuestion (max 4 questions) + +- No clarifications -> Skip to Phase 3 -Phase 2: Impact Assessment & Severity Auto-Detection - └─ Calculate risk_score → Auto-determine severity - ├─ ≥8.0 → critical - ├─ ≥5.0 → high - ├─ ≥3.0 → medium - └─ <3.0 → low - └─ Hotfix mode: Skip, assume critical +Phase 3: Fix Planning (NO CODE EXECUTION - planning only) + +- Decision (based on Phase 1 severity): + |- Low/Medium -> Load schema: cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json -> Direct Claude planning (following schema) -> fix-plan.json -> MUST proceed to Phase 4 + +- High/Critical -> cli-lite-planning-agent -> fix-plan.json -> MUST proceed to Phase 4 -Phase 3: Fix Planning & Strategy Selection - └─ Decision (by risk score): - ├─ risk_score ≥5.0 or hotfix → Single best strategy (fastest) - └─ risk_score <5.0 → Multiple strategy options for user selection +Phase 4: Confirmation & Selection + |- Display fix-plan summary (tasks, severity, estimated time) + +- AskUserQuestion: + |- Confirm: Allow / Modify / Cancel + |- Execution: Agent / Codex / Auto + +- Review: Gemini / Agent / Skip -Phase 4: Verification Strategy - └─ Select test scope by risk score - └─ Define branch strategy (feature vs hotfix) - -Phase 5: User Confirmation - └─ Default mode: 3 dimensions (approach, execution, verification) - └─ Hotfix mode: 2 dimensions (deploy confirmation, monitoring) - -Phase 6: Execution Dispatch - ├─ Export Enhanced Task JSON - ├─ Dispatch to lite-execute --in-memory - └─ Hotfix mode: Generate follow-up tasks +Phase 5: Dispatch + |- Build executionContext (fix-plan + diagnoses + clarifications + selections) + +- SlashCommand("/workflow:lite-execute --in-memory --mode bugfix") ``` -### Phase Summary +## Implementation -| Phase | Default Mode | Hotfix Mode | -|-------|--------------|-------------| -| 1. Diagnosis | Adaptive search depth | Minimal (known issue) | -| 2. Impact Assessment | Full risk scoring | Critical path only | -| 3. Fix Planning | Strategy options based on complexity | Single surgical fix | -| 4. Verification | Test level matches risk score | Smoke tests only | -| 5. User Confirmation | 3 dimensions | 2 dimensions | -| 6. Execution | Via lite-execute | Via lite-execute + monitoring | +### Phase 1: Intelligent Multi-Angle Diagnosis ---- - -## Detailed Phase Execution - -### Input Parsing - -**Parse --hotfix flag**: +**Session Setup**: ```javascript -const hotfixMode = $ARGUMENTS.includes('--hotfix') || $ARGUMENTS.includes('-h') -const bugDescription = $ARGUMENTS.replace(/--hotfix|-h/g, '').trim() -``` - -### Phase 1: Diagnosis & Root Cause Analysis - -**Goal**: Identify root cause and affected code paths - -**Session Folder Setup**: -```javascript -// Generate session identifiers for artifact storage const bugSlug = bug_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40) const timestamp = new Date().toISOString().replace(/[:.]/g, '-') -const shortTimestamp = timestamp.substring(0, 19).replace('T', '-') // YYYY-MM-DD-HH-mm-ss +const shortTimestamp = timestamp.substring(0, 19).replace('T', '-') const sessionId = `${bugSlug}-${shortTimestamp}` const sessionFolder = `.workflow/.lite-fix/${sessionId}` + +bash(`mkdir -p ${sessionFolder}`) ``` -**Execution Strategy**: - -**Default Mode** - Adaptive search: -- **High confidence keywords** (e.g., specific error messages): Direct grep search (5min) -- **Medium confidence**: cli-explore-agent with focused search (10-15min) -- **Low confidence** (vague symptoms): cli-explore-agent with broad search (20min) - +**Diagnosis Decision Logic**: ```javascript -// Confidence-based strategy selection -if (has_specific_error_message || has_file_path_hint) { - // Quick targeted search - grep -r '${error_message}' src/ --include='*.ts' -n | head -10 - git log --oneline --since='1 week ago' -- '*affected*' -} else { - // Deep exploration - Task(subagent_type="cli-explore-agent", prompt=` - Bug: ${bug_description} - Execute diagnostic search: - 1. Search error patterns and similar issues - 2. Trace execution path in affected modules - 3. Check recent changes - Return: Root cause hypothesis, affected paths, reproduction steps - `) +const hotfixMode = $ARGUMENTS.includes('--hotfix') || $ARGUMENTS.includes('-h') + +needsDiagnosis = ( + !hotfixMode && + ( + bug.lacks_specific_error_message || + bug.requires_codebase_context || + bug.needs_execution_tracing || + bug.root_cause_unclear + ) +) + +if (!needsDiagnosis) { + // Skip to Phase 2 (Clarification) or Phase 3 (Fix Planning) + proceed_to_next_phase() } ``` -**Hotfix Mode** - Minimal search: -```bash -Read(suspected_file) # User typically knows the file -git blame ${suspected_file} -``` +**Context Protection**: File reading >=50k chars -> force `needsDiagnosis=true` (delegate to cli-explore-agent) -**Output Structure**: +**Severity Pre-Assessment** (Intelligent Analysis): ```javascript -diagnosisContext = { - symptom: string, - error_message: string | null, - keywords: string[], - confidence_level: "high" | "medium" | "low", - root_cause: { - file: "src/auth/tokenValidator.ts", - line_range: "45-52", - issue: "Token expiration check uses wrong comparison", - introduced_by: "commit abc123" - }, - reproduction_steps: ["Login", "Wait 15min", "Access protected route"], - affected_scope: { - users: "All authenticated users", - features: ["login", "API access"], - data_risk: "none" - } +// Analyzes bug severity based on: +// - Symptoms: Error messages, crash reports, user complaints +// - Scope: How many users/features are affected? +// - Urgency: Production down vs minor inconvenience +// - Impact: Data loss, security, business impact + +const severity = analyzeBugSeverity(bug_description) +// Returns: 'Low' | 'Medium' | 'High' | 'Critical' +// Low: Minor UI issue, localized, no data impact +// Medium: Multiple users affected, degraded functionality +// High: Significant functionality broken, many users affected +// Critical: Production down, data loss risk, security issue + +// Angle assignment based on bug type (orchestrator decides, not agent) +const DIAGNOSIS_ANGLE_PRESETS = { + runtime_error: ['error-handling', 'dataflow', 'state-management', 'edge-cases'], + performance: ['performance', 'bottlenecks', 'caching', 'data-access'], + security: ['security', 'auth-patterns', 'dataflow', 'validation'], + data_corruption: ['data-integrity', 'state-management', 'transactions', 'validation'], + ui_bug: ['state-management', 'event-handling', 'rendering', 'data-binding'], + integration: ['api-contracts', 'error-handling', 'timeouts', 'fallbacks'] } -// Save diagnosis results for CLI/agent access in lite-execute -const diagnosisFile = `${sessionFolder}/diagnosis.json` -Write(diagnosisFile, JSON.stringify(diagnosisContext, null, 2)) +function selectDiagnosisAngles(bugDescription, count) { + const text = bugDescription.toLowerCase() + let preset = 'runtime_error' // default + + if (/slow|timeout|performance|lag|hang/.test(text)) preset = 'performance' + else if (/security|auth|permission|access|token/.test(text)) preset = 'security' + else if (/corrupt|data|lost|missing|inconsistent/.test(text)) preset = 'data_corruption' + else if (/ui|display|render|style|click|button/.test(text)) preset = 'ui_bug' + else if (/api|integration|connect|request|response/.test(text)) preset = 'integration' + + return DIAGNOSIS_ANGLE_PRESETS[preset].slice(0, count) +} + +const selectedAngles = selectDiagnosisAngles(bug_description, severity === 'Critical' ? 4 : (severity === 'High' ? 3 : (severity === 'Medium' ? 2 : 1))) + +console.log(` +## Diagnosis Plan + +Bug Severity: ${severity} +Selected Angles: ${selectedAngles.join(', ')} + +Launching ${selectedAngles.length} parallel diagnoses... +`) ``` -**Output**: `diagnosisContext` (in-memory) -**Artifact**: Saved to `{sessionFolder}/diagnosis.json` for CLI/agent use +**Launch Parallel Diagnoses** - Orchestrator assigns angle to each agent: -**TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress +```javascript +// Launch agents with pre-assigned diagnosis angles +const diagnosisTasks = selectedAngles.map((angle, index) => + Task( + subagent_type="cli-explore-agent", + description=`Diagnose: ${angle}`, + prompt=` +## Task Objective +Execute **${angle}** diagnosis for bug root cause analysis. Analyze codebase from this specific angle to discover root cause, affected paths, and fix hints. + +## Assigned Context +- **Diagnosis Angle**: ${angle} +- **Bug Description**: ${bug_description} +- **Diagnosis Index**: ${index + 1} of ${selectedAngles.length} +- **Output File**: ${sessionFolder}/diagnosis-${angle}.json + +## MANDATORY FIRST STEPS (Execute by Agent) +**You (cli-explore-agent) MUST execute these steps in order:** +1. Run: ~/.claude/scripts/get_modules_by_depth.sh (project structure) +2. Run: rg -l "{error_keyword_from_bug}" --type ts (locate relevant files) +3. Execute: cat ~/.claude/workflows/cli-templates/schemas/diagnosis-json-schema.json (get output schema reference) + +## Diagnosis Strategy (${angle} focus) + +**Step 1: Error Tracing** (Bash) +- rg for error messages, stack traces, log patterns +- git log --since='2 weeks ago' for recent changes +- Trace execution path in affected modules + +**Step 2: Root Cause Analysis** (Gemini CLI) +- What code paths lead to this ${angle} issue? +- What edge cases are not handled from ${angle} perspective? +- What recent changes might have introduced this bug? + +**Step 3: Write Output** +- Consolidate ${angle} findings into JSON +- Identify ${angle}-specific clarification needs +- Provide fix hints based on ${angle} analysis + +## Expected Output + +**File**: ${sessionFolder}/diagnosis-${angle}.json + +**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 3, follow schema exactly + +**Required Fields** (all ${angle} focused): +- symptom: Bug symptoms and error messages +- root_cause: Root cause hypothesis from ${angle} perspective + **IMPORTANT**: Use structured format: + \`{file: "src/module/file.ts", line_range: "45-60", issue: "Description", confidence: 0.85}\` +- affected_files: Files involved from ${angle} perspective + **IMPORTANT**: Use object format with relevance scores: + \`[{path: "src/file.ts", relevance: 0.85, rationale: "Contains ${angle} logic"}]\` +- reproduction_steps: Steps to reproduce the bug +- fix_hints: Suggested fix approaches from ${angle} viewpoint +- dependencies: Dependencies relevant to ${angle} diagnosis +- constraints: ${angle}-specific limitations affecting fix +- clarification_needs: ${angle}-related ambiguities (with options array) +- _metadata.diagnosis_angle: "${angle}" +- _metadata.diagnosis_index: ${index + 1} + +## Success Criteria +- [ ] Schema obtained via cat diagnosis-json-schema.json +- [ ] get_modules_by_depth.sh executed +- [ ] Root cause identified with confidence score +- [ ] At least 3 affected files identified with ${angle} rationale +- [ ] Fix hints are actionable (specific code changes, not generic advice) +- [ ] Reproduction steps are verifiable +- [ ] JSON output follows schema exactly +- [ ] clarification_needs includes options array + +## Output +Write: ${sessionFolder}/diagnosis-${angle}.json +Return: 2-3 sentence summary of ${angle} diagnosis findings +` + ) +) + +// Execute all diagnosis tasks in parallel +``` + +**Auto-discover Generated Diagnosis Files**: +```javascript +// After diagnoses complete, auto-discover all diagnosis-*.json files +const diagnosisFiles = bash(`find ${sessionFolder} -name "diagnosis-*.json" -type f`) + .split('\n') + .filter(f => f.trim()) + +// Read metadata to build manifest +const diagnosisManifest = { + session_id: sessionId, + bug_description: bug_description, + timestamp: new Date().toISOString(), + severity: severity, + diagnosis_count: diagnosisFiles.length, + diagnoses: diagnosisFiles.map(file => { + const data = JSON.parse(Read(file)) + const filename = path.basename(file) + return { + angle: data._metadata.diagnosis_angle, + file: filename, + path: file, + index: data._metadata.diagnosis_index + } + }) +} + +Write(`${sessionFolder}/diagnoses-manifest.json`, JSON.stringify(diagnosisManifest, null, 2)) + +console.log(` +## Diagnosis Complete + +Generated diagnosis files in ${sessionFolder}: +${diagnosisManifest.diagnoses.map(d => `- diagnosis-${d.angle}.json (angle: ${d.angle})`).join('\n')} + +Manifest: diagnoses-manifest.json +Angles diagnosed: ${diagnosisManifest.diagnoses.map(d => d.angle).join(', ')} +`) +``` + +**Output**: +- `${sessionFolder}/diagnosis-{angle1}.json` +- `${sessionFolder}/diagnosis-{angle2}.json` +- ... (1-4 files based on severity) +- `${sessionFolder}/diagnoses-manifest.json` --- -### Phase 2: Impact Assessment & Severity Auto-Detection +### Phase 2: Clarification (Optional) -**Goal**: Quantify blast radius and auto-determine severity +**Skip if**: No diagnosis or `clarification_needs` is empty across all diagnoses -**Risk Score Calculation**: +**Aggregate clarification needs from all diagnosis angles**: ```javascript -risk_score = (user_impact × 0.4) + (system_risk × 0.3) + (business_impact × 0.3) +// Load manifest and all diagnosis files +const manifest = JSON.parse(Read(`${sessionFolder}/diagnoses-manifest.json`)) +const diagnoses = manifest.diagnoses.map(diag => ({ + angle: diag.angle, + data: JSON.parse(Read(diag.path)) +})) -// Auto-severity mapping -if (risk_score >= 8.0) severity = "critical" -else if (risk_score >= 5.0) severity = "high" -else if (risk_score >= 3.0) severity = "medium" -else severity = "low" - -// Workflow adaptation -if (severity >= "high") { - diagnosis_depth = "focused" - test_strategy = "smoke_and_critical" - review_optional = true -} else { - diagnosis_depth = "comprehensive" - test_strategy = "full_suite" - review_optional = false -} -``` - -**Assessment Output**: -```javascript -impactContext = { - affected_users: { - count: "5000 active users (100%)", - severity: "high" - }, - system_risk: { - availability: "degraded_30%", - cascading_failures: "possible_logout_storm" - }, - business_impact: { - revenue: "medium", - reputation: "high", - sla_breach: "yes" - }, - risk_score: 7.1, - severity: "high", - workflow_adaptation: { - test_strategy: "focused_integration", - review_required: false, - time_budget: "1_hour" +// Aggregate clarification needs from all diagnoses +const allClarifications = [] +diagnoses.forEach(diag => { + if (diag.data.clarification_needs?.length > 0) { + diag.data.clarification_needs.forEach(need => { + allClarifications.push({ + ...need, + source_angle: diag.angle + }) + }) } +}) + +// Deduplicate by question similarity +function deduplicateClarifications(clarifications) { + const unique = [] + clarifications.forEach(c => { + const isDuplicate = unique.some(u => + u.question.toLowerCase() === c.question.toLowerCase() + ) + if (!isDuplicate) unique.push(c) + }) + return unique } -// Save impact assessment for CLI/agent access -const impactFile = `${sessionFolder}/impact.json` -Write(impactFile, JSON.stringify(impactContext, null, 2)) -``` +const uniqueClarifications = deduplicateClarifications(allClarifications) -**Output**: `impactContext` (in-memory) -**Artifact**: Saved to `{sessionFolder}/impact.json` for CLI/agent use - -**Hotfix Mode**: Skip detailed assessment, assume critical - -**TodoWrite**: Mark Phase 2 completed, Phase 3 in_progress - ---- - -### Phase 3: Fix Planning & Strategy Selection - -**Goal**: Generate fix options with trade-off analysis - -**Strategy Generation**: - -**Default Mode** - Complexity-adaptive: -- **Low risk score (<5.0)**: Generate 2-3 strategy options for user selection -- **High risk score (≥5.0)**: Generate single best strategy for speed - -```javascript -strategies = generateFixStrategies(root_cause, risk_score) - -if (risk_score >= 5.0 || mode === "hotfix") { - // Single best strategy - return strategies[0] // Fastest viable fix -} else { - // Multiple options with trade-offs - return strategies // Let user choose -} -``` - -**Example Strategies**: -```javascript -// Low risk: Multiple options -[ - { - strategy: "immediate_patch", - description: "Fix comparison operator", - estimated_time: "15 minutes", - risk: "low", - pros: ["Quick fix"], - cons: ["Doesn't address underlying issue"] - }, - { - strategy: "comprehensive_fix", - description: "Refactor token validation logic", - estimated_time: "2 hours", - risk: "medium", - pros: ["Addresses root cause"], - cons: ["Longer implementation"] - } -] - -// High risk or hotfix: Single option -{ - strategy: "surgical_fix", - description: "Minimal change to fix comparison", - files: ["src/auth/tokenValidator.ts:47"], - estimated_time: "5 minutes", - risk: "minimal" -} -``` - -**Complexity Assessment**: -```javascript -if (complexity === "high" && risk_score < 5.0) { - suggestCommand("/workflow:plan --mode bugfix") - return // Escalate to full planning -} - -// Save fix plan for CLI/agent access -const planFile = `${sessionFolder}/fix-plan.json` -Write(planFile, JSON.stringify(fixPlan, null, 2)) -``` - -**Output**: `fixPlan` (in-memory) -**Artifact**: Saved to `{sessionFolder}/fix-plan.json` for CLI/agent use - -**TodoWrite**: Mark Phase 3 completed, Phase 4 in_progress - ---- - -### Phase 4: Verification Strategy - -**Goal**: Define testing approach based on severity - -**Adaptive Test Strategy**: - -| Risk Score | Test Scope | Duration | Automation | -|------------|------------|----------|------------| -| **< 3.0** (Low) | Full test suite | 15-20 min | `npm test` | -| **3.0-5.0** (Medium) | Focused integration | 8-12 min | `npm test -- affected-module.test.ts` | -| **5.0-8.0** (High) | Smoke + critical | 5-8 min | `npm test -- critical.smoke.test.ts` | -| **≥ 8.0** (Critical) | Smoke only | 2-5 min | `npm test -- smoke.test.ts` | -| **Hotfix** | Production smoke | 2-3 min | `npm test -- production.smoke.test.ts` | - -**Branch Strategy**: - -**Default Mode**: -```javascript -{ - type: "feature_branch", - base: "main", - name: "fix/token-expiration-edge-case", - merge_target: "main" -} -``` - -**Hotfix Mode**: -```javascript -{ - type: "hotfix_branch", - base: "production_tag_v2.3.1", // ⚠️ From production tag - name: "hotfix/token-validation-fix", - merge_target: ["main", "production"] // Dual merge -} -``` - -**TodoWrite**: Mark Phase 4 completed, Phase 5 in_progress - ---- - -### Phase 5: User Confirmation & Execution Selection - -**Adaptive Confirmation Dimensions**: - -**Default Mode** - 3 dimensions (adapted by risk score): - -```javascript -dimensions = [ - { - question: "Confirm fix approach?", - options: ["Proceed", "Modify", "Escalate to /workflow:plan"] - }, - { - question: "Execution method:", - options: ["Agent", "CLI Tool (Codex/Gemini)", "Manual (plan only)"] - }, - { - question: "Verification level:", - options: adaptedByRiskScore() // Auto-suggest based on Phase 2 - } -] - -// If risk_score >= 5.0, auto-skip code review dimension -// If risk_score < 5.0, add optional code review dimension -if (risk_score < 5.0) { - dimensions.push({ - question: "Post-fix review:", - options: ["Gemini", "Skip"] +if (uniqueClarifications.length > 0) { + AskUserQuestion({ + questions: uniqueClarifications.map(need => ({ + question: `[${need.source_angle}] ${need.question}\n\nContext: ${need.context}`, + header: need.source_angle, + multiSelect: false, + options: need.options.map(opt => ({ + label: opt, + description: `Use ${opt} approach` + })) + })) }) } ``` -**Hotfix Mode** - 2 dimensions (minimal): -```javascript -[ - { - question: "Confirm hotfix deployment:", - options: ["Deploy", "Stage First", "Abort"] - }, - { - question: "Post-deployment monitoring:", - options: ["Real-time (15 min)", "Passive (alerts only)"] - } -] -``` - -**TodoWrite**: Mark Phase 5 completed, Phase 6 in_progress +**Output**: `clarificationContext` (in-memory) --- -### Phase 6: Execution Dispatch & Follow-up +### Phase 3: Fix Planning -**Export Enhanced Task JSON**: +**Planning Strategy Selection** (based on Phase 1 severity): +**IMPORTANT**: Phase 3 is **planning only** - NO code execution. All execution happens in Phase 5 via lite-execute. + +**Low/Medium Severity** - Direct planning by Claude: ```javascript -const taskId = `BUGFIX-${shortTimestamp}` -const taskFile = `${sessionFolder}/task.json` +// Step 1: Read schema +const schema = Bash(`cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json`) -const enhancedTaskJson = { - id: taskId, - title: bug_description, - status: "pending", - - meta: { - type: "bugfix", - created_at: new Date().toISOString(), - severity: impactContext.severity, - risk_score: impactContext.risk_score, - estimated_time: fixPlan.estimated_time, - workflow: mode === "hotfix" ? "lite-fix-hotfix" : "lite-fix", - session_id: sessionId, - session_folder: sessionFolder - }, - - context: { - requirements: [bug_description], - diagnosis: diagnosisContext, - impact: impactContext, - plan: fixPlan, - verification_strategy: verificationStrategy, - branch_strategy: branchStrategy - } +// Step 2: Generate fix-plan following schema (Claude directly, no agent) +const fixPlan = { + summary: "...", + root_cause: "...", + strategy: "immediate_patch|comprehensive_fix|refactor", + tasks: [...], // Each task: { id, title, scope, ..., depends_on, complexity } + estimated_time: "...", + recommended_execution: "Agent", + severity: severity, + risk_level: "...", + _metadata: { timestamp: new Date().toISOString(), source: "direct-planning", planning_mode: "direct" } } -Write(taskFile, JSON.stringify(enhancedTaskJson, null, 2)) +// Step 3: Write fix-plan to session folder +Write(`${sessionFolder}/fix-plan.json`, JSON.stringify(fixPlan, null, 2)) + +// Step 4: MUST continue to Phase 4 (Confirmation) - DO NOT execute code here ``` -**Dispatch to lite-execute**: +**High/Critical Severity** - Invoke cli-lite-planning-agent: ```javascript +Task( + subagent_type="cli-lite-planning-agent", + description="Generate detailed fix plan", + prompt=` +Generate fix plan and write fix-plan.json. + +## Output Schema Reference +Execute: cat ~/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json (get schema reference before generating plan) + +## Bug Description +${bug_description} + +## Multi-Angle Diagnosis Context + +${manifest.diagnoses.map(diag => `### Diagnosis: ${diag.angle} (${diag.file}) +Path: ${diag.path} + +Read this file for detailed ${diag.angle} analysis.`).join('\n\n')} + +Total diagnoses: ${manifest.diagnosis_count} +Angles covered: ${manifest.diagnoses.map(d => d.angle).join(', ')} + +Manifest: ${sessionFolder}/diagnoses-manifest.json + +## User Clarifications +${JSON.stringify(clarificationContext) || "None"} + +## Severity Level +${severity} + +## Requirements +Generate fix-plan.json with: +- summary: 2-3 sentence overview of the fix +- root_cause: Consolidated root cause from all diagnoses +- strategy: "immediate_patch" | "comprehensive_fix" | "refactor" +- tasks: 1-5 structured fix tasks (**IMPORTANT: group by fix area, NOT by file**) + - **Task Granularity Principle**: Each task = one complete fix unit + - title: action verb + target (e.g., "Fix token validation edge case") + - scope: module path (src/auth/) or feature name + - action: "Fix" | "Update" | "Refactor" | "Add" | "Delete" + - description + - modification_points: ALL files to modify for this fix (group related changes) + - implementation (2-5 steps covering all modification_points) + - verification (test criteria) + - depends_on: task IDs this task depends on (use sparingly) +- estimated_time, recommended_execution, severity, risk_level +- _metadata: + - timestamp, source, planning_mode + - diagnosis_angles: ${JSON.stringify(manifest.diagnoses.map(d => d.angle))} + +## Task Grouping Rules +1. **Group by fix area**: All changes for one fix = one task (even if 2-3 files) +2. **Avoid file-per-task**: Do NOT create separate tasks for each file +3. **Substantial tasks**: Each task should represent 10-45 minutes of work +4. **True dependencies only**: Only use depends_on when Task B cannot start without Task A's output +5. **Prefer parallel**: Most tasks should be independent (no depends_on) + +## Execution +1. Read ALL diagnosis files for comprehensive context +2. Execute CLI planning using Gemini (Qwen fallback) +3. Synthesize findings from multiple diagnosis angles +4. Parse output and structure fix-plan +5. Write JSON: Write('${sessionFolder}/fix-plan.json', jsonContent) +6. Return brief completion summary +` +) +``` + +**Output**: `${sessionFolder}/fix-plan.json` + +--- + +### Phase 4: Task Confirmation & Execution Selection + +**Step 4.1: Display Fix Plan** +```javascript +const fixPlan = JSON.parse(Read(`${sessionFolder}/fix-plan.json`)) + +console.log(` +## Fix Plan + +**Summary**: ${fixPlan.summary} +**Root Cause**: ${fixPlan.root_cause} +**Strategy**: ${fixPlan.strategy} + +**Tasks** (${fixPlan.tasks.length}): +${fixPlan.tasks.map((t, i) => `${i+1}. ${t.title} (${t.scope})`).join('\n')} + +**Severity**: ${fixPlan.severity} +**Risk Level**: ${fixPlan.risk_level} +**Estimated Time**: ${fixPlan.estimated_time} +**Recommended**: ${fixPlan.recommended_execution} +`) +``` + +**Step 4.2: Collect Confirmation** +```javascript +AskUserQuestion({ + questions: [ + { + question: `Confirm fix plan? (${fixPlan.tasks.length} tasks, ${fixPlan.severity} severity)`, + header: "Confirm", + multiSelect: true, + options: [ + { label: "Allow", description: "Proceed as-is" }, + { label: "Modify", description: "Adjust before execution" }, + { label: "Cancel", description: "Abort workflow" } + ] + }, + { + question: "Execution method:", + header: "Execution", + multiSelect: false, + options: [ + { label: "Agent", description: "@code-developer agent" }, + { label: "Codex", description: "codex CLI tool" }, + { label: "Auto", description: `Auto: ${fixPlan.severity === 'Low' ? 'Agent' : 'Codex'}` } + ] + }, + { + question: "Code review after fix?", + header: "Review", + multiSelect: false, + options: [ + { label: "Gemini Review", description: "Gemini CLI" }, + { label: "Agent Review", description: "@code-reviewer" }, + { label: "Skip", description: "No review" } + ] + } + ] +}) +``` + +--- + +### Phase 5: Dispatch to Execution + +**CRITICAL**: lite-fix NEVER executes code directly. ALL execution MUST go through lite-execute. + +**Step 5.1: Build executionContext** + +```javascript +// Load manifest and all diagnosis files +const manifest = JSON.parse(Read(`${sessionFolder}/diagnoses-manifest.json`)) +const diagnoses = {} + +manifest.diagnoses.forEach(diag => { + if (file_exists(diag.path)) { + diagnoses[diag.angle] = JSON.parse(Read(diag.path)) + } +}) + +const fixPlan = JSON.parse(Read(`${sessionFolder}/fix-plan.json`)) + executionContext = { mode: "bugfix", - severity: impactContext.severity, + severity: fixPlan.severity, planObject: fixPlan, - diagnosisContext: diagnosisContext, - impactContext: impactContext, - verificationStrategy: verificationStrategy, - branchStrategy: branchStrategy, - executionMethod: user_selection.execution_method, - - // Session artifacts location + diagnosisContext: diagnoses, + diagnosisAngles: manifest.diagnoses.map(d => d.angle), + diagnosisManifest: manifest, + clarificationContext: clarificationContext || null, + executionMethod: userSelection.execution_method, + codeReviewTool: userSelection.code_review_tool, + originalUserInput: bug_description, session: { id: sessionId, folder: sessionFolder, artifacts: { - diagnosis: `${sessionFolder}/diagnosis.json`, - impact: `${sessionFolder}/impact.json`, - plan: `${sessionFolder}/fix-plan.json`, - task: `${sessionFolder}/task.json` - } - } -} - -SlashCommand("/workflow:lite-execute --in-memory --mode bugfix") -``` - -**Hotfix Auto Follow-up**: - -```javascript -if (mode === "hotfix") { - follow_up_tasks = [ - { - id: `FOLLOWUP-${taskId}-comprehensive`, - title: "Replace hotfix with comprehensive fix", - priority: "high", - due_date: "within_3_days", - description: "Refactor quick hotfix into proper solution with full test coverage" - }, - { - id: `FOLLOWUP-${taskId}-postmortem`, - title: "Incident postmortem", - priority: "medium", - due_date: "within_1_week", - sections: ["Timeline", "Root cause", "Prevention measures"] - } - ] - - Write(`${sessionFolder}/followup.json`, follow_up_tasks) - - console.log(` - ⚠️ Hotfix follow-up tasks generated: - - Comprehensive fix: ${follow_up_tasks[0].id} (due in 3 days) - - Postmortem: ${follow_up_tasks[1].id} (due in 1 week) - - Location: ${sessionFolder}/followup.json - `) -} -``` - -**TodoWrite**: Mark Phase 6 completed - ---- - -## Data Structures - -### diagnosisContext -```javascript -{ - symptom: string, - error_message: string | null, - keywords: string[], - confidence_level: "high" | "medium" | "low", // Search confidence - root_cause: { - file: string, - line_range: string, - issue: string, - introduced_by: string - }, - reproduction_steps: string[], - affected_scope: {...} -} -``` - -### impactContext -```javascript -{ - affected_users: { count: string, severity: string }, - system_risk: { availability: string, cascading_failures: string }, - business_impact: { revenue: string, reputation: string, sla_breach: string }, - risk_score: number, // 0-10 - severity: "low" | "medium" | "high" | "critical", - workflow_adaptation: { - diagnosis_depth: string, - test_strategy: string, - review_optional: boolean, - time_budget: string - } -} -``` - -### fixPlan -```javascript -{ - strategy: string, - summary: string, - tasks: [{ - title: string, - file: string, - action: "Update" | "Create" | "Delete", - implementation: string[], - verification: string[] - }], - estimated_time: string, - recommended_execution: "Agent" | "CLI" | "Manual" -} -``` - -### executionContext - -Context passed to lite-execute via --in-memory (Phase 6): - -```javascript -{ - mode: "bugfix", - severity: "high" | "medium" | "low" | "critical", - - // Core data objects - planObject: {...}, // Complete fixPlan (see above) - diagnosisContext: {...}, // Complete diagnosisContext (see above) - impactContext: {...}, // Complete impactContext (see above) - - // Verification and branch strategies - verificationStrategy: {...}, - branchStrategy: {...}, - executionMethod: "Agent" | "CLI" | "Manual", - - // Session artifacts location (for lite-execute to access saved files) - session: { - id: string, // Session identifier: {bugSlug}-{shortTimestamp} - folder: string, // Session folder path: .workflow/.lite-fix/{session-id} - artifacts: { - diagnosis: string, // diagnosis.json path - impact: string, // impact.json path - plan: string, // fix-plan.json path - task: string // task.json path + diagnoses: manifest.diagnoses.map(diag => ({ + angle: diag.angle, + path: diag.path + })), + diagnoses_manifest: `${sessionFolder}/diagnoses-manifest.json`, + fix_plan: `${sessionFolder}/fix-plan.json` } } } ``` -### Enhanced Task JSON Export +**Step 5.2: Dispatch** -Task JSON structure exported in Phase 6: - -```json -{ - "id": "BUGFIX-{timestamp}", - "title": "Original bug description", - "status": "pending", - - "meta": { - "type": "bugfix", - "created_at": "ISO timestamp", - "severity": "low|medium|high|critical", - "risk_score": 7.1, - "estimated_time": "X minutes", - "workflow": "lite-fix|lite-fix-hotfix", - "session_id": "{bugSlug}-{shortTimestamp}", - "session_folder": ".workflow/.lite-fix/{session-id}" - }, - - "context": { - "requirements": ["Original bug description"], - "diagnosis": {/* diagnosisContext */}, - "impact": {/* impactContext */}, - "plan": {/* fixPlan */}, - "verification_strategy": {/* test strategy */}, - "branch_strategy": {/* branch strategy */} - } -} +```javascript +SlashCommand(command="/workflow:lite-execute --in-memory --mode bugfix") ``` -**Schema Notes**: -- Aligns with Enhanced Task JSON Schema (6-field structure) -- `context_package_path` omitted (not used by lite-fix) -- `flow_control` omitted (handled by lite-execute) - ---- - -## Best Practices - -### When to Use Default Mode - -**Use for all standard bugs:** -- Automatically adapts to severity (no manual mode selection needed) -- Risk score determines workflow complexity -- Handles 90% of bug fixing scenarios - -**Typical scenarios:** -- UI bugs, logic errors, edge cases -- Performance issues (non-critical) -- Integration failures -- Data validation bugs - -### When to Use Hotfix Mode - -**Only use for production incidents:** -- Production is down or critically degraded -- Revenue/reputation at immediate risk -- SLA breach occurring -- Issue is well-understood (minimal diagnosis needed) - -**Hotfix characteristics:** -- Creates hotfix branch from production tag -- Minimal diagnosis (assumes known issue) -- Smoke tests only -- Auto-generates follow-up tasks -- Requires incident tracking - -### Branching Strategy - -**Default Mode (feature branch)**: -```bash -# Standard feature branch workflow -git checkout -b fix/issue-description main -# ... implement fix -git checkout main && git merge fix/issue-description -``` - -**Hotfix Mode (dual merge)**: -```bash -# ✅ Correct: Branch from production tag -git checkout -b hotfix/fix-name v2.3.1 - -# Merge to both targets -git checkout main && git merge hotfix/fix-name -git checkout production && git merge hotfix/fix-name -git tag v2.3.2 - -# ❌ Wrong: Branch from main -git checkout -b hotfix/fix-name main # Contains unreleased code! -``` - ---- - -## Error Handling - -| Error | Cause | Resolution | -|-------|-------|------------| -| Root cause unclear | Vague symptoms | Extend diagnosis time or use /cli:mode:bug-diagnosis | -| Multiple potential causes | Complex interaction | Use /cli:discuss-plan for analysis | -| Fix too complex | High-risk refactor | Escalate to /workflow:plan --mode bugfix | -| High risk score but unsure | Uncertain severity | Default mode will adapt, proceed normally | - ---- - ## Session Folder Structure -Each lite-fix execution creates a dedicated session folder to organize all artifacts: - ``` -.workflow/.lite-fix/{bug-slug}-{short-timestamp}/ -├── diagnosis.json # Phase 1: Root cause analysis -├── impact.json # Phase 2: Impact assessment -├── fix-plan.json # Phase 3: Fix strategy -├── task.json # Phase 6: Enhanced Task JSON -└── followup.json # Hotfix mode only: Follow-up tasks +.workflow/.lite-fix/{bug-slug}-{timestamp}/ +|- diagnosis-{angle1}.json # Diagnosis angle 1 +|- diagnosis-{angle2}.json # Diagnosis angle 2 +|- diagnosis-{angle3}.json # Diagnosis angle 3 (if applicable) +|- diagnosis-{angle4}.json # Diagnosis angle 4 (if applicable) +|- diagnoses-manifest.json # Diagnosis index ++- fix-plan.json # Fix plan ``` -**Folder Naming Convention**: -- `{bug-slug}`: First 40 characters of bug description, lowercased, non-alphanumeric replaced with `-` -- `{short-timestamp}`: YYYY-MM-DD-HH-mm-ss format -- Example: `.workflow/.lite-fix/user-avatar-upload-fails-413-2025-01-15-14-30-45/` - -**File Contents**: -- `diagnosis.json`: Complete diagnosisContext object (Phase 1) -- `impact.json`: Complete impactContext object (Phase 2) -- `fix-plan.json`: Complete fixPlan object (Phase 3) -- `task.json`: Enhanced Task JSON with all context (Phase 6) -- `followup.json`: Follow-up tasks (hotfix mode only) - -**Access Patterns**: -- **lite-fix**: Creates folder and writes all artifacts during execution, passes paths via `executionContext.session.artifacts` -- **lite-execute**: Reads artifact paths from `executionContext.session.artifacts` -- **User**: Can inspect artifacts for debugging or reference -- **Reuse**: Pass `task.json` path to `/workflow:lite-execute {path}` for re-execution - - - -**Legacy Cache** (deprecated, use session folder instead): +**Example**: ``` -.workflow/.lite-fix-cache/ -└── diagnosis-cache/ - └── ${bug_hash}.json +.workflow/.lite-fix/user-avatar-upload-fails-413-2025-11-25-14-30-25/ +|- diagnosis-error-handling.json +|- diagnosis-dataflow.json +|- diagnosis-validation.json +|- diagnoses-manifest.json ++- fix-plan.json ``` +## Error Handling -## Quality Gates +| Error | Resolution | +|-------|------------| +| Diagnosis agent failure | Skip diagnosis, continue with bug description only | +| Planning agent failure | Fallback to direct planning by Claude | +| Clarification timeout | Use diagnosis findings as-is | +| Confirmation timeout | Save context, display resume instructions | +| Modify loop > 3 times | Suggest breaking task or using /workflow:plan | +| Root cause unclear | Extend diagnosis time or use broader angles | +| Too complex for lite-fix | Escalate to /workflow:plan --mode bugfix | -**Before execution** (auto-checked): -- [ ] Root cause identified (>70% confidence for default, >90% for hotfix) -- [ ] Impact scope defined -- [ ] Fix strategy reviewed -- [ ] Verification plan matches risk level -**Hotfix-specific**: -- [ ] Production tag identified -- [ ] Rollback plan documented -- [ ] Follow-up tasks generated -- [ ] Monitoring configured - ---- - -## When to Use lite-fix - -✅ **Perfect for:** -- Any bug with clear symptoms -- Localized fixes (1-5 files) -- Known technology stack -- Time-sensitive but not catastrophic (default mode adapts) -- Production incidents (use --hotfix) - -❌ **Not suitable for:** -- Root cause completely unclear → use `/cli:mode:bug-diagnosis` first -- Requires architectural changes → use `/workflow:plan` -- Complex legacy code without tests → use `/workflow:plan --legacy-refactor` -- Performance deep-dive → use `/workflow:plan --performance-optimization` -- Data migration → use `/workflow:plan --data-migration` - ---- - -**Last Updated**: 2025-11-20 -**Version**: 2.0.0 -**Status**: Design Document (Simplified) diff --git a/.claude/workflows/cli-templates/schemas/diagnosis-json-schema.json b/.claude/workflows/cli-templates/schemas/diagnosis-json-schema.json new file mode 100644 index 00000000..155082eb --- /dev/null +++ b/.claude/workflows/cli-templates/schemas/diagnosis-json-schema.json @@ -0,0 +1,234 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Diagnosis Context Schema", + "description": "Bug diagnosis results from cli-explore-agent for root cause analysis", + "type": "object", + "required": [ + "symptom", + "root_cause", + "affected_files", + "reproduction_steps", + "fix_hints", + "dependencies", + "constraints", + "clarification_needs", + "_metadata" + ], + "properties": { + "symptom": { + "type": "object", + "required": ["description", "error_message"], + "properties": { + "description": { + "type": "string", + "description": "Human-readable description of the bug symptoms" + }, + "error_message": { + "type": ["string", "null"], + "description": "Exact error message if available, null if no specific error" + }, + "stack_trace": { + "type": ["string", "null"], + "description": "Stack trace excerpt if available" + }, + "frequency": { + "type": "string", + "enum": ["always", "intermittent", "rare", "unknown"], + "description": "How often the bug occurs" + }, + "user_impact": { + "type": "string", + "description": "How the bug affects end users" + } + }, + "description": "Observable symptoms and error manifestation" + }, + "root_cause": { + "type": "object", + "required": ["file", "issue", "confidence"], + "properties": { + "file": { + "type": "string", + "description": "File path where the root cause is located" + }, + "line_range": { + "type": "string", + "description": "Line range containing the bug (e.g., '45-60')" + }, + "function": { + "type": "string", + "description": "Function or method name containing the bug" + }, + "issue": { + "type": "string", + "description": "Description of what's wrong in the code" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score 0.0-1.0 (0.8+ high, 0.5-0.8 medium, <0.5 low)" + }, + "introduced_by": { + "type": "string", + "description": "Commit hash or date when bug was introduced (if known)" + }, + "category": { + "type": "string", + "enum": ["logic_error", "edge_case", "race_condition", "null_reference", "type_mismatch", "resource_leak", "validation", "integration", "configuration", "other"], + "description": "Bug category classification" + } + }, + "description": "Root cause analysis with confidence score" + }, + "affected_files": { + "type": "array", + "items": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "required": ["path", "relevance"], + "properties": { + "path": {"type": "string", "description": "File path relative to project root"}, + "relevance": {"type": "number", "minimum": 0, "maximum": 1, "description": "Relevance score 0.0-1.0 (0.7+ high, 0.5-0.7 medium, <0.5 low)"}, + "rationale": {"type": "string", "description": "Brief explanation of why this file is affected from this diagnosis angle"}, + "change_type": { + "type": "string", + "enum": ["fix_target", "needs_update", "test_coverage", "reference_only"], + "description": "Type of change needed for this file" + } + } + } + ] + }, + "description": "Files affected by the bug. Prefer object format with relevance scores for synthesis prioritization." + }, + "reproduction_steps": { + "type": "array", + "items": {"type": "string"}, + "minItems": 1, + "description": "Step-by-step instructions to reproduce the bug" + }, + "fix_hints": { + "type": "array", + "items": { + "type": "object", + "required": ["description", "approach"], + "properties": { + "description": { + "type": "string", + "description": "What needs to be fixed" + }, + "approach": { + "type": "string", + "description": "Suggested fix approach with specific guidance" + }, + "code_example": { + "type": "string", + "description": "Example code snippet showing the fix pattern" + }, + "risk": { + "type": "string", + "enum": ["low", "medium", "high"], + "description": "Risk level of implementing this fix" + } + } + }, + "description": "Actionable fix suggestions from this diagnosis angle" + }, + "dependencies": { + "type": "string", + "description": "External and internal dependencies relevant to the bug" + }, + "constraints": { + "type": "string", + "description": "Technical constraints and limitations affecting the fix" + }, + "related_issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["similar_bug", "regression", "related_feature", "tech_debt"], + "description": "Relationship type" + }, + "reference": { + "type": "string", + "description": "Issue ID, commit hash, or file reference" + }, + "description": { + "type": "string", + "description": "Brief description of the relationship" + } + } + }, + "description": "Related issues, regressions, or similar bugs found during diagnosis" + }, + "clarification_needs": { + "type": "array", + "items": { + "type": "object", + "required": ["question", "context", "options"], + "properties": { + "question": { + "type": "string", + "description": "The clarification question to ask user" + }, + "context": { + "type": "string", + "description": "Background context explaining why this clarification is needed" + }, + "options": { + "type": "array", + "items": {"type": "string"}, + "description": "Available options for user to choose from (2-4 options)" + } + } + }, + "description": "Ambiguities requiring user input before fix planning" + }, + "_metadata": { + "type": "object", + "required": ["timestamp", "bug_description", "source"], + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp of diagnosis" + }, + "bug_description": { + "type": "string", + "description": "Original bug description that triggered diagnosis" + }, + "source": { + "type": "string", + "const": "cli-explore-agent", + "description": "Agent that performed diagnosis" + }, + "diagnosis_angle": { + "type": "string", + "description": "Diagnosis angle (e.g., 'error-handling', 'dataflow', 'state-management')" + }, + "diagnosis_index": { + "type": "integer", + "minimum": 1, + "maximum": 4, + "description": "Diagnosis index (1-4) in parallel diagnosis set" + }, + "total_diagnoses": { + "type": "integer", + "minimum": 1, + "maximum": 4, + "description": "Total number of parallel diagnoses" + }, + "duration_seconds": { + "type": "integer", + "description": "Diagnosis duration in seconds" + } + } + } + } +} diff --git a/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json b/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json new file mode 100644 index 00000000..0b5d8260 --- /dev/null +++ b/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json @@ -0,0 +1,273 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Fix Plan Schema", + "description": "Bug fix plan from cli-lite-planning-agent or direct planning", + "type": "object", + "required": [ + "summary", + "root_cause", + "strategy", + "tasks", + "estimated_time", + "recommended_execution", + "severity", + "risk_level", + "_metadata" + ], + "properties": { + "summary": { + "type": "string", + "description": "2-3 sentence overview of the fix plan" + }, + "root_cause": { + "type": "string", + "description": "Consolidated root cause statement from all diagnoses" + }, + "strategy": { + "type": "string", + "enum": ["immediate_patch", "comprehensive_fix", "refactor"], + "description": "Fix strategy: immediate_patch (minimal change), comprehensive_fix (proper solution), refactor (structural improvement)" + }, + "tasks": { + "type": "array", + "minItems": 1, + "maxItems": 5, + "items": { + "type": "object", + "required": ["id", "title", "scope", "action", "description", "implementation", "verification"], + "properties": { + "id": { + "type": "string", + "pattern": "^FIX[0-9]+$", + "description": "Task identifier (FIX1, FIX2, FIX3...)" + }, + "title": { + "type": "string", + "description": "Task title (action verb + target, e.g., 'Fix token validation edge case')" + }, + "scope": { + "type": "string", + "description": "Task scope: module path (src/auth/), feature name, or single file. Prefer module level." + }, + "file": { + "type": "string", + "description": "Primary file (deprecated, use scope + modification_points instead)" + }, + "action": { + "type": "string", + "enum": ["Fix", "Update", "Refactor", "Add", "Delete", "Configure"], + "description": "Primary action type" + }, + "description": { + "type": "string", + "description": "What to fix (1-2 sentences)" + }, + "modification_points": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["file", "target", "change"], + "properties": { + "file": { + "type": "string", + "description": "File path within scope" + }, + "target": { + "type": "string", + "description": "Function/class/line range (e.g., 'validateToken:45-60')" + }, + "change": { + "type": "string", + "description": "Brief description of change" + } + } + }, + "description": "All modification points for this fix task. Group related changes into one task." + }, + "implementation": { + "type": "array", + "items": {"type": "string"}, + "minItems": 2, + "maxItems": 5, + "description": "Step-by-step fix implementation guide" + }, + "verification": { + "type": "array", + "items": {"type": "string"}, + "minItems": 1, + "maxItems": 3, + "description": "Verification/test criteria to confirm fix works" + }, + "reference": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Pattern name to follow" + }, + "files": { + "type": "array", + "items": {"type": "string"}, + "description": "Reference file paths to study" + }, + "examples": { + "type": "string", + "description": "Specific guidance or example references" + } + }, + "description": "Reference materials for fix implementation (optional)" + }, + "depends_on": { + "type": "array", + "items": { + "type": "string", + "pattern": "^FIX[0-9]+$" + }, + "description": "Task IDs this task depends on (e.g., ['FIX1'])" + }, + "risk": { + "type": "string", + "enum": ["low", "medium", "high"], + "description": "Risk level of this specific fix task" + } + } + }, + "description": "Structured fix task breakdown (1-5 tasks)" + }, + "flow_control": { + "type": "object", + "properties": { + "execution_order": { + "type": "array", + "items": { + "type": "object", + "properties": { + "phase": { + "type": "string", + "description": "Phase name (e.g., 'parallel-1', 'sequential-1')" + }, + "tasks": { + "type": "array", + "items": {"type": "string"}, + "description": "Task IDs in this phase" + }, + "type": { + "type": "string", + "enum": ["parallel", "sequential"], + "description": "Execution type" + } + } + }, + "description": "Ordered execution phases" + }, + "exit_conditions": { + "type": "object", + "properties": { + "success": { + "type": "string", + "description": "Condition for successful fix completion" + }, + "failure": { + "type": "string", + "description": "Condition that indicates fix failure" + } + }, + "description": "Conditions for fix workflow termination" + } + }, + "description": "Execution flow control (optional, auto-inferred from depends_on if not provided)" + }, + "focus_paths": { + "type": "array", + "items": {"type": "string"}, + "description": "Key file paths affected by this fix (aggregated from tasks)" + }, + "test_strategy": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": ["unit", "integration", "e2e", "smoke", "full"], + "description": "Test scope to run after fix" + }, + "specific_tests": { + "type": "array", + "items": {"type": "string"}, + "description": "Specific test files or patterns to run" + }, + "manual_verification": { + "type": "array", + "items": {"type": "string"}, + "description": "Manual verification steps if automated tests not available" + } + }, + "description": "Testing strategy for fix verification" + }, + "rollback_plan": { + "type": "object", + "properties": { + "strategy": { + "type": "string", + "enum": ["git_revert", "feature_flag", "manual"], + "description": "Rollback strategy if fix fails" + }, + "steps": { + "type": "array", + "items": {"type": "string"}, + "description": "Rollback steps" + } + }, + "description": "Rollback plan if fix causes issues (optional, recommended for high severity)" + }, + "estimated_time": { + "type": "string", + "description": "Total estimated fix time (e.g., '30 minutes', '2 hours')" + }, + "recommended_execution": { + "type": "string", + "enum": ["Agent", "Codex"], + "description": "Recommended execution method based on complexity" + }, + "severity": { + "type": "string", + "enum": ["Low", "Medium", "High", "Critical"], + "description": "Bug severity level" + }, + "risk_level": { + "type": "string", + "enum": ["low", "medium", "high"], + "description": "Risk level of implementing the fix" + }, + "_metadata": { + "type": "object", + "required": ["timestamp", "source"], + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp of planning" + }, + "source": { + "type": "string", + "enum": ["cli-lite-planning-agent", "direct-planning"], + "description": "Planning source" + }, + "planning_mode": { + "type": "string", + "enum": ["direct", "agent-based"], + "description": "Planning execution mode" + }, + "diagnosis_angles": { + "type": "array", + "items": {"type": "string"}, + "description": "Diagnosis angles used for context" + }, + "duration_seconds": { + "type": "integer", + "description": "Planning duration in seconds" + } + } + } + } +} diff --git a/.claude/workflows/intelligent-tools-strategy.md b/.claude/workflows/intelligent-tools-strategy.md index ea0c3e48..30cedb9c 100644 --- a/.claude/workflows/intelligent-tools-strategy.md +++ b/.claude/workflows/intelligent-tools-strategy.md @@ -41,20 +41,12 @@ codex -C [dir] --full-auto exec "[prompt]" [--skip-git-repo-check -s danger-full ### Model Selection -**Gemini**: -- `gemini-2.5-pro` - Default model (auto-selected) -- `gemini-2.5-flash` - Fast processing +**Available Models** (user selects via `-m` after prompt): +- Gemini: `gemini-2.5-pro`, `gemini-2.5-flash` +- Qwen: `coder-model`, `vision-model` +- Codex: `gpt-5.1`, `gpt-5.1-codex`, `gpt-5.1-codex-mini` -**Qwen**: -- `coder-model` - Default model (auto-selected) -- `vision-model` - Image analysis (rare) - -**Codex**: -- `gpt-5.1` - Default model (auto-selected) -- `gpt-5.1-codex` - Extended capabilities -- `gpt-5.1-codex-mini` - Lightweight tasks - -**Note**: All tools auto-select appropriate models. `-m` parameter rarely needed; omit for best results +**Usage**: `-m ` placed AFTER `-p "prompt"` (e.g., `gemini -p "..." -m gemini-2.5-flash`) ### Quick Decision Matrix @@ -582,10 +574,13 @@ prompts/ ### Dynamic Timeout Allocation +**Minimum timeout: 5 minutes (300000ms)** - Never set below this threshold. + **Timeout Ranges**: -- **Simple** (analysis, search): 20-40min (1200000-2400000ms) -- **Medium** (refactoring, documentation): 40-60min (2400000-3600000ms) -- **Complex** (implementation, migration): 60-120min (3600000-7200000ms) +- **Simple** (analysis, search): 5-10min (300000-600000ms) +- **Medium** (refactoring, documentation): 10-20min (600000-1200000ms) +- **Complex** (implementation, migration): 20-60min (1200000-3600000ms) +- **Heavy** (large codebase, multi-file): 60-120min (3600000-7200000ms) **Codex Multiplier**: 1.5x of allocated time