<purpose>
Audit Nyquist validation gaps for a completed phase. Generate missing tests. Update VALIDATION.md.
</purpose>

<required_reading>
@C:/Users/Christopher/.claude/get-magic-done/references/ui-brand.md
</required_reading>

<process>

## 0. Mode-Aware Path Resolution (v1.5.9 Parallel Milestone Organization)

Resolve organizational mode + active milestone slug ONCE; all subsequent path lookups route through `resolveMilestonePaths(mode, slug, artifact)`. Workflow consumes `active_milestone_slug` from init JSON — it does NOT parse `--milestone` itself (P3 thin-wrapper; flag parsed once at gmd-tools.cjs init dispatch entry per Plan 66-01).

```bash
INIT=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" init phase-op "${PHASE_ARG}" --raw)
MODE=$(echo "$INIT" | jq -r '.organizational_mode')
SLUG=$(echo "$INIT" | jq -r '.active_milestone_slug // empty')
NEEDS_PROMPT=$(echo "$INIT" | jq -r '.active_milestone_needs_prompt')
```

**Tier 4 prompt (parallel mode, no flag, no pointer, multiple/zero In Progress milestones):**

If `$NEEDS_PROMPT == "true"`:
- Read `.active_milestone_candidates` array from init JSON
- Invoke AskUserQuestion with the candidate list
- Persist selection: `node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" state set-current-milestone "<chosen-slug>"`
- Re-run init to pick up the now-set slug (re-execute the INIT=$(...) block above)

**Path lookups (used throughout this workflow):**

```bash
REQS_PATH=$(node -e "const {resolveMilestonePaths}=require('$HOME/.claude/get-magic-done/bin/lib/path-resolve.js'); console.log(resolveMilestonePaths('$MODE', '$SLUG' || null, 'REQUIREMENTS'))")
ROADMAP_PATH=$(node -e "const {resolveMilestonePaths}=require('$HOME/.claude/get-magic-done/bin/lib/path-resolve.js'); console.log(resolveMilestonePaths('$MODE', '$SLUG' || null, 'ROADMAP'))")
STATE_PATH=$(node -e "const {resolveMilestonePaths}=require('$HOME/.claude/get-magic-done/bin/lib/path-resolve.js'); console.log(resolveMilestonePaths('$MODE', '$SLUG' || null, 'STATE'))")
PHASES_DIR=$(node -e "const {resolveMilestonePaths}=require('$HOME/.claude/get-magic-done/bin/lib/path-resolve.js'); console.log(resolveMilestonePaths('$MODE', '$SLUG' || null, 'phases-dir'))")
```

**Sequential mode:** `MODE=sequential, SLUG=null` → paths resolve to root `.planning/` (byte-identical to pre-v1.5.9 behavior per P1). No Tier 4 prompt fires.

**Parallel mode:** `MODE=parallel, SLUG=<active>` → paths route to `.planning/milestones/<slug>/`. If `--milestone <slug>` flag was passed at `/gmd:validate-phase` invocation, it overrides the pointer (Tier 1; init.cjs handled this at flag-parse entry).

**Project-level paths stay literal** (root in BOTH modes per Phase 65 Decision O6-lean PROJECT_LEVEL_PATHS table): `.planning/PROJECT.md`, `.planning/MILESTONES.md`, `.planning/config.json`.

## 0.5. Initialize

The Step 0 INIT block above also covers Step 0.5's existing init read; parse the same JSON for: `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `padded_phase`, `organizational_mode`, `active_milestone_slug`, `active_milestone_needs_prompt`, `active_milestone_candidates`.

```bash
AUDITOR_MODEL=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" resolve-model gmd-nyquist-auditor --complexity standard --raw)
NYQUIST_CFG=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config get workflow.nyquist_validation --raw)
```

If `NYQUIST_CFG` is `false`: exit with "Nyquist validation is disabled. Enable via /gmd:settings."

### 0a. Profile Gate (VERIFY-04)

Auto-invocation from `execute-phase.md` passes `CALL_MODE=auto`. Manual invocation (user runs `/gmd:validate-phase` directly) defaults to `CALL_MODE=manual` and always proceeds regardless of profile.

```bash
PROFILE=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-get model_profile 2>/dev/null || echo "balanced")
CALL_MODE="${CALL_MODE:-manual}"

if [ "$CALL_MODE" = "auto" ]; then
  case "$PROFILE" in
    quality)
      # Proceed — quality profile auto-runs validate-phase per VERIFY-04 lock
      ;;
    *)
      echo "[skipped] profile=$PROFILE — auto-validate runs only under quality profile. Use /gmd:validate-phase manually to run regardless of profile."
      exit 0
      ;;
  esac
fi
# Manual invocation always proceeds regardless of model_profile.
```

Display banner: `GMD > VALIDATE PHASE {N}: {name}`

## 1. Detect Input State

