<purpose>
Verify phase goal achievement through **two-stage review**:

- **Stage 1 (goal-backward):** Check the codebase delivers what the phase promised — truths / artifacts / key_links / requirements / anti-patterns.
- **Stage 2 (code quality review):** Review the phase's git diff for code quality, architecture, and plan alignment using the ported superpowers `code-reviewer.md` checklist.

Stage 1 answers "did we build the right thing?" Stage 2 answers "did we build it right?"
Both stages produce SEPARATE sections in VERIFICATION.md (`## Goal Achievement` and `## Code Quality Review`).

Executed by a verification subagent spawned from execute-phase.md.
</purpose>

<core_principle>
**Task completion ≠ Goal achievement, and goal achievement ≠ good code**

A task "create chat component" can be marked complete when the component is a placeholder. The task was done — but the goal "working chat interface" was not achieved. And even a working chat component can be poorly factored, leak secrets, or break at scale.

**Stage 1 — Goal-backward verification:**
1. What must be TRUE for the goal to be achieved?
2. What must EXIST for those truths to hold?
3. What must be WIRED for those artifacts to function?

**Stage 2 — Code quality review:**
1. Extract the phase git diff (BASE_SHA..HEAD_SHA).
2. Run the Strengths / Critical / Important / Minor / Assessment checklist against each changed file.
3. Categorize findings by severity and produce a stage-2 report.
4. Combine stage-1 and stage-2 into a final status via the mapping in agents/gmd-verifier.md.

Then verify each level against the actual codebase.
</core_principle>

<dispatch>

## Dispatch contract for gmd-verifier

The verify-phase workflow dispatches gmd-verifier with an explicit `<stages>` block so the two-stage flow is scripted rather than implicit. Stage 2 is opt-in: if `<stages>` is absent, gmd-verifier defaults to stage 1 only (legacy behavior).

### Step 1: Derive phase diff range BEFORE the Task spawn

```bash
# Derive phase diff range for stage-2 code-quality review
BASE_SHA=$(git log --format="%H" --reverse --grep="${PHASE_NUMBER}-" | head -1)
if [ -n "$BASE_SHA" ]; then
  BASE_SHA="${BASE_SHA}~1"
else
  # Fallback: use the commit before the first plan summary landed
  BASE_SHA=$(git log --format="%H" --reverse --diff-filter=A -- ".planning/phases/${PHASE_DIR_NAME}/*-SUMMARY.md" | head -1)
  [ -n "$BASE_SHA" ] && BASE_SHA="${BASE_SHA}~1"
fi
HEAD_SHA=$(git rev-parse HEAD)
```

If `BASE_SHA` cannot be derived (e.g., first phase, no matching commits), fall back to `HEAD~20..HEAD` and document the fallback in the VERIFICATION.md report metadata.

### Step 1.5: Compute the regression cross-reference (WIRE-02) — fail-open

REUSE the Step-1 `BASE_SHA`/`HEAD_SHA`. This site stays in LOCKSTEP with execute-phase.md `verify_phase_goal` Step 1.5 — same CLI invocation, same injection rule:

```bash
# Regression cross-reference (WIRE-02) — fail-open: empty/unavailable never blocks verify
REGRESSION_XREF_BLOCK=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" code-slice --diff "${BASE_SHA}..${HEAD_SHA}" --format block 2>/dev/null || true)
```

The block carries the changed entities with callers partitioned test/non-test, callees + `type:external` stubs (the Phase-111 column), the freshness verdict, and the Tier-2 pull commands. A failed derivation yields an absent or `xref_status: unavailable` block — never a blocked verify. Inject `${REGRESSION_XREF_BLOCK}` into the Step-2 dispatch prompt after `</diff_range>` (omit when empty).

### Step 2: Dispatch gmd-verifier with `<stages>` + `<diff_range>` blocks

