<purpose>

Mark a shipped version (v1.0, v1.1, v2.0) as complete. Creates historical record in MILESTONES.md, performs full PROJECT.md evolution review, reorganizes ROADMAP.md with milestone groupings, and tags the release in git.

</purpose>

<required_reading>

1. templates/milestone.md
2. templates/milestone-archive.md
3. `.planning/ROADMAP.md`
4. `.planning/REQUIREMENTS.md`
5. `.planning/PROJECT.md`

</required_reading>

<archival_behavior>

When a milestone completes:

1. Extract full milestone details to `.planning/milestones/v[X.Y]-ROADMAP.md`
2. Archive requirements to `.planning/milestones/v[X.Y]-REQUIREMENTS.md`
3. Update ROADMAP.md — replace milestone details with one-line summary
4. Delete REQUIREMENTS.md (fresh one for next milestone)
5. Perform full PROJECT.md evolution review
6. Offer to create next milestone inline

**Context Efficiency:** Archives keep ROADMAP.md constant-size and REQUIREMENTS.md milestone-scoped.

**ROADMAP archive** uses `templates/milestone-archive.md` — includes milestone header (status, phases, date), full phase details, milestone summary (decisions, issues, tech debt).

**REQUIREMENTS archive** contains all requirements marked complete with outcomes, traceability table with final status, notes on changed requirements.

</archival_behavior>

<process>

<step name="resolve_mode_aware_paths">

## 0. Mode-Aware Path Resolution (Phase 66-04 CMD-05)

Resolve organizational_mode + active_milestone_slug ONCE at workflow start, then route all mode-variant `.planning/` path lookups through `resolveMilestonePaths(mode, slug, artifact)`. Sequential mode resolves to root `.planning/` paths (byte-identical to pre-v1.5.9). Parallel mode routes to `.planning/milestones/<slug>/`. Project-level paths (PROJECT.md, MILESTONES.md, config.json) stay literal per Phase 65 Decision O6-lean.

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

MODE=$(echo "$INIT" | jq -r '.organizational_mode // "sequential"')
SLUG=$(echo "$INIT" | jq -r '.active_milestone_slug // empty')

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'))")
```

If `MODE == "parallel"` and `INIT.active_milestone_needs_prompt == true`: prompt via AskUserQuestion using `INIT.active_milestone_candidates`; write selection via `node bin/gmd-tools.cjs state set-current-milestone <slug>` then re-run Step 0.

Sequential-mode behavior in Steps 1-12 below is byte-identical to pre-v1.5.9 (P1 baseline). Parallel-mode additions live in Step 7 below.

</step>

<step name="verify_readiness">

**Use `roadmap analyze` for comprehensive readiness check:**

```bash
ROADMAP=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" roadmap analyze)
```

This returns all phases with plan/summary counts and disk status. Use this to verify:
- Which phases belong to this milestone?
- All phases complete (all plans have summaries)? Check `disk_status === 'complete'` for each.
- `progress_percent` should be 100%.

**HARD ABORT GATE — Pre-flight completeness check (load-bearing):**

Without this gate, dispatching the audit-milestone Task against an incomplete milestone has previously hung for 5+ hours (see `.planning/debug/resolved/v1.5.1-ship-hang.md`). The audit needs complete artifacts to terminate; partial state can spin indefinitely.

```bash
PROGRESS=$(echo "$ROADMAP" | node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{try{const j=JSON.parse(d);console.log(j.progress_percent||0)}catch(e){console.log(0)}})")
INCOMPLETE_PHASES=$(echo "$ROADMAP" | node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{try{const j=JSON.parse(d);const bad=(j.phases||[]).filter(p=>p.disk_status!=='complete').map(p=>'  '+p.number+' ('+p.disk_status+'): '+(p.name||'').slice(0,80));console.log(bad.join('\n'))}catch(e){}})")
```

**If `PROGRESS` < 100 OR `INCOMPLETE_PHASES` is non-empty: STOP THE WORKFLOW. Do NOT dispatch the audit-milestone Task.** Surface this exact message to the user:

```
✗ Cannot complete milestone — incomplete work detected

Progress: {PROGRESS}% (need 100%)
Incomplete phases:
{INCOMPLETE_PHASES}

