---
name: support-debug
description: "Use when a bug, test failure, error, crash, or unexpected behavior needs systematic investigation — triggered by phrases like 'debug this', 'why is X failing', 'trace this error', 'figure out what's wrong', 'investigate the failure', 'this is broken', 'help me debug'. Enforces a four-phase process (fact-check → root-cause investigation → hypothesis testing → implementation) with a 3-fix threshold that stops the random-fix spiral. Skip when the user is asking a design or architecture question (not a failure to investigate), when the failure is a known limitation already documented, or when the work is prototype iteration where the lightweight feedback loop in iterate-prototype is the right shape."
---

# Support: Debug

## Overview

Random fixes waste time and create new bugs. Quick patches mask underlying issues. This skill enforces a rigorous four-phase debugging process that finds root causes before attempting fixes.

**Core Principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.

**Violating the letter of this process is violating the spirit of debugging.**

## The Iron Laws

```
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST.
FACT-CHECK THE PROBLEM BEFORE ASSUMING THE SYSTEM IS WRONG.
IF 3 FIXES FAIL, STOP AND DISCUSS ARCHITECTURE.
AFTER EVERY FIX, RECORD THE LESSON IN SUPPORT-GOTCHA.
```

If you have not completed Phase 1, you cannot propose fixes. Period.

## When to Use

Use for ANY technical issue:
- Test failures
- Bugs in production
- Unexpected behavior
- Performance problems
- Build failures
- Integration issues
- "It was working yesterday"

**Use this ESPECIALLY when:**
- Under time pressure (emergencies make guessing tempting)
- "Just one quick fix" seems obvious
- You have already tried multiple fixes
- Previous fix did not work
- You do not fully understand the issue

**Do NOT skip when:**
- Issue seems simple (simple bugs have root causes too)
- You are in a hurry (systematic debugging is faster than thrashing)
- User wants it fixed NOW (systematic is faster than guess-and-check)
- You think you already know the answer (verify first)

## I/O Contract

| Field | Value |
|---|---|
| **Requires** | Bug description, error output, or unexpected behavior report |
| **Produces** | Root cause analysis + implemented fix + test demonstrating the fix |
| **Feeds into** | `support-gotcha` (record lesson learned) |
| **Updates** | `.forge/work/{type}/{name}/manifest.yaml` if bug is part of a feature |

### Output Format

When debugging is complete, produce:

```markdown
## Debug Report: {brief description}

### Root Cause
{What actually caused the problem and why}

### Investigation Path
{Key steps taken to find root cause, including dead ends}

### Fix Applied
{What was changed and why this addresses the root cause}

### Test Added
{Test that demonstrates the fix and prevents regression}

### Lesson Learned
{What to watch for in the future -- feeds into support-gotcha}
```

## Codex Mode Check

Run the Codex consent flow from `protocols/codex.md` BEFORE any debugging work. The selected mode applies for the rest of this skill's invocation — both the Trace methodology and the Four Phases (Linear Debugging) follow the same consent.

- **Takeover:** Dispatch Codex with the bug description, error messages/stack trace, and skill methodology. Codex performs the investigation. Claude reviews hypotheses and tests the fix.
- **Verify** or **Skip / Codex unavailable:** Proceed manually. On the Linear path, Phase 2.5 will dispatch Codex to propose alternative hypotheses (Verify only).

## Phase 0: Fact-Check First

**BEFORE starting the four-phase process, verify the reported problem is real.**

This phase applies the `rules/common/verification.md` rule specifically to bug reports. The verification rule is the authority on when and how to verify; this phase is how support-debug implements that rule for debugging contexts.

1. **Verify the Reported Behavior**
   - Can you reproduce exactly what the user describes?
   - Is the error message exactly what they reported?
   - Is the behavior actually wrong, or is it correct behavior they did not expect?

2. **Verify Assumptions About Libraries/APIs**
   - User says "library X should do Y" -- verify via documentation
   - Use context7 or web search to confirm library behavior
   - Check the actual version of the library in use (behavior may differ between versions)
   - Read the library's changelog if behavior recently changed

3. **Verify Environment Assumptions**
   - "It works on my machine" -- check environment differences
   - "It was working yesterday" -- check what changed (git log, dependency updates, env changes)
   - "The API returns X" -- actually call the API and verify

4. **If the Problem Is Not What Was Reported**
   - State clearly: "I investigated and the actual issue is different from what was reported."
   - Explain what is actually happening
   - Then proceed with Phases 1-4 for the real issue

**Example of fact-checking catching a misreport:**
```
User: "The fetch API is broken -- it's not sending the Content-Type header."
Fact-check: Fetch API does send Content-Type for POST requests with body.
             The actual issue: fetch was sending a GET request (missing method: 'POST').
Real root cause: Missing method parameter, not a broken API.
```