```bash
VALIDATION_FILE=$(ls "${PHASE_DIR}"/*-VALIDATION.md 2>/dev/null | head -1)
SUMMARY_FILES=$(ls "${PHASE_DIR}"/*-SUMMARY.md 2>/dev/null)
```

- **State A** (`VALIDATION_FILE` non-empty): Audit existing
- **State B** (`VALIDATION_FILE` empty, `SUMMARY_FILES` non-empty): Reconstruct from artifacts
- **State C** (`SUMMARY_FILES` empty): Exit — "Phase {N} not executed. Run /gmd:execute-phase {N} first."

## 2. Discovery

### 2a. Read Phase Artifacts

Read all PLAN and SUMMARY files. Extract: task lists, requirement IDs, key-files changed, verify blocks.

### 2b. Build Requirement-to-Task Map

Per task: `{ task_id, plan_id, wave, requirement_ids, has_automated_command }`

### 2c. Detect Test Infrastructure

State A: Parse from existing VALIDATION.md Test Infrastructure table.
State B: Filesystem scan:

```bash
find . -name "pytest.ini" -o -name "jest.config.*" -o -name "vitest.config.*" -o -name "pyproject.toml" 2>/dev/null | head -10
find . \( -name "*.test.*" -o -name "*.spec.*" -o -name "test_*" \) -not -path "*/node_modules/*" 2>/dev/null | head -40
```

### 2d. Cross-Reference

Match each requirement to existing tests by filename, imports, test descriptions. Record: requirement → test_file → status.

## 3. Gap Analysis

Classify each requirement:

| Status | Criteria |
|--------|----------|
| COVERED | Test exists, targets behavior, runs green |
| PARTIAL | Test exists, failing or incomplete |
| MISSING | No test found |

Build: `{ task_id, requirement, gap_type, suggested_test_path, suggested_command }`

No gaps → skip to Step 6, set `nyquist_compliant: true`.

## 4. Present Gap Plan

Call AskUserQuestion with gap table and options:
1. "Fix all gaps" → Step 5
2. "Skip — mark manual-only" → add to Manual-Only, Step 6
3. "Cancel" → exit

## 5. Spawn gmd-nyquist-auditor

```
Task(
  prompt="Read C:/Users/Christopher/.claude/agents/gmd-nyquist-auditor.md for instructions.\n\n" +
    "<files_to_read>{PLAN, SUMMARY, impl files, VALIDATION.md}</files_to_read>" +
    "<gaps>{gap list}</gaps>" +
    "<test_infrastructure>{framework, config, commands}</test_infrastructure>" +
    "<constraints>Never modify impl files. Max 3 debug iterations. Escalate impl bugs.</constraints>",
  subagent_type="gmd-nyquist-auditor",
  model="{AUDITOR_MODEL}",
  description="Fill validation gaps for Phase {N}"
)
```

Handle return:
- `## GAPS FILLED` → record tests + map updates, Step 6
- `## PARTIAL` → record resolved, move escalated to manual-only, Step 6
- `## ESCALATE` → move all to manual-only, Step 6

## 6. Generate/Update VALIDATION.md

**State B (create):**
1. Read template from `C:/Users/Christopher/.claude/get-magic-done/templates/VALIDATION.md`
2. Fill: frontmatter, Test Infrastructure, Per-Task Map, Manual-Only, Sign-Off
3. Write to `${PHASE_DIR}/${PADDED_PHASE}-VALIDATION.md`

**State A (update):**
1. Update Per-Task Map statuses, add escalated to Manual-Only, update frontmatter
2. Append audit trail:

```markdown
## Validation Audit {date}
| Metric | Count |
|--------|-------|
| Gaps found | {N} |
| Resolved | {M} |
| Escalated | {K} |
```

## 7. Commit

```bash
git add {test_files}
git commit -m "test(phase-${PHASE}): add Nyquist validation tests"

node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit-docs "docs(phase-${PHASE}): add/update validation strategy"
```

## 8. Results + Routing

**Compliant:**
```
GMD > PHASE {N} IS NYQUIST-COMPLIANT
All requirements have automated verification.
▶ Next: /gmd:audit-milestone
```

**Partial:**
```
GMD > PHASE {N} VALIDATED (PARTIAL)
{M} automated, {K} manual-only.
▶ Retry: /gmd:validate-phase {N}
```

Display `/clear` reminder.

</process>

<success_criteria>
- [ ] Nyquist config checked (exit if disabled)
- [ ] Input state detected (A/B/C)
- [ ] State C exits cleanly
- [ ] PLAN/SUMMARY files read, requirement map built
- [ ] Test infrastructure detected
- [ ] Gaps classified (COVERED/PARTIAL/MISSING)
- [ ] User gate with gap table
- [ ] Auditor spawned with complete context
- [ ] All three return formats handled
- [ ] VALIDATION.md created or updated
- [ ] Test files committed separately
- [ ] Results with routing presented
</success_criteria>