Recommendation:
- Run `/gmd:execute-phase <N>` for partial phases (have plans but missing summaries)
- Run `/gmd:plan-phase <N>` for unplanned phases
- Re-run `/gmd:complete-milestone` once all phases reach disk_status === 'complete'

Why this gate exists: dispatching gmd-integration-checker against a partial milestone has previously caused 5+ hour silent hangs (see .planning/debug/resolved/v1.5.1-ship-hang.md).
```

Exit the complete-milestone workflow now. Return control to the user.

**Requirements completion check (REQUIRED before presenting):**

Parse REQUIREMENTS.md traceability table:
- Count total v1 requirements vs checked-off (`[x]`) requirements
- Identify any non-Complete rows in the traceability table

Present:

```
Milestone: [Name, e.g., "v1.0 MVP"]

Includes:
- Phase 1: Foundation (2/2 plans complete)
- Phase 2: Authentication (2/2 plans complete)
- Phase 3: Core Features (3/3 plans complete)
- Phase 4: Polish (1/1 plan complete)

Total: {phase_count} phases, {total_plans} plans, all complete
Requirements: {N}/{M} v1 requirements checked off
```

**If requirements incomplete** (N < M):

```
⚠ Unchecked Requirements:

- [ ] {REQ-ID}: {description} (Phase {X})
- [ ] {REQ-ID}: {description} (Phase {Y})
```

**Mandatory Audit Gate:** Run audit before proceeding — all profiles, no skip. The dispatch is shape-gated: `foundation-cleanup` and `hf` shapes rely on the closure-script zero-regression sweep + `mirror-check.js` (proof of cross-phase wiring for those shapes) and skip the integration-checker agent dispatch.

Resolve milestone shape (same precedence as audit-milestone step 3a):
```bash
SHAPE_FLAG=$(echo "$ARGUMENTS" | grep -oE '--shape=[a-z-]+' | sed 's/--shape=//')
if [ -n "$SHAPE_FLAG" ]; then
  MILESTONE_SHAPE="$SHAPE_FLAG"
else
  MILESTONE_SHAPE=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config get workflow.milestone_shape --raw 2>/dev/null || echo "full-milestone")
  [ -z "$MILESTONE_SHAPE" ] && MILESTONE_SHAPE="full-milestone"
fi
```

If `$MILESTONE_SHAPE` is `foundation-cleanup` or `hf`: skip the integration-checker dispatch. Note in MILESTONES.md under `### Audit Notes` that the shape gate elided the agent pass, and continue to the post-audit traceability step (treat all requirements as `not_checked` from the agent's perspective; the closure-script sweep is the authoritative cross-phase proof for these shapes).

Otherwise (full-milestone), resolve the integration checker model and dispatch:
```bash
integration_checker_model=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" resolve-model gmd-integration-checker --complexity complex --raw)
```

Dispatch audit-milestone as a Task (do NOT set run_in_background — audit MUST complete before proceeding):

```
Task(
  prompt="Run milestone audit for v{version}.

  <files_to_read>
  - .planning/REQUIREMENTS.md
  - .planning/ROADMAP.md
  </files_to_read>

  Milestone version: {version}
  Check all phase verifications and cross-phase integration.
  Return structured results with per-requirement status (verified | gaps_found | not_checked) and gap descriptions.

  **Budget: 15 minutes wall-clock.** If you cannot complete the audit in time, return `status: BUDGET_EXCEEDED` with partial findings rather than continuing — see your <budget> discipline block. Returning partial results is always preferable to a hang.",
  subagent_type="gmd-integration-checker",
  model="{integration_checker_model}"
)
```

**After audit returns results — update traceability:**

Parse audit output for per-requirement status. For each requirement in REQUIREMENTS.md traceability table:
- If audit reports `verified` → mark status as `verified` in traceability table
- If audit reports `gaps_found` → mark status as `gaps_found` in traceability table
- If audit reports `not_checked` → leave status unchanged

**Gap-blocking logic:**

If audit found gaps:

Display gaps with requirement IDs and severity:
```
Audit found {N} gaps:

- {REQ-ID}: {description} — {gap reason}
- {REQ-ID}: {description} — {gap reason}
```

Present exactly 2 options via AskUserQuestion:

