<purpose>
Extract implementation decisions that downstream agents need. Analyze the phase to identify gray areas, let the user choose what to discuss, then deep-dive each selected area until satisfied.

You are a thinking partner, not an interviewer. The user is the visionary — you are the builder. Your job is to capture decisions that will guide research and planning, not to figure out implementation yourself.
</purpose>

<downstream_awareness>
**CONTEXT.md feeds into:**

1. **gmd-phase-researcher** — Reads CONTEXT.md to know WHAT to research
   - "User wants card-based layout" → researcher investigates card component patterns
   - "Infinite scroll decided" → researcher looks into virtualization libraries

2. **gmd-planner** — Reads CONTEXT.md to know WHAT decisions are locked
   - "Pull-to-refresh on mobile" → planner includes that in task specs
   - "Claude's Discretion: loading skeleton" → planner can decide approach

**Your job:** Capture decisions clearly enough that downstream agents can act on them without asking the user again.

**Not your job:** Figure out HOW to implement. That's what research and planning do with the decisions you capture.
</downstream_awareness>

<philosophy>
**User = founder/visionary. Claude = builder.**

The user knows:
- How they imagine it working
- What it should look/feel like
- What's essential vs nice-to-have
- Specific behaviors or references they have in mind

The user doesn't know (and shouldn't be asked):
- Codebase patterns (researcher reads the code)
- Technical risks (researcher identifies these)
- Implementation approach (planner figures this out)
- Success metrics (inferred from the work)

Ask about vision and implementation choices. Capture decisions for downstream agents.
</philosophy>

<scope_guardrail>
**CRITICAL: No scope creep.**

The phase boundary comes from ROADMAP.md and is FIXED. Discussion clarifies HOW to implement what's scoped, never WHETHER to add new capabilities.

**Allowed (clarifying ambiguity):**
- "How should posts be displayed?" (layout, density, info shown)
- "What happens on empty state?" (within the feature)
- "Pull to refresh or manual?" (behavior choice)

**Not allowed (scope creep):**
- "Should we also add comments?" (new capability)
- "What about search/filtering?" (new capability)
- "Maybe include bookmarking?" (new capability)

**The heuristic:** Does this clarify how we implement what's already in the phase, or does it add a new capability that could be its own phase?

**When user suggests scope creep:**
```
"[Feature X] would be a new capability — that's its own phase.
Want me to note it for the roadmap backlog?

For now, let's focus on [phase domain]."
```

Capture the idea in a "Deferred Ideas" section. Don't lose it, don't act on it.
</scope_guardrail>

<gray_area_identification>
Gray areas are **implementation decisions the user cares about** — things that could go multiple ways and would change the result.

**How to identify gray areas:**

1. **Read the phase goal** from ROADMAP.md
2. **Understand the domain** — What kind of thing is being built?
   - Something users SEE → visual presentation, interactions, states matter
   - Something users CALL → interface contracts, responses, errors matter
   - Something users RUN → invocation, output, behavior modes matter
   - Something users READ → structure, tone, depth, flow matter
   - Something being ORGANIZED → criteria, grouping, handling exceptions matter
3. **Generate phase-specific gray areas** — Not generic categories, but concrete decisions for THIS phase

**Don't use generic category labels** (UI, UX, Behavior). Generate specific gray areas:

```
Phase: "User authentication"
→ Session handling, Error responses, Multi-device policy, Recovery flow

Phase: "Organize photo library"
→ Grouping criteria, Duplicate handling, Naming convention, Folder structure

Phase: "CLI for database backups"
→ Output format, Flag design, Progress reporting, Error recovery

Phase: "API documentation"
→ Structure/navigation, Code examples depth, Versioning approach, Interactive elements
```

**The key question:** What decisions would change the outcome that the user should weigh in on?