## Adaptive Triage: Linear vs. Trace

After Phase 0 (fact-checking), assess bug complexity to choose the investigation method:

### Quick Triage (main agent, 2 minutes)

**Prerequisite:** This triage assumes you completed Phase 0 (fact-check). If you did not reproduce the bug and verify assumptions, go back to Phase 0 first. Do not triage based on the user's description alone.

Can you identify the likely cause from the stack trace, error message, or a single code path?

**YES → Linear debugging (Phases 1-4 below).** Fast, cheap, sufficient for most bugs.

**NO → Trace methodology.** Use when:
- No clear stack trace or error message
- Intermittent or non-deterministic behavior
- Bug spans multiple systems or services
- Previous fix attempts failed
- User says "we've been trying to fix this"

### Trace Methodology (for complex bugs)

Dispatch the **tracer** subagent which investigates with 3 competing hypotheses in parallel:

1. **Lane 1 (code-path):** Implementation bug, wrong logic, missing check
2. **Lane 2 (config/env):** Wrong env var, version mismatch, deploy issue
3. **Lane 3 (assumption):** Test is wrong, expectation is wrong, data changed

Each lane gathers evidence FOR and AGAINST its hypothesis, ranked by strength:
> controlled reproduction > primary artifacts > multiple sources > inference > speculation

After investigation, a rebuttal round between top hypotheses determines the most likely root cause with a confidence rating (HIGH/MEDIUM/LOW).

When the tracer returns its verdict, proceed to Phase 4 (Implementation) with the identified root cause. If confidence is LOW, the tracer will recommend a discriminating probe — run it before attempting a fix.

## The Four Phases (Linear Debugging)

You MUST complete each phase before proceeding to the next. (Codex consent was set above in the Codex Mode Check section; do not re-run it here.)

### Phase 1: Root Cause Investigation

**BEFORE attempting ANY fix:**

1. **Read Error Messages Carefully**
   - Do not skip past errors or warnings
   - They often contain the exact solution
   - Read stack traces completely
   - Note line numbers, file paths, error codes
   - Search for the exact error message in the codebase

2. **Reproduce Consistently**
   - Can you trigger it reliably?
   - What are the exact steps?
   - Does it happen every time?
   - If not reproducible, gather more data -- do NOT guess

3. **Check Recent Changes**
   - What changed that could cause this?
   - `git diff`, recent commits, `git log --oneline -20`
   - New dependencies, config changes
   - Environmental differences (Node version, OS, Docker image)

4. **Gather Evidence in Multi-Component Systems**

   When the system has multiple components (CI -> build -> signing, API -> service -> database):

   **BEFORE proposing fixes, add diagnostic instrumentation:**

   ```
   For EACH component boundary:
     - Log what data enters the component
     - Log what data exits the component
     - Verify environment/config propagation
     - Check state at each layer

   Run once to gather evidence showing WHERE it breaks.
   THEN analyze evidence to identify the failing component.
   THEN investigate that specific component.
   ```

   **Example (multi-layer system):**
   ```bash
   # Layer 1: API Gateway
   echo "=== Request received: ==="
   echo "Method: $METHOD, Path: $PATH, Headers: $HEADERS"

   # Layer 2: Service
   echo "=== Service input: ==="
   echo "Parsed body: $BODY"

   # Layer 3: Database
   echo "=== Query executed: ==="
   echo "SQL: $QUERY, Params: $PARAMS"

   # Layer 4: Response
   echo "=== Response: ==="
   echo "Status: $STATUS, Body: $RESPONSE_BODY"
   ```

   This reveals which layer fails (API -> Service OK, Service -> Database FAIL).

5. **Trace Data Flow (Backward Tracing)**

   When the error is deep in the call stack:

   - Start at the error location
   - Where does the bad value come from?
   - What called this function with the bad value?
   - Keep tracing backward until you find the SOURCE
   - Fix at the source, not at the symptom

   ```
   Error: Cannot read property 'name' of undefined
     at renderUser (user.tsx:42)         <- symptom
     at UserList (list.tsx:18)           <- passed undefined user
     at loadUsers (api.ts:55)            <- returned null instead of []
     at fetchData (fetch.ts:12)          <- ROOT CAUSE: missing error handling
   ```

   Fix at `fetch.ts:12`, not at `user.tsx:42`.

### Phase 2: Pattern Analysis

**Find the pattern before fixing:**

1. **Find Working Examples**
   - Locate similar working code in the same codebase
   - What works that is similar to what is broken?
   - If a similar feature works, diff the two implementations

