<purpose>

Start a new milestone cycle for an existing project. Loads project context, gathers milestone goals (from MILESTONE-CONTEXT.md or conversation), updates PROJECT.md and STATE.md, optionally runs parallel research, defines scoped requirements with REQ-IDs, spawns the roadmapper to create phased execution plan, and commits all artifacts. Brownfield equivalent of new-project.

</purpose>

<required_reading>

Read all files referenced by the invoking prompt's execution_context before starting.

</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 new-milestone --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')
```

**If `$MODE == "sequential"`:** Continue to Step 1 below (existing flow). PROJECT.md keeps its embedded `## Current Milestone` section per Phase 65 LAYOUT-02 sequential schema. This is the P1 byte-identical baseline — sequential-mode behavior is UNCHANGED from pre-v1.5.9.

**If `$MODE == "parallel"`:** Jump to **Step 1-PARALLEL** below (new branch shipped in Plan 66-03 CMD-04). Parallel mode scaffolds a fresh `.planning/milestones/<new-slug>/` directory tree via `scaffoldParallelMilestone` + adds a row to root `MILESTONES.md` `## In Progress` table + prompts (default=Yes) for `current_milestone:` pointer advance. Step 1 sequential flow is SKIPPED in parallel mode.

**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`.

## 1. Load Context

- Read PROJECT.md (existing project, validated requirements, decisions)
- Read MILESTONES.md (what shipped previously)
- Read STATE.md (pending todos, blockers)
- Check for MILESTONE-CONTEXT.md (from /gmd:discuss-milestone)

## 1.5. Mandatory Brainstorming

**Brainstorming is ALWAYS invoked for new milestones (hard invocation per user decision).**

The brainstorming skill (skills/brainstorming/SKILL.md) is active for the entire new-milestone workflow. Its hard gate applies — no major design decisions finalized without brainstorming evidence.

After milestone goals are gathered (Step 2), activate brainstorming for key design decisions:
1. Identify 2-3 high-impact design areas from the milestone goals
2. For each area, run a brainstorming round (per brainstorming skill protocol)
3. Capture brainstorming outcomes as locked decisions

This ensures milestone-level decisions benefit from structured divergent-convergent thinking, same as new-project.

## 2. Gather Milestone Goals

**If MILESTONE-CONTEXT.md exists:**
- Use features and scope from discuss-milestone
- Present summary for confirmation

**If no context file:**
- Present what shipped in last milestone
- Ask inline (freeform, NOT AskUserQuestion): "What do you want to build next?"
- Wait for their response, then use AskUserQuestion to probe specifics
- If user selects "Other" at any point to provide freeform input, ask follow-up as plain text — not another AskUserQuestion

## 3. Determine Milestone Version

- Parse last version from MILESTONES.md
- Suggest next version (v1.0 → v1.1, or v2.0 for major)

<!-- critic-gate: milestone-shape (CRIT-WIRE-01 / Phase 51-01) -->
<step name="critic_review_milestone_shape" priority="late">

High-signal milestone-shape gate: patch (v1.5.x), minor (v1.X), or major (vX.0) carries
semver implications + downstream phase-scoping consequences. TD-08 (spec-misdescription
about CLI behavior) was caught at a structurally identical gate. Dispatcher invoked here
UNCONDITIONALLY (D6 — internal `isEnabled('critic')` check returns no-op envelope when
disabled; workflow output is byte-identical to a no-critic baseline per CRIT-AUDIT-04).

Import the dispatcher SoT directly per D2 (no shell-out, no Task-tool coupling in the
library):

```javascript
const { dispatchCritic } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/critic-dispatch.js');
```

Construct the caller-injected `spawnSubagent` wrapper (Claude Code Task tool is the
spawn primitive in v1.5.5; v1.5.7 Codex CLI adapter will inject its own primitive
without any v1.5.5 code change per D2 harness-neutrality contract):

```javascript
const spawnSubagent = async ({ agent, prompt, cross_model }) => {
  // Workflow inlines a Task() call that invokes the gmd-critic agent.
  // See agents/gmd-critic.md for the JSON output contract (Plan 50-02).
  return await Task({
    subagent_type: 'gmd-critic',
    description: 'Critic review: milestone-shape',
    prompt: JSON.stringify(prompt),
  });
};
```

Dispatch (UNCONDITIONAL per D6 — no `if (isEnabled('critic'))` wrapper at workflow side):

```javascript
// CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
// Sequential branch byte-identical to v1.5.5 Plan 50-01 baseline (P1 preserved).
// MODE + SLUG sourced from Step 0 init JSON (shell-level variables; workflow
// executor passes them into the JS scope of this dispatchCritic call).
const { resolveMilestonePaths } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/path-resolve.js');
const affects_paths = (MODE === 'parallel')
  ? [
      resolveMilestonePaths('parallel', null, 'MILESTONES'),   // .planning/MILESTONES.md (project-level — same in both modes)
      resolveMilestonePaths('parallel', SLUG, 'MILESTONE'),    // .planning/milestones/<slug>/MILESTONE.md (slug-scoped)
    ]
  : ['.planning/PROJECT.md', '.planning/MILESTONES.md'];