AskUserQuestion(
  header: "Milestone Audit Gaps",
  question: "Audit found {N} gaps. How would you like to proceed?",
  options: [
    { label: "Complete anyway", description: "Acknowledge gaps, record them in MILESTONES.md under ### Known Gaps with REQ-IDs" },
    { label: "Address gaps first", description: "Exit complete-milestone, return to development" }
  ]
)

If user selects "Complete anyway": note gaps in MILESTONES.md under `### Known Gaps` with REQ-IDs and descriptions.
If user selects "Address gaps first": exit complete-milestone workflow immediately.

If audit found NO gaps: proceed directly to completion.

<config-check>

```bash
cat .planning/config.json 2>/dev/null
```

</config-check>

<if mode="yolo">

```
⚡ Auto-approved: Milestone scope verification
[Show breakdown summary without prompting]
Proceeding to stats gathering...
```

Proceed to gather_stats.

</if>

<if mode="interactive" OR="custom with gates.confirm_milestone_scope true">

```
Ready to mark this milestone as shipped?
(yes / wait / adjust scope)
```

Wait for confirmation.
- "adjust scope": Ask which phases to include.
- "wait": Stop, user returns when ready.

</if>

</step>

<step name="gather_stats">

Calculate milestone statistics:

```bash
git log --oneline --grep="feat(" | head -20
git diff --stat FIRST_COMMIT..LAST_COMMIT | tail -1
find . -name "*.swift" -o -name "*.ts" -o -name "*.py" | xargs wc -l 2>/dev/null
git log --format="%ai" FIRST_COMMIT | tail -1
git log --format="%ai" LAST_COMMIT | head -1
```

Present:

```
Milestone Stats:
- Phases: [X-Y]
- Plans: [Z] total
- Tasks: [N] total (from phase summaries)
- Files modified: [M]
- Lines of code: [LOC] [language]
- Timeline: [Days] days ([Start] → [End])
- Git range: feat(XX-XX) → feat(YY-YY)
```

</step>

<step name="extract_accomplishments">

Extract one-liners from SUMMARY.md files using summary-extract:

```bash
# For each phase in milestone, extract one-liner
for summary in .planning/phases/*-*/*-SUMMARY.md; do
  node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" summary-extract "$summary" --fields one_liner | jq -r '.one_liner'
done
```

Extract 4-6 key accomplishments. Present:

```
Key accomplishments for this milestone:
1. [Achievement from phase 1]
2. [Achievement from phase 2]
3. [Achievement from phase 3]
4. [Achievement from phase 4]
5. [Achievement from phase 5]
```

</step>

<step name="create_milestone_entry">

**Note:** MILESTONES.md entry is now created automatically by `gmd-tools milestone complete` in the archive_milestone step. The entry includes version, date, phase/plan/task counts, and accomplishments extracted from SUMMARY.md files.

If additional details are needed (e.g., user-provided "Delivered" summary, git range, LOC stats), add them manually after the CLI creates the base entry.

</step>

<step name="evolve_project_full_review">

Full PROJECT.md evolution review at milestone completion.

Read all phase summaries:

```bash
cat .planning/phases/*-*/*-SUMMARY.md
```

**Full review checklist:**

1. **"What This Is" accuracy:**
   - Compare current description to what was built
   - Update if product has meaningfully changed

2. **Core Value check:**
   - Still the right priority? Did shipping reveal a different core value?
   - Update if the ONE thing has shifted

3. **Requirements audit:**

   **Validated section:**
   - All Active requirements shipped this milestone → Move to Validated
   - Format: `- ✓ [Requirement] — v[X.Y]`

   **Active section:**
   - Remove requirements moved to Validated
   - Add new requirements for next milestone
   - Keep unaddressed requirements

   **Out of Scope audit:**
   - Review each item — reasoning still valid?
   - Remove irrelevant items
   - Add requirements invalidated during milestone

4. **Context update:**
   - Current codebase state (LOC, tech stack)
   - User feedback themes (if any)
   - Known issues or technical debt

5. **Key Decisions audit:**
   - Extract all decisions from milestone phase summaries
   - Add to Key Decisions table with outcomes
   - Mark ✓ Good, ⚠️ Revisit, or — Pending

6. **Constraints check:**
   - Any constraints changed during development? Update as needed

Update PROJECT.md inline. Update "Last updated" footer:

