UNPKG

@claude-powers/slash-commands

Version:

๐Ÿš€ Claude Powers - Essential slash commands for Claude Code

531 lines (449 loc) โ€ข 15.4 kB
# Fix Bugs Command Auto-detects, analyzes, and fixes bugs automatically using advanced AI, reducing production bugs by up to 90%. ## Description The `/fix-bugs` command represents the future of bug fixing: - **Automatic detection** of common and complex bugs - **Root cause analysis** to understand the real problem - **Intelligent correction** that preserves functionality - **Automatic testing** of fixes before applying - **Learning mode** that learns from project patterns - **Safe mode** with automatic rollback if something goes wrong - **Detailed explanations** of each applied fix - **Prevention suggestions** to avoid similar bugs ## Usage ``` /fix-bugs [directory] [--types] [--confidence] [--mode] [--test-after] ``` ### Parameters - `directory`: specific directory to analyze and fix - `--types`: Types of bugs to look for (memory-leaks, null-pointers, race-conditions, etc.) - `--confidence`: Minimum confidence level to apply fixes (low, medium, high) - `--mode`: Operation mode (safe, aggressive, learning, preview) - `--test-after`: Run tests after each fix - `--rollback-on-fail`: Automatic rollback if tests fail - `--explain`: Explain each fix made - `--prevent`: Suggest changes to prevent similar bugs ### Examples ``` /fix-bugs /fix-bugs src/ --types=memory-leaks,null-pointers --confidence=high /fix-bugs --mode=safe --test-after --rollback-on-fail /fix-bugs utils/ --mode=learning --explain /fix-bugs --types=race-conditions --confidence=medium --prevent /fix-bugs components/ --mode=preview --dry-run ``` ## Types of Bugs Detected and Fixed ### ๐Ÿšจ Memory Leaks ```javascript // โŒ BEFORE - Memory leak detected function DataProcessor() { const data = []; useEffect(() => { const interval = setInterval(() => { fetchData().then(newData => { data.push(...newData); // Memory leak: array grows indefinitely }); }, 1000); // Missing cleanup }, []); return <div>{data.length} items</div>; } // โœ… AFTER - Automatic fix applied function DataProcessor() { const [data, setData] = useState([]); useEffect(() => { const interval = setInterval(() => { fetchData().then(newData => { setData(prevData => { // Limit array size to prevent memory leak const combined = [...prevData, ...newData]; return combined.slice(-1000); // Keep only last 1000 items }); }); }, 1000); // Automatically added cleanup return () => clearInterval(interval); }, []); return <div>{data.length} items</div>; } ``` ### ๐ŸŽฏ Null Pointer Exceptions ```javascript // โŒ BEFORE - Potential null pointer function UserProfile({ user }) { return ( <div> <h1>{user.name}</h1> {/* Crash if user is null */} <img src={user.avatar.url} alt="Avatar" /> {/* Double null risk */} <p>Joined: {user.createdAt.toLocaleDateString()}</p> </div> ); } // โœ… AFTER - Null safety automatically added function UserProfile({ user }) { // Null check automatically added if (!user) { return <div>Loading user...</div>; } return ( <div> <h1>{user.name || 'Anonymous User'}</h1> <img src={user.avatar?.url || '/default-avatar.png'} alt="Avatar" onError={(e) => { e.target.src = '/default-avatar.png'; }} /> <p> Joined: {user.createdAt ? new Date(user.createdAt).toLocaleDateString() : 'Unknown' } </p> </div> ); } ``` ### โšก Race Conditions ```javascript // โŒ BEFORE - Race condition in async operations async function updateUserData(userId, newData) { const user = await fetchUser(userId); const updated = { ...user, ...newData }; // Race condition: user might have changed between fetch and save await saveUser(userId, updated); } // โœ… AFTER - Race condition eliminated async function updateUserData(userId, newData) { let retries = 3; while (retries > 0) { try { const user = await fetchUser(userId); const updated = { ...user, ...newData, version: user.version + 1 }; // Optimistic locking automatically added await saveUserWithVersion(userId, updated, user.version); return updated; } catch (error) { if (error.code === 'VERSION_CONFLICT' && retries > 1) { retries--; // Exponential backoff added await new Promise(resolve => setTimeout(resolve, Math.pow(2, 3 - retries) * 100)); continue; } throw error; } } } ``` ### ๐Ÿ”„ Infinite Loops / Recursion ```javascript // โŒ BEFORE - Potential infinite recursion function calculateFactorial(n) { if (n === 0) return 1; return n * calculateFactorial(n - 1); // No protection against negative numbers } // โœ… AFTER - Safe recursion with guards function calculateFactorial(n) { // Input validation automatically added if (typeof n !== 'number' || !Number.isInteger(n)) { throw new Error('Input must be a non-negative integer'); } if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } // Stack overflow protection if (n > 170) { throw new Error('Number too large: factorial would exceed JavaScript number limits'); } if (n === 0 || n === 1) return 1; return n * calculateFactorial(n - 1); } ``` ### ๐ŸŒ Async/Await Issues ```javascript // โŒ BEFORE - Unhandled promise rejections async function processData() { const data = await fetchData(); // Unhandled if it throws data.forEach(async item => { await processItem(item); // Won't wait for completion }); console.log('All done!'); // Executes immediately } // โœ… AFTER - Proper async handling async function processData() { try { const data = await fetchData(); // Promise.all added for concurrent processing await Promise.all( data.map(async item => { try { return await processItem(item); } catch (error) { console.error(`Failed to process item ${item.id}:`, error); // Continue processing other items return null; } }) ); console.log('All processing completed!'); } catch (error) { console.error('Failed to fetch data:', error); throw new Error(`Data processing failed: ${error.message}`); } } ``` ### ๐Ÿ” Security Vulnerabilities ```javascript // โŒ BEFORE - XSS vulnerability function UserComment({ comment }) { return ( <div dangerouslySetInnerHTML={{ __html: comment.text }} // XSS risk /> ); } // โœ… AFTER - XSS protection added import DOMPurify from 'dompurify'; function UserComment({ comment }) { // Automatic sanitization added const sanitizedText = DOMPurify.sanitize(comment.text, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'], ALLOWED_ATTR: ['href'], ALLOWED_URI_REGEXP: /^https?:\/\// }); return ( <div dangerouslySetInnerHTML={{ __html: sanitizedText }} /> ); } ``` ## Configuration `.claude/fix-bugs-config.json`: ```json { "confidence": { "minimum": "medium", "autoApply": "high", "requireConfirmation": "low" }, "bugTypes": { "memoryLeaks": { "enabled": true, "priority": "high", "patterns": ["event-listeners", "intervals", "observers", "subscriptions"] }, "nullPointers": { "enabled": true, "priority": "high", "addGuards": true, "defaultValues": true }, "raceConditions": { "enabled": true, "priority": "medium", "addLocking": true, "retryLogic": true }, "infiniteLoops": { "enabled": true, "priority": "high", "maxIterations": 10000, "stackProtection": true }, "asyncIssues": { "enabled": true, "priority": "medium", "promiseHandling": true, "errorBoundaries": true }, "securityVulns": { "enabled": true, "priority": "critical", "autoSanitize": true, "validateInputs": true }, "performanceIssues": { "enabled": false, "priority": "low", "inefficientAlgorithms": true, "memoryOptimization": true } }, "safety": { "backupBeforeFix": true, "runTestsAfterFix": true, "rollbackOnTestFail": true, "maxFilesPerRun": 10, "requireUserConfirmation": false }, "learning": { "enabled": true, "storePatterns": true, "adaptToProject": true, "suggestPreventions": true }, "testing": { "generateTestsForFixes": true, "runExistingTests": true, "performanceRegression": true, "securityRegression": true } } ``` ## Command Output ### Bug Analysis ``` ๐Ÿ”ง CLAUDE POWER - BUG DETECTION & FIXING ======================================== ๐Ÿ” ANALYSIS COMPLETED: scanned files: 127 analyzed lines: 15,847 analysis time: 23.4s ๐Ÿšจ DETECTED BUGS: โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Type โ”‚ Count โ”‚ Severity โ”‚ Fixable โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Memory Leaks โ”‚ 8 โ”‚ High โ”‚ 8 โ”‚ โ”‚ Null Pointers โ”‚ 15 โ”‚ High โ”‚ 15 โ”‚ โ”‚ Race Conditions โ”‚ 3 โ”‚ Medium โ”‚ 3 โ”‚ โ”‚ Infinite Loops โ”‚ 2 โ”‚ High โ”‚ 2 โ”‚ โ”‚ Async Issues โ”‚ 12 โ”‚ Medium โ”‚ 11 โ”‚ โ”‚ Security Vulns โ”‚ 4 โ”‚ Critical โ”‚ 4 โ”‚ โ”‚ Performance Issues โ”‚ 7 โ”‚ Low โ”‚ 5 โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ๐ŸŽฏ CONFIDENCE LEVELS: โ€ข High Confidence: 32 bugs (auto-fix available) โ€ข Medium Confidence: 15 bugs (review recommended) โ€ข Low Confidence: 3 bugs (manual review required) โšก TOTAL IMPACT: โ€ข Critical bugs that could crash app: 19 โ€ข Security vulnerabilities: 4 โ€ข Performance degradations: 7 โ€ข Maintainability issues: 20 ``` ### Applied Fixes ``` ๐Ÿ”ง AUTOMATICALLY APPLIED FIXES: ================================== ๐Ÿ“ src/components/UserDashboard.tsx ๐Ÿšจ [CRITICAL] Memory leak in useEffect (line 45) โœ… Fixed: Added cleanup in return statement โœ… Tested: Unit tests passing ๐Ÿ’ก Prevention: Use custom hook useInterval for intervals ๐Ÿ“ src/utils/dataProcessor.js ๐ŸŽฏ [HIGH] Null pointer in processUserData (line 78) โœ… Fixed: Added null guards and default values โœ… Tested: Integration tests passing ๐Ÿ’ก Prevention: Use TypeScript for null safety ๐Ÿ“ src/services/ApiService.js โšก [MEDIUM] Race condition in updateUser (line 134) โœ… Fixed: Implemented optimistic locking โœ… Tested: Race condition tests added ๐Ÿ’ก Prevention: Implement state management with Redux Toolkit ๐Ÿ“ src/hooks/useAuth.ts ๐Ÿ” [CRITICAL] XSS vulnerability in user input (line 23) โœ… Fixed: Added sanitization with DOMPurify โœ… Tested: Security tests added ๐Ÿ’ก Prevention: Input validation in backend as well ๐Ÿงช TESTING RESULTS: โ€ข Tests executed: 247 โ€ข Tests passing: 247 (100%) โ€ข New coverage: 94.2% (+3.1%) โ€ข Execution time: 12.3s โ€ข Performance regression: None detected ๐Ÿ“Š POST-FIX METRICS: โ€ข Critical bugs eliminated: 19 โ†’ 0 (100% reduction) โ€ข Security vulnerabilities: 4 โ†’ 0 (100% reduction) โ€ข Static warnings: 87 โ†’ 23 (73% reduction) โ€ข Average cyclomatic complexity: 8.2 โ†’ 6.4 (22% improvement) ๐Ÿ’ก SUGGESTED PREVENTION: 1. Configure ESLint rules for memory leaks 2. Implement TypeScript strict mode 3. Add pre-commit hooks for security scanning 4. Setup automated dependency vulnerability scanning 5. Implement error boundaries in React components ``` ### Learning Mode Output ``` ๐Ÿง  CLAUDE POWER - LEARNING MODE INSIGHTS ======================================== ๐Ÿ“ˆ DETECTED PATTERNS IN YOUR PROJECT: โ€ข Frequent use of useEffect without cleanup (8 cases) โ€ข Common pattern: fetching data in components (12 cases) โ€ข Anti-pattern: inconsistent null checks (15 cases) โ€ข Memory leak pattern: intervals without clear (5 cases) ๐ŸŽฏ PERSONALIZED RECOMMENDATIONS: 1. Create custom hook useApiData for data fetching 2. Implement utility function saflyAccess for null safety 3. Setup ESLint rule react-hooks/exhaustive-deps 4. Create wrapper component for error boundaries ๐Ÿ“š UPDATED KNOWLEDGE BASE: โ€ข Saved 23 new project-specific bug patterns โ€ข Updated confidence in 12 types of fixes โ€ข Learned 8 new prevention strategies โ€ข Generated 15 custom ESLint rules ๐Ÿ”„ AUTOMATIC ADAPTATION: โ€ข Confidence levels adjusted based on success rate โ€ข Fix templates updated for your coding style โ€ข Automatic exclusions for detected false positives โ€ข Priorities rebalanced according to impact on your codebase ``` ## Advanced Integrations ### Pre-commit Hook ```bash #!/bin/sh # .git/hooks/pre-commit echo "๐Ÿ”ง Running auto bug detection and fixing..." # Run bug detection with high confidence auto-fix npx claude-power fix-bugs \ --staged-only \ --confidence=high \ --test-after \ --rollback-on-fail if [ $? -ne 0 ]; then echo "โŒ Critical bugs detected that require manual review" echo "Run 'npx claude-power fix-bugs --mode=preview' to see issues" exit 1 fi echo "โœ… No critical bugs detected, commit proceeding" ``` ### GitHub Actions ```yaml name: Auto Bug Fix on: push: branches: [develop, feature/*] pull_request: branches: [main, develop] jobs: auto-fix-bugs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: token: ${{ secrets.GITHUB_TOKEN }} - name: Setup Node.js uses: actions/setup-node@v3 - name: Install dependencies run: npm ci - name: Run auto bug fixes run: | npx claude-power fix-bugs \ --confidence=high \ --test-after \ --mode=safe \ --output=json > bug-fixes.json - name: Commit auto-fixes run: | if [ -s bug-fixes.json ]; then git config --local user.email "action@github.com" git config --local user.name "Claude Power Auto-Fix" git add . git commit -m "fix: auto-fix bugs detected by Claude Power $(cat bug-fixes.json | jq -r '.fixes[].description' | head -5) Co-authored-by: Claude Power <claude@anthropic.com>" git push fi ``` --- *Part of the **Claude Power** ecosystem - Bugs automatically eliminated* ๐Ÿ”ง๐Ÿš€