agentleFS
mikulgohilmikulgohil/claude-skills/skills/fundamentals/debugging/SKILL.md

debugging

Skill0 starsChanged 5 months agoMITView on GitHub

Systematic debugging methodology — reproduce, isolate, hypothesize, verify — plus language-specific debuggers and common-scenario playbooks (leaks, races, deadlocks, crashes). Use when tracking down a bug of unknown cause.

116 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use Problem-Solving Techniques, media-processing and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • truongtv22Skill

    Problem-Solving Techniques

    Apply systematic problem-solving techniques for complexity spirals (simplification cascades), innovation blocks (collision-zone thinking), recurring patterns (meta-pattern recognition), assumption constraints (inversion exercise), scale uncertainty (scale game), and dispatch when stuck. Techniques derived from Microsoft Amplifier project patterns adapted for immediate application.

    Also in 4 projects that use this

  • mrgoonieSkill

    media-processing

    Process multimedia files with FFmpeg (video/audio encoding, conversion, streaming, filtering, hardware acceleration) and ImageMagick (image manipulation, format conversion, batch processing, effects, composition). Use when converting media formats, encoding videos with specific codecs (H.264, H.265, VP9), resizing/cropping images, extracting audio from video, applying filters and effects, optimizing file sizes, creating streaming manifests (HLS/DASH), generating thumbnails, batch processing images, creating composite images, or implementing media processing pipelines. Supports 100+ formats, hardware acceleration (NVENC, QSV), and complex filtergraphs.

    Also in 6 projects that use this

  • JetBrainsSkill

    ssr

    Guide for using Structural Search and Replace in IntelliJ. Use when creating or modifying SSR inspections or search patterns.

    Also in 3 projects that use this

  • mrgoonieSkill

    web-frameworks

    Build modern full-stack web applications with Next.js (App Router, Server Components, RSC, PPR, SSR, SSG, ISR), Turborepo (monorepo management, task pipelines, remote caching, parallel execution), and RemixIcon (3100+ SVG icons in outlined/filled styles). Use when creating React applications, implementing server-side rendering, setting up monorepos with multiple packages, optimizing build performance and caching strategies, adding icon libraries, managing shared dependencies, or working with TypeScript full-stack projects.

    Also in 6 projects that use this

  • DevNewbie1826Skill

    remove-ai-slops

    Remove AI-generated code slop from branch changes or an explicit file list while preserving behavior, including junk tests (prose pins, source greps, copied inventories, mock echoes), each proven by its class rule before a cut. Use when asked to remove slop, clean AI code, deslop, clean up generated code, strip slop, prune junk tests, or review generated-code cleanup. Start by locking behavior with regression tests, then use the category and workflow references.

    Also in 3 projects that use this

  • DevNewbie1826Skill

    programming

    MUST USE for work on Python, Rust, TypeScript, JavaScript, or Go source files and project manifests, and whenever a test or spec file is written, reshaped, reviewed, or deleted. Triggers: write or edit code; add, change, or delete a test; test authoring gate; junk tests; new project; Go HTTP service (gin lane); Bubble Tea TUI; CJK IME; Connect-Go RPC; sqlc or pgx; branded IDs; exhaustive matching; unsafe Rust; Miri; oversized file; refactoring; logging, log levels, structured logging, or observability; arena, allocator, bumpalo, const fn, const generics, compile-time programming, zero-allocation APIs, bitfields, repr, scope guards, errdefer-style cleanup, Zig-like patterns, zero-copy parsing, packed data, or FFI; Rust public API design or macros.

    Also in 3 projects that use this

  • +6 more from mrgoonie

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 104 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Add a regression test. Update documentation or runbooks if applicable.

    line 87
  2. Distinctive:

    Place logs at decision points, not just error paths:

    line 202

“Common” is measured: kept by at least 6 in 10 of the 104 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Debug Operations

Systematic debugging methodology with language-specific tooling and common scenario playbooks.

Bug Classification Decision Tree