const affects_reqs = [];   // milestone-shape gate is pre-REQ-scoping in both modes

// GROUND-03 (v1.8.2.5): caller-resolved grounding bundle for the critic's read mandate.
// The milestone SPEC may not exist yet at this pre-scoping gate — that is fine; the
// bundle is PROJECT.md + protocol anchor + the affects_paths the gate already computed.
// Caller-resolved only; the library does no I/O (D2).
const files_to_read = [
  ...affects_paths,                            // already computed at this gate
  '.planning/PROJECT.md',
  '.planning/specs/gmd-critic-protocol.md',
];

const envelope = await dispatchCritic({
  spawnSubagent,
  decision_point: "Milestone version shape — patch (v1.5.x), minor (v1.X), or major (vX.0)?",
  lead_recommendation: SUGGESTED_VERSION,             // e.g., "v1.6 (minor)"
  lead_rationale: SUGGESTED_VERSION_RATIONALE,        // e.g., "additive features, no breaking changes"
  workflow: '/gmd:new-milestone',
  phase: 'milestone-shape',
  affects_paths,
  affects_reqs,
  files_to_read,                               // GROUND-03
});
```

After the await:

- If `envelope._disabled === true` (gate off; dispatcher returned no-op-with-marker per
  CRIT-DISP-04), proceed silently to "Confirm with user" below — no menu surface change,
  no NDJSON entry, byte-identical to a no-critic baseline.
- If `envelope.verdict !== 'noop'` (critic ran), surface verdict + alternative_argument +
  missed_concerns + the literal text `decision_id: <envelope.decision_id>` in the
  user-visible menu copy so the user can trace the decision to the NDJSON entry.

Surface template when critic ran:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► CRITIC REVIEW (milestone-shape)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

decision_id: ${envelope.decision_id}
verdict: ${envelope.verdict}
confidence: ${envelope.confidence}

${envelope.verdict === 'endorse' ? '' : `alternative: ${envelope.alternative_argument}`}
${(envelope.missed_concerns || []).length ? `missed_concerns:\n${envelope.missed_concerns.map(c => '  - ' + c).join('\n')}` : ''}
```

</step>

- Confirm with user

## 4. Update PROJECT.md

Add/update:

```markdown
## Current Milestone: v[X.Y] [Name]

**Goal:** [One sentence describing milestone focus]

**Target features:**
- [Feature 1]
- [Feature 2]
- [Feature 3]
```

Update Active requirements section and "Last updated" footer.

## 5. Update STATE.md

```markdown
## Current Position

Phase: Not started (defining requirements)
Plan: —
Status: Defining requirements
Last activity: [today] — Milestone v[X.Y] started
```

Keep Accumulated Context section from previous milestone.

## 6. Cleanup and Commit

Delete MILESTONE-CONTEXT.md if exists (consumed).

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs: start milestone v[X.Y] [Name]" --files .planning/PROJECT.md .planning/STATE.md
```

## 6.5. Vault Sync — Milestone Artifacts

After PROJECT.md and STATE.md are committed, sync to Obsidian vault:

```bash
node bin/gmd-tools.cjs vault-sync .planning/PROJECT.md 2>/dev/null
node bin/gmd-tools.cjs vault-sync .planning/STATE.md 2>/dev/null
```

Graceful if vault not configured (skip with note).

## 7. Load Context and Resolve Models

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

Extract from init JSON: `researcher_model`, `synthesizer_model`, `roadmapper_model`, `commit_docs`, `research_enabled`, `current_milestone`, `project_exists`, `roadmap_exists`.

<step name="vault_preflight" priority="early">
Run `vault-orient` to pre-warm the 5-min query cache and build a compressed `<vault_context>` block for injection into every downstream Task() prompt. This is the D9b orchestrator-side default: vault-use as the default code path, not an opt-in. Component-gate-aware: skips silently when `components.obsidian.enabled: false`.

```bash
VAULT_ORIENT_RAW=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" vault-orient \
  --agent orchestrator-new-milestone 2>/dev/null || echo '{"skipped":"vault unavailable"}')