2. **Compare Against References**
   - If implementing a known pattern, read the reference implementation COMPLETELY
   - Do not skim -- read every line
   - Understand the pattern fully before applying
   - Use context7 to fetch current documentation for the library/framework

3. **Identify Differences**
   - What is different between working and broken?
   - List every difference, however small
   - Do not assume "that can't matter" -- small differences often matter

4. **Understand Dependencies**
   - What other components does this need?
   - What settings, config, environment?
   - What assumptions does it make?
   - Check versions of all involved dependencies

#### Phase 2.5: Codex Alternative Hypotheses 
After pattern analysis, check the mode recorded at Phase 0. If **Verify** was selected, dispatch Codex to propose alternative root causes and different hypotheses. Merge Claude's analysis + Codex alternatives into Phase 3 hypothesis testing. If **Takeover** was selected, skip this step (Codex already ran the investigation). If **Skip**, do nothing. Do NOT re-run the consent flow. See **Codex Integration** section below for full details.

#### Graphify Context (Query-only)

**Protocol:** `protocols/graphify.md` | **Mode:** Query-only — no guard, no build prompts.

If `graphify-out/graph.json` exists and the `graphify` CLI is available, check the `graphify.query` preference in `.forge/local.yaml`:
- `always` → run CLI queries below
- `never` → skip CLI queries, trace manually
- `ask` or absent → prompt once before the first query ("Graphify CLI detected. Use graph queries for dependency tracing? (a) Yes (b) Always (c) No (d) Never")

If graph.json is missing OR CLI is unavailable, trace manually. Do not prompt for install or build — debugging should stay fast.

**CLI queries:**
- `graphify path "[error source]" "[suspected cause]" --graph graphify-out/graph.json` — trace dependency chain from symptom to potential root cause
- `graphify explain "[unfamiliar component]" --graph graphify-out/graph.json` — understand components encountered during investigation
- `graphify query "what calls [failing function]" --budget 1000 --graph graphify-out/graph.json` — find all callers of the failing code

**Codex bridge:** Pass graph-traced dependency paths to the Codex verify step below for alternative hypothesis generation.

#### Codex Integration
**Modes:** Verify or Takeover | **Protocol:** `protocols/codex.md`

- **Verify:** Claude investigates, Codex proposes alternative hypotheses.
- **Takeover:** Codex investigates root cause, Claude reviews and tests hypotheses.

**When:** After Phase 2 pattern analysis, before forming hypotheses in Phase 3.

**Context to pass:**
- Path to the file(s) containing the bug
- Claude's pattern analysis findings (inline summary)
- Error output / stack trace (inline)

**What Codex reviews:**
- Alternative hypotheses Claude hasn't considered
- Different root causes based on different assumptions
- Similar patterns in other parts of the codebase that might have the same bug

**Prompt focus:** "Given this bug and this pattern analysis, propose alternative root causes. What assumptions might be wrong? What other code paths could produce this symptom? Don't confirm existing analysis — generate new angles."

**Presentation:** Claude's analysis + Codex's alternative hypotheses. Both feed into Phase 3 hypothesis testing.

### Phase 3: Hypothesis and Testing

**Scientific method:**

1. **Form Single Hypothesis**
   - State clearly: "I think X is the root cause because Y"
   - Write it down explicitly
   - Be specific, not vague
   - The hypothesis must explain ALL observed symptoms

2. **Test Minimally**
   - Make the SMALLEST possible change to test the hypothesis
   - One variable at a time
   - Do NOT fix multiple things at once
   - Predict what should happen if your hypothesis is correct

3. **Verify Before Continuing**
   - Did the test confirm your hypothesis? Yes -> Phase 4
   - Did it not? Form a NEW hypothesis based on what you learned
   - Do NOT add more fixes on top of an unconfirmed hypothesis

4. **When You Do Not Know**
   - Say "I don't understand X" explicitly
   - Do not pretend to know
   - Research more: read source code, check documentation, search for the error
   - Ask the user for additional context if needed

### Phase 4: Implementation

**Fix the root cause, not the symptom:**

1. **Create Failing Test Case**
   - Write the simplest possible test that demonstrates the bug
   - It must FAIL before the fix (this proves it tests the right thing)
   - Automated test if possible, one-off test script if no framework
   - This test MUST exist before you write the fix
   - Use `build-tdd` discipline for writing proper failing tests

2. **Implement Single Fix**
   - Address the ROOT CAUSE identified in Phase 1-3
   - ONE change at a time
   - No "while I'm here" improvements
   - No bundled refactoring
   - No "let me also fix this other thing"

3. **Verify Fix**
   - The new test passes
   - All existing tests still pass
   - The original reported issue is resolved
   - No new warnings or errors introduced