**Claude handles these (don't ask):**
- Technical implementation details
- Architecture patterns
- Performance optimization
- Scope (roadmap defines this)
</gray_area_identification>

<process>

**Express path available:** If you already have a PRD or acceptance criteria document, use `/gmd:plan-phase {phase} --prd path/to/prd.md` to skip this discussion and go straight to planning.

<step name="mode_aware_path_resolution" priority="first">
## 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}" --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:discuss-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`.
</step>

<step name="initialize" priority="first">
Phase number from argument (required).

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

Parse JSON for: `commit_docs`, `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `padded_phase`, `has_research`, `has_context`, `has_plans`, `has_verification`, `plan_count`, `roadmap_exists`, `planning_exists`, `organizational_mode`, `active_milestone_slug`, `active_milestone_needs_prompt`, `active_milestone_candidates`.

**If `phase_found` is false:**
```
Phase [X] not found in roadmap.

Use /gmd:progress to see available phases.
```
Exit workflow.

**If `phase_found` is true:** Continue to check_existing.
</step>

<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-discuss-phase 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).

**Code-map slice (Tier-1 push — WIRE-01):** after building `VAULT_CONTEXT_BLOCK`, obtain the scoped code-map slice. Per-site source for discuss-phase: NO file list exists pre-planning, so the slice is the entry-points fallback (the orient code_channel entry-point content) — never fabricate scope:

```bash
CODE_MAP_CONTEXT_BLOCK=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" code-slice --entry-points --format block 2>/dev/null || true)
```

**Injection contract for `<code_map_context>`:** inject `CODE_MAP_CONTEXT_BLOCK` immediately AFTER `<vault_context>`, BEFORE `<files_to_read>`, in the downstream Task() prompts named below (scope_review + spec_review_gate — the two spawn sites carrying `{VAULT_CONTEXT_BLOCK}`). When empty, omit entirely — never inject an empty `<code_map_context></code_map_context>`. The block already embeds the Tier-2 pull commands + the freshness verdict (launch point, not payload — D-V184-05); the orchestrator never widens it. NOTE: `<code_map_context>` is the injected-block tag — distinct from the same-named-looking CONTEXT.md template section emitted by write_context, which this contract never touches.
</step>

<step name="check_existing">
Check if CONTEXT.md already exists using `has_context` from init.

```bash
ls ${phase_dir}/*-CONTEXT.md 2>/dev/null
```

**If exists:**
Use AskUserQuestion:
- header: "Context"
- question: "Phase [X] already has context. What do you want to do?"
- options:
  - "Update it" — Review and revise existing context
  - "View it" — Show me what's there
  - "Skip" — Use existing context as-is

If "Update": Load existing, continue to analyze_phase
If "View": Display CONTEXT.md, then offer update/skip
If "Skip": Exit workflow

**If doesn't exist:**

Check `has_plans` and `plan_count` from init. **If `has_plans` is true:**

Use AskUserQuestion:
- header: "Plans exist"
- question: "Phase [X] already has {plan_count} plan(s) created without user context. Your decisions here won't affect existing plans unless you replan."
- options:
  - "Continue and replan after" — Capture context, then run /gmd:plan-phase {X} to replan
  - "View existing plans" — Show plans before deciding
  - "Cancel" — Skip discuss-phase

If "Continue and replan after": Continue to analyze_phase.
If "View existing plans": Display plan files, then offer "Continue" / "Cancel".
If "Cancel": Exit workflow.

**If `has_plans` is false:** Continue to load_prior_context.
</step>

<step name="load_prior_context">
Read project-level and prior phase context to avoid re-asking decided questions and maintain consistency.

**Step 1: Read project-level files**
```bash
# Core project files (PROJECT.md is project-level — root in both modes;
# REQUIREMENTS/STATE are mode-aware via Step 0 resolution).
cat .planning/PROJECT.md 2>/dev/null
cat "${REQS_PATH}" 2>/dev/null
cat "${STATE_PATH}" 2>/dev/null
```

Extract from these:
- **PROJECT.md** — Vision, principles, non-negotiables, user preferences
- **REQUIREMENTS.md** — Acceptance criteria, constraints, must-haves vs nice-to-haves
- **STATE.md** — Current progress, any flags or session notes

**Step 2: Read all prior CONTEXT.md files**
```bash
# Find all CONTEXT.md files from phases before current (mode-aware via Step 0).
find "${PHASES_DIR}" -name "*-CONTEXT.md" 2>/dev/null | sort
```

For each CONTEXT.md where phase number < current phase:
- Read the `<decisions>` section — these are locked preferences
- Read `<specifics>` — particular references or "I want it like X" moments
- Note any patterns (e.g., "user consistently prefers minimal UI", "user rejected single-key shortcuts")

**Step 3: Build internal `<prior_decisions>` context**

Structure the extracted information:
```
<prior_decisions>
## Project-Level
- [Key principle or constraint from PROJECT.md]
- [Requirement that affects this phase from REQUIREMENTS.md]

## From Prior Phases
### Phase N: [Name]
- [Decision that may be relevant to current phase]
- [Preference that establishes a pattern]

### Phase M: [Name]
- [Another relevant decision]
</prior_decisions>
```

**Usage in subsequent steps:**
- `analyze_phase`: Skip gray areas already decided in prior phases
- `present_gray_areas`: Annotate options with prior decisions ("You chose X in Phase 5")
- `discuss_areas`: Pre-fill answers or flag conflicts ("This contradicts Phase 3 — same here or different?")

**If no prior context exists:** Continue without — this is expected for early phases.
</step>

<step name="scout_codebase">
Lightweight scan of existing code to inform gray area identification and discussion. Uses ~10% context — acceptable for an interactive session.

**Step 1: Check for existing codebase maps**
```bash
ls .planning/codebase/*.md 2>/dev/null
```

**If codebase maps exist:** Read the most relevant ones (CONVENTIONS.md, STRUCTURE.md, STACK.md based on phase type). Extract:
- Reusable components/hooks/utilities
- Established patterns (state management, styling, data fetching)
- Integration points (where new code would connect)

Skip to Step 3 below.

**Step 2: If no codebase maps, do targeted grep**

Extract key terms from the phase goal (e.g., "feed" → "post", "card", "list"; "auth" → "login", "session", "token").

```bash
# Find files related to phase goal terms
grep -rl "{term1}\|{term2}" src/ app/ --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" 2>/dev/null | head -10

# Find existing components/hooks
ls src/components/ 2>/dev/null
ls src/hooks/ 2>/dev/null
ls src/lib/ src/utils/ 2>/dev/null
```

Read the 3-5 most relevant files to understand existing patterns.

**Step 3: Build internal codebase_context**

From the scan, identify:
- **Reusable assets** — existing components, hooks, utilities that could be used in this phase
- **Established patterns** — how the codebase does state management, styling, data fetching
- **Integration points** — where new code would connect (routes, nav, providers)
- **Creative options** — approaches the existing architecture enables or constrains

Store as internal `<codebase_context>` for use in analyze_phase and present_gray_areas. This is NOT written to a file — it's used within this session only.
</step>

<step name="assess_complexity">
Assess phase complexity to determine whether brainstorming mode should be activated.

**Heuristics:**
- 5+ requirements mapped to this phase = complex
- Novel technology (not in existing stack) = complex
- Visual/UX components with user-facing design decisions = complex
- Pure infrastructure with clear patterns = simple

**If complex:** Offer brainstorming mode choice using AskUserQuestion:
- header: "Brainstorm"
- question: "This phase has [complexity indicators]. How do you want to brainstorm design decisions?"
- options:
  - "Human-in-the-loop" — I'll participate in each brainstorming round
  - "Autonomous" — Run brainstorming in parallel, present decisions for approval
  - "Skip brainstorming" — Proceed with standard discuss flow

**If simple:** Continue with existing lightweight discuss flow (skip brainstorming).

**Skill invocation:** When brainstorming mode is active, the brainstorming skill (skills/brainstorming/SKILL.md) is active. Its hard gate applies — no design decisions finalized without brainstorming evidence.

**Human-on-the-loop mode (Autonomous):**
When user selects "Autonomous" brainstorming mode:
- Dispatch parallel subagents (max 3) to brainstorm different design areas
- Orchestrator collects results and presents decisions for approval
- Checkpoint frequency based on complexity (complex = more frequent)

Store brainstorming mode selection for use in `discuss_areas` step.
</step>

<step name="analyze_phase">
Analyze the phase to identify gray areas worth discussing. **Use both `prior_decisions` and `codebase_context` to ground the analysis.**

**Read the phase description from ROADMAP.md and determine:**

1. **Domain boundary** — What capability is this phase delivering? State it clearly.

2. **Check prior decisions** — Before generating gray areas, check if any were already decided:
   - Scan `<prior_decisions>` for relevant choices (e.g., "Ctrl+C only, no single-key shortcuts")
   - These are **pre-answered** — don't re-ask unless this phase has conflicting needs
   - Note applicable prior decisions for use in presentation

3. **Gray areas by category** — For each relevant category (UI, UX, Behavior, Empty States, Content), identify 1-2 specific ambiguities that would change implementation. **Annotate with code context where relevant** (e.g., "You already have a Card component" or "No existing pattern for this").

4. **Skip assessment** — If no meaningful gray areas exist (pure infrastructure, clear-cut implementation, or all already decided in prior phases), the phase may not need discussion.

**Output your analysis internally, then present to user.**

Example analysis for "Post Feed" phase (with code and prior context):
```
Domain: Displaying posts from followed users
Existing: Card component (src/components/ui/Card.tsx), useInfiniteQuery hook, Tailwind CSS
Prior decisions: "Minimal UI preferred" (Phase 2), "No pagination — always infinite scroll" (Phase 4)
Gray areas:
- UI: Layout style (cards vs timeline vs grid) — Card component exists with shadow/rounded variants
- UI: Information density (full posts vs previews) — no existing density patterns
- Behavior: Loading pattern — ALREADY DECIDED: infinite scroll (Phase 4)
- Empty State: What shows when no posts exist — EmptyState component exists in ui/
- Content: What metadata displays (time, author, reactions count)
```
</step>

<step name="present_gray_areas">
Present the domain boundary, prior decisions, and gray areas to user.

**First, state the boundary and any prior decisions that apply:**
```
Phase [X]: [Name]
Domain: [What this phase delivers — from your analysis]

We'll clarify HOW to implement this.
(New capabilities belong in other phases.)

[If prior decisions apply:]
**Carrying forward from earlier phases:**
- [Decision from Phase N that applies here]
- [Decision from Phase M that applies here]
```

<!-- critic-gate: gray-area-selection (CRIT-WIRE-03 / Phase 51-03) -->

**Critic review (D5 / CRIT-WIRE-03 gate 1):**

Before presenting the AskUserQuestion menu below, dispatch the critic against the
generated gray-area set. Gray-area selection is the MASTER decision of this
workflow — it determines which subsequent approach-selection gates exist. Wrong
gray-area selection forecloses legitimate cross-phase concerns. Per D6 the call
is **UNCONDITIONAL** — the dispatcher honors `components.critic.enabled` internally
and returns `verdict: 'noop'` when the gate is closed.

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

// Caller-injected harness-neutral spawn primitive (D2). In Claude Code this
// wraps the Task tool; in v1.5.7 Codex CLI adapter, an alternate primitive.
const spawnSubagent = async ({ agent, prompt, cross_model }) => {
  // Task(subagent_type=agent, prompt=JSON.stringify(prompt)) → critic JSON envelope
};

// CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
// MODE + SLUG + REQS_PATH + STATE_PATH sourced from Step 0 init JSON.
// phase_dir (from init JSON) is already mode-aware per Plan 66-02 — resolves to
// milestones/<slug>/phases/... in parallel mode. Parallel mode additionally
// surfaces milestone-level REQUIREMENTS.md + STATE.md as affects_paths since
// gray-area selection is the MASTER decision and may touch REQ/STATE scope.
// affects_reqs (PHASE_REQ_IDS) is active-milestone-scoped by construction in
// parallel mode (Plan 66-02 made the path lookup mode-aware; the REQ-ID list
// reaching this dispatch comes from the milestone-scoped ROADMAP.md).
const affects_paths = (MODE === 'parallel')
  ? [`${phase_dir}/${padded_phase}-CONTEXT.md`, REQS_PATH, STATE_PATH]
  : [`${phase_dir}/${padded_phase}-CONTEXT.md`];

const grayAreaCriticEnvelope = await dispatchCritic({
  spawnSubagent: spawnSubagent,
  decision_point: `Gray-area selection — which gray areas surface for Phase ${PHASE}?`,
  lead_recommendation: <generated_gray_area_summary>, // e.g. "Layout style + Loading behavior + Content ordering + Post metadata"
  lead_rationale: <why_these_areas>, // e.g. "High-signal per code-context scout + prior-decision annotations"
  workflow: '/gmd:discuss-phase',
  phase: PHASE,
  affects_paths,
  affects_reqs: PHASE_REQ_IDS,    // active-milestone-scoped via Plan 66-02 mode-aware ROADMAP.md lookup
});

// Stash decision_id into workflow-scoped variable for write_context emission.
const CRITIC_DECISION_GRAY_AREA_ID = grayAreaCriticEnvelope.decision_id;
```

**Surface critic feedback in user-visible menu copy** when `verdict !== 'noop'`.
Include the literal `decision_id: <uuid>` per CRIT-DISP-02 so the user can trace
the critic round to its NDJSON entry. Example surface block to render above the
AskUserQuestion call:

```
Critic verdict: refine (decision_id: <uuid>)
Alternative argument: <alternative_argument>
Missed concerns: <missed_concerns>
```

When `verdict === 'noop'` (disabled path per D6), proceed silently — no menu
copy, no marker. The `decision_id` is still generated (CRIT-DISP-02) and stashed,
but `write_context` MUST NOT emit a reciprocal marker for a noop decision (the
decision wasn't influential).

**Then use AskUserQuestion (multiSelect: true):**
- header: "Discuss"
- question: "Which areas do you want to discuss for [phase name]?"
- options: Generate 3-4 phase-specific gray areas, each with:
  - "[Specific area]" (label) — concrete, not generic
  - [1-2 questions this covers + code context annotation] (description)
  - **Highlight the recommended choice with brief explanation why**

**Prior decision annotations:** When a gray area was already decided in a prior phase, annotate it:
```
☐ Exit shortcuts — How should users quit?
  (You decided "Ctrl+C only, no single-key shortcuts" in Phase 5 — revisit or keep?)
```

**Code context annotations:** When the scout found relevant existing code, annotate the gray area description:
```
☐ Layout style — Cards vs list vs timeline?
  (You already have a Card component with shadow/rounded variants. Reusing it keeps the app consistent.)
```

**Combining both:** When both prior decisions and code context apply:
```
☐ Loading behavior — Infinite scroll or pagination?
  (You chose infinite scroll in Phase 4. useInfiniteQuery hook already set up.)
```

**Do NOT include a "skip" or "you decide" option.** User ran this command to discuss — give them real choices.

**Examples by domain (with code context):**

For "Post Feed" (visual feature):
```
☐ Layout style — Cards vs list vs timeline? (Card component exists with variants)
☐ Loading behavior — Infinite scroll or pagination? (useInfiniteQuery hook available)
☐ Content ordering — Chronological, algorithmic, or user choice?
☐ Post metadata — What info per post? Timestamps, reactions, author?
```

For "Database backup CLI" (command-line tool):
```
☐ Output format — JSON, table, or plain text? Verbosity levels?
☐ Flag design — Short flags, long flags, or both? Required vs optional?
☐ Progress reporting — Silent, progress bar, or verbose logging?
☐ Error recovery — Fail fast, retry, or prompt for action?
```

For "Organize photo library" (organization task):
```
☐ Grouping criteria — By date, location, faces, or events?
☐ Duplicate handling — Keep best, keep all, or prompt each time?
☐ Naming convention — Original names, dates, or descriptive?
☐ Folder structure — Flat, nested by year, or by category?
```

Continue to discuss_areas with selected areas.
</step>

<step name="discuss_areas">
For each selected area, conduct a focused discussion loop.

**Philosophy: 4 questions, then check.**

Ask 4 questions per area before offering to continue or move on. Each answer often reveals the next question.

**For each area:**

1. **Announce the area:**
   ```
   Let's talk about [Area].
   ```

<!-- critic-gate: approach-selection-per-area (CRIT-WIRE-03 / Phase 51-03) -->

   **Critic review (D5 / CRIT-WIRE-03 gate 2):**

   Before opening the 4-question batch for THIS area, dispatch the critic against
   the lead's recommended approach for the area. This is the SPEC's CRIT-WIRE-03
   explicit "approach-selection between presented options" call site.

   ```
   Fire ONCE per area iteration (NOT per question) — see CONTEXT.md gate-selection
   heuristic. Approach-selection is the high-signal moment; per-question is
   over-coverage. Workflows fire 9 AskUserQuestion calls total; only 3 are
   high-signal worth wiring. Per-question dispatch would generate 4N noise entries
   per phase discussion (where N = number of areas selected).
   ```

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

   // Workflow-scoped accumulator for per-area decision_ids — keyed by area name.
   // Initialized at the top of the discuss_areas step (before the for-each-area loop).
   // CRITIC_DECISIONS_BY_AREA = {};

   // CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
   // Per-area gate narrower than gray-area MASTER gate (above): CONTEXT.md only
   // in sequential; CONTEXT.md + REQS_PATH in parallel (per-area decisions can
   // touch milestone-scoped REQ subset). phase_dir is mode-aware via Plan 66-02.
   // affects_reqs is the per-area REQ subset — active-milestone-scoped by
   // construction.
   const areaAffects_paths = (MODE === 'parallel')
     ? [`${phase_dir}/${padded_phase}-CONTEXT.md`, REQS_PATH]
     : [`${phase_dir}/${padded_phase}-CONTEXT.md`];

   const areaCriticEnvelope = await dispatchCritic({
     spawnSubagent: spawnSubagent,
     decision_point: `Approach selection for area ${area} — which option direction?`,
     lead_recommendation: <area_recommendation_summary>,
     lead_rationale: <why_this_recommendation>,
     workflow: '/gmd:discuss-phase',
     phase: PHASE,
     affects_paths: areaAffects_paths,
     affects_reqs: <REQ_IDS_relevant_to_this_area>,    // active-milestone-scoped subset
   });

   // Stash per-area decision_id for write_context emission.
   CRITIC_DECISIONS_BY_AREA[area] = areaCriticEnvelope.decision_id;
   ```

   When `verdict !== 'noop'`, surface verdict + alternative_argument +
   missed_concerns + `decision_id: <uuid>` in user-visible menu copy ABOVE the
   first AskUserQuestion of this area's 4-question batch. Per D6 the call is
   **UNCONDITIONAL** — disabled-path returns `verdict: 'noop'` and surfaces
   nothing. The disabled path still produces a stashed `decision_id`
   (CRIT-DISP-02), but `write_context` MUST NOT emit a marker for it.

2. **Ask 4 questions using AskUserQuestion:**
   - header: "[Area]" (max 12 chars — abbreviate if needed)
   - question: Specific decision for this area
   - options: 2-3 concrete choices (AskUserQuestion adds "Other" automatically), with the recommended choice highlighted and brief explanation why
   - **Annotate options with code context** when relevant:
     ```
     "How should posts be displayed?"
     - Cards (reuses existing Card component — consistent with Messages)
     - List (simpler, would be a new pattern)
     - Timeline (needs new Timeline component — none exists yet)
     ```
   - Include "You decide" as an option when reasonable — captures Claude discretion
   - **Context7 for library choices:** When a gray area involves library selection (e.g., "magic links" → query next-auth docs) or API approach decisions, use `mcp__context7__*` tools to fetch current documentation and inform the options. Don't use Context7 for every question — only when library-specific knowledge improves the options.

3. **After 4 questions, check:**
   - header: "[Area]" (max 12 chars)
   - question: "More questions about [area], or move to next?"
   - options: "More questions" / "Next area"

   If "More questions" → ask 4 more, then check again
   If "Next area" → proceed to next selected area
   If "Other" (free text) → interpret intent: continuation phrases ("chat more", "keep going", "yes", "more") map to "More questions"; advancement phrases ("done", "move on", "next", "skip") map to "Next area". If ambiguous, ask: "Continue with more questions about [area], or move to the next area?"

4. **After all initially-selected areas complete:**
   - Summarize what was captured from the discussion so far
   - AskUserQuestion:
     - header: "Done"
     - question: "We've discussed [list areas]. Which gray areas remain unclear?"
     - options: "Explore more gray areas" / "I'm ready for context"
   - If "Explore more gray areas":
     - Identify 2-4 additional gray areas based on what was learned
     - Return to present_gray_areas logic with these new areas
     - Loop: discuss new areas, then prompt again
   - If "I'm ready for context": Proceed to write_context

**Question design:**
- Options should be concrete, not abstract ("Cards" not "Option A")
- Each answer should inform the next question
- If user picks "Other" to provide freeform input (e.g., "let me describe it", "something else", or an open-ended reply), ask your follow-up as plain text — NOT another AskUserQuestion. Wait for them to type at the normal prompt, then reflect their input back and confirm before resuming AskUserQuestion for the next question.

**Inline drift detection (`drift_check`):**
After each decision is captured during the discussion, perform a lightweight drift check (~200-500 tokens):

1. Compare the decision against:
   - ROADMAP.md phase scope (does this decision stay within the phase boundary?)
   - Prior phase decisions from STATE.md (does this contradict earlier choices?)
   - REQUIREMENTS.md (does this align with or deviate from stated requirements?)

2. Implementation: simple checklist comparison, not NLP or semantic analysis
   ```
   Drift check:
   - [ ] Within phase scope (ROADMAP.md)?
   - [ ] Consistent with prior decisions (STATE.md)?
   - [ ] Aligned with requirements (REQUIREMENTS.md)?
   ```

3. If drift detected: surface the conflict and offer options using AskUserQuestion:
   - header: "Drift"
   - question: "This decision may conflict with [source]: [specific conflict]. How to proceed?"
   - options:
     - "Revise decision" — Adjust to align with existing scope/decisions
     - "Override" — Keep this decision, acknowledge the deviation
     - "Discuss further" — Explore the conflict before deciding

4. If no drift: continue silently (zero overhead when on track)

**Scope creep handling:**
If user mentions something outside the phase domain:
```
"[Feature] sounds like a new capability — that belongs in its own phase.
I'll note it as a deferred idea.

Back to [current area]: [return to current question]"
```

Track deferred ideas internally.
</step>

<step name="scope_gate">
Before writing CONTEXT.md, verify scope alignment via subagent review.

<!-- critic-gate: scope-boundary-review (CRIT-WIRE-03 / Phase 51-03) -->

**Critic review (D5 / CRIT-WIRE-03 gate 3):**

Before dispatching the structural scope_review subagent below, dispatch the
critic against the FULL collected decision set. The critic operates on
**decision-shape (semantic)** — does this set match phase scope and stay within
boundary? — while the existing scope_review subagent operates on **REQ-coverage
(structural)** — are all phase requirements addressed? Both can dissent
independently; the critic call is **COMPLEMENTARY**, NOT a replacement.

This is the pre-CONTEXT.md-write boundary review. The lead has just collected
the full discussion's decisions; this is the last semantic gate before locking
them into CONTEXT.md via the write_context step. TD-07's publish-boundary catch
was at this gate shape.

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

// CRIT-01/02/03 (Plan 66-05): milestone-scoped affects_paths in parallel mode.
// Pre-CONTEXT.md-write boundary review — surfaces broader scope artifacts in
// parallel mode (REQS_PATH + STATE_PATH alongside CONTEXT.md) since this is
// the final semantic gate before locking decisions. phase_dir is mode-aware
// via Plan 66-02. affects_reqs (PHASE_REQ_IDS) is active-milestone-scoped by
// construction in parallel mode.
const scopeGateAffects_paths = (MODE === 'parallel')
  ? [`${phase_dir}/${padded_phase}-CONTEXT.md`, REQS_PATH, STATE_PATH]
  : [`${phase_dir}/${padded_phase}-CONTEXT.md`];

const scopeGateCriticEnvelope = await dispatchCritic({
  spawnSubagent: spawnSubagent,
  decision_point: `CONTEXT.md decision set for Phase ${PHASE} — does this match phase scope and stay within boundary?`,
  lead_recommendation: <decision_set_summary>, // serialized digest of all area decisions
  lead_rationale: <why_this_decision_set>,
  workflow: '/gmd:discuss-phase',
  phase: PHASE,
  affects_paths: scopeGateAffects_paths,
  affects_reqs: PHASE_REQ_IDS,    // active-milestone-scoped via Plan 66-02 mode-aware ROADMAP.md lookup
});

// Stash decision_id for write_context emission.
const CRITIC_DECISION_SCOPE_GATE_ID = scopeGateCriticEnvelope.decision_id;
```

When `verdict !== 'noop'`, surface verdict + alternative_argument +
missed_concerns + `decision_id: <uuid>` to the user. Per D6 the call is
**UNCONDITIONAL**. If the critic dissents on scope-shape, revise decisions
BEFORE running the structural scope_review subagent below.

Dispatch a subagent with the Task tool to review scope alignment:

```
Task(prompt="
<scope_review>
Review the collected decisions for Phase {X}: {Name} against project scope.

{VAULT_CONTEXT_BLOCK}

{CODE_MAP_CONTEXT_BLOCK}

<files_to_read>
- {roadmap_path} (Phase scope definition)
- {state_path} (Prior phase decisions)
- {requirements_path} (Project requirements)
</files_to_read>

<decisions_to_review>
{collected_decisions_from_discussion}
</decisions_to_review>

Check:
1. Does the overall scope match ROADMAP.md phase boundary?
2. Does the approach conflict with decisions from prior phases?
3. Are all phase requirements addressed by at least one decision?
4. Are there any decisions that belong to a different phase?

Return:
- ## SCOPE ALIGNED — all checks pass
- ## SCOPE ISSUES — list of specific issues with recommendations
</scope_review>
", description="Scope alignment review")
```

**If SCOPE ALIGNED:** Continue to write_context.
**If SCOPE ISSUES:** Present issues to user, revise decisions as needed, then re-check or proceed with acknowledgment.
</step>

<step name="write_context">
Create CONTEXT.md capturing decisions made.

**Find or create phase directory:**

Use values from init: `phase_dir`, `phase_slug`, `padded_phase`.

If `phase_dir` is null (phase exists in roadmap but no directory) — mode-aware via Step 0:
```bash
mkdir -p "${PHASES_DIR}/${padded_phase}-${phase_slug}"
```

**File location:** `${phase_dir}/${padded_phase}-CONTEXT.md`

**CRIT-WIRE-05 reciprocal-marker emission (instruction to executing agent):**

```markdown
When writing the `<decisions>` block below, for each decision that was
INFLUENCED by a critic verdict !== 'noop' (tracked via the workflow-scoped
stash variables CRITIC_DECISION_GRAY_AREA_ID + CRITIC_DECISIONS_BY_AREA +
CRITIC_DECISION_SCOPE_GATE_ID populated by the 3 dispatchCritic calls in
present_gray_areas / discuss_areas / scope_gate steps), insert
`<!-- critic-decision: <stashed_decision_id> -->` IMMEDIATELY ABOVE the
decision entry. UUID literal substitution from the workflow-scoped variable.

Do NOT generate new UUIDs — use the dispatcher-returned IDs only
(CRIT-DISP-02 contract: invocation-time UUIDs are the round-trip-integrity
anchor; workflow-generated UUIDs would foreclose CRIT-TELM-02 join semantics).

Disabled-path discipline: when a dispatcher call returned `verdict: 'noop'`
(D6 default-disabled), the stashed decision_id IS still defined (CRIT-DISP-02)
but the decision was NOT influential — DO NOT emit a marker. Marker emission
gates on `verdict !== 'noop'` AND `lead integrated the recommendation`, never
on stash-defined-ness alone.
```

**Worked example** — adjacent reciprocal marker on a critic-influenced decision:

```markdown
### Database Schema
<!-- critic-decision: 9104e545-a879-4b4e-a036-5b3a476e1c9d -->
- Use Postgres with JSONB columns for flexible metadata (critic verdict: refine — alternative_argument was MongoDB; lead chose Postgres after considering critic's missed_concerns about transaction guarantees)
```

The UUID `9104e545-a879-4b4e-a036-5b3a476e1c9d` matches the corresponding
NDJSON entry's `decision_id` field — round-trip semantically sound for future
CRIT-TELM-02 outcome-class join (validated / false_positive / missed /
confirmed). See `references/critic-observations-schema.md` Section 4 for the
full marker convention spec.

**Structure the content by what was discussed:**

```markdown
# Phase [X]: [Name] - Context

**Gathered:** [date]
**Status:** Ready for planning

<domain>
## Phase Boundary

[Clear statement of what this phase delivers — the scope anchor]

</domain>

<decisions>
## Implementation Decisions

### [Category 1 that was discussed]
- [Decision or preference captured]
- [Another decision if applicable]

### [Category 2 that was discussed]
- [Decision or preference captured]

### Claude's Discretion
[Areas where user said "you decide" — note that Claude has flexibility here]

</decisions>

<code_context>
## Existing Code Insights

### Reusable Assets
- [Component/hook/utility]: [How it could be used in this phase]

### Established Patterns
- [Pattern]: [How it constrains/enables this phase]

### Integration Points
- [Where new code connects to existing system]

</code_context>

<specifics>
## Specific Ideas

[Any particular references, examples, or "I want it like X" moments from discussion]

[If none: "No specific requirements — open to standard approaches"]

</specifics>

<deferred>
## Deferred Ideas

[Ideas that came up but belong in other phases. Don't lose them.]

[If none: "None — discussion stayed within phase scope"]

</deferred>

---

*Phase: XX-name*
*Context gathered: [date]*
```

Write file.
</step>

<step name="spec_review_gate">
After CONTEXT.md is written, dispatch a spec reviewer subagent to validate quality.

This satisfies DESIGN-02 (spec review gate before CONTEXT.md finalization).

Dispatch subagent using the spec reviewer prompt template:

```
Task(prompt="
Read and follow the spec reviewer instructions:
@skills/brainstorming/spec-reviewer-prompt.md

{VAULT_CONTEXT_BLOCK}

{CODE_MAP_CONTEXT_BLOCK}

<context_file>
{phase_dir}/{padded_phase}-CONTEXT.md
</context_file>

<phase_info>
Phase: {phase_number} - {phase_name}
Roadmap goal: {phase_goal_from_roadmap}
Requirements: {phase_req_ids}
</phase_info>

Review CONTEXT.md across all 6 dimensions:
1. Scope alignment
2. Concreteness
3. Ambiguity
4. Completeness
5. Conflict detection
6. Scope leakage

Return structured review with PASS/FAIL per dimension.
", description="Spec review of CONTEXT.md")
```

**If any dimension is FAIL:**
- Surface the findings to the user
- Revise CONTEXT.md to address failures
- Re-run spec review (max 2 iterations)

**If all dimensions PASS:** Continue to vault_sync.
</step>

<step name="vault_sync">
After CONTEXT.md is finalized (spec review passed), sync to Obsidian vault.

```bash
node bin/gmd-tools.cjs vault-sync "${phase_dir}/${padded_phase}-CONTEXT.md" 2>/dev/null
```

**Graceful degradation:** If vault is not configured or sync fails, skip with a note:
```
Vault sync: skipped (vault not configured or sync unavailable)
```

This ensures CONTEXT.md is available in the Obsidian vault for cross-reference during research and planning.
</step>

<step name="confirm_creation">
Present summary and next steps:

```
Created: ${PHASES_DIR}/${PADDED_PHASE}-${SLUG}/${PADDED_PHASE}-CONTEXT.md

## Decisions Captured

### [Category]
- [Key decision]

### [Category]
- [Key decision]

[If deferred ideas exist:]
## Noted for Later
- [Deferred idea] — future phase

---

## ▶ Next Up

**Phase ${PHASE}: [Name]** — [Goal from ROADMAP.md]

`/gmd:plan-phase ${PHASE}`

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

---

**Also available:**
- `/gmd:plan-phase ${PHASE} --skip-research` — plan without research
- Review/edit CONTEXT.md before continuing

---
```
</step>

<step name="git_commit">
Commit phase context (uses `commit_docs` from init internally):

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs(${padded_phase}): capture phase context" --files "${phase_dir}/${padded_phase}-CONTEXT.md"
```

Confirm: "Committed: docs(${padded_phase}): capture phase context"
</step>

<step name="update_state">
Update STATE.md with session info:

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" state record-session \
  --stopped-at "Phase ${PHASE} context gathered" \
  --resume-file "${phase_dir}/${padded_phase}-CONTEXT.md"
```

Commit STATE.md:

```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" commit "docs(state): record phase ${PHASE} context session" --files "${STATE_PATH}"
```
</step>

<step name="auto_advance">
Check for auto-advance trigger:

1. Parse `--auto` flag from $ARGUMENTS
2. **Sync chain flag with intent** — if user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference):
   ```bash
   if [[ ! "$ARGUMENTS" =~ --auto ]]; then
     node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-set workflow._auto_chain_active false 2>/dev/null
   fi
   ```
3. Read both the chain flag and user preference:
   ```bash
   AUTO_CHAIN=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-get workflow._auto_chain_active 2>/dev/null || echo "false")
   AUTO_CFG=$(node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-get workflow.auto_advance 2>/dev/null || echo "false")
   ```

**If `--auto` flag present AND `AUTO_CHAIN` is not true:** Persist chain flag to config (handles direct `--auto` usage without new-project):
```bash
node "$HOME/.claude/get-magic-done/bin/gmd-tools.cjs" config-set workflow._auto_chain_active true
```

**If `--auto` flag present OR `AUTO_CHAIN` is true OR `AUTO_CFG` is true:**

Display banner:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GMD ► AUTO-ADVANCING TO PLAN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Context captured. Launching plan-phase...
```

Launch plan-phase using the Skill tool to avoid nested Task sessions (which cause runtime freezes due to deep agent nesting — see #686):
```
Skill(skill="gmd:plan-phase", args="${PHASE} --auto")
```

This keeps the auto-advance chain flat — discuss, plan, and execute all run at the same nesting level rather than spawning increasingly deep Task agents.

**Handle plan-phase return:**
- **PHASE COMPLETE** → Full chain succeeded. Display:
  ```
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   GMD ► PHASE ${PHASE} COMPLETE
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Auto-advance pipeline finished: discuss → plan → execute

  Next: /gmd:discuss-phase ${NEXT_PHASE} --auto
  <sub>/clear first → fresh context window</sub>
  ```
- **PLANNING COMPLETE** → Planning done, execution didn't complete:
  ```
  Auto-advance partial: Planning complete, execution did not finish.
  Continue: /gmd:execute-phase ${PHASE}
  ```
- **PLANNING INCONCLUSIVE / CHECKPOINT** → Stop chain:
  ```
  Auto-advance stopped: Planning needs input.
  Continue: /gmd:plan-phase ${PHASE}
  ```
- **GAPS FOUND** → Stop chain:
  ```
  Auto-advance stopped: Gaps found during execution.
  Continue: /gmd:plan-phase ${PHASE} --gaps
  ```

**If neither `--auto` nor config enabled:**
Route to `confirm_creation` step (existing behavior — show manual next steps).
</step>

</process>

<success_criteria>
- Phase validated against roadmap
- Prior context loaded (PROJECT.md, REQUIREMENTS.md, STATE.md, prior CONTEXT.md files)
- Already-decided questions not re-asked (carried forward from prior phases)
- Codebase scouted for reusable assets, patterns, and integration points
- Gray areas identified through intelligent analysis with code and prior decision annotations
- User selected which areas to discuss
- Each selected area explored until user satisfied (with code-informed and prior-decision-informed options)
- Scope creep redirected to deferred ideas
- CONTEXT.md captures actual decisions, not vague vision
- CONTEXT.md includes code_context section with reusable assets and patterns
- Deferred ideas preserved for future phases
- STATE.md updated with session info
- User knows next steps
</success_criteria>