```

**Compress orient JSON to a ~300-tok `<vault_context>` block:**

1. Parse the orient JSON. If `.skipped` is set OR the JSON contains an error field, set `VAULT_CONTEXT_BLOCK=""` (empty) and skip to step 3.
2. Otherwise, extract:
   - `index_summary` — cap at 1200 chars (append `…[truncated]` if longer)
   - `in_scope_notes[0..4]` — top 5 notes, emit `path + summary` only (no bodies)
   - `directives[*].summary` (or first-line fallback) — directive summaries only, no bodies
3. Build the block in this exact shape (omit entirely if compression produced nothing):

   ```
   <vault_context>
   ## Index Summary
   {index_summary}

   ## In-Scope Notes (top 5)
   - {path}: {summary}
   - ...

   ## Directives (summary only; re-read via vault-read if needed)
   - {path}: {summary}
   - ...

   vault_status: {ok | empty | error}
   </vault_context>
   ```

**Injection contract:** The `VAULT_CONTEXT_BLOCK` must be injected into every downstream Task() prompt immediately before the existing `<files_to_read>` block. When empty (skipped/error/empty orient), omit the block entirely — never inject an empty `<vault_context></vault_context>`. Cached orient means subsequent subagent `vault-query` calls hit the warm 5-min cache (~116ms cached vs ~1700ms uncached on Windows).
</step>

## 8. Research Decision

AskUserQuestion: "Research the domain ecosystem for new features before defining requirements?"
- "Research first (Recommended)" — Discover patterns, features, architecture for NEW capabilities
- "Skip research" — Go straight to requirements

**Persist choice to config** (so future `/gmd:plan-phase` honors it):

```bash
# If "Research first": persist true
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-set workflow.research true

# If "Skip research": persist false
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-set workflow.research false
```

**If "Research first":**

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► RESEARCHING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

◆ Spawning 4 researchers in parallel...
  → Stack, Features, Architecture, Pitfalls
```

```bash
mkdir -p .planning/research
```

Spawn 4 parallel gmd-project-researcher agents. Each uses this template with dimension-specific fields:

**Common structure for all 4 researchers:**
```
Task(prompt="
<research_type>Project Research — {DIMENSION} for [new features].</research_type>

<milestone_context>
SUBSEQUENT MILESTONE — Adding [target features] to existing app.
{EXISTING_CONTEXT}
Focus ONLY on what's needed for the NEW features.
</milestone_context>

<question>{QUESTION}</question>

{VAULT_CONTEXT_BLOCK}

<files_to_read>
- .planning/PROJECT.md (Project context)
</files_to_read>

<downstream_consumer>{CONSUMER}</downstream_consumer>

<quality_gate>{GATES}</quality_gate>

<output>
Write to: .planning/research/{FILE}
Use template: C:/Users/Christopher/.claude/get-magic-done/templates/research-project/{FILE}
</output>
", subagent_type="gmd-project-researcher", model="{researcher_model}", description="{DIMENSION} research")
```

**Dimension-specific fields:**

| Field | Stack | Features | Architecture | Pitfalls |
|-------|-------|----------|-------------|----------|
| EXISTING_CONTEXT | Existing validated capabilities (DO NOT re-research): [from PROJECT.md] | Existing features (already built): [from PROJECT.md] | Existing architecture: [from PROJECT.md or codebase map] | Focus on common mistakes when ADDING these features to existing system |
| QUESTION | What stack additions/changes are needed for [new features]? | How do [target features] typically work? Expected behavior? | How do [target features] integrate with existing architecture? | Common mistakes when adding [target features] to [domain]? |
| CONSUMER | Specific libraries with versions for NEW capabilities, integration points, what NOT to add | Table stakes vs differentiators vs anti-features, complexity noted, dependencies on existing | Integration points, new components, data flow changes, suggested build order | Warning signs, prevention strategy, which phase should address it |
| GATES | Versions current (verify with Context7), rationale explains WHY, integration considered | Categories clear, complexity noted, dependencies identified | Integration points identified, new vs modified explicit, build order considers deps | Pitfalls specific to adding these features, integration pitfalls covered, prevention actionable |
| FILE | STACK.md | FEATURES.md | ARCHITECTURE.md | PITFALLS.md |

After all 4 complete, spawn synthesizer:

```
Task(prompt="
Synthesize research outputs into SUMMARY.md.

{VAULT_CONTEXT_BLOCK}

<files_to_read>
- .planning/research/STACK.md
- .planning/research/FEATURES.md
- .planning/research/ARCHITECTURE.md
- .planning/research/PITFALLS.md
</files_to_read>

Write to: .planning/research/SUMMARY.md
Use template: C:/Users/Christopher/.claude/get-magic-done/templates/research-project/SUMMARY.md
Commit after writing.
", subagent_type="gmd-research-synthesizer", model="{synthesizer_model}", description="Synthesize research")
```

Display key findings from SUMMARY.md:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► RESEARCH COMPLETE ✓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