```markdown
---
*Last updated: [date] after v[X.Y] milestone*
```

**Example full evolution (v1.0 → v1.1 prep):**

Before:

```markdown
## What This Is

A real-time collaborative whiteboard for remote teams.

## Core Value

Real-time sync that feels instant.

## Requirements

### Validated

(None yet — ship to validate)

### Active

- [ ] Canvas drawing tools
- [ ] Real-time sync < 500ms
- [ ] User authentication
- [ ] Export to PNG

### Out of Scope

- Mobile app — web-first approach
- Video chat — use external tools
```

After v1.0:

```markdown
## What This Is

A real-time collaborative whiteboard for remote teams with instant sync and drawing tools.

## Core Value

Real-time sync that feels instant.

## Requirements

### Validated

- ✓ Canvas drawing tools — v1.0
- ✓ Real-time sync < 500ms — v1.0 (achieved 200ms avg)
- ✓ User authentication — v1.0

### Active

- [ ] Export to PNG
- [ ] Undo/redo history
- [ ] Shape tools (rectangles, circles)

### Out of Scope

- Mobile app — web-first approach, PWA works well
- Video chat — use external tools
- Offline mode — real-time is core value

## Context

Shipped v1.0 with 2,400 LOC TypeScript.
Tech stack: Next.js, Supabase, Canvas API.
Initial user testing showed demand for shape tools.
```

**Step complete when:**

- [ ] "What This Is" reviewed and updated if needed
- [ ] Core Value verified as still correct
- [ ] All shipped requirements moved to Validated
- [ ] New requirements added to Active for next milestone
- [ ] Out of Scope reasoning audited
- [ ] Context updated with current state
- [ ] All milestone decisions added to Key Decisions
- [ ] "Last updated" footer reflects milestone completion

</step>

<step name="reorganize_roadmap">

Update `.planning/ROADMAP.md` — group completed milestone phases:

```markdown
# Roadmap: [Project Name]

## Milestones

- ✅ **v1.0 MVP** — Phases 1-4 (shipped YYYY-MM-DD)
- 🚧 **v1.1 Security** — Phases 5-6 (in progress)
- 📋 **v2.0 Redesign** — Phases 7-10 (planned)

## Phases

<details>
<summary>✅ v1.0 MVP (Phases 1-4) — SHIPPED YYYY-MM-DD</summary>

- [x] Phase 1: Foundation (2/2 plans) — completed YYYY-MM-DD
- [x] Phase 2: Authentication (2/2 plans) — completed YYYY-MM-DD
- [x] Phase 3: Core Features (3/3 plans) — completed YYYY-MM-DD
- [x] Phase 4: Polish (1/1 plan) — completed YYYY-MM-DD

</details>

### 🚧 v[Next] [Name] (In Progress / Planned)

- [ ] Phase 5: [Name] ([N] plans)
- [ ] Phase 6: [Name] ([N] plans)

## Progress

| Phase             | Milestone | Plans Complete | Status      | Completed  |
| ----------------- | --------- | -------------- | ----------- | ---------- |
| 1. Foundation     | v1.0      | 2/2            | Complete    | YYYY-MM-DD |
| 2. Authentication | v1.0      | 2/2            | Complete    | YYYY-MM-DD |
| 3. Core Features  | v1.0      | 3/3            | Complete    | YYYY-MM-DD |
| 4. Polish         | v1.0      | 1/1            | Complete    | YYYY-MM-DD |
| 5. Security Audit | v1.1      | 0/1            | Not started | -          |
| 6. Hardening      | v1.1      | 0/2            | Not started | -          |
```

</step>

<step name="archive_requirements">

**Requirements Archival (before archive_milestone):**

After gap resolution (or no gaps), archive completed requirements to individual files:

1. Read REQUIREMENTS.md, identify all requirements marked complete (checkbox `[x]`).

2. For each completed requirement, create `.planning/requirements/{ID}.md` with Obsidian frontmatter:

```markdown
---
id: {REQ-ID}
description: {requirement text}
status: complete
phase: {phase number}
milestone: {current milestone version}
completed: {date}
tags:
  - requirement
  - archived
---

# {REQ-ID}: {requirement text}

Completed in Phase {phase} during milestone {version}.

## Verification
- Verified by: gmd-verifier (Phase {phase} VERIFICATION.md)
- Integration checked: gmd-integration-checker (milestone audit)
```

