<purpose>
Systematic debugging workflow using the scientific method. Persists state across
context resets so debugging can survive long investigations. Creates checkpoints
before risky changes so you can always roll back.

Phases: Observe → Hypothesize → Checkpoint → Test → Conclude
</purpose>

<process>

<step name="init" priority="first">
## 1. Initialize Session

Generate session ID: `debug-{YYYYMMDD}-{HHmm}`

```bash
mkdir -p .aperant/debug/{session-id}
mkdir -p .aperant/debug/{session-id}/checkpoints
```

If `--resume` flag:
- If session ID provided: read `.aperant/debug/{session-id}/DEBUG.md`
- If no ID: find most recent session:
  ```bash
  ls -t .aperant/debug/ | head -1
  ```
- Parse DEBUG.md to determine current phase
- Skip to that phase

Read project constitution:
```bash
cat AGENTS.md 2>/dev/null || cat CLAUDE.md 2>/dev/null
```
</step>

<step name="observe">
## 2. Observe Phase

Collect all available evidence:

### 2a. Reproduce the Issue
Run the failing command, test, or interaction. Capture:
- Exact error message (verbatim)
- Stack trace (if available)
- Exit code
- Relevant log output

### 2b. Gather Context
```bash
git branch --show-current
git log --oneline -10
git diff --stat
```

Identify:
- Which files are involved in the failure
- When the issue was first noticed (recent commits?)
- What changed recently that could be related

### 2c. Write Initial DEBUG.md

```markdown
# Debug Session: {session-id}

## Status: OBSERVING

## Problem Statement
{User's description}

## Symptoms
- {symptom 1 — exact error or behavior}
- {symptom 2}

## Error Output
\`\`\`
{verbatim error output}
\`\`\`

## Environment
- Branch: {branch}
- Last 5 commits: {list}
- Changed files: {list}

## Hypotheses
(none yet)

## Tests Performed
(none yet)

## Checkpoints
(none yet)

## Conclusion
(pending)

## Timeline
- {ISO timestamp} — Session started
```
</step>

<step name="hypothesize">
## 3. Hypothesize Phase

Investigate the codebase to form theories:

### 3a. Targeted Investigation
- Read files referenced in error messages/stack traces
- Grep for error strings to find their origin
- Check recent git changes in affected files:
  ```bash
  git log --oneline -10 -- {affected-files}
  ```
- Look for common patterns: typos, missing null checks, wrong imports, race conditions

### 3b. Rank Hypotheses
Generate 2-5 hypotheses ranked by likelihood:

```markdown
## Hypotheses
1. **[MOST LIKELY]** {hypothesis} — Evidence: {what suggests this}
2. **[LIKELY]** {hypothesis} — Evidence: {what suggests this}
3. **[POSSIBLE]** {hypothesis} — Evidence: {what suggests this}
```

Update DEBUG.md status to `HYPOTHESIZING`.
</step>

<step name="checkpoint">
## 4. Checkpoint Phase

Before making any code changes, save a checkpoint:

```bash
# Save current HEAD
git rev-parse HEAD > .aperant/debug/{session-id}/checkpoints/pre-test.ref

# If there are uncommitted changes, stash them
git stash push -m "debug-{session-id}-checkpoint" 2>/dev/null || true
```

Record in DEBUG.md:
```markdown
## Checkpoints
- {timestamp} — pre-test: {sha} (before testing hypotheses)
```

### Reverting to Checkpoint
If a test goes wrong, revert:
```bash
# Restore to checkpoint
git checkout $(cat .aperant/debug/{session-id}/checkpoints/pre-test.ref) -- .

# Or pop stash if changes were stashed
git stash pop
```
</step>

<step name="test">
## 5. Test Phase

For each hypothesis (most likely first):

### 5a. Design Test
- Define what change or check would confirm/refute the hypothesis
- Define expected outcome if hypothesis is correct
- Keep tests minimal — change one thing at a time

### 5b. Execute Test
- Make the minimal code change
- Run the relevant test/command
- Capture the output

### 5c. Record Result
```markdown
### Test {n}: Testing hypothesis "{name}"
- **Action:** {what was changed/checked}
- **Expected:** {expected result if hypothesis correct}
- **Actual:** {actual result}
- **Verdict:** CONFIRMED | REFUTED | INCONCLUSIVE
- **Notes:** {insights gained}
```

### 5d. Branch on Result
- **CONFIRMED:** Proceed to conclusion (step 6)
- **REFUTED:** Undo the test change, move to next hypothesis
- **INCONCLUSIVE:** Refine the test or hypothesis, retry

If all hypotheses exhausted:
- Update status to `STUCK`
- Generate new hypotheses based on what was learned
- Consider git bisect:
  ```bash
  git bisect start
  git bisect bad HEAD
  git bisect good {known-good-commit}
  ```
- Loop back to step 3
</step>

<step name="conclude">
## 6. Conclude Phase

### 6a. Document Root Cause
```markdown
## Status: RESOLVED

## Conclusion

### Root Cause
{Clear, specific explanation}

### Why It Happened
{How the bug was introduced}

### Fix
{Description of the fix}

### Files Changed
- {file}: {change description}

### Prevention
- {How to prevent recurrence — test, lint rule, type constraint}
```

### 6b. Apply Fix
- Implement the minimal fix
- Run full verification:
  ```bash
  pnpm typecheck 2>&1 | tail -20
  pnpm test 2>&1 | tail -30
  pnpm lint 2>&1 | tail -20
  ```

### 6c. Commit
```bash
apt-tools commit "fix: {description}" --files {changed-files}
```

### 6d. Update Timeline
```markdown
## Timeline
- {t1} — Session started
- {t2} — Observed: {symptoms}
- {t3} — Hypothesized: {count} theories
- {t4} — Tested: {count} hypotheses
- {t5} — Root cause: {brief}
- {t6} — Fix applied and verified
```
</step>

<step name="stuck_handler">
## 7. Stuck Handler

If stuck after 3+ rounds of hypothesize-test without resolution:

1. Update DEBUG.md with status `STUCK`
2. Summarize what has been tried and eliminated
3. Suggest escalation paths:
   - `git bisect` to find the introducing commit
   - Add instrumentation/logging to narrow the search
   - Ask the user specific questions about expected behavior
   - Try a different approach entirely

```
Debug session {session-id}: STUCK after {n} rounds.

Tried and ruled out:
{list of refuted hypotheses}

Suggested next steps:
{list of escalation options}

State saved. Resume with: /apt:debug --resume {session-id}
```
</step>

</process>
