Skip to main content
ClaudeWave
Skill171 repo starsupdated 27d ago

debugging

Systematically diagnose and fix software bugs by analyzing error messages, stack traces, logs, and runtime behavior across multiple languages. Use when the user requests debugging or provides relevant inputs for this workflow.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/debugging && cp -r /tmp/debugging/code-and-development/debugging ~/.claude/skills/debugging
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Debugging

This skill equips an AI agent with a systematic methodology for diagnosing and resolving software bugs. Rather than guessing at fixes, the agent follows a structured process — reproduce, isolate, diagnose, fix, verify — to find root causes and produce reliable corrections. It handles a wide range of bug categories including logic errors, runtime exceptions, race conditions, memory leaks, and performance regressions across multiple languages and runtime environments.

## Workflow

1. **Reproduce the problem.** Confirm the bug is observable and repeatable. Gather the exact error message, stack trace, log output, or description of unexpected behavior. Identify the minimum input or sequence of steps that triggers the issue. If the bug is intermittent, note the frequency and any environmental conditions (load, timing, specific data) that correlate with its appearance.

2. **Isolate the fault location.** Use the stack trace, error message, and code structure to narrow down the region of code responsible. Trace data flow backward from the point of failure to find where the value diverged from expectations. Eliminate unrelated code paths by checking whether the bug persists when components are stubbed out or bypassed. For large codebases, use binary search strategies — disable half the system, check if the bug still occurs, and repeat.

3. **Diagnose the root cause.** Once the faulty region is identified, determine exactly why the code misbehaves. Common root causes include: incorrect assumptions about input (null, empty, out-of-range), state mutation from a concurrent thread, stale cache or memoized value, incorrect operator precedence, missing await on an async call, or a dependency version incompatibility. Distinguish the root cause from its symptoms — a NullPointerException is a symptom; the root cause may be a missing validation three function calls earlier.

4. **Develop and apply the fix.** Write the smallest change that addresses the root cause without introducing side effects. If the fix involves changing a shared interface, trace all callers to ensure compatibility. Prefer defensive fixes that handle the error class broadly (e.g., adding input validation) over narrow patches that only address the single observed failure.

5. **Verify the fix and prevent regression.** Run the reproduction steps again to confirm the bug is resolved. Write or update a test case that encodes the previously-failing scenario so the bug cannot silently return. Check that existing tests still pass. If the bug was in a critical path, consider adding logging or monitoring to detect similar issues in the future.

## Supported Technologies

| Category          | Tools and Techniques                                              |
|-------------------|-------------------------------------------------------------------|
| Stack traces      | Python tracebacks, Java/JS stack traces, Go panic output, Rust backtraces |
| Logging           | Python `logging`, JavaScript `console`, structured JSON logs      |
| Debuggers         | `pdb` / `ipdb`, Chrome DevTools, `gdb` / `lldb`, `dlv` (Go)     |
| Profiling         | `cProfile`, `py-spy`, Chrome Performance tab, `pprof`            |
| Memory analysis   | `tracemalloc`, `heapq`, Valgrind, Chrome Heap Snapshots          |
| Concurrency       | Thread dumps, `asyncio` debug mode, Go race detector (`-race`)   |

## Usage

Provide one or more of the following inputs:

- **Code snippet or file path** containing the buggy code.
- **Error message or stack trace** — paste the full output, not a summary.
- **Description of unexpected behavior** — what you expected versus what happened.
- **Steps to reproduce** — the exact commands, inputs, or user actions that trigger the bug.
- **Logs** — relevant log output from before and during the failure.

The more context you provide, the faster and more accurately the agent can diagnose the issue.

## Examples

### Example 1 — Debugging a race condition in Python async code

**Bug report:** "Sometimes the response is missing the `user_profile` field, but only under load."

Buggy code in `src/api/handler.py`:

```python
import asyncio
import aiohttp

user_cache = {}

async def fetch_user(session, user_id):
    if user_id in user_cache:
        return user_cache[user_id]
    async with session.get(f"https://api.example.com/users/{user_id}") as resp:
        data = await resp.json()
    user_cache[user_id] = data
    return data

async def build_response(user_id):
    async with aiohttp.ClientSession() as session:
        profile, orders = await asyncio.gather(
            fetch_user(session, user_id),
            fetch_orders(session, user_id),
        )
    return {"user_profile": profile, "orders": orders}
```

**Agent diagnosis:**

The `user_cache` dictionary is shared mutable state accessed by concurrent coroutines without synchronization. When two requests for the same `user_id` arrive simultaneously, both see a cache miss, both issue HTTP requests, and the second write may overwrite the first with a partially different object. More critically, dictionary mutation during concurrent iteration can produce `RuntimeError` on Python 3.

**Root cause:** Unsynchronized shared mutable state in a concurrent context.

**Fix:**

```python
import asyncio
import aiohttp

user_cache = {}
cache_locks = {}
global_lock = asyncio.Lock()

async def fetch_user(session, user_id):
    async with global_lock:
        if user_id not in cache_locks:
            cache_locks[user_id] = asyncio.Lock()
        lock = cache_locks[user_id]

    async with lock:
        if user_id in user_cache:
            return user_cache[user_id]
        async with session.get(f"https://api.example.com/users/{user_id}") as resp:
            data = await resp.json()
        user_cache[user_id] = data
        return data
```

The per-key lock ensures only one coroutine fetches a given user at a time. Others wait and then read from the cache.

### Example 2 — Debugging a
agent-evaluationSkill

Design reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.

agent-observabilitySkill

Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.

human-in-the-loopSkill

Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.

mcp-server-buildingSkill

Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.

multi-agent-orchestrationSkill

Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.

tool-schema-designSkill

Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.

agent-red-teamingSkill

Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.

prompt-injection-defenseSkill

Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.