3. Update REQUIREMENTS.md: remove archived requirements from the active list, add summary line:
   `**Archived:** N requirements from {milestone} (see .planning/requirements/)`

4. Create `.planning/requirements/ARCHIVE.base` if it doesn't exist:

```markdown
---
name: Archived Requirements
source: folder
folder: .planning/requirements
filter:
  - property: tags
    operator: contains
    value: requirement
columns:
  - property: id
  - property: status
  - property: phase
  - property: milestone
  - property: completed
sort:
  - property: milestone
    direction: asc
---
```

</step>

<step name="archive_milestone">

**Delegate archival to gmd-tools:**

```bash
ARCHIVE=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" milestone complete "v[X.Y]" --name "[Milestone Name]")
```

The CLI handles:
- Creating `.planning/milestones/` directory
- Archiving ROADMAP.md to `milestones/v[X.Y]-ROADMAP.md`
- Archiving REQUIREMENTS.md to `milestones/v[X.Y]-REQUIREMENTS.md` with archive header
- Moving audit file to milestones if it exists
- Creating/appending MILESTONES.md entry with accomplishments from SUMMARY.md files
- Updating STATE.md (status, last activity)

Extract from result: `version`, `date`, `phases`, `plans`, `tasks`, `accomplishments`, `archived`.

Verify: `✅ Milestone archived to .planning/milestones/`

**Phase archival (optional):** After archival completes, ask the user:

AskUserQuestion(header="Archive Phases", question="Archive phase directories to milestones/?", options: "Yes — move to milestones/v[X.Y]-phases/" | "Skip — keep phases in place")

If "Yes": move phase directories to the milestone archive:
```bash
mkdir -p .planning/milestones/v[X.Y]-phases
# For each phase directory in .planning/phases/:
mv .planning/phases/{phase-dir} .planning/milestones/v[X.Y]-phases/
```
Verify: `✅ Phase directories archived to .planning/milestones/v[X.Y]-phases/`

If "Skip": Phase directories remain in `.planning/phases/` as raw execution history. Use `/gmd:cleanup` later to archive retroactively.

After archival, the AI still handles:
- Reorganizing ROADMAP.md with milestone grouping (requires judgment)
- Full PROJECT.md evolution review (requires understanding)
- Deleting original ROADMAP.md and REQUIREMENTS.md
- These are NOT fully delegated because they require AI interpretation of content

</step>

<step name="reorganize_roadmap_and_delete_originals">

After `milestone complete` has archived, reorganize ROADMAP.md with milestone groupings, then delete originals:

**Reorganize ROADMAP.md** — group completed milestone phases:

```markdown
# Roadmap: [Project Name]

## Milestones

- ✅ **v1.0 MVP** — Phases 1-4 (shipped YYYY-MM-DD)
- 🚧 **v1.1 Security** — Phases 5-6 (in progress)

## Phases

<details>
<summary>✅ v1.0 MVP (Phases 1-4) — SHIPPED YYYY-MM-DD</summary>

- [x] Phase 1: Foundation (2/2 plans) — completed YYYY-MM-DD
- [x] Phase 2: Authentication (2/2 plans) — completed YYYY-MM-DD

</details>
```

**Then delete originals:**

```bash
rm .planning/ROADMAP.md
rm .planning/REQUIREMENTS.md
```

</step>

<step name="write_retrospective">

**Append to living retrospective:**

Check for existing retrospective:
```bash
ls .planning/RETROSPECTIVE.md 2>/dev/null
```

**If exists:** Read the file, append new milestone section before the "## Cross-Milestone Trends" section.

**If doesn't exist:** Create from template at `C:/Users/Christopher/.claude/get-magic-done/templates/retrospective.md`.

**Gather retrospective data:**

1. From SUMMARY.md files: Extract key deliverables, one-liners, tech decisions
2. From VERIFICATION.md files: Extract verification scores, gaps found
3. From UAT.md files: Extract test results, issues found
4. From git log: Count commits, calculate timeline
5. From the milestone work: Reflect on what worked and what didn't

**Write the milestone section:**