**Stack additions:** [from SUMMARY.md]
**Feature table stakes:** [from SUMMARY.md]
**Watch Out For:** [from SUMMARY.md]
```

**If "Skip research":** Continue to Step 9.

## 9. Define Requirements

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► DEFINING REQUIREMENTS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

Read PROJECT.md: core value, current milestone goals, validated requirements (what exists).

**If research exists:** Read FEATURES.md, extract feature categories.

Present features by category:
```
## [Category 1]
**Table stakes:** Feature A, Feature B
**Differentiators:** Feature C, Feature D
**Research notes:** [any relevant notes]
```

**If no research:** Gather requirements through conversation. Ask: "What are the main things users need to do with [new features]?" Clarify, probe for related capabilities, group into categories.

<!-- critic-gate: scope-inclusion-exclusion (CRIT-WIRE-01 / Phase 51-01) -->
<step name="critic_review_scope_inclusion" priority="late">

High-signal scope inclusion/exclusion gate: determines what ships in v[X.Y] vs deferred.
TD-08 (spec-misdescription about CLI behavior) was caught from a structurally identical
category-scoping decision. Dispatcher invoked here UNCONDITIONALLY per D6 — internal
gate honors `components.critic.enabled` and returns no-op envelope when disabled
(CRIT-AUDIT-04 byte-identical baseline contract).

Import dispatcher SoT directly per D2 (re-import is idempotent if already in scope from
the milestone-shape step):

```javascript
const { dispatchCritic } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/critic-dispatch.js');
```

Construct the caller-injected `spawnSubagent` (same shape as Step 3 milestone-shape
gate; v1.5.7 Codex CLI adapter swaps the spawn primitive without code change per D2):

```javascript
const spawnSubagent = async ({ agent, prompt, cross_model }) => {
  return await Task({
    subagent_type: 'gmd-critic',
    description: 'Critic review: scope-inclusion-exclusion',
    prompt: JSON.stringify(prompt),
  });
};
```

Dispatch (UNCONDITIONAL per D6):

```javascript
// CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
// affects_reqs in parallel mode carries ONLY the active milestone's REQ-IDs
// (REQ_IDS_BEING_SCOPED is already active-milestone-scoped at this gate by
// construction, since the scope-inclusion step iterates this milestone's
// REQ candidates only).
const { resolveMilestonePaths } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/path-resolve.js');
const affects_paths = (MODE === 'parallel')
  ? [resolveMilestonePaths('parallel', SLUG, 'REQUIREMENTS')]   // .planning/milestones/<slug>/REQUIREMENTS.md
  : ['.planning/REQUIREMENTS.md'];

// GROUND-03 (v1.8.2.5): caller-resolved grounding bundle for the critic's read mandate.
// In parallel mode add the active milestone SPEC (composed caller-side — path-resolve.js
// has no SPEC key, so the library does no resolution per D2). Sequential mode uses the
// flat slug-prefixed SPEC if SLUG is known; otherwise the REQUIREMENTS path + PROJECT.md
// + protocol anchor still ground the critic. Caller-resolved only.
const SPEC_PATH = (MODE === 'parallel')
  ? `.planning/milestones/${SLUG}/${SLUG}-SPEC.md`
  : (SLUG ? `.planning/milestones/${SLUG}-SPEC.md` : null);
const files_to_read = [
  ...affects_paths,                            // the gate's resolved REQUIREMENTS path
  ...(SPEC_PATH ? [SPEC_PATH] : []),           // active-milestone SPEC (caller-resolved)
  '.planning/PROJECT.md',
  '.planning/specs/gmd-critic-protocol.md',
];

const envelopeScopeIncl = await dispatchCritic({
  spawnSubagent,
  decision_point: "Category scope inclusion/exclusion — which features ship in v[X.Y] vs deferred?",
  lead_recommendation: CATEGORY_SUMMARY,            // e.g., "Auth: AUTH-01..04 in scope; AUTH-05 deferred"
  lead_rationale: CATEGORY_RATIONALE,               // one-line why this scoping
  workflow: '/gmd:new-milestone',
  phase: 'scope-inclusion',
  affects_paths,
  affects_reqs: REQ_IDS_BEING_SCOPED,               // string[] of REQ-IDs touched by this category (active-milestone-scoped in parallel)
  files_to_read,                                    // GROUND-03
});
```

After the await:

- If `envelopeScopeIncl._disabled === true`, proceed silently to the AskUserQuestion
  scope-multiSelect below.
- If `envelopeScopeIncl.verdict !== 'noop'`, surface verdict + alternative_argument +
  the literal text `decision_id: <envelopeScopeIncl.decision_id>` in the user-visible
  menu copy alongside the AskUserQuestion options. Allows user to weigh critic alternative
  before answering the multiSelect.

Surface template when critic ran:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► CRITIC REVIEW (scope-inclusion-exclusion)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

decision_id: ${envelopeScopeIncl.decision_id}
verdict: ${envelopeScopeIncl.verdict}
confidence: ${envelopeScopeIncl.confidence}

${envelopeScopeIncl.verdict === 'endorse' ? '' : `alternative: ${envelopeScopeIncl.alternative_argument}`}
${(envelopeScopeIncl.missed_concerns || []).length ? `missed_concerns:\n${envelopeScopeIncl.missed_concerns.map(c => '  - ' + c).join('\n')}` : ''}
```

