---
name: bugfix
description: "Fix a bug using systematic debugging methodology. Finds root cause before fixing, creates regression test."
argument-hint: "[bug description]"
---

# /bugfix — Systematic Bug Fix Workflow

Find the ROOT CAUSE before writing any fix. Do not guess. Do not apply quick patches. Lightweight workflow — no brainstorm or architecture unless the root cause is architectural.

## Execution Protocol

**REQUIRED SUB-SKILL**: load and follow the skill — do not substitute judgment.
Step summaries describe outcomes; the loaded skill defines the process.

## Input

Ask the user for:
1. **Bug description** — what is happening vs. what should happen
2. **Steps to reproduce**
3. **Error output** — stack traces, logs, screenshots
4. **When it started** — recent changes or events that might correlate

## Step 0: Repo-State Detection & Routing Redirect

Before any other check, detect whether this repo is in **prototype mode** or **production mode** per `rules/common/skill-selection.md` Step 1.

1. **Local context wins** (the mixed-mode override). Check work-item-local signals first; these override the project-level declared mode: path under `pocs/` or `*-prototype/`; manifest shows prototype-phase active. If either fires, treat as prototype and proceed to the redirect.
2. **Otherwise, read `.claude/CLAUDE.md`'s `project.mode:`** (set by `/setup` Step 2.5):
   - `prototype` or `greenfield` → offer the redirect below.
   - `production` → skip the redirect — production bugs need `/bugfix`'s systematic debugging discipline.
   - Absent → ask the user once and persist per `rules/common/skill-selection.md` Step 1.

Note: an "empty `aiwiki/architecture/`" check is intentionally NOT a signal here — see `rules/common/skill-selection.md` Step 1.

**If prototype mode is detected**, stop and offer the redirect:

```
This looks like a prototype bug (signals: <list matched signals>).

/bugfix runs full systematic debugging with regression test creation — appropriate for production code, overkill for prototype iteration. Prototype bugs are usually captured as feedback items and addressed via iterate-prototype.

Redirect to iterate-prototype (capture as feedback item)? [Y]es / [n]o continue with /bugfix anyway / [a]bort
```

User responses:
- **Y / yes**: invoke `iterate-prototype` with the bug description as a feedback item. Skip the rest of /bugfix.
- **n / no**: proceed to Step 0a. User explicitly accepts production-grade debug discipline for prototype work.
- **a / abort**: stop.

If production mode, proceed to Step 0a directly.

## Step 0a: Preflight Checks

1. **Git is clean** — stash or commit first
2. **Tests pass** — note which are already failing
3. **Branch** — `fix/{bug-description-slug}`

## Step 0b: Wiki Bootstrap

**Skip wiki bootstrap if** the user passed `--size trivial`, OR the bug description matches obvious trivial patterns ("fix typo", "rename X to Y", "bump version", "update dep", "change copy"). Trivial bugfixes don't merit aiwiki state — Step 5 (gotcha capture) is also no-op'd on this path because `aiwiki/gotchas/` does not exist.

**Otherwise:** REQUIRED SUB-SKILL: Use **support-wiki-bootstrap** to ensure aiwiki/ exists.

Gotchas surfaced during debug will write to `aiwiki/gotchas/`.

Check if `.forge/work/bugfix/{name}/manifest.yaml` exists.

**If it exists**: Read the manifest. Resume from the last incomplete phase. Report what has already been completed and what remains. If `status: escalated` or `status: completed`, do NOT resume — surface the `successor_path` and ask the user what to do.

**If it does not exist**: Create the work directory (`.forge/work/bugfix/{name}/`) and manifest using the template at `.claude/templates/manifests/bugfix.yaml`. Fill placeholders `{name}`, `{description}`, `{date}`.

If this bugfix was escalated from a hotfix, set `escalated_from: work/hotfix/{predecessor-name}`.

## Step 1: Debug — Systematic Root Cause Analysis

REQUIRED SUB-SKILL: Use **support-debug** with full 4-phase methodology.