```markdown
## Milestone: v{version} — {name}

**Shipped:** {date}
**Phases:** {phase_count} | **Plans:** {plan_count}

### What Was Built
{Extract from SUMMARY.md one-liners}

### What Worked
{Patterns that led to smooth execution}

### What Was Inefficient
{Missed opportunities, rework, bottlenecks}

### Patterns Established
{New conventions discovered during this milestone}

### Key Lessons
{Specific, actionable takeaways}

### Cost Observations
- Model mix: {X}% opus, {Y}% sonnet, {Z}% haiku
- Sessions: {count}
- Notable: {efficiency observation}
```

**Update cross-milestone trends:**

If the "## Cross-Milestone Trends" section exists, update the tables with new data from this milestone.

**Commit:**
```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs: update retrospective for v${VERSION}" --files .planning/RETROSPECTIVE.md
```

## G1 Workflow-Boundary Maintenance Sweep (SYNC-03)

With the milestone retrospective committed, run `vault-maintain --core` to sweep the vault before milestone transition: regenerate `Maps/Cross-Scope-Dependencies.md` and `Maps/_Test-Coverage-Map.md`, run schema-validate, refresh status. This is the G1 layer of the K-mixed sync cadence (per SPEC §11.4 + Phase 21 Decision 1). Failures are recoverable — the SessionStart 24h hook is the safety net.

```bash
node bin/gmd-tools.cjs vault-maintain --core || {
  echo "vault-maintain --core failed at milestone boundary (recoverable; SessionStart 24h hook will retry)" >&2
}
```

Why here: the milestone retrospective write changed vault state. Sweeping before the milestone closes keeps the next milestone's planner working from a fresh `_Cross-Scope-Map`. Why fail-open: a transient failure in maintain should never block milestone completion.

## Post-Workflow Vault Extraction (J2)

After the milestone RETROSPECTIVE.md is committed, extract knowledge candidates to `.vault/Knowledge/_inbox/`.

```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 "[J2] vault-extract-knowledge skipped: obsidian component disabled" >&2
else
  node bin/gmd-tools.cjs vault-extract-knowledge \
    --trigger J2 \
    --source-files ".planning/RETROSPECTIVE.md" \
    --caller complete-milestone \
    --phase "${MILESTONE_SLUG}" \
  || echo "[J2] extraction returned non-zero — continuing; check .vault/_logs/" >&2
fi
```

**Flag-form rule (load-bearing):** every flag uses space separator. `--trigger J2`, NOT `--trigger=J2`. `--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 host workflow (milestone complete) still succeeds.

</step>

<step name="parallel_milestone_finalize">

## 7. Parallel-Mode Finalize (Phase 66-04 CMD-05; SKIP in sequential mode)

If `$MODE == "parallel"`: move the MILESTONES.md row from `## In Progress` to `## Shipped` and conditionally clear the root `current_milestone:` pointer.

If `$MODE == "sequential"`: skip this entire step (no parallel-mode artifacts to move; existing Steps 1-6 + 8-12 cover the closing semantics).

### 7.1 MILESTONES.md row move (In Progress → Shipped)

`.planning/MILESTONES.md` is project-level (root in both modes per Phase 65 Decision O6-lean PROJECT_LEVEL_PATHS). Locate the row for `$SLUG` in the `## In Progress` table and append it to the `## Shipped` table with an additional `shipped_at:` column containing today's ISO date. Preserve all other rows in both tables exactly (no reordering).

```bash
TODAY=$(date -u +%Y-%m-%d)
# Implement via Node helper or sed/awk — preserve other rows verbatim.
# Pattern: read MILESTONES.md; find row matching $SLUG in '## In Progress'
# table block; remove from In Progress; append to '## Shipped' table block
# with shipped_at: $TODAY column.
```

### 7.2 Conditional clear of root current_milestone pointer (STATE-01 authority)

