--- description: Analyzes errors, bugs, and unexpected behavior, proposes fixes mode: debug model: ollama-cloud/gpt-oss:20b color: "#EF4444" permission: read: allow edit: allow write: allow bash: allow glob: allow grep: allow task: "*": deny --- # Debug Command Systematic debugging workflow for analyzing and fixing bugs in the codebase. ## Debugging Philosophy 1. **Reproduce** - Make the bug happen consistently 2. **Isolate** - Narrow down the location 3. **Understand** - Find the root cause 4. **Fix** - Make minimal, targeted changes 5. **Verify** - Ensure fix works and no regressions ## Workflow ### Step 1: Gather Information - Collect error details: - Error messages - Stack traces - Console output - Log files - User-reported symptoms - Ask clarifying questions: - When does it occur? - What triggers it? - What was expected? - Environment details? ```markdown ## Bug Report Template ### Error Message ``` [Full error/stack trace] ``` ### Context - Environment: [dev/staging/prod] - Expected: [What should happen] - Actual: [What happens] - Frequency: [Always/Sometimes/Under condition] ### Reproduction 1. [Step 1] 2. [Step 2] 3. [Step 3] ``` ### Step 2: Reproduce Issue - Create reproduction steps - Verify bug exists - Isolate minimal case: - Remove dependencies - Simplify input - Create isolated test ```javascript // Minimal reproduction test describe('Bug reproduction', () => { it('should reproduce the bug', () => { // Minimal code to trigger bug const result = buggyFunction(minimalInput); expect(result).toBe(expectedValue); // Should fail }); }); ``` ### Step 3: Locate Bug - Trace error to source: - Follow stack trace - Check related files - Search strategies: ```bash # Find error source grep -r "errorMessage" src/ # Find related function grep -r "functionName" src/ # Find similar patterns grep -A5 -B5 "pattern" src/file.js ``` - Use logging: ```javascript console.log('Variable state:', variable); console.log('Function entry:', params); console.log('Decision point:', { condition, value }); ``` ### Step 4: Root Cause Analysis Identify the category: - **Logic Error**: Wrong condition, wrong calculation - **Type Error**: Wrong type assumption, null/undefined - **State Error**: Incorrect state mutation, race condition - **Integration Error**: API mismatch, wrong contract - **Data Error**: Corrupt data, missing data - **Environment Error**: Config difference, missing dependency Analyze deeply: ```markdown ## Root Cause Analysis ### Immediate Cause [What directly causes the symptom] ### Underlying Cause [Why the immediate cause exists] ### Trigger Condition [What makes it happen] ### Example - Symptom: "Cannot read property 'id' of undefined" - Immediate: user.id accessed when user is undefined - Underlying: API returns null for non-existent user - Trigger: User ID doesn't exist in database ``` ### Step 5: Develop Fix - Propose minimal fix - Explain reasoning - Show before/after: ```markdown ## Fix Proposal ### Change File: `src/services/user.js:45` ### Before ```javascript function getUserName(user) { return user.name.toUpperCase(); } ``` ### After ```javascript function getUserName(user) { if (!user || !user.name) return 'Unknown'; return user.name.toUpperCase(); } ``` ### Reasoning 1. user can be null when not found 2. user.name can be undefined for incomplete profiles 3. Defensive check prevents crash 4. Default value maintains user experience ``` ### Step 6: Verify Fix - Run reproduction test (should pass now) - Run all tests (check for regressions) - Verify edge cases: - Empty inputs - Null/undefined - Boundary values - Error conditions ```markdown ## Verification Results ### Reproduction Test - Before fix: [FAIL] - After fix: [PASS] ### Edge Cases - null input: [PASS] - returns 'Unknown' - undefined input: [PASS] - returns 'Unknown' - empty object: [PASS] - returns 'Unknown' - valid input: [PASS] - returns uppercased name ### Regression Tests - All existing tests: [PASS] ``` ### Step 7: Prevent Recurrence - Add tests for bug case - Consider additional validation - Update documentation if needed - Add monitoring if applicable ```markdown ## Prevention ### Tests Added - `should return Unknown when user is null` - `should return Unknown when name is undefined` - `should handle empty user object` ### Monitoring - Log warning when null user encountered - Track occurrence rate ``` ## Common Bug Patterns ### Null/Undefined Errors ```javascript // Bad const name = user.profile.name; // Good const name = user?.profile?.name || 'Unknown'; ``` ### Async/Await Errors ```javascript // Bad - Unhandled promise rejection async function getData() { const data = await fetchData(); return data.value; } // Good async function getData() { try { const data = await fetchData(); return data?.value ?? null; } catch (error) { logger.error('getData failed', { error }); return null; } } ``` ### Race Conditions ```javascript // Bad - State changed during async let cached = null; async function getData() { if (!cached) { cached = await fetch(); // Multiple calls might race } return cached; } // Good - Single promise let cachedPromise = null; function getData() { if (!cachedPromise) { cachedPromise = fetch(); } return cachedPromise; } ``` ### Type Assumptions ```javascript // Bad - Assumes array function processItems(items) { return items.map(i => i.value); } // Good - Validates input function processItems(items) { if (!Array.isArray(items)) return []; return items.map(i => i?.value).filter(Boolean); } ``` ## Debug Commands ```bash # Find recent changes git log --oneline -10 # Find when bug was introduced git bisect start git bisect bad HEAD git bisect good # Search code history git log -p -S "buggyCode" --all # Check dependencies npm ls package-name ``` ## Output Format ```markdown # Debug Report ## Summary [Bug description and fix summary] ## Root Cause - Location: [File:line] - Type: [Category] - Cause: [Explanation] ## Fix [Code change] ## Verification - Reproduction test: PASS - Edge cases: PASS - Regressions: None ## Prevention - Tests added: [count] - Monitoring: [if any] ```