```
Task(
  subagent_type="gmd-verifier",
  model="{verifier_model}",
  prompt="""
    <objective>
    Verify phase ${PHASE_NUMBER} with two-stage flow:
      stage 1: goal-backward verification (must_haves -> truths -> artifacts -> wiring -> requirements)
      stage 2: code quality review on git diff ${BASE_SHA}..${HEAD_SHA}
    Create VERIFICATION.md with both stages reported as distinct sections:
      ## Goal Achievement      (stage 1)
      ## Code Quality Review   (stage 2)
    </objective>

    <stages>
    stage_1: goal_backward
    stage_2: code_quality
    require_both: true
    </stages>

    <diff_range>
    base: ${BASE_SHA}
    head: ${HEAD_SHA}
    </diff_range>

    ${REGRESSION_XREF_BLOCK}

    <files_to_read>
    - ${PHASE_DIR}/*-PLAN.md
    - ${PHASE_DIR}/*-SUMMARY.md
    - .planning/ROADMAP.md
    - .planning/REQUIREMENTS.md
    - .planning/STATE.md
    </files_to_read>
  """
)
```

### Step 3: Combined status routing

After the verifier returns, read the final status from VERIFICATION.md frontmatter and route:

| Final status            | Action                                                     |
| ----------------------- | ---------------------------------------------------------- |
| `passed`                | Update roadmap; advance to next phase                      |
| `passed_with_warnings`  | Present stage-2 Important findings; ask user to acknowledge |
| `code_quality_gaps`     | Present stage-2 Critical findings; block merge             |
| `gaps_found`            | Offer `/gmd:plan-phase {phase} --gaps`                     |
| `human_needed`          | Present human verification items                           |

**Note:** `passed_with_warnings` and `code_quality_gaps` are stage-2-only statuses introduced by the code quality review. Legacy stage-1-only callers will never see them — they continue to see `passed | gaps_found | human_needed` exactly as before.

**Bundling (NOTE-01 — lockstep with execute-phase.md update_roadmap):** on the standalone path, whoever commits VERIFICATION.md runs the SAME `git add -f .planning/codebase/_notes/ 2>/dev/null || true` first — gmd-verifier writes judgment notes during stage 2 but never commits; this named add is what lands them in the VERIFICATION.md commit. (Identical pathspec at both sites — the phase-113 audit greps both.)

</dispatch>

<required_reading>
@C:/Users/Christopher/.claude/get-magic-done/references/verification-patterns.md
@C:/Users/Christopher/.claude/get-magic-done/templates/verification-report.md
</required_reading>

<process>

<step name="load_context" priority="first">
Load phase operation context:

```bash
INIT=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" init phase-op "${PHASE_ARG}")
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
```

Extract from init JSON: `phase_dir`, `phase_number`, `phase_name`, `has_plans`, `plan_count`.

Then load phase details and list plans/summaries:
```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" roadmap get-phase "${phase_number}"
grep -E "^| ${phase_number}" .planning/REQUIREMENTS.md 2>/dev/null
ls "$phase_dir"/*-SUMMARY.md "$phase_dir"/*-PLAN.md 2>/dev/null
```

Extract **phase goal** from ROADMAP.md (the outcome to verify, not tasks) and **requirements** from REQUIREMENTS.md if it exists.
</step>

<step name="establish_must_haves">
**Option A: Must-haves in PLAN frontmatter**

Use gmd-tools to extract must_haves from each PLAN:

```bash
for plan in "$PHASE_DIR"/*-PLAN.md; do
  MUST_HAVES=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" frontmatter get "$plan" --field must_haves)
  echo "=== $plan ===" && echo "$MUST_HAVES"
done
```

Returns JSON: `{ truths: [...], artifacts: [...], key_links: [...] }`

Aggregate all must_haves across plans for phase-level verification.

**Option B: Use Success Criteria from ROADMAP.md**

If no must_haves in frontmatter (MUST_HAVES returns error or empty), check for Success Criteria:

```bash
PHASE_DATA=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" roadmap get-phase "${phase_number}" --raw)
```