</step>

**Scope each category** via AskUserQuestion (multiSelect: true, header max 12 chars):
- "[Feature 1]" — [brief description]
- "[Feature 2]" — [brief description]
- "None for this milestone" — Defer entire category

Track: Selected → this milestone. Unselected table stakes → future. Unselected differentiators → out of scope.

**Identify gaps** via AskUserQuestion:
- "No, research covered it" — Proceed
- "Yes, let me add some" — Capture additions

**Generate REQUIREMENTS.md:**
- v1 Requirements grouped by category (checkboxes, REQ-IDs)
- Future Requirements (deferred)
- Out of Scope (explicit exclusions with reasoning)
- Traceability section (empty, filled by roadmap)

**REQ-ID format:** `[CATEGORY]-[NUMBER]` (AUTH-01, NOTIF-02). Continue numbering from existing.

**Requirement quality criteria:**

Good requirements are:
- **Specific and testable:** "User can reset password via email link" (not "Handle password reset")
- **User-centric:** "User can X" (not "System does Y")
- **Atomic:** One capability per requirement (not "User can login and manage profile")
- **Independent:** Minimal dependencies on other requirements

Present FULL requirements list for confirmation:

```
## Milestone v[X.Y] Requirements

### [Category 1]
- [ ] **CAT1-01**: User can do X
- [ ] **CAT1-02**: User can do Y

### [Category 2]
- [ ] **CAT2-01**: User can do Z

Does this capture what you're building? (yes / adjust)
```

<!-- critic-gate: requirements-scoping (CRIT-WIRE-01 / Phase 51-01) -->
<step name="critic_review_requirements_scoping" priority="late">

High-signal requirements-scoping gate: the final REQ list is the milestone's binding
contract. Run BEFORE the "Does this capture what you're building?" prompt above so the
user has the critic's perspective alongside the proposed REQ set. Dispatcher invoked
UNCONDITIONALLY per D6 (gate-state-blind workflow output per CRIT-AUDIT-04).

Import dispatcher SoT (idempotent re-import; see prior gates for full pattern):

```javascript
const { dispatchCritic } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/critic-dispatch.js');
const spawnSubagent = async ({ agent, prompt, cross_model }) => {
  return await Task({
    subagent_type: 'gmd-critic',
    description: 'Critic review: requirements-scoping',
    prompt: JSON.stringify(prompt),
  });
};
```

Dispatch (UNCONDITIONAL per D6):

```javascript
// CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
// FULL_REQ_ID_LIST is the active milestone's complete REQ set (constructed
// from the scope-selected categories above); in parallel mode it carries
// ONLY this milestone's REQ-IDs (active-milestone-only scoping per CRIT-02).
const { resolveMilestonePaths } = require('${CLAUDE_PLUGIN_ROOT}/bin/lib/path-resolve.js');
const affects_paths = (MODE === 'parallel')
  ? [resolveMilestonePaths('parallel', SLUG, 'REQUIREMENTS')]   // .planning/milestones/<slug>/REQUIREMENTS.md
  : ['.planning/REQUIREMENTS.md'];

// GROUND-03 (v1.8.2.5): caller-resolved grounding bundle for the critic's read mandate.
// Same shape as the scope-inclusion gate: the gate's resolved REQUIREMENTS path + the
// active milestone SPEC (composed caller-side — path-resolve.js has no SPEC key, so the
// library does no resolution per D2) + PROJECT.md + protocol anchor. Caller-resolved only.
const SPEC_PATH = (MODE === 'parallel')
  ? `.planning/milestones/${SLUG}/${SLUG}-SPEC.md`
  : (SLUG ? `.planning/milestones/${SLUG}-SPEC.md` : null);
const files_to_read = [
  ...affects_paths,                            // the gate's resolved REQUIREMENTS path
  ...(SPEC_PATH ? [SPEC_PATH] : []),           // active-milestone SPEC (caller-resolved)
  '.planning/PROJECT.md',
  '.planning/specs/gmd-critic-protocol.md',
];

const envelopeReqScoping = await dispatchCritic({
  spawnSubagent,
  decision_point: "Final REQ list — does this capture the milestone scope correctly?",
  lead_recommendation: REQ_LIST_SUMMARY,            // e.g., "12 REQs across 3 categories: AUTH-01..04, NOTIF-01..05, UI-01..03"
  lead_rationale: REQ_LIST_RATIONALE,               // one-line why this REQ set
  workflow: '/gmd:new-milestone',
  phase: 'requirements-scoping',
  affects_paths,
  affects_reqs: FULL_REQ_ID_LIST,                   // string[] of all REQ-IDs in the milestone (active-milestone-only in parallel)
  files_to_read,                                    // GROUND-03
});
```