Clear root `.planning/STATE.md` `current_milestone:` field IFF it currently equals `$SLUG`. The CLI helper handles the conditional (matches→clear; mismatch→no-op; absent→no-op).

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" state complete-milestone-clear "$SLUG" --raw
```

This dispatches to `bin/lib/state.cjs::completeMilestoneClearPointer(cwd, $SLUG)`. STATE-01 authority is preserved — downstream shipped-milestone retrospective archive blocks remain byte-identical (verified by state-authority.test.cjs T6 md5 stability + state.test.cjs T10).

**Pre-scope idiom preservation (critic R2):** When the user has already advanced the root pointer to a newer milestone via `/gmd:switch-milestone` (e.g., `current_milestone: v1-6` while completing `v1-5-9`), the no-op semantics keep the pointer untouched — the pre-scope idiom v1.5.9-SPEC dogfooded stays first-class.

### 7.3 Atomic commit

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "feat: ship milestone $SLUG" --files .planning/MILESTONES.md .planning/STATE.md
```

This single commit covers: MILESTONES.md row move + STATE.md pointer clear (if applicable).

</step>

<step name="update_state">

Most STATE.md updates were handled by `milestone complete`, but verify and update remaining fields:

**Project Reference:**

```markdown
## Project Reference

See: .planning/PROJECT.md (updated [today])

**Core value:** [Current core value from PROJECT.md]
**Current focus:** [Next milestone or "Planning next milestone"]
```

**Accumulated Context:**
- Clear decisions summary (full log in PROJECT.md)
- Clear resolved blockers
- Keep open blockers for next milestone

</step>

<step name="handle_branches">

Check branching strategy and offer merge options.

Use `init milestone-op` for context, or load config directly:

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

Extract `branching_strategy`, `phase_branch_template`, `milestone_branch_template`, and `commit_docs` from init JSON.

**If "none":** Skip to git_tag.

**For "phase" strategy:**

```bash
BRANCH_PREFIX=$(echo "$PHASE_BRANCH_TEMPLATE" | sed 's/{.*//')
PHASE_BRANCHES=$(git branch --list "${BRANCH_PREFIX}*" 2>/dev/null | sed 's/^\*//' | tr -d ' ')
```

**For "milestone" strategy:**

```bash
BRANCH_PREFIX=$(echo "$MILESTONE_BRANCH_TEMPLATE" | sed 's/{.*//')
MILESTONE_BRANCH=$(git branch --list "${BRANCH_PREFIX}*" 2>/dev/null | sed 's/^\*//' | tr -d ' ' | head -1)
```

**If no branches found:** Skip to git_tag.

**If branches exist:**

```
## Git Branches Detected

Branching strategy: {phase/milestone}
Branches: {list}

Options:
1. **Merge to main** — Merge branch(es) to main
2. **Delete without merging** — Already merged or not needed
3. **Keep branches** — Leave for manual handling
```

AskUserQuestion with options: Squash merge (Recommended), Merge with history, Delete without merging, Keep branches.

**Squash merge:**

```bash
CURRENT_BRANCH=$(git branch --show-current)
git checkout main

if [ "$BRANCHING_STRATEGY" = "phase" ]; then
  for branch in $PHASE_BRANCHES; do
    git merge --squash "$branch"
    # Strip .planning/ from staging if commit_docs is false
    if [ "$COMMIT_DOCS" = "false" ]; then
      git reset HEAD .planning/ 2>/dev/null || true
    fi
    git commit -m "feat: $branch for v[X.Y]"
  done
fi

if [ "$BRANCHING_STRATEGY" = "milestone" ]; then
  git merge --squash "$MILESTONE_BRANCH"
  # Strip .planning/ from staging if commit_docs is false
  if [ "$COMMIT_DOCS" = "false" ]; then
    git reset HEAD .planning/ 2>/dev/null || true
  fi
  git commit -m "feat: $MILESTONE_BRANCH for v[X.Y]"
fi

git checkout "$CURRENT_BRANCH"
```

**Merge with history:**

```bash
CURRENT_BRANCH=$(git branch --show-current)
git checkout main

if [ "$BRANCHING_STRATEGY" = "phase" ]; then
  for branch in $PHASE_BRANCHES; do
    git merge --no-ff --no-commit "$branch"
    # Strip .planning/ from staging if commit_docs is false
    if [ "$COMMIT_DOCS" = "false" ]; then
      git reset HEAD .planning/ 2>/dev/null || true
    fi
    git commit -m "Merge branch '$branch' for v[X.Y]"
  done
fi

if [ "$BRANCHING_STRATEGY" = "milestone" ]; then
  git merge --no-ff --no-commit "$MILESTONE_BRANCH"
  # Strip .planning/ from staging if commit_docs is false
  if [ "$COMMIT_DOCS" = "false" ]; then
    git reset HEAD .planning/ 2>/dev/null || true
  fi
  git commit -m "Merge branch '$MILESTONE_BRANCH' for v[X.Y]"
fi

git checkout "$CURRENT_BRANCH"
```