The skill handles tracer subagent dispatch internally — escalating to parallel hypothesis testing when linear debugging stalls.

After root cause is identified, produce a debugging summary:

```
Root cause: {one sentence}
Evidence: {file:line} → {file:line} → {root cause location}
Hypotheses tested: {N} — {list with CONFIRMED/REJECTED}
```

This feeds into Step 5 (gotcha) and the PR description (Step 4).

### GATE: Root Cause Identified
Root cause must be confirmed with evidence before any fix is attempted. Present the debugging summary to the user for review. Update manifest: `phases.debug.root-cause.status: complete, phases.debug.root-cause.gate-passed: true`.

## Step 1.5: Regression Plan (Complex Bugs Only)

If the root cause spans multiple files, involves race conditions, or required tracer escalation — produce a focused regression plan before fixing:

1. **Regression test(s)** — exact tests to write (not a full test plan, just the regression cases)
2. **Related areas to verify** — other code paths that touch the same root cause
3. **Confidence level** — how certain is this the only root cause?

If the bug is straightforward (single file, clear fix), skip this step.

## Step 2: Build — Test-Driven Fix

REQUIRED SUB-SKILL: Use **build-tdd**.
Write a regression test that reproduces the bug FIRST, watch it fail, then write the minimal fix.

### GATE: Fix Verified
Regression test passes. All existing tests still pass. No unrelated changes introduced. (No manifest field for this gate — bugfix manifest tracks debug → code-review → deliver. The passing regression test is the artifact; proceed to Step 3.)

## Step 3: Quality — Code Review

REQUIRED SUB-SKILL: Use **quality-code-review**.

### GATE: Code Review Passed
All critical and important review items resolved. Update manifest: `phases.quality.code-review.status: complete, phases.quality.code-review.gate-passed: true`.

## Step 4: Deliver — Create PR

REQUIRED SUB-SKILL: Use **build-pr-workflow**.
Atomic PR — just the fix and its regression test. Title: `fix: {description}`.

## Step 5: Support — Record Lessons

**Skip if** wiki bootstrap was skipped at Step 0b (trivial-scope path) — `aiwiki/gotchas/` does not exist and a typo / version bump / dep update does not warrant a gotcha entry. Otherwise:

REQUIRED SUB-SKILL: Use **support-gotcha**.

Use the debugging summary from Step 1 as input. Check `aiwiki/gotchas/` for prior bugs in the same area — if this is the 3rd+ occurrence, the gotcha auto-drafts a `proposed_rule:` block; the next session-start prompts for promotion. Wiki-lint validates the gotcha file structure on save.

Present a final summary:

```
Bug fixed: {description}
Root cause: {one sentence}
Gotcha recorded: aiwiki/gotchas/{filename}.md
Prevention: {what would prevent this class of bug}
```

## Gate Exemptions

| Standard Gate | Bugfix Equivalent | Rationale |
|---|---|---|
| quality-test-plan | Skipped | Bugfixes target a single root cause — the regression test from build-tdd (Step 2) plus existing tests provide sufficient coverage. A full test plan is overhead for a focused fix. |
| quality-test-execution | Skipped | build-tdd (Step 2) verifies the regression test passes and all existing tests still pass. A separate test-execution phase adds no value for a minimal, atomic fix. |

## Escalation

If root cause is **architectural** → suggest `/refactor` or `/feature`.
If root cause is **a dependency bug** → document, create workaround with TODO, file upstream issue.
If root cause is **environment-specific** → document requirements, update onboarding docs.

### Escalating to /refactor or /feature

When escalation is the right answer, perform the handoff in this order to keep state consistent:

1. Create the successor manifest by invoking the target command (`/refactor` or `/feature`) with `escalated_from: work/bugfix/{this-name}` set on creation.
2. Update the bugfix manifest: `status: escalated`, `successor_path: work/{type}/{successor-name}`.
3. Leave the bugfix folder in place — it is the audit trail.

Session-start and pre-compact hooks skip `status: escalated` — the bugfix will not resurface as resumable work after this point.