After the await:

- If `envelopeReqScoping._disabled === true`, proceed silently to "yes / adjust" prompt
  and the REQUIREMENTS.md write below — workflow output is byte-identical to a no-critic
  baseline.
- If `envelopeReqScoping.verdict !== 'noop'`, surface verdict + alternative_argument +
  the literal text `decision_id: <envelopeReqScoping.decision_id>` in the user-visible
  menu copy.

Surface template when critic ran:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► CRITIC REVIEW (requirements-scoping)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

decision_id: ${envelopeReqScoping.decision_id}
verdict: ${envelopeReqScoping.verdict}
confidence: ${envelopeReqScoping.confidence}

${envelopeReqScoping.verdict === 'endorse' ? '' : `alternative: ${envelopeReqScoping.alternative_argument}`}
${(envelopeReqScoping.missed_concerns || []).length ? `missed_concerns:\n${envelopeReqScoping.missed_concerns.map(c => '  - ' + c).join('\n')}` : ''}
```

**CRIT-WIRE-05 reciprocal-marker emission contract:**

When `envelopeReqScoping.verdict !== 'noop'` AND the user accepts a critic-influenced
REQ revision (adds/removes/refines a REQ per critic recommendation per the "yes / adjust"
loop), the REQUIREMENTS.md write below MUST insert a reciprocal marker per CRIT-SCHEMA-03
/ CRIT-TELM-01a (authoritative reference: references/critic-observations-schema.md
Section 4 "CRIT-TELM-01a reciprocal-marker convention").

Marker shape (literal HTML comment; UUID is `envelopeReqScoping.decision_id` per
CRIT-DISP-02 invocation-time UUID generation — workflow MUST NOT mint its own UUID):

```markdown
<!-- critic-decision: ${envelopeReqScoping.decision_id} -->
```

Placement guidance per references/critic-observations-schema.md Section 4:
- For a per-REQ revision (single REQ added/removed/refined): place the marker on the line
  IMMEDIATELY ABOVE the changed REQ entry inside REQUIREMENTS.md.
- For a structural revision (whole-category re-scope, multiple REQs): place the marker
  immediately below the file's frontmatter as a top-level acknowledgement.

The UUID round-trips with the corresponding NDJSON entry's `decision_id` field per
CRIT-SCHEMA-03 — load-bearing for the future CRIT-TELM-02 correlation routine.

</step>

If "adjust": Return to scoping.

**Commit requirements:**
```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs: define milestone v[X.Y] requirements" --files .planning/REQUIREMENTS.md
```

**Vault sync — REQUIREMENTS.md:**
```bash
node bin/gmd-tools.cjs vault-sync .planning/REQUIREMENTS.md 2>/dev/null
```

## 10. Create Roadmap

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► CREATING ROADMAP
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

◆ Spawning roadmapper...
```

**Starting phase number:** Read MILESTONES.md for last phase number. Continue from there (v1.0 ended at phase 5 → v1.1 starts at phase 6).

```
Task(prompt="
<planning_context>
{VAULT_CONTEXT_BLOCK}
<files_to_read>
- .planning/PROJECT.md
- .planning/REQUIREMENTS.md
- .planning/research/SUMMARY.md (if exists)
- .planning/config.json
- .planning/MILESTONES.md
</files_to_read>
</planning_context>

<instructions>
Create roadmap for milestone v[X.Y]:
1. Start phase numbering from [N]
2. Derive phases from THIS MILESTONE's requirements only
3. Map every requirement to exactly one phase
4. Derive 2-5 success criteria per phase (observable user behaviors)
5. Validate 100% coverage
6. Write files immediately (ROADMAP.md, STATE.md, update REQUIREMENTS.md traceability)
7. Return ROADMAP CREATED with summary

Write files first, then return.
</instructions>
", subagent_type="gmd-roadmapper", model="{roadmapper_model}", description="Create roadmap")
```

**Handle return:**

**If `## ROADMAP BLOCKED`:** Present blocker, work with user, re-spawn.

**If `## ROADMAP CREATED`:** Read ROADMAP.md, present inline:

```
## Proposed Roadmap

**[N] phases** | **[X] requirements mapped** | All covered ✓

| # | Phase | Goal | Requirements | Success Criteria |
|---|-------|------|--------------|------------------|
| [N] | [Name] | [Goal] | [REQ-IDs] | [count] |

### Phase Details

**Phase [N]: [Name]**
Goal: [goal]
Requirements: [REQ-IDs]
Success criteria:
1. [criterion]
2. [criterion]
```