4. **If Fix Does Not Work**
   - STOP
   - Count: How many fixes have you tried?
   - If fewer than 3: Return to Phase 1, re-analyze with new information from the failed fix
   - **If 3 or more: STOP and question the architecture (see step 5)**
   - Do NOT attempt Fix #4 without architectural discussion

5. **If 3+ Fixes Have Failed: Escalate**

   Before concluding this is an architectural problem, if you have not yet used trace methodology, dispatch the **tracer** subagent now. Multiple failed fixes often indicate a wrong assumption (Lane 3) rather than a wrong architecture.

   **Patterns indicating an architectural problem:**
   - Each fix reveals new shared state, coupling, or a problem in a different place
   - Fixes require "massive refactoring" to implement
   - Each fix creates new symptoms elsewhere
   - The code path is so tangled that isolating the issue is nearly impossible

   **STOP and question fundamentals:**
   - Is this pattern fundamentally sound?
   - Are we sticking with it through sheer inertia?
   - Should we refactor the architecture instead of continuing to fix symptoms?
   - Is there a simpler design that would eliminate this class of bugs?

   **Discuss with the user before attempting more fixes.**

   This is NOT a failed hypothesis -- this is a wrong architecture.

6. **After Fix: Record the Lesson**
   - Invoke `support-gotcha` to record what went wrong
   - Include: what happened, why, how to prevent it in the future
   - Tag which skills should incorporate this lesson
   - This is how the system learns and improves

## STOP Signals

If you catch yourself thinking any of these, or the user says anything similar — **STOP and return to Phase 1:**

| Trigger | What It Means | Action |
|---|---|---|
| "Quick fix" / "Just try X" | Guessing, not debugging | Return to Phase 1 |
| "Add multiple changes at once" | Can't isolate what worked | One change at a time |
| "Skip the test" | Untested fixes don't stick | Write test first |
| "One more fix" (after 2+ failures) | 3-fix threshold hit | Question architecture |
| "The library must be broken" | Almost certainly your code | Verify via docs/context7 |
| "I see the problem, let me fix it" | Symptoms ≠ root cause | Verify before fixing |
| "I don't fully understand but this might work" | Incomplete understanding | Research more before proceeding |
| "Pattern says X but I'll adapt it" | Partial pattern reading | Read the FULL reference first |
| "The user said it's X so let me fix X" | Unchecked user report | Fact-check first (Phase 0) |
| User: "Stop guessing" / "Did you check?" | You assumed without evidence | Return to Phase 1 |
| User: "Think harder" / frustrated tone | Your approach isn't working | Change strategy |

## Integration with the forge Harness

### How Debug Fits in Commands

- `/bugfix` command: invokes `support-debug` as the primary skill
- `/hotfix` command: invokes `support-debug` with expedited gates (but same four phases)
- `/feature` command: invokes `support-debug` if build phase encounters issues

### Post-Fix Workflow

After a successful fix:

1. **Invoke support-gotcha** -- Record the lesson
2. **Update manifest** -- If debugging was part of a feature, update the manifest status
3. **Check for pattern** -- If this is the 3rd time a similar bug occurred, gotcha system will flag it for promotion to a rule

### Tools for Fact-Checking

When verifying library behavior or API specifications:

- **context7**: Fetch current documentation for any library
  - `mcp__plugin_context7_context7__resolve-library-id` to find the library
  - `mcp__plugin_context7_context7__query-docs` to read the docs
- **Web search**: For recent changes, CVEs, or migration guides
- **Project dependencies**: Check `package.json`, `pyproject.toml`, etc. for exact versions
- **Changelogs**: Check if behavior changed between versions

## When Process Reveals No Clear Root Cause

If systematic investigation reveals the issue is truly environmental, timing-dependent, or external:

1. You have completed the process (this is valid)
2. Document what you investigated and ruled out
3. Implement appropriate handling (retry logic, timeout, descriptive error message)
4. Add monitoring/logging for future investigation
5. Record in `support-gotcha` for awareness

**But:** 95% of "no root cause" cases are incomplete investigation. Be honest about whether you truly exhausted all avenues.

## Quick Reference

| Phase | Key Activities | Success Criteria |
|---|---|---|
| **0. Fact-Check** | Verify reported problem, check library docs, confirm environment | Problem confirmed as described (or real issue identified) |
| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence, trace data flow | Understand WHAT is wrong and WHERE it originates |
| **2. Pattern** | Find working examples, compare, identify differences | Differences between working and broken are cataloged |
| **3. Hypothesis** | Form theory, test with minimal change, verify | Confirmed hypothesis or new hypothesis formed |
| **4. Implementation** | Create failing test, implement single fix, verify all tests pass | Bug fixed, test added, no regressions |
| **Post-Fix** | Record lesson in support-gotcha, update manifest | Lesson recorded for future prevention |