Bug Report / Symptom
│
├─ Crash
│  ├─ Segfault / Access Violation
│  │  └─ Check: null pointer, buffer overflow, use-after-free, stack overflow
│  ├─ Panic / Fatal Error
│  │  └─ Check: assertion failure, unrecoverable state, out-of-memory
│  └─ Unhandled Exception
│     └─ Check: missing error handler, unexpected input type, network failure
│
├─ Hang
│  ├─ Deadlock
│  │  └─ Check: lock ordering, mutex contention, channel blocking
│  ├─ Infinite Loop
│  │  └─ Check: loop termination condition, counter overflow, recursive call
│  └─ Blocked I/O
│     └─ Check: network timeout, DNS resolution, disk full, file lock
│
├─ Wrong Output
│  ├─ Logic Error
│  │  └─ Check: operator precedence, boundary conditions, boolean logic
│  ├─ Data Corruption
│  │  └─ Check: concurrent mutation, encoding mismatch, truncation
│  └─ Off-by-One
│     └─ Check: loop bounds, array indexing, fence-post errors
│
├─ Performance
│  ├─ Slow Queries
│  │  └─ Check: missing index, N+1 queries, full table scan, lock wait
│  ├─ Memory Bloat
│  │  └─ Check: cache without eviction, leaked references, large allocations
│  └─ CPU Spikes
│     └─ Check: hot loops, regex backtracking, excessive GC, busy-wait
│
└─ Intermittent
   ├─ Race Condition
   │  └─ Check: shared mutable state, read-modify-write, check-then-act
   ├─ Timing-Dependent
   │  └─ Check: timeout values, clock skew, event ordering assumptions
   └─ Environment-Specific
      └─ Check: OS differences, locale, timezone, file system case sensitivity

Systematic Debugging Workflow

Six-step process from symptom to prevention:

Step 1: Reproduce

Confirm the bug exists and create a reliable reproduction. A bug you cannot reproduce is a bug you cannot confidently fix. Capture exact inputs, environment, and sequence of operations.

Step 2: Isolate

Narrow the fault to the smallest possible scope. Use binary search (git bisect, commenting out code halves), stubs, feature flags, and environment isolation to eliminate innocent code.

Step 3: Identify

Find the root cause, not just the proximate trigger. Use the 5 Whys technique, trace execution, inspect state at key points. Distinguish between the symptom and the underlying defect.

Step 4: Fix

Apply the minimal correct change that addresses the root cause. Avoid shotgun debugging (changing multiple things at once). Understand why the fix works, not just that it works.

Step 5: Verify

Confirm the fix resolves the original issue without introducing regressions. Re-run the original reproduction case. Run the full test suite. Test edge cases related to the fix.

Step 6: Prevent

Add a regression test. Update documentation or runbooks if applicable. Consider whether the same class of bug could exist elsewhere. Share findings with the team.

Reproduction Checklist

[ ] Minimal reproduction steps documented (numbered, unambiguous)
[ ] Environment captured (OS, runtime version, dependencies, config)
[ ] Exact inputs recorded (request payload, CLI args, file contents)
[ ] Timing sensitivity assessed (does it fail only under load? after delay?)
[ ] Single-threaded reproduction attempted (eliminates concurrency noise)
[ ] Reproduction automated as script or test case
[ ] Confirmed reproduction is deterministic (fails N/N attempts)
[ ] Identified whether reproduction requires specific data/state

Isolation Techniques Quick Reference

TechniqueMethodBest For
Binary search (git)git bisect start BAD GOOD then git bisect run ./test.shFinding which commit introduced the bug
Binary search (code)Comment out half the code, test, repeatNarrowing fault location in unfamiliar code
Stubs/MocksReplace dependencies with known-good fakesIsolating from external services
Feature flagsToggle features off one by oneFinding which feature causes the issue
Environment isolationDocker container, fresh VM, clean installEliminating environment contamination
Network interceptionmitmproxy, Charles Proxy, mock serverIsolating client vs server issues
Input reductionRemove input fields/data until bug disappearsFinding minimal trigger
Dependency pinningLock all deps, update one at a timeFinding breaking dependency update

Root Cause Analysis Template

5 Whys Example

Problem: API returns 500 error on user login

1. Why? → The database query throws a timeout exception
2. Why? → The users table scan takes >30 seconds
3. Why? → There is no index on the email column
4. Why? → The migration that adds the index was never run in production
5. Why? → The deployment script skips migrations when the --fast flag is used

Root cause: Deployment script's --fast flag bypasses migrations
Fix: Remove --fast flag behavior that skips migrations, add migration check to health endpoint
Prevention: CI check that verifies all migrations are applied after deployment

Fault Tree Basics

                    [System Failure]
                    /              \
            [Hardware]          [Software]
            /       \           /        \
       [Disk]    [Memory]  [Config]   [Code Bug]
                              |          |
                         [Missing    [Race in
                          env var]    worker pool]

Work from the top (observed failure) down to leaves (root causes). Each branch is an AND/OR gate -- AND means all children must be true, OR means any one child suffices.

Language-Specific Debugger Quick Reference