**Ask for approval** via AskUserQuestion:
- "Approve" — Commit and continue
- "Adjust phases" — Tell me what to change
- "Review full file" — Show raw ROADMAP.md

**If "Adjust":** Get notes, re-spawn roadmapper with revision context, loop until approved.
**If "Review":** Display raw ROADMAP.md, re-ask.

**Commit roadmap** (after approval):
```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs: create milestone v[X.Y] roadmap ([N] phases)" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md
```

**Vault sync — ROADMAP.md:**
```bash
node bin/gmd-tools.cjs vault-sync .planning/ROADMAP.md 2>/dev/null
```

## 11. Done

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► MILESTONE INITIALIZED ✓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

**Milestone v[X.Y]: [Name]**

| Artifact       | Location                    |
|----------------|-----------------------------|
| Project        | `.planning/PROJECT.md`      |
| Research       | `.planning/research/`       |
| Requirements   | `.planning/REQUIREMENTS.md` |
| Roadmap        | `.planning/ROADMAP.md`      |

**[N] phases** | **[X] requirements** | Ready to build ✓

## ▶ Next Up

**Phase [N]: [Phase Name]** — [Goal]

`/gmd:discuss-phase [N]` — gather context and clarify approach

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

Also: `/gmd:plan-phase [N]` — skip discussion, plan directly
```

## Step 1-PARALLEL — Parallel-mode new milestone scaffold (v1.5.9 CMD-04)

Reached ONLY when Step 0 detected `MODE=parallel`. This branch creates a fresh `.planning/milestones/<new-slug>/` directory tree, adds a row to root `MILESTONES.md` `## In Progress` table, and prompts (default=Yes) for `current_milestone:` pointer advance. Steps 1-11 above are SKIPPED in parallel mode — milestone requirements/roadmap are authored inside the new milestone via subsequent `/gmd:plan-phase` invocations.

### 1P.1 Prompt for milestone version + name

Same prompts as sequential mode Step 2 (gather milestone goals + version shape).
Reuse the existing milestone-shape critic gate (Step 3 above) — its dispatcher
library API is signature-stable per CRIT-03 (verified by Plan 66-05 smoke test).
In parallel mode the `affects_paths` array refines to milestone-scoped artifacts
(Plan 66-05 wires this refinement; Plan 66-03 only ships scaffolding here).

### 1P.2 Prompt for milestone slug (kebab-case validation)

Loop until valid kebab-case slug provided (lifted pattern from
`workflows/new-project.md` Step 3.6; validateKebabSlug is the shared helper
extracted in Plan 66-03 Task 1):

```bash
REPO="$HOME/.claude/get-magic-done"
while true; do
  read -p "Milestone slug (kebab-case): " SLUG
  VALIDATION=$(node -e "const {validateKebabSlug}=require('$REPO/bin/lib/slug-validate.js'); console.log(JSON.stringify(validateKebabSlug('$SLUG')))")
  if echo "$VALIDATION" | grep -q '"valid":true'; then break; fi
  echo "Invalid: $(echo $VALIDATION | jq -r .error)"
done
```

Also reject if `.planning/milestones/$SLUG/` already exists (idempotency —
`scaffoldParallelMilestone` will throw, but pre-check gives a cleaner UX message).

### 1P.3 Scaffold milestones/<slug>/ directory tree

Render `templates/milestone-manifest.md` body with `{{project-slug}}`,
`{{milestone-slug}}`, `{{ISO-date}}` token substitution (canonical Phase 65-04
token set; mirrors `workflows/new-project.md` Step 3.6). Then invoke the
Phase 65-03 scaffold helper. Template path resolution uses
`bin/lib/get-template-root.js` (Phase 69-02 / DEFER-66-02): dev-repo layout
first, npm-global $HOME/.claude/get-magic-done/templates fallback.

```bash
ISO_DATE=$(node -e "console.log(new Date().toISOString().slice(0,10))")
PROJECT_SLUG=$(basename "$PWD")  # caller may refine via prompt if needed

node -e "
  const fs = require('fs');
  const path = require('path');
  const { scaffoldParallelMilestone } = require('$REPO/bin/lib/scaffold-parallel.js');
  const { getTemplateRoot } = require('$REPO/bin/lib/get-template-root.js');

  const templatePath = path.join(getTemplateRoot(), 'milestone-manifest.md');
  let body = fs.readFileSync(templatePath, 'utf8');

  body = body
    .replace(/\\{\\{project-slug\\}\\}/g,   process.argv[2])
    .replace(/\\{\\{milestone-slug\\}\\}/g, process.argv[1])
    .replace(/\\{\\{ISO-date\\}\\}/g,       process.argv[3]);

  scaffoldParallelMilestone({
    cwd: process.cwd(),
    slug: process.argv[1],
    milestoneTemplateBody: body,
    projectSlug: process.argv[2],
    isoDate: process.argv[3],
  });
" "$SLUG" "$PROJECT_SLUG" "$ISO_DATE"
```