**Delete without merging:**

```bash
if [ "$BRANCHING_STRATEGY" = "phase" ]; then
  for branch in $PHASE_BRANCHES; do
    git branch -d "$branch" 2>/dev/null || git branch -D "$branch"
  done
fi

if [ "$BRANCHING_STRATEGY" = "milestone" ]; then
  git branch -d "$MILESTONE_BRANCH" 2>/dev/null || git branch -D "$MILESTONE_BRANCH"
fi
```

**Keep branches:** Report "Branches preserved for manual handling"

</step>

<step name="git_tag">

Create git tag:

```bash
git tag -a v[X.Y] -m "v[X.Y] [Name]

Delivered: [One sentence]

Key accomplishments:
- [Item 1]
- [Item 2]
- [Item 3]

See .planning/MILESTONES.md for full details."
```

Confirm: "Tagged: v[X.Y]"

Ask: "Push tag to remote? (y/n)"

If yes:
```bash
git push origin v[X.Y]
```

</step>

<step name="git_commit_milestone">

Commit milestone completion.

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "chore: complete v[X.Y] milestone" --files .planning/milestones/v[X.Y]-ROADMAP.md .planning/milestones/v[X.Y]-REQUIREMENTS.md .planning/milestones/v[X.Y]-MILESTONE-AUDIT.md .planning/MILESTONES.md .planning/PROJECT.md .planning/STATE.md
```
```

Confirm: "Committed: chore: complete v[X.Y] milestone"

</step>

<step name="offer_next">

```
✅ Milestone v[X.Y] [Name] complete

Shipped:
- [N] phases ([M] plans, [P] tasks)
- [One sentence of what shipped]

Archived:
- milestones/v[X.Y]-ROADMAP.md
- milestones/v[X.Y]-REQUIREMENTS.md

Summary: .planning/MILESTONES.md
Tag: v[X.Y]

---

## ▶ Next Up

**Start Next Milestone** — questioning → research → requirements → roadmap

`/gmd:new-milestone`

<sub>`/clear` first → fresh context window</sub>

---
```

</step>

</process>

<milestone_naming>

**Version conventions:**
- **v1.0** — Initial MVP
- **v1.1, v1.2** — Minor updates, new features, fixes
- **v2.0, v3.0** — Major rewrites, breaking changes, new direction

**Names:** Short 1-2 words (v1.0 MVP, v1.1 Security, v1.2 Performance, v2.0 Redesign).

</milestone_naming>

<what_qualifies>

**Create milestones for:** Initial release, public releases, major feature sets shipped, before archiving planning.

**Don't create milestones for:** Every phase completion (too granular), work in progress, internal dev iterations (unless truly shipped).

Heuristic: "Is this deployed/usable/shipped?" If yes → milestone. If no → keep working.

</what_qualifies>

<success_criteria>

Milestone completion is successful when:

- [ ] MILESTONES.md entry created with stats and accomplishments
- [ ] PROJECT.md full evolution review completed
- [ ] All shipped requirements moved to Validated in PROJECT.md
- [ ] Key Decisions updated with outcomes
- [ ] ROADMAP.md reorganized with milestone grouping
- [ ] Roadmap archive created (milestones/v[X.Y]-ROADMAP.md)
- [ ] Requirements archive created (milestones/v[X.Y]-REQUIREMENTS.md)
- [ ] REQUIREMENTS.md deleted (fresh for next milestone)
- [ ] STATE.md updated with fresh project reference
- [ ] Git tag created (v[X.Y])
- [ ] Milestone commit made (includes archive files and deletion)
- [ ] Requirements completion checked against REQUIREMENTS.md traceability table
- [ ] Incomplete requirements surfaced with proceed/audit/abort options
- [ ] Known gaps recorded in MILESTONES.md if user proceeded with incomplete requirements
- [ ] RETROSPECTIVE.md updated with milestone section
- [ ] Cross-milestone trends updated
- [ ] User knows next step (/gmd:new-milestone)

</success_criteria>