Parse the `success_criteria` array from the JSON output. If non-empty:
1. Use each Success Criterion directly as a **truth** (they are already written as observable, testable behaviors)
2. Derive **artifacts** (concrete file paths for each truth)
3. Derive **key links** (critical wiring where stubs hide)
4. Document the must-haves before proceeding

Success Criteria from ROADMAP.md are the contract — they override PLAN-level must_haves when both exist.

**Option C: Derive from phase goal (fallback)**

If no must_haves in frontmatter AND no Success Criteria in ROADMAP:
1. State the goal from ROADMAP.md
2. Derive **truths** (3-7 observable behaviors, each testable)
3. Derive **artifacts** (concrete file paths for each truth)
4. Derive **key links** (critical wiring where stubs hide)
5. Document derived must-haves before proceeding
</step>

<step name="verify_truths">
For each observable truth, determine if the codebase enables it.

**Status:** ✓ VERIFIED (all supporting artifacts pass) | ✗ FAILED (artifact missing/stub/unwired) | ? UNCERTAIN (needs human)

For each truth: identify supporting artifacts → check artifact status → check wiring → determine truth status.

**Example:** Truth "User can see existing messages" depends on Chat.tsx (renders), /api/chat GET (provides), Message model (schema). If Chat.tsx is a stub or API returns hardcoded [] → FAILED. If all exist, are substantive, and connected → VERIFIED.
</step>

<step name="verify_artifacts">
Use gmd-tools for artifact verification against must_haves in each PLAN:

```bash
for plan in "$PHASE_DIR"/*-PLAN.md; do
  ARTIFACT_RESULT=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" verify artifacts "$plan")
  echo "=== $plan ===" && echo "$ARTIFACT_RESULT"
done
```

Parse JSON result: `{ all_passed, passed, total, artifacts: [{path, exists, issues, passed}] }`

**Artifact status from result:**
- `exists=false` → MISSING
- `issues` not empty → STUB (check issues for "Only N lines" or "Missing pattern")
- `passed=true` → VERIFIED (Levels 1-2 pass)

**Level 3 — Wired (manual check for artifacts that pass Levels 1-2):**
```bash
grep -r "import.*$artifact_name" src/ --include="*.ts" --include="*.tsx"  # IMPORTED
grep -r "$artifact_name" src/ --include="*.ts" --include="*.tsx" | grep -v "import"  # USED
```
WIRED = imported AND used. ORPHANED = exists but not imported/used.

| Exists | Substantive | Wired | Status |
|--------|-------------|-------|--------|
| ✓ | ✓ | ✓ | ✓ VERIFIED |
| ✓ | ✓ | ✗ | ⚠️ ORPHANED |
| ✓ | ✗ | - | ✗ STUB |
| ✗ | - | - | ✗ MISSING |
</step>

<step name="verify_wiring">
Use gmd-tools for key link verification against must_haves in each PLAN:

```bash
for plan in "$PHASE_DIR"/*-PLAN.md; do
  LINKS_RESULT=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" verify key-links "$plan")
  echo "=== $plan ===" && echo "$LINKS_RESULT"
done
```

Parse JSON result: `{ all_verified, verified, total, links: [{from, to, via, verified, detail}] }`

**Link status from result:**
- `verified=true` → WIRED
- `verified=false` with "not found" → NOT_WIRED
- `verified=false` with "Pattern not found" → PARTIAL

**Fallback patterns (if key_links not in must_haves):**

| Pattern | Check | Status |
|---------|-------|--------|
| Component → API | fetch/axios call to API path, response used (await/.then/setState) | WIRED / PARTIAL (call but unused response) / NOT_WIRED |
| API → Database | Prisma/DB query on model, result returned via res.json() | WIRED / PARTIAL (query but not returned) / NOT_WIRED |
| Form → Handler | onSubmit with real implementation (fetch/axios/mutate/dispatch), not console.log/empty | WIRED / STUB (log-only/empty) / NOT_WIRED |
| State → Render | useState variable appears in JSX (`{stateVar}` or `{stateVar.property}`) | WIRED / NOT_WIRED |