LanguageToolLaunch CommandKey Commands
Node.jsChrome DevToolsnode --inspect-brk app.jsOpen chrome://inspect, set breakpoints in Sources
Node.jsndbnpx ndb app.jsEnhanced DevTools with blackboxing
Pythonpdbpython -m pdb script.pyn next, s step, c continue, p expr print, bt backtrace
Pythondebugpypython -m debugpy --listen 5678 --wait-for-client script.pyVS Code "Attach" launch config
Pythonbreakpoint()Insert breakpoint() in codeDrops into pdb at that line (Python 3.7+)
GoDelvedlv debug ./cmd/serverb main.go:42 break, c continue, n next, p var print
GoDelve (test)dlv test ./pkg/...Debug test functions directly
GoDelve (attach)dlv attach PIDDebug running process
Rustrust-gdbrust-gdb target/debug/myappb main, r, n, p variable, bt
Rustrust-lldbrust-lldb target/debug/myappb s main, r, n, p variable, bt
RustCodeLLDBVS Code extensionGUI breakpoints, variable inspection
BrowserDevToolsF12 or Ctrl+Shift+IElements, Console, Network, Sources, Performance, Memory

Quick Debug Snippets

// Node.js: drop into debugger at this point
debugger;

// Node.js: conditional breakpoint
if (user.id === 'problem-user') debugger;
# Python: drop into debugger at this point
breakpoint()

# Python: conditional breakpoint
if user_id == 'problem-user':
    breakpoint()
// Go: print goroutine stacks (send SIGQUIT or SIGABRT)
// kill -QUIT <pid>
// Or in code:
import "runtime/debug"
debug.PrintStack()
// Rust: enable full backtraces
// RUST_BACKTRACE=1 cargo run
// RUST_BACKTRACE=full cargo run

Log-Based Debugging Patterns

Strategic Logging

Place logs at decision points, not just error paths:

[ENTRY] function_name(args_summary)     -- entering the function
[STATE] key_variable=value              -- state at critical decision point
[BRANCH] taking path X because Y       -- which branch and why
[EXIT] function_name -> result_summary  -- leaving the function
[ERROR] operation failed: detail        -- error with context

Correlation IDs

Trace a single request across services:

# Generate at entry point, propagate through all calls
X-Request-ID: 550e8400-e29b-41d4-a716-446655440000

# Search across all service logs
rg "550e8400-e29b-41d4-a716-446655440000" /var/log/services/

Timeline Reconstruction

# Merge and sort logs from multiple sources by timestamp
sort -t' ' -k1,2 service-a.log service-b.log service-c.log > timeline.log

# Find gaps in activity (potential hang/block)
awk '{print $1, $2}' timeline.log | uniq -c | sort -rn | head -20

Structured Log Queries

# jq queries on JSON logs
# Find all errors for a specific user
jq 'select(.level == "error" and .user_id == "u123")' app.log

# Get timing distribution for slow requests
jq 'select(.duration_ms > 1000) | .duration_ms' app.log | sort -n

# Count errors by type
jq -r 'select(.level == "error") | .error_type' app.log | sort | uniq -c | sort -rn

Common Gotchas

GotchaWhy It HurtsFix
Fixing symptoms, not root causeBug resurfaces in a different formUse 5 Whys to dig deeper
Debugging in production without safety netRisk of data loss or extended outageUse read-only queries, feature flags, canary deploys
Heisenbug (disappears under observation)Adding logging/breakpoints changes timingUse non-invasive tools: strace, sampling profiler, rr
Assumption bias ("it can't be X")Skipping the actual cause because you trust itTest every assumption explicitly, even "obvious" ones
Missing reproduction caseCannot verify fix, cannot prevent regressionInvest time upfront in reliable reproduction
Over-relying on print/log debuggingSlow iteration, pollutes code, misses concurrency bugsUse proper debugger, profiler, or tracing tool
Not checking recent changesThe answer is often in the last few commitsgit log --oneline -20, git diff HEAD~5
Ignoring warning messagesWarnings often predict the error that followsTreat warnings as errors during debugging
Debugging wrong version/branchWasting time on already-fixed or different codeVerify git branch, git log -1, runtime version
Not reading the full stack traceRoot cause is often in the middle, not the topRead bottom-up: find your code in the trace first
Changing multiple things at onceCannot tell which change fixed (or broke) itOne change per test cycle
Not capturing the "before" stateCannot diff against working baselineSnapshot config, deps, data before debugging

Reference Files

FileContentsLines
references/systematic-methods.mdScientific method, binary search, delta debugging, differential debugging, time-travel debugging, team debugging~600
references/tool-specific.mdBrowser DevTools, Node.js, Python, Go, Rust, database, network, Docker debugging tools~650
references/common-scenarios.mdMemory leaks, deadlocks, race conditions, performance regressions, API debugging, deployment issues~550

See Also

  • testing-ops -- Write tests to prevent bugs from recurring
  • security-ops -- Security-specific debugging (auth failures, injection, CSRF)
  • monitoring-ops -- Production observability, alerting, dashboards
  • code-stats -- Measure code complexity and identify bug-prone areas
  • container-orchestration -- Docker and Kubernetes debugging context
  • git-ops -- Git bisect workflow and history investigation

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.