{"slug":"debugging-strategies","title":"debugging-strategies","summary":"Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-09-01T18:59:49.24554Z","repo":{"url":"https://github.com/wshobson/agents","stars":40003,"forks":4267,"license":"MIT","updatedAt":"2026-09-26T19:54:17Z"},"bodyHtml":"<hr>\n<h2>name: debugging-strategies\ndescription: Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.</h2>\n<h1>Debugging Strategies</h1>\n<p>Transform debugging from frustrating guesswork into systematic problem-solving with proven strategies, powerful tools, and methodical approaches.</p>\n<h2>When to Use This Skill</h2>\n<ul>\n<li>Tracking down elusive bugs</li>\n<li>Investigating performance issues</li>\n<li>Understanding unfamiliar codebases</li>\n<li>Debugging production issues</li>\n<li>Analyzing crash dumps and stack traces</li>\n<li>Profiling application performance</li>\n<li>Investigating memory leaks</li>\n<li>Debugging distributed systems</li>\n</ul>\n<h2>Core Principles</h2>\n<h3>1. The Scientific Method</h3>\n<p><strong>1. Observe</strong>: What's the actual behavior?\n<strong>2. Hypothesize</strong>: What could be causing it?\n<strong>3. Experiment</strong>: Test your hypothesis\n<strong>4. Analyze</strong>: Did it prove/disprove your theory?\n<strong>5. Repeat</strong>: Until you find the root cause</p>\n<h3>2. Debugging Mindset</h3>\n<p><strong>Don't Assume:</strong></p>\n<ul>\n<li>\"It can't be X\" - Yes it can</li>\n<li>\"I didn't change Y\" - Check anyway</li>\n<li>\"It works on my machine\" - Find out why</li>\n</ul>\n<p><strong>Do:</strong></p>\n<ul>\n<li>Reproduce consistently</li>\n<li>Isolate the problem</li>\n<li>Keep detailed notes</li>\n<li>Question everything</li>\n<li>Take breaks when stuck</li>\n</ul>\n<h3>3. Rubber Duck Debugging</h3>\n<p>Explain your code and problem out loud (to a rubber duck, colleague, or yourself). Often reveals the issue.</p>\n<h2>Systematic Debugging Process</h2>\n<h3>Phase 1: Reproduce</h3>\n<pre><code>## 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</code></pre>\n<h3>Phase 2: Gather Information</h3>\n<pre><code>## 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</code></pre>\n<h3>Phase 3: Form Hypothesis</h3>\n<pre><code>## 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</code></pre>\n<h3>Phase 4: Test &amp; Verify</h3>\n<pre><code>## 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</code></pre>\n<h2>Debugging Tools</h2>\n<h3>JavaScript/TypeScript Debugging</h3>\n<pre><code>// 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 &gt; 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 &gt; 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</code></pre>\n<p><strong>VS Code Debugger Configuration:</strong></p>\n<pre><code>// .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\": [\"&lt;node_internals&gt;/**\"]\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</code></pre>\n<h3>Python Debugging</h3>\n<pre><code># 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</code></pre>\n<h3>Go Debugging</h3>\n<pre><code>// 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</code></pre>\n<h2>Advanced Debugging Techniques</h2>\n<h3>Technique 1: Binary Search Debugging</h3>\n<pre><code># 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</code></pre>\n<h3>Technique 2: Differential Debugging</h3>\n<p>Compare working vs broken:</p>\n<pre><code>## 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</code></pre>\n<h3>Technique 3: Trace Debugging</h3>\n<pre><code>// 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) =&gt; sum + item.price, 0);\n  }\n}\n</code></pre>\n<h3>Technique 4: Memory Leak Detection</h3>\n<pre><code>// 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 &gt; 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(() =&gt; {\n  beforeMemory = process.memoryUsage().heapUsed;\n});\n\nafterEach(() =&gt; {\n  const afterMemory = process.memoryUsage().heapUsed;\n  const diff = afterMemory - beforeMemory;\n\n  if (diff &gt; 10 * 1024 * 1024) {\n    // 10MB threshold\n    console.warn(`Possible memory leak: ${diff / 1024 / 1024}MB`);\n  }\n});\n</code></pre>\n<h2>Debugging Patterns by Issue Type</h2>\n<h3>Pattern 1: Intermittent Bugs</h3>\n<pre><code>## 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</code></pre>\n<h3>Pattern 2: Performance Issues</h3>\n<pre><code>## 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</code></pre>\n<h3>Pattern 3: Production Bugs</h3>\n<pre><code>## 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</code></pre>\n<h2>Best Practices</h2>\n<ol>\n<li><strong>Reproduce First</strong>: Can't fix what you can't reproduce</li>\n<li><strong>Isolate the Problem</strong>: Remove complexity until minimal case</li>\n<li><strong>Read Error Messages</strong>: They're usually helpful</li>\n<li><strong>Check Recent Changes</strong>: Most bugs are recent</li>\n<li><strong>Use Version Control</strong>: Git bisect, blame, history</li>\n<li><strong>Take Breaks</strong>: Fresh eyes see better</li>\n<li><strong>Document Findings</strong>: Help future you</li>\n<li><strong>Fix Root Cause</strong>: Not just symptoms</li>\n</ol>\n<h2>Common Debugging Mistakes</h2>\n<ul>\n<li><strong>Making Multiple Changes</strong>: Change one thing at a time</li>\n<li><strong>Not Reading Error Messages</strong>: Read the full stack trace</li>\n<li><strong>Assuming It's Complex</strong>: Often it's simple</li>\n<li><strong>Debug Logging in Prod</strong>: Remove before shipping</li>\n<li><strong>Not Using Debugger</strong>: console.log isn't always best</li>\n<li><strong>Giving Up Too Soon</strong>: Persistence pays off</li>\n<li><strong>Not Testing the Fix</strong>: Verify it actually works</li>\n</ul>\n<h2>Quick Debugging Checklist</h2>\n<pre><code>## 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</code></pre>\n","files":[{"path":"SKILL.md","sizeBytes":11879,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-09-01T19:03:18.623444Z","sha256":"5A0F857E88A0129DB166DDAF53492178CF82BFA7094D35AA39190ACDE4BE452A","sizeBytes":5178},"review":null,"source":{"repositoryUrl":"https://github.com/wshobson/agents","path":"plugins/developer-essentials/skills/debugging-strategies","license":"MIT","commit":"9b15b34b0bfc13a815cbfc2366e14ea549e09422","subtreeSha":"BACD0B960EF27D31A6259168C2798643A45215DFA3C9528C2BD01572152A84D6","lastSyncedAt":"2026-09-26T23:12:03.520842Z"},"reviewedAt":"2026-09-01T19:10:43.315779Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/wshobson/agents/tree/main/plugins/developer-essentials/skills/debugging-strategies"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install wshobson-agents@llmmart"},{"target":"git","command":"git clone https://github.com/wshobson/agents.git"}]}