### 1P.4 Add row to MILESTONES.md ## In Progress table

Append a row to root `.planning/MILESTONES.md` `## In Progress` table per Phase 65
LAYOUT-03 schema (3-table forward-looking index). Default status =
`In Progress` per CONTEXT.md Decision Area 5 (user may explicitly mark `Planned`
for the pre-scope idiom — that's a documentation-only flip from "In Progress"
to "Planned" in MILESTONES.md, with `Pointer Advance` answered "n" in 1P.5).

Row format (per LAYOUT-03):

```markdown
| <slug> | <name> | <iso-date> | <goal-one-liner> | In Progress |
```

Insert under the `## In Progress` heading using a sed/awk anchor. Validate
afterwards:

```bash
node -e "const {readInProgressMilestones}=require('$REPO/bin/lib/active-milestone.js'); console.log(readInProgressMilestones('.'))"
```

The new slug should appear in the returned array.

### 1P.5 AskUserQuestion — Advance current_milestone pointer?

Per CONTEXT.md Decision Area 5 (critic R2): PROMPT with `Yes` pre-selected.
NOT silent auto-advance — silent advance would foreclose the v1.5.9-SPEC's own
pre-scope idiom (where v1.5.9 was authored as pre-scope while v1.5.7 stayed
current). Default=Yes honors the SUCCESS-CRITERIA item 4 "default yes" wording
while preserving operator agency.

```
AskUserQuestion: "Advance current_milestone pointer to <new-slug>? [Y/n]"
  options:
    - Yes (default; Enter accepts)  -> advance pointer
    - n                              -> skip; new milestone scaffolded but inactive
```

**If Yes (default):**

```bash
node "$REPO/bin/gmd-tools.cjs" state set-current-milestone "$SLUG"
```

Print: `Scaffolded milestone $SLUG. current_milestone advanced. Run /gmd:plan-phase 1 to begin.`

**If n:**

Pointer stays at prior milestone (pre-scope idiom preserved). Print:
`Scaffolded milestone $SLUG. current_milestone unchanged. Run /gmd:switch-milestone $SLUG to activate.`

### 1P.6 Atomic commit (if commit_docs: true)

Single commit covers: `.planning/milestones/$SLUG/` (4 files + research/ subdir),
`.planning/MILESTONES.md` row addition, and (if pointer advanced) the root
`.planning/STATE.md` `current_milestone:` pointer flip.

```bash
COMMIT_DOCS=$(echo "$INIT" | jq -r '.commit_docs')
if [ "$COMMIT_DOCS" = "true" ]; then
  node "$REPO/bin/gmd-tools.cjs" commit "feat: scaffold milestone $SLUG ($NAME)" \
    --files .planning/milestones/$SLUG .planning/MILESTONES.md .planning/STATE.md
fi
```

### 1P.7 Done

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► MILESTONE SCAFFOLDED ✓ (parallel mode)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

**Milestone: $SLUG**

| Artifact       | Location                                  |
|----------------|-------------------------------------------|
| Manifest       | `.planning/milestones/$SLUG/MILESTONE.md` |
| Requirements   | `.planning/milestones/$SLUG/REQUIREMENTS.md` (empty — fill via /gmd:plan-phase) |
| Roadmap        | `.planning/milestones/$SLUG/ROADMAP.md` (empty — fill via /gmd:plan-phase) |
| State          | `.planning/milestones/$SLUG/STATE.md` (empty — fill via /gmd:plan-phase) |
| Research       | `.planning/milestones/$SLUG/research/` (empty subdir) |
| Index row      | `.planning/MILESTONES.md` ## In Progress  |

## ▶ Next Up

`/gmd:plan-phase 1` — author REQUIREMENTS.md + ROADMAP.md inside this milestone

<sub>Pointer status: <advanced | unchanged> per 1P.5 selection.</sub>
```

</process>

<success_criteria>
- [ ] PROJECT.md updated with Current Milestone section
- [ ] STATE.md reset for new milestone
- [ ] MILESTONE-CONTEXT.md consumed and deleted (if existed)
- [ ] Research completed (if selected) — 4 parallel agents, milestone-aware
- [ ] Requirements gathered and scoped per category
- [ ] REQUIREMENTS.md created with REQ-IDs
- [ ] gmd-roadmapper spawned with phase numbering context
- [ ] Roadmap files written immediately (not draft)
- [ ] User feedback incorporated (if any)
- [ ] ROADMAP.md phases continue from previous milestone
- [ ] All commits made (if planning docs committed)
- [ ] User knows next step: `/gmd:discuss-phase [N]`

**Atomic commits:** Each phase commits its artifacts immediately.
</success_criteria>
