{"id":"debugging-strategies","name":"debugging-strategies","summary":"体系的なデバッグ技術、プロファイリングツール、根本原因分析を習得し、あらゆるコードベースや技術スタックでバグを効率的に追跡しましょう。","body":"# Debugging Strategies\n\nTransform debugging from frustrating guesswork into systematic problem-solving with proven strategies, powerful tools, and methodical approaches.\n\n## When to Use This Skill\n\n- Tracking down elusive bugs\n- Investigating performance issues\n- Understanding unfamiliar codebases\n- Debugging production issues\n- Analyzing crash dumps and stack traces\n- Profiling application performance\n- Investigating memory leaks\n- Debugging distributed systems\n\n## Core Principles\n\n### 1. The Scientific Method\n\n**1. Observe**: What's the actual behavior?\n**2. Hypothesize**: What could be causing it?\n**3. Experiment**: Test your hypothesis\n**4. Analyze**: Did it prove/disprove your theory?\n**5. Repeat**: Until you find the root cause\n\n### 2. Debugging Mindset\n\n**Don't Assume:**\n\n- \"It can't be X\" - Yes it can\n- \"I didn't change Y\" - Check anyway\n- \"It works on my machine\" - Find out why\n\n**Do:**\n\n- Reproduce consistently\n- Isolate the problem\n- Keep detailed notes\n- Question everything\n- Take breaks when stuck\n\n### 3. Rubber Duck Debugging\n\nExplain your code and problem out loud (to a rubber duck, colleague, or yourself). Often reveals the issue.\n\n## Systematic Debugging Process\n\n### Phase 1: Reproduce\n\n```markdown\n## Reproduction Checklist\n\n1. **Can you reproduce it?**\n   - Always? Sometimes? Randomly?\n   - Specific conditions needed?\n   - Can others reproduce it?\n\n2. **Create minimal reproduction**\n   - Simplify to smallest example\n   - Remove unrelated code\n   - Isolate the problem\n\n3. **Document steps**\n   - Write down exact steps\n   - Note environment details\n   - Capture error messages\n```\n\n### Phase 2: Gather Information\n\n```markdown\n## Information Collection\n\n1. **Error Messages**\n   - Full stack trace\n   - Error codes\n   - Console/log output\n\n2. **Environment**\n   - OS version\n   - Language/runtime version\n   - Dependencies versions\n   - Environment variables\n\n3. **Recent Changes**\n   - Git history\n   - Deployment timeline\n   - Configuration changes\n\n4. **Scope**\n   - Affects all users or specific ones?\n   - All browsers or specific ones?\n   - Production only or also dev?\n```\n\n### Phase 3: Form Hypothesis\n\n```markdown\n## Hypothesis Formation\n\nBased on gathered info, ask:\n\n1. **What changed?**\n   - Recent code changes\n   - Dependency updates\n   - Infrastructure changes\n\n2. **What's different?**\n   - Working vs broken environment\n   - Working vs broken user\n   - Before vs after\n\n3. **Where could this fail?**\n   - Input validation\n   - Business logic\n   - Data layer\n   - External services\n```\n\n### Phase 4: Test & Verify\n\n```markdown\n## Testing Strategies\n\n1. **Binary Search**\n   - Comment out half the code\n   - Narrow down problematic section\n   - Repeat until found\n\n2. **Add Logging**\n   - Strategic console.log/print\n   - Track variable values\n   - Trace execution flow\n\n3. **Isolate Components**\n   - Test each piece separately\n   - Mock dependencies\n   - Remove complexity\n\n4. **Compare Working vs Broken**\n   - Diff configurations\n   - Diff environments\n   - Diff data\n```\n\n## Debugging Tools\n\n### JavaScript/TypeScript Debugging\n\n```typescript\n// Chrome DevTools Debugger\nfunction processOrder(order: Order) {\n  debugger; // Execution pauses here\n\n  const total = calculateTotal(order);\n  console.log(\"Total:\", total);\n\n  // Conditional breakpoint\n  if (order.items.length > 10) {\n    debugger; // Only breaks if condition true\n  }\n\n  return total;\n}\n\n// Console debugging techniques\nconsole.log(\"Value:\", value); // Basic\nconsole.table(arrayOfObjects); // Table format\nconsole.time(\"operation\");\n/* code */ console.timeEnd(\"operation\"); // Timing\nconsole.trace(); // Stack trace\nconsole.assert(value > 0, \"Value must be positive\"); // Assertion\n\n// Performance profiling\nperformance.mark(\"start-operation\");\n// ... operation code\nperformance.mark(\"end-operation\");\nperformance.measure(\"operation\", \"start-operation\", \"end-operation\");\nconsole.log(performance.getEntriesByType(\"measure\"));\n```\n\n**VS Code Debugger Configuration:**\n\n```json\n// .vscode/launch.json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Program\",\n      \"program\": \"${workspaceFolder}/src/index.ts\",\n      \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n      \"outFiles\": [\"${workspaceFolder}/dist/**/*.js\"],\n      \"skipFiles\": [\"<node_internals>/**\"]\n    },\n    {\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"name\": \"Debug Tests\",\n      \"program\": \"${workspaceFolder}/node_modules/jest/bin/jest\",\n      \"args\": [\"--runInBand\", \"--no-cache\"],\n      \"console\": \"integratedTerminal\"\n    }\n  ]\n}\n```\n\n### Python Debugging\n\n```python\n# Built-in debugger (pdb)\nimport pdb\n\ndef calculate_total(items):\n    total = 0\n    pdb.set_trace()  # Debugger starts here\n\n    for item in items:\n        total += item.price * item.quantity\n\n    return total\n\n# Breakpoint (Python 3.7+)\ndef process_order(order):\n    breakpoint()  # More convenient than pdb.set_trace()\n    # ... code\n\n# Post-mortem debugging\ntry:\n    risky_operation()\nexcept Exception:\n    import pdb\n    pdb.post_mortem()  # Debug at exception point\n\n# IPython debugging (ipdb)\nfrom ipdb import set_trace\nset_trace()  # Better interface than pdb\n\n# Logging for debugging\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\ndef fetch_user(user_id):\n    logger.debug(f'Fetching user: {user_id}')\n    user = db.query(User).get(user_id)\n    logger.debug(f'Found user: {user}')\n    return user\n\n# Profile performance\nimport cProfile\nimport pstats\n\ncProfile.run('slow_function()', 'profile_stats')\nstats = pstats.Stats('profile_stats')\nstats.sort_stats('cumulative')\nstats.print_stats(10)  # Top 10 slowest\n```\n\n### Go Debugging\n\n```go\n// Delve debugger\n// Install: go install github.com/go-delve/delve/cmd/dlv@latest\n// Run: dlv debug main.go\n\nimport (\n    \"fmt\"\n    \"runtime\"\n    \"runtime/debug\"\n)\n\n// Print stack trace\nfunc debugStack() {\n    debug.PrintStack()\n}\n\n// Panic recovery with debugging\nfunc processRequest() {\n    defer func() {\n        if r := recover(); r != nil {\n            fmt.Println(\"Panic:\", r)\n            debug.PrintStack()\n        }\n    }()\n\n    // ... code that might panic\n}\n\n// Memory profiling\nimport _ \"net/http/pprof\"\n// Visit http://localhost:6060/debug/pprof/\n\n// CPU profiling\nimport (\n    \"os\"\n    \"runtime/pprof\"\n)\n\nf, _ := os.Create(\"cpu.prof\")\npprof.StartCPUProfile(f)\ndefer pprof.StopCPUProfile()\n// ... code to profile\n```\n\n## Advanced Debugging Techniques\n\n### Technique 1: Binary Search Debugging\n\n```bash\n# Git bisect for finding regression\ngit bisect start\ngit bisect bad                    # Current commit is bad\ngit bisect good v1.0.0            # v1.0.0 was good\n\n# Git checks out middle commit\n# Test it, then:\ngit bisect good   # if it works\ngit bisect bad    # if it's broken\n\n# Continue until bug found\ngit bisect reset  # when done\n```\n\n### Technique 2: Differential Debugging\n\nCompare working vs broken:\n\n```markdown\n## What's Different?\n\n| Aspect       | Working     | Broken         |\n| ------------ | ----------- | -------------- |\n| Environment  | Development | Production     |\n| Node version | 18.16.0     | 18.15.0        |\n| Data         | Empty DB    | 1M records     |\n| User         | Admin       | Regular user   |\n| Browser      | Chrome      | Safari         |\n| Time         | During day  | After midnight |\n\nHypothesis: Time-based issue? Check timezone handling.\n```\n\n### Technique 3: Trace Debugging\n\n```typescript\n// Function call tracing\nfunction trace(\n  target: any,\n  propertyKey: string,\n  descriptor: PropertyDescriptor,\n) {\n  const originalMethod = descriptor.value;\n\n  descriptor.value = function (...args: any[]) {\n    console.log(`Calling ${propertyKey} with args:`, args);\n    const result = originalMethod.apply(this, args);\n    console.log(`${propertyKey} returned:`, result);\n    return result;\n  };\n\n  return descriptor;\n}\n\nclass OrderService {\n  @trace\n  calculateTotal(items: Item[]): number {\n    return items.reduce((sum, item) => sum + item.price, 0);\n  }\n}\n```\n\n### Technique 4: Memory Leak Detection\n\n```typescript\n// Chrome DevTools Memory Profiler\n// 1. Take heap snapshot\n// 2. Perform action\n// 3. Take another snapshot\n// 4. Compare snapshots\n\n// Node.js memory debugging\nif (process.memoryUsage().heapUsed > 500 * 1024 * 1024) {\n  console.warn(\"High memory usage:\", process.memoryUsage());\n\n  // Generate heap dump\n  require(\"v8\").writeHeapSnapshot();\n}\n\n// Find memory leaks in tests\nlet beforeMemory: number;\n\nbeforeEach(() => {\n  beforeMemory = process.memoryUsage().heapUsed;\n});\n\nafterEach(() => {\n  const afterMemory = process.memoryUsage().heapUsed;\n  const diff = afterMemory - beforeMemory;\n\n  if (diff > 10 * 1024 * 1024) {\n    // 10MB threshold\n    console.warn(`Possible memory leak: ${diff / 1024 / 1024}MB`);\n  }\n});\n```\n\n## Debugging Patterns by Issue Type\n\n### Pattern 1: Intermittent Bugs\n\n```markdown\n## Strategies for Flaky Bugs\n\n1. **Add extensive logging**\n   - Log timing information\n   - Log all state transitions\n   - Log external interactions\n\n2. **Look for race conditions**\n   - Concurrent access to shared state\n   - Async operations completing out of order\n   - Missing synchronization\n\n3. **Check timing dependencies**\n   - setTimeout/setInterval\n   - Promise resolution order\n   - Animation frame timing\n\n4. **Stress test**\n   - Run many times\n   - Vary timing\n   - Simulate load\n```\n\n### Pattern 2: Performance Issues\n\n```markdown\n## Performance Debugging\n\n1. **Profile first**\n   - Don't optimize blindly\n   - Measure before and after\n   - Find bottlenecks\n\n2. **Common culprits**\n   - N+1 queries\n   - Unnecessary re-renders\n   - Large data processing\n   - Synchronous I/O\n\n3. **Tools**\n   - Browser DevTools Performance tab\n   - Lighthouse\n   - Python: cProfile, line_profiler\n   - Node: clinic.js, 0x\n```\n\n### Pattern 3: Production Bugs\n\n```markdown\n## Production Debugging\n\n1. **Gather evidence**\n   - Error tracking (Sentry, Bugsnag)\n   - Application logs\n   - User reports\n   - Metrics/monitoring\n\n2. **Reproduce locally**\n   - Use production data (anonymized)\n   - Match environment\n   - Follow exact steps\n\n3. **Safe investigation**\n   - Don't change production\n   - Use feature flags\n   - Add monitoring/logging\n   - Test fixes in staging\n```\n\n## Best Practices\n\n1. **Reproduce First**: Can't fix what you can't reproduce\n2. **Isolate the Problem**: Remove complexity until minimal case\n3. **Read Error Messages**: They're usually helpful\n4. **Check Recent Changes**: Most bugs are recent\n5. **Use Version Control**: Git bisect, blame, history\n6. **Take Breaks**: Fresh eyes see better\n7. **Document Findings**: Help future you\n8. **Fix Root Cause**: Not just symptoms\n\n## Common Debugging Mistakes\n\n- **Making Multiple Changes**: Change one thing at a time\n- **Not Reading Error Messages**: Read the full stack trace\n- **Assuming It's Complex**: Often it's simple\n- **Debug Logging in Prod**: Remove before shipping\n- **Not Using Debugger**: console.log isn't always best\n- **Giving Up Too Soon**: Persistence pays off\n- **Not Testing the Fix**: Verify it actually works\n\n## Quick Debugging Checklist\n\n```markdown\n## When Stuck, Check:\n\n- [ ] Spelling errors (typos in variable names)\n- [ ] Case sensitivity (fileName vs filename)\n- [ ] Null/undefined values\n- [ ] Array index off-by-one\n- [ ] Async timing (race conditions)\n- [ ] Scope issues (closure, hoisting)\n- [ ] Type mismatches\n- [ ] Missing dependencies\n- [ ] Environment variables\n- [ ] File paths (absolute vs relative)\n- [ ] Cache issues (clear cache)\n- [ ] Stale data (refresh database)\n```","author":"@wshobson","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/wshobson/agents/tree/main/plugins/developer-essentials/skills/debugging-strategies","license":"MIT","category":"coding","lang":"en","tokens":2909,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":[]}}