---
name: gmd:debug
description: Systematic debugging with persistent state across context resets
argument-hint: [issue description]
allowed-tools:
  - Read
  - Bash
  - Task
  - AskUserQuestion
---

<objective>
Debug issues using scientific method with subagent isolation.

**Orchestrator role:** Gather symptoms, spawn gmd-debugger agent, handle checkpoints, spawn continuations.

**Why subagent:** Investigation burns context fast (reading files, forming hypotheses, testing). Fresh 200k context per investigation. Main context stays lean for user interaction.
</objective>

<context>
User's issue: $ARGUMENTS

Check for active sessions:
```bash
ls .planning/debug/*.md 2>/dev/null | grep -v resolved | head -5
```
</context>

<process>

## 0. Initialize Context

```bash
INIT=$(node "${CLAUDE_PLUGIN_ROOT}/bin/gmd-tools.cjs" state load)
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
```

Extract `commit_docs` from init JSON. Resolve debugger model:
```bash
debugger_model=$(node "${CLAUDE_PLUGIN_ROOT}/bin/gmd-tools.cjs" resolve-model gmd-debugger --raw)
```

## 1. Check Active Sessions

If active sessions exist AND no $ARGUMENTS:
- List sessions with status, hypothesis, next action
- User picks number to resume OR describes new issue

If $ARGUMENTS provided OR user describes new issue:
- Continue to symptom gathering

## 2. Gather Symptoms (if new issue)

Use AskUserQuestion for each:

1. **Expected behavior** - What should happen?
2. **Actual behavior** - What happens instead?
3. **Error messages** - Any errors? (paste or describe)
4. **Timeline** - When did this start? Ever worked?
5. **Reproduction** - How do you trigger it?

After all gathered, confirm ready to investigate.

## 3. Spawn gmd-debugger Agent

Fill prompt and spawn:

```markdown
<objective>
Investigate issue: {slug}

**Summary:** {trigger}
</objective>

<symptoms>
expected: {expected}
actual: {actual}
errors: {errors}
reproduction: {reproduction}
timeline: {timeline}
</symptoms>

<mode>
symptoms_prefilled: true
goal: find_and_fix
</mode>

<debug_file>
Create: .planning/debug/{slug}.md
</debug_file>
```

```
Task(
  prompt=filled_prompt,
  subagent_type="gmd-debugger",
  model="{debugger_model}",
  description="Debug {slug}"
)
```

## 4. Handle Agent Return

**If `## ROOT CAUSE FOUND`:**
- Display root cause and evidence summary
- Offer options:
  - "Fix now" - spawn fix subagent
  - "Plan fix" - suggest /gmd:plan-phase --gaps
  - "Manual fix" - done

**If `## CHECKPOINT REACHED`:**
- Present checkpoint details to user
- Get user response
- If checkpoint type is `human-verify`:
  - If user confirms fixed: continue so agent can finalize/resolve/archive
  - If user reports issues: continue so agent returns to investigation/fixing
- Spawn continuation agent (see step 5)

**If `## INVESTIGATION INCONCLUSIVE`:**
- Show what was checked and eliminated
- Offer options:
  - "Continue investigating" - spawn new agent with additional context
  - "Manual investigation" - done
  - "Add more context" - gather more symptoms, spawn again

## Post-Workflow Vault Extraction (J3)

After the debug session transcript is written to `.planning/debug/{slug}.md`, extract knowledge candidates to `.vault/Knowledge/_inbox/`.

Run this block when the debug session writes or updates `.planning/debug/{SESSION_ID}.md` (i.e., after ROOT CAUSE FOUND or after investigation concludes):

```bash
# Locate config (Phase 17 idiom)
HAS_CFG=""
if [[ -f get-magic-done/config.json ]]; then HAS_CFG="get-magic-done/config.json"
elif [[ -f config.json ]]; then HAS_CFG="config.json"
fi

# Gate on components.obsidian.enabled
if [[ -z "$HAS_CFG" ]] || [[ "$(jq -r '.components.obsidian.enabled // false' "$HAS_CFG" 2>/dev/null)" != "true" ]]; then
  echo "[J3] vault-extract-knowledge skipped: obsidian component disabled" >&2
else
  node bin/gmd-tools.cjs vault-extract-knowledge \
    --trigger J3 \
    --source-files ".planning/debug/${SESSION_ID}.md" \
    --caller gmd-debug \
    --phase "${SESSION_ID}" \
  || echo "[J3] extraction returned non-zero — continuing; check .vault/_logs/" >&2
fi
```

**Flag-form rule (load-bearing):** every flag uses space separator. `--trigger J3`, NOT `--trigger=J3`. `--source-files "<path>"`, NOT `--source=<path>`. The parseAllFlags tokenizer at bin/gmd-tools.cjs:182 silently drops equals-form tokens — hooks would appear to run but extract nothing.

**Failure is non-fatal.** Extraction is additive enrichment; if it fails, the debug workflow still succeeds.

## 5. Spawn Continuation Agent (After Checkpoint)

When user responds to checkpoint, spawn fresh agent:

```markdown
<objective>
Continue debugging {slug}. Evidence is in the debug file.
</objective>

<prior_state>
<files_to_read>
- .planning/debug/{slug}.md (Debug session state)
</files_to_read>
</prior_state>

<checkpoint_response>
**Type:** {checkpoint_type}
**Response:** {user_response}
</checkpoint_response>

<mode>
goal: find_and_fix
</mode>
```

```
Task(
  prompt=continuation_prompt,
  subagent_type="gmd-debugger",
  model="{debugger_model}",
  description="Continue debug {slug}"
)
```

</process>

<success_criteria>
- [ ] Active sessions checked
- [ ] Symptoms gathered (if new)
- [ ] gmd-debugger spawned with context
- [ ] Checkpoints handled correctly
- [ ] Root cause confirmed before fixing
</success_criteria>