Record status and evidence for each key link.
</step>

<step name="verify_requirements">
If REQUIREMENTS.md exists:
```bash
grep -E "Phase ${PHASE_NUM}" .planning/REQUIREMENTS.md 2>/dev/null
```

For each requirement: parse description → identify supporting truths/artifacts → status: ✓ SATISFIED / ✗ BLOCKED / ? NEEDS HUMAN.
</step>

<step name="scan_antipatterns">
Extract files modified in this phase from SUMMARY.md, scan each:

| Pattern | Search | Severity |
|---------|--------|----------|
| TODO/FIXME/XXX/HACK | `grep -n -E "TODO\|FIXME\|XXX\|HACK"` | ⚠️ Warning |
| Placeholder content | `grep -n -iE "placeholder\|coming soon\|will be here"` | 🛑 Blocker |
| Empty returns | `grep -n -E "return null\|return \{\}\|return \[\]\|=> \{\}"` | ⚠️ Warning |
| Log-only functions | Functions containing only console.log | ⚠️ Warning |

Categorize: 🛑 Blocker (prevents goal) | ⚠️ Warning (incomplete) | ℹ️ Info (notable).
</step>

<step name="identify_human_verification">
**Always needs human:** Visual appearance, user flow completion, real-time behavior (WebSocket/SSE), external service integration, performance feel, error message clarity.

**Needs human if uncertain:** Complex wiring grep can't trace, dynamic state-dependent behavior, edge cases.

Format each as: Test Name → What to do → Expected result → Why can't verify programmatically.
</step>

<step name="determine_status">
**passed:** All truths VERIFIED, all artifacts pass levels 1-3, all key links WIRED, no blocker anti-patterns.

**gaps_found:** Any truth FAILED, artifact MISSING/STUB, key link NOT_WIRED, or blocker found.

**human_needed:** All automated checks pass but human verification items remain.

**Score:** `verified_truths / total_truths`
</step>

<step name="generate_fix_plans">
If gaps_found:

1. **Cluster related gaps:** API stub + component unwired → "Wire frontend to backend". Multiple missing → "Complete core implementation". Wiring only → "Connect existing components".

2. **Generate plan per cluster:** Objective, 2-3 tasks (files/action/verify each), re-verify step. Keep focused: single concern per plan.

3. **Order by dependency:** Fix missing → fix stubs → fix wiring → verify.
</step>

<step name="create_report">
```bash
REPORT_PATH="$PHASE_DIR/${PHASE_NUM}-VERIFICATION.md"
```

Fill template sections: frontmatter (phase/timestamp/status/score), goal achievement, artifact table, wiring table, requirements coverage, anti-patterns, human verification, gaps summary, fix plans (if gaps_found), metadata.

See C:/Users/Christopher/.claude/get-magic-done/templates/verification-report.md for complete template.
</step>

<step name="return_to_orchestrator">
Return status (`passed` | `gaps_found` | `human_needed`), score (N/M must-haves), report path.

If gaps_found: list gaps + recommended fix plan names.
If human_needed: list items requiring human testing.

Orchestrator routes: `passed` → update_roadmap | `gaps_found` → create/execute fixes, re-verify | `human_needed` → present to user.
</step>

</process>

<success_criteria>
- [ ] Must-haves established (from frontmatter or derived)
- [ ] All truths verified with status and evidence
- [ ] All artifacts checked at all three levels
- [ ] All key links verified
- [ ] Requirements coverage assessed (if applicable)
- [ ] Anti-patterns scanned and categorized
- [ ] Human verification items identified
- [ ] Overall status determined
- [ ] Fix plans generated (if gaps_found)
- [ ] VERIFICATION.md created with complete report
- [ ] Results returned to orchestrator
</success_criteria>
