Files
msd-core/gsd-core/workflows/discuss-phase-assumptions.md
Tom Boucher ff4a57b78c chore(#1671): migrate the remaining 13 LARGE/XL workflows to the fragment model — Phase 6.3 (#3030)
* chore(#2994): fragmentize progress.md forensic audit onto the fragment model

Extract the --forensic-gated forensic_audit step to
workflows/progress/steps/forensic-audit.md behind a section marker, and
repair progress.md's init line to forward --forensic so the atom is
actually true in production rather than only under direct CLI tests.

progress.md shrinks 32630 -> 27207 bytes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize the four manifest-wired workflows

new-project, quick, new-milestone and progress each already had a
dedicated cmdInit* entry point but zero marked sections. Extract nine
gated bodies to workflows/<wf>/steps/ behind section markers and repair
each init line to forward its flags.

Fold --full into the discuss/research/validate facts inside cmdInitQuick
so the when= grammar never sees an OR, per the chunked-mode precedent.

Fixes found while working, per the no-defer rule:
- cmdInitProgress passed no phase info to buildSectionManifestField, so
  state:phase-mvp-mode was permanently false — an atom in the vocabulary
  whose fact could never be computed.
- the quick init router folded flag tokens into the free-text
  description, which the new forwarding would have corrupted.
- a #2508 dispatch note was nested inside quick.md's Agent(prompt=)
  fence, leaking orchestrator guidance into the subagent prompt.
- progress.md had a 3-vs-4 backtick outer-fence imbalance.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize verify-work.md and admit state:ui-phase-active

Wire cmdInitVerifyWork to buildSectionManifestField — it was a dedicated
entry point that never emitted a manifest — and mark two sections.

state:ui-phase-active folds (plan:pre hooks include an active ui step) OR
(the phase dir holds a *-UI-SPEC.md) into one boolean in init.cts, so the
grammar still sees a single operator-free atom. The inner Playwright-MCP
check stays as prose inside the fragment: it is live session state and no
init seam can precompute it.

The MVP false-branch note is a real fallback, not redundant prose, so it
sits outside the marker — gating it away would delete the text needed
precisely when MVP mode is off.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): follow moved workflow content in drift guards

Retarget every guard that asserted on content this branch moved into
workflows/<wf>/steps/, mirroring 815b3d897. Each retargeted assertion was
verified to still fail when its step file is blanked, so none was
weakened into vacuity.

Three assertions in verify-mvp-uat were genuinely red. Three more were
worse than red — passing for the wrong reason:
- quick-commit-boundary and worktree-cleanup anchored on indexOf('Step
  5.6'), which matched a later cross-reference and sliced 16069 chars
  that coincidentally held the asserted substrings. Replaced with an
  expandWorkflowSections helper that splices step content back in place.
- phase6-review-capabilities lost its end boundary and widened to EOF.
- playwright-ui-verify matched 'UI' in an unrelated bullet and 'fall
  back' in a subagent-dispatch line after the real content moved.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize code-review and complete-milestone, admit three atoms

Add dedicated cmdInitCodeReview and cmdInitCompleteMilestone entry points
alongside the shared generic ones rather than modifying them — init.phase-op
and init.manager carry a CRITICAL blast radius (179 dependents, 24
processes) and stay byte-identical for their other callers.

Admit flag:--fix, state:fallow-enabled and state:git-create-tag, each with
a consuming section and a fact its own entry point computes.

Both sections had the resolver-in-body hazard: the fallow config-gate and
the git.create_tag check each sat inside the very block being gated, so
gating would have disabled the resolver that decides the gate. Both are
hoisted into init and the bodies now consume the resolved fact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): retarget code-review and milestone drift guards, fix two red tests

Retarget guards that asserted on content moved into steps/, proving
non-vacuity by blanking each step file and confirming failure.

Also fixes two genuinely red tests found while working, per the no-defer
rule:
- workflow-fragments' frozen-vocabulary lock was missing
  state:ui-phase-active, so commit 7ef7f8336 shipped red. Lint and build
  both passed over it, which is why neither is sufficient verification.
- code-review's quick.md capability-hook assertion carried a stale
  delimiter after the 18ff35d20 extraction.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize autonomous.md and admit state:plan-strategy-converge

Five sections share one atom, the pattern plan-phase already uses for
flag:--research-phase. The atom folds --converge OR --cross-ai into a
single boolean in cmdInitAutonomous so the grammar stays operator-free.

cmdInitAutonomous is additive; init.milestone-op, init.manager and
init.phase-op are untouched and still consumed. The $PLAN_STRATEGY bash
resolver is deliberately retained — ungated local-planning bullets still
read it, so the init-side fact supplements it rather than replacing it.

converge-fail-fast required splitting one bash fence so the always-run
CONVERGENCE_ARGS construction stays outside the marker. All three
flag-absent fallbacks were left outside their markers.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize review and discuss-phase-assumptions

Admit state:reviewer-instances-configured (two peripheral notes share it;
the core reviewer-lane dispatch stays unmarked — it is the workflow's
primary always-evaluated logic, not an optional branch) and
state:auto-advance-active, which folds --auto OR two config keys into one
boolean so the grammar stays operator-free.

discuss-phase-assumptions was the highest-risk edit in this PR. Its
auto_advance step is a full if/elif/else; gating it whole would have
deleted the flag-absent fallback needed exactly when --auto is off. Split
verified exact: resolvers 636-651 and the 'End here' fallback 668-669 both
stay outside the marker; only 653-667 is gated.

Adds emitted-drift acks for the two files that grew — review.md (+55 B)
and autonomous.md (+737 B from 80799211c, which had none and would have
red-gated the push.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize docs-update, update, transition and new-milestone Part A

Completes the 13-workflow rollout. Three of these had no init call at all
and gained a dedicated entry point plus their first gsd_run query line.

Admits state:is-monorepo and adds state:next-channel, state:workstream-active
and state:flat-mode. Vocabulary 26 -> 30 atoms.

Part A of new-milestone applies when NO workstream is active — the negation
of state:workstream-active. Rather than teach the grammar negation, which is
the Greenspun drift the frozen list exists to prevent, it gets a separate
positively-phrased atom whose fact is the inverse. Part B, which always runs,
stays outside the marker.

flag:--verify-only is deliberately NOT admitted: docs-update has no
contiguous purely-additive region for it, and an atom without a consuming
section is dead vocabulary. Evidence recorded in the slice report.

update.md reuses its existing resolved $GSD_TOOLS rather than prepending the
canonical preamble, which would have clobbered it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): stop automated-ui-verification re-resolving its own gate, retire dead vocabulary

Two defects the new tests caught.

The automated-ui-verification step re-ran gsd_run loop render-hooks and
recomputed UI_PHASE_ACTIVE inside a body that is only read when that fact
is already true — the circular self-disabling pattern this design forbids,
introduced by 3c654b168. cmdInitVerifyWork now exposes ui_phase_active and
the step consumes it. Its launcher preamble goes too: no gsd_run remains.
The Playwright-MCP check stays as prose — that is live session state.

Dead vocabulary predating this PR: flag:--full and state:needs-codebase-map
were admitted with a gate-1 claim that never materialized. flag:--full is
removed, redundant once quick folds it into discuss/research/validate.
state:needs-codebase-map gets the real consumer it always lacked, gating
new-project's codebase-map offer. Vocabulary 30 -> 29, and no atom is now
without a consuming section.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): add the atom-admission, inversion and resolver-hoist gates

The two existing parity guards prove vocabulary/predicate symmetry but
never that a fact is computed — an atom no cmdInit* assembles evaluates
false forever. These close that hole:

- per-atom satisfiability for all 29 atoms, plus an anti-vacuity assertion
  so the loop cannot silently cover zero atoms
- dead-vocabulary check against the shipped manifest
- inversion guard: the flag-absent fallbacks in discuss-phase-assumptions
  and verify-work must stay outside their markers
- data-driven resolver-hoist guard over the shipped manifest, so a future
  extraction cannot reintroduce the circular class
- compound-fold coverage (--full, --cross-ai, --rc, config-only --auto)
- null-vs-[] degraded/computed distinction, and flag value shapes

Also repairs the frozen-vocabulary lock, which was stale and red for the
seven atoms earlier commits on this branch shipped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#2994): add changeset for the fragment-model rollout

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): cite the issue on the two new allow-test-rule exemptions

ADR-456 requires an issue ref on the same line as the annotation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#2994): correct the atom-count claims after retiring flag:--full

The vocabulary doc comments still said 30 entries; it is 29 since
flag:--full was removed as dead vocabulary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): dedupe the phase-fallback block and harden --ws parsing

Review findings.

MAJOR: the three new init entry points each pasted a verbatim copy of the
guardedFindPhase/guardedGetRoadmapPhase fallback, taking the repo from four
copies to seven — DEFECT.GENERATIVE-FIX. Extracted applyRoadmapFallback and
folded six of the seven; each call site keeps its own field-set via a
closure. Duplication removed rather than papered over with a parity test.
cmdInitPhaseOp stays out: its fallback omits has_reviews, so it is not a
byte-identical copy, and it is CRITICAL-radius.

LOW, pre-existing: GSD_WS captured [^[:space:]]+ and expands unquoted, so a
workstream name holding glob metacharacters would expand against the
filesystem. Narrowed to [A-Za-z0-9._-]+. The unquoted expansion is kept —
it must word-split into two args and vanish when empty.

Also restores the vocabulary ordering convention, and fixes a masked test
bug the mandated run surfaced: the flag-forwarding guard checked only the
first init line per workflow, but new-milestone has two, so a real failure
was reporting exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): drop the stale new-milestone emitted-drift ack

new-milestone.md was acked for a +406 B growth measured against an
intermediate commit. Net against origin/next it SHRANK by 8 bytes, so
nothing needed the ack and it explained nothing — which the differential
attribution check reports as a stale acknowledgment, not a pass.

update.md's entry stays: it genuinely grew +703 B.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): resolve the 15 failures from the full matrix run

All 15 were real and identical on both lanes.

REAL REGRESSION: autonomous.md hit 41479 chars against the #2196 guard's
40960 cap — a CHARS cap distinct from the LARGE tier byte cap, which the
five section stubs pushed it over. Extracted the 3a.5 UI Design Contract
body to references/; now 39968 chars, and the file nets -795 B vs base, so
its growth ack is deleted rather than left stale.

REAL DEFECT: docs referenced /gsd-transition, which is not a live
registered command. Reworded.

STALE FIXTURE: the emission byte-identity test hardcoded two marked
workflows; this branch legitimately marks fifteen. Fixture corrected — the
source was right.

The rest were drift guards over the eight workflows the earlier sweep did
not cover, retargeted at where the content now lives with non-vacuity
proven by blanking each step file and confirming failure. The GSD_WS
forwarding guard was checked as a possible real break and is not one: the
charclass narrowing is intact and forwarding works end to end.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): drop the ack for a newly-added reference file

A new file's emitted ripple is attributable to the diff that adds it, so
the acknowledgment explained nothing and the differential check reports it
as stale. Removing the last entry removes the fragment — an empty one
signals nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): retarget the UI-contract guards and clear two transitive advisories

The §3a.5 extraction that brought autonomous.md under the #2196 char cap
moved its body to references/autonomous-ui-design-contract.md, so ten
guards in autonomous-ui-steps and check-ui-safety-gate were asserting it
against the host. Retargeted via a combined read, each proven non-vacuous
by blanking the reference file and confirming failure.

This class had already bitten twice on this branch because each sweep was
scoped to the workflows touched at that moment, so this one was
exhaustive: ~70 test files across all 13 workflows, zero further broken or
vacuous assertions found.

Also clears two high transitive advisories the matrix flagged on one lane
— fast-uri GHSA-7p8r-x3mc-p8w7 and three ip-address SSRF/trust-boundary
issues. Both pre-date this branch: package-lock.json was untouched until
now, so the production tree was byte-identical to the base. Lockfile-only,
package.json unchanged, verified against a real npm ci install.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): backfill changeset pr number to 3030

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 19:59:58 -04:00

28 KiB
Raw Blame History

Extract implementation decisions that downstream agents need — using codebase-first analysis and assumption surfacing instead of interview-style questioning.

You are a thinking partner, not an interviewer. Analyze the codebase deeply, surface what you believe based on evidence, and ask the user only to correct what's wrong.

<available_agent_types> Valid GSD subagent types (use exact names — do not fall back to 'general-purpose'):

  • gsd-assumptions-analyzer — Analyzes codebase to surface implementation assumptions </available_agent_types>

<downstream_awareness> CONTEXT.md feeds into:

  1. gsd-phase-researcher — Reads CONTEXT.md to know WHAT to research
  2. gsd-planner — Reads CONTEXT.md to know WHAT decisions are locked

Your job: Capture decisions clearly enough that downstream agents can act on them without asking the user again. Output is identical to discuss mode — same CONTEXT.md format. </downstream_awareness>

**Assumptions mode philosophy:**

The user is a visionary, not a codebase archaeologist. They need enough context to evaluate whether your assumptions match their intent — not to answer questions you could figure out by reading the code.

  • Read the codebase FIRST, form opinions SECOND, ask ONLY about what's genuinely unclear
  • Every assumption must cite evidence (file paths, patterns found)
  • Every assumption must state consequences if wrong
  • Minimize user interactions: ~2-4 corrections vs ~15-20 questions

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

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 "Deferred Ideas". Don't lose it, don't act on it. </scope_guardrail>

<answer_validation> IMPORTANT: Answer validation — After every AskUserQuestion call, if the response is empty/whitespace-only:

  • "Other" with empty text (the user wants to type freeform): output "What would you like to discuss?", STOP generating, wait for the user's next message, then reflect it back and continue. Do NOT retry AskUserQuestion or call any tools.
  • Any other empty response: retry once with the same parameters; if still empty, present options as a plain-text numbered list. Never proceed with empty input.

Text mode (--text or workflow.text_mode: true): follow workflows/discuss-phase/modes/text.md — do not use AskUserQuestion at all. </answer_validation>

Phase number from argument (required).
_GSD_SHIM_NAME="gsd-tools.cjs"; _GSD_RUNTIME_ROOT="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; GSD_TOOLS="${_GSD_RUNTIME_ROOT}/gsd-core/bin/${_GSD_SHIM_NAME}"; if [ -f "$GSD_TOOLS" ]; then gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${_GSD_RUNTIME_ROOT}/.codex/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${_GSD_RUNTIME_ROOT}/.codex/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${HERMES_HOME:-$HOME/.hermes}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${HERMES_HOME:-$HOME/.hermes}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CURSOR_CONFIG_DIR:-$HOME/.cursor}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CODEX_HOME:-$HOME/.codex}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CODEX_HOME:-$HOME/.codex}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${GEMINI_CONFIG_DIR:-$HOME/.gemini}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${COPILOT_CONFIG_DIR:-$HOME/.copilot}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${AUGMENT_CONFIG_DIR:-$HOME/.augment}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${TRAE_CONFIG_DIR:-$HOME/.trae}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${TRAE_CONFIG_DIR:-$HOME/.trae}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${QWEN_CONFIG_DIR:-$HOME/.qwen}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${QWEN_CONFIG_DIR:-$HOME/.qwen}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CLINE_CONFIG_DIR:-$HOME/.cline}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CLINE_CONFIG_DIR:-$HOME/.cline}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${GROK_AGENTS_HOME:-$HOME/.agents}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${GROK_AGENTS_HOME:-$HOME/.agents}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; else echo "ERROR: gsd-tools.cjs not found at $GSD_TOOLS and gsd-tools is not on PATH. Run: npx -y @opengsd/gsd-core@latest --claude --local" >&2; exit 1; fi; if [ -n "${CLAUDE_ENV_FILE:-}" ] && [ -n "${GSD_TOOLS:-}" ]; then printf "export PATH='%s':\"\$PATH\"\n" "${GSD_TOOLS%/*}" >> "$CLAUDE_ENV_FILE" 2>/dev/null || true; fi
RESPONSE_LANGUAGE=$(gsd_run query config-get response_language --default "" 2>/dev/null || echo "")
AUTO_PARAM=""; if [[ "$ARGUMENTS" =~ (^|[[:space:]])--auto([[:space:]]|$) ]]; then AUTO_PARAM="--auto"; fi
INIT=$(gsd_run query init.discuss-phase-assumptions "${PHASE}" $AUTO_PARAM)
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
AGENT_SKILLS_ANALYZER=$(gsd_run query agent-skills gsd-assumptions-analyzer)
# #2072: resolve the routed model so model_overrides / models.discuss are honored
# (the resolver maps gsd-assumptions-analyzer → phaseType "discuss"); thread it below.
ANALYZER_MODEL=$(gsd_run query resolve-model gsd-assumptions-analyzer --raw)

If response_language is set: All user-facing questions, prompts, and explanations in this workflow MUST be presented in {response_language}. Technical terms, code, file paths, and subagent prompts stay in English — only user-facing output is translated.

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.

If phase_found is false:

Phase [X] not found in roadmap.

Use /gsd:progress to see available phases.

Exit workflow.

If phase_found is true: Continue to check_existing.

Auto mode — If --auto is present in ARGUMENTS:

  • In check_existing: auto-select "Update it" (if context exists) or continue without prompting
  • In present_assumptions: skip confirmation gate, proceed directly to write CONTEXT.md
  • In correct_assumptions: auto-select recommended option for each correction
  • Log each auto-selected choice inline
  • After completion, auto-advance to plan-phase
Check if CONTEXT.md already exists using `has_context` from init.
ls ${phase_dir}/*-CONTEXT.md 2>/dev/null || true

If exists:

If --auto: Auto-select "Update it". Log: [auto] Context exists — updating with assumption-based analysis.

Otherwise: Use AskUserQuestion:

  • header: "Context"
  • question: "Phase [X] already has context. What do you want to do?"
  • options:
    • "Update it" — Re-analyze codebase and refresh assumptions
    • "View it" — Show me what's there
    • "Skip" — Use existing context as-is

If "Update": Load existing, continue to load_prior_context 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:

If --auto: Auto-select "Continue and replan after". Log: [auto] Plans exist — continuing with assumption analysis, will replan after.

Otherwise: 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"
    • "View existing plans"
    • "Cancel"

If "Continue and replan after": Continue to load_prior_context. 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.

Read project-level and prior phase context to avoid re-asking decided questions.

Step 1: Read project-level files

cat .planning/PROJECT.md 2>/dev/null || true
cat .planning/REQUIREMENTS.md 2>/dev/null || true
cat .planning/STATE.md 2>/dev/null || true

Extract from these:

  • PROJECT.md — Vision, principles, non-negotiables, user preferences
  • REQUIREMENTS.md — Acceptance criteria, constraints
  • STATE.md — Current progress, any flags

Step 2: Read all prior CONTEXT.md files

(find .planning/phases -name "*-CONTEXT.md" 2>/dev/null || true) | 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 patterns (e.g., "user consistently prefers minimal UI")

Step 3: Build internal <prior_decisions> context

Structure the extracted information for use in assumption generation.

If no prior context exists: Continue without — expected for early phases.

Check if any pending todos are relevant to this phase's scope.
TODO_MATCHES=$(gsd_run query todo.match-phase "${PHASE_NUMBER}")

Parse JSON for: todo_count, matches[].

If todo_count is 0: Skip silently.

If matches found: Present matched todos, use AskUserQuestion (multiSelect) to fold relevant ones into scope.

For selected (folded) todos: Store as <folded_todos> for CONTEXT.md <decisions> section. For unselected: Store as <reviewed_todos> for CONTEXT.md <deferred> section.

Auto mode (--auto): Fold all todos with score >= 0.4 automatically. Log the selection.

Read the project-level methodology file if it exists. This must happen before assumption analysis so that active lenses shape how assumptions are generated and evaluated.
cat .planning/METHODOLOGY.md 2>/dev/null || true

If METHODOLOGY.md exists:

  • Parse each named lens: its diagnoses, recommendations, and triggering conditions
  • Store as internal <active_lenses> for use in deep_codebase_analysis and present_assumptions
  • When spawning the gsd-assumptions-analyzer, pass the lens list so it can flag which lenses apply
  • When presenting assumptions, append a "Methodology" section showing which lenses were applied and what they flagged (if anything)

If METHODOLOGY.md does not exist: Skip silently. This artifact is optional.

Lightweight scan of existing code to inform assumption generation.

Step 1: Check for existing codebase maps

ls .planning/codebase/*.md 2>/dev/null || true

If codebase maps exist: Read relevant ones (CONVENTIONS.md, STRUCTURE.md, STACK.md). Extract reusable components, patterns, integration points. Skip to Step 3.

Step 2: If no codebase maps, do targeted grep

Extract key terms from phase goal, search for related files.

grep -rl "{term1}\|{term2}" src/ app/ --include="*.ts" --include="*.tsx" 2>/dev/null | head -10

Read the 3-5 most relevant files.

Step 3: Build internal <codebase_context>

Identify reusable assets, established patterns, integration points, and creative options. Store internally for use in deep_codebase_analysis.

Spawn a `gsd-assumptions-analyzer` agent to deeply analyze the codebase for this phase. This keeps raw file contents out of the main context window, protecting token budget.

Resolve calibration tier (if USER-PROFILE.md exists):

PROFILE_PATH="$HOME/.claude/gsd-core/USER-PROFILE.md"

If file exists at PROFILE_PATH:

  • Priority 1: Read config.json > preferences.vendor_philosophy (project-level override)
  • Priority 2: Read USER-PROFILE.md Vendor Choices/Philosophy rating (global)
  • Priority 3: Default to "standard"

Map to calibration tier:

  • conservative OR thorough-evaluator → full_maturity (more alternatives, detailed evidence)
  • opinionated → minimal_decisive (fewer alternatives, decisive recommendations)
  • pragmatic-fast OR any other value → standard

If no USER-PROFILE.md: calibration_tier = "standard"

Spawn Explore subagent (runs in a subagent — no output until it returns, ~1–5 min; expected, not a freeze):

Runtime-aware dispatch (#2508 Phase 4). GSD workflows dispatch specialized subagents by role. Before dispatching on a built-in-only runtime (kimi-code — three built-ins only), resolve the role to a built-in via gsd_run query resolve-dispatch-type --requested <role> --raw. On named-dispatch runtimes (Claude/OpenCode/…) the role is returned unchanged; on kimi-code it maps to coder/explore/plan by role-suffix. The persona rides ${AGENT_SKILLS_<ROLE>} (Phase 3) regardless. See @gsd-core/references/runtime-aware-dispatch.md.

Model omission (#2517). Omit the model parameter entirely when the value it would carry (ANALYZER_MODEL) is "inherit" or empty. An empty value 404s on runtimes without native tier aliases — the default on non-Claude runtimes. Omitting it inherits the orchestrator's model. See @gsd-core/references/model-profile-resolution.md.

Agent(subagent_type="gsd-assumptions-analyzer", model="{ANALYZER_MODEL}", prompt="""
Analyze the codebase for Phase {PHASE}: {phase_name}.

Phase goal: {roadmap_description}
Prior decisions: {prior_decisions_summary}
Codebase scout hints: {codebase_context_summary}
Calibration: {calibration_tier}

Your job:
1. Read ROADMAP.md phase {PHASE} description
2. Read any prior CONTEXT.md files from earlier phases
3. Glob/Grep for files related to: {phase_relevant_terms}
4. Read 5-15 most relevant source files
5. Return structured assumptions

## Output Format

Return EXACTLY this structure:

## Assumptions

### [Area Name] (e.g., "Technical Approach")
- **Assumption:** [Decision statement]
  - **Why this way:** [Evidence from codebase — cite file paths]
  - **If wrong:** [Concrete consequence of this being wrong]
  - **Confidence:** Confident | Likely | Unclear

(3-5 areas, calibrated by tier:
- full_maturity: 3-5 areas, 2-3 alternatives per Likely/Unclear item
- standard: 3-4 areas, 2 alternatives per Likely/Unclear item
- minimal_decisive: 2-3 areas, decisive single recommendation per item)

## Needs External Research
[Topics where codebase alone is insufficient — library version compatibility,
ecosystem best practices, etc. Leave empty if codebase provides enough evidence.]

${AGENT_SKILLS_ANALYZER}
""")

ORCHESTRATOR RULE — CODEX RUNTIME: After calling Agent() above, stop working on this task immediately. Do not read more files, analyze the codebase, or process assumptions while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.

Parse the subagent's response. Extract:

  • assumptions[] — each with area, statement, evidence, consequence, confidence
  • needs_research[] — topics requiring external research (may be empty)

Initialize canonical refs accumulator:

  • Source 1: Copy Canonical refs: from ROADMAP.md for this phase, expand to full paths
  • Source 2: Check REQUIREMENTS.md and PROJECT.md for specs/ADRs referenced
  • Source 3: Add any docs referenced in codebase scout results
**Skip if:** `needs_research` from deep_codebase_analysis is empty.

If research topics were flagged, spawn a general-purpose research agent (runs in a subagent — no output until it returns, ~1–5 min; expected, not a freeze):

Agent(subagent_type="general-purpose", prompt="""
Research the following topics for Phase {PHASE}: {phase_name}.

Topics needing research:
{needs_research_content}

For each topic, return:
- **Finding:** [What you learned]
- **Source:** [URL or library docs reference]
- **Confidence impact:** [Which assumption this resolves and to what confidence level]

Use Context7 (resolve-library-id then query-docs) for library-specific questions.
Use WebSearch for ecosystem/best-practice questions.
""")

> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above, stop working on this task immediately. Do not independently research any of these topics while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work and wasted context. Only resume when the subagent result is available.

Merge findings back into assumptions:

  • Update confidence levels where research resolves ambiguity
  • Add source attribution to affected assumptions
  • Store research findings for DISCUSSION-LOG.md

If no gaps flagged: Skip entirely. Most phases will skip this step.

Display all assumptions grouped by area with confidence badges.

Format for display:

## Phase {PHASE}: {phase_name} — Assumptions

Based on codebase analysis, here's what I'd go with:

### {Area Name}
{Confidence badge} **{Assumption statement}**
↳ Evidence: {file paths cited}
↳ If wrong: {consequence}

### {Area Name 2}
...

[If external research was done:]
### External Research Applied
- {Topic}: {Finding} (Source: {URL})

If --auto:

  • If all assumptions are Confident or Likely: log assumptions, skip to write_context. Log: [auto] All assumptions Confident/Likely — proceeding to context capture.
  • If any assumptions are Unclear: log a warning, auto-select recommended alternative for each Unclear item. Log: [auto] {N} Unclear assumptions auto-resolved with recommended defaults. Proceed to write_context.

Otherwise: Use AskUserQuestion:

  • header: "Assumptions"
  • question: "These all look right?"
  • options:
    • "Yes, proceed" — Write CONTEXT.md with these assumptions as decisions
    • "Let me correct some" — Select which assumptions to change

If "Yes, proceed": Skip to write_context. If "Let me correct some": Continue to correct_assumptions.

The assumptions are already displayed above from present_assumptions.

Present a multiSelect where each option's label is the assumption statement and description is the "If wrong" consequence:

Use AskUserQuestion (multiSelect):

  • header: "Corrections"
  • question: "Which assumptions need correcting?"
  • options: [one per assumption, label = assumption statement, description = "If wrong: {consequence}"]

For each selected correction, ask ONE focused question:

Use AskUserQuestion:

  • header: "{Area Name}"
  • question: "What should we do instead for: {assumption statement}?"
  • options: [2-3 concrete alternatives describing user-visible outcomes, recommended option first]

Record each correction:

  • Original assumption
  • User's chosen alternative
  • Reason (if provided via "Other" free text)

After all corrections processed, continue to write_context with updated assumptions.

Auto mode: Should not reach this step (--auto skips from present_assumptions).

Create phase directory if needed. Write CONTEXT.md using the standard 6-section format.

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

Map assumptions to CONTEXT.md sections:

  • Assumptions → <decisions> (each assumption becomes a locked decision: D-01, D-02, etc.)
  • Corrections → override the original assumption in <decisions>
  • Areas where all assumptions were Confident → marked as locked decisions
  • Areas with corrections → include user's chosen alternative as the decision
  • Folded todos → included in <decisions> under "### Folded Todos"
# Phase {PHASE}: {phase_name} - Context

**Gathered:** {date} (assumptions mode)
**Status:** Ready for planning

<domain>
## Phase Boundary

{Domain boundary from ROADMAP.md — clear statement of scope anchor}
</domain>

<decisions>
## Implementation Decisions

### {Area Name 1}
- **D-01:** {Decision — from assumption or correction}
- **D-02:** {Decision}

### {Area Name 2}
- **D-03:** {Decision}

### Claude's Discretion
{Any assumptions where the user confirmed "you decide" or left as-is with Likely confidence}

### Folded Todos
{If any todos were folded into scope}
</decisions>

<canonical_refs>
## Canonical References

**Downstream agents MUST read these before planning or implementing.**

{Accumulated canonical refs from analyze step — full relative paths}

[If no external specs: "No external specs — requirements fully captured in decisions above"]
</canonical_refs>

<code_context>
## Existing Code Insights

### Reusable Assets
{From codebase scout + Explore subagent findings}

### Established Patterns
{Patterns that constrain/enable this phase}

### Integration Points
{Where new code connects to existing system}
</code_context>

<specifics>
## Specific Ideas

{Any particular references from corrections or user input}

[If none: "No specific requirements — open to standard approaches"]
</specifics>

<deferred>
## Deferred Ideas

{Ideas mentioned during corrections that are out of scope}

### Reviewed Todos (not folded)
{Todos reviewed but not folded — with reason}

[If none: "None — analysis stayed within phase scope"]
</deferred>

Write file.

Write audit trail of assumptions and corrections.

File: ${phase_dir}/${padded_phase}-DISCUSSION-LOG.md

# Phase {PHASE}: {phase_name} - Discussion Log (Assumptions Mode)

> **Audit trail only.** Do not use as input to planning, research, or execution agents.
> Decisions captured in CONTEXT.md — this log preserves the analysis.

**Date:** {ISO date}
**Phase:** {padded_phase}-{phase_name}
**Mode:** assumptions
**Areas analyzed:** {comma-separated area names}

## Assumptions Presented

### {Area Name}
| Assumption | Confidence | Evidence |
|------------|-----------|----------|
| {Statement} | {Confident/Likely/Unclear} | {file paths} |

{Repeat for each area}

## Corrections Made

{If corrections were made:}

### {Area Name}
- **Original assumption:** {what Claude assumed}
- **User correction:** {what the user chose instead}
- **Reason:** {user's rationale, if provided}

{If no corrections: "No corrections — all assumptions confirmed."}

## Auto-Resolved

{If --auto and Unclear items existed:}
- {Assumption}: auto-selected {recommended option}

{If not applicable: omit this section}

## External Research

{If research was performed:}
- {Topic}: {Finding} (Source: {URL})

{If no research: omit this section}

Write file.

Commit phase context and discussion log:
gsd_run query commit "docs(${padded_phase}): capture phase context (assumptions mode)" --files "${phase_dir}/${padded_phase}-CONTEXT.md" "${phase_dir}/${padded_phase}-DISCUSSION-LOG.md"

Confirm: "Committed: docs(${padded_phase}): capture phase context (assumptions mode)"

Update STATE.md with session info:
gsd_run query state.record-session \
  --stopped-at "Phase ${PHASE} context gathered (assumptions mode)" \
  --resume-file "${phase_dir}/${padded_phase}-CONTEXT.md"

Commit STATE.md:

gsd_run query commit "docs(state): record phase ${PHASE} context session" --files .planning/STATE.md
Present summary and next steps:
Created: .planning/phases/${PADDED_PHASE}-${SLUG}/${PADDED_PHASE}-CONTEXT.md

## Decisions Captured (Assumptions Mode)

### {Area Name}
- {Key decision} (from assumption / corrected)

{Repeat per area}

[If corrections were made:]
## Corrections Applied
- {Area}: {original} → {corrected}

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

---

## ▶ Next Up — [${PROJECT_CODE}] ${PROJECT_TITLE}

**Phase ${PHASE}: {phase_name}** — {Goal from ROADMAP.md}

`/clear` then:

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

---

**Also available:**
- `/gsd:plan-phase ${PHASE} --skip-research` — plan without research
- `/gsd:ui-phase ${PHASE}` — generate UI design contract (if frontend work)
- Review/edit CONTEXT.md before continuing

---
Check for auto-advance trigger:
  1. Parse --auto flag from $ARGUMENTS
  2. Sync chain flag:
    if [[ ! "$ARGUMENTS" =~ --auto ]]; then
      gsd_run query config-set workflow._auto_chain_active false || true
    fi
    
  3. Read consolidated auto-mode (active = chain flag OR user preference):
    AUTO_MODE=$(gsd_run query check auto-mode --pick active 2>/dev/null || echo "false")
    

If --auto flag present AND AUTO_MODE is not true:

gsd_run query config-set workflow._auto_chain_active true

If section_manifest is null or "auto-advance-dispatch" is in its included list: read and execute gsd-core/workflows/discuss-phase-assumptions/steps/auto-advance-dispatch.md. Otherwise skip — do not read the file.

If neither --auto nor config enabled: End here — confirm_creation already ran; do not route back to it.

<success_criteria>

  • Phase validated against roadmap
  • Prior context loaded (no re-asking decided questions)
  • Codebase deeply analyzed via Explore subagent (5-15 files read)
  • Assumptions surfaced with evidence and confidence levels
  • User confirmed or corrected assumptions (~2-4 interactions max)
  • Scope creep redirected to deferred ideas
  • CONTEXT.md captures actual decisions (identical format to discuss mode)
  • CONTEXT.md includes canonical_refs with full file paths (MANDATORY)
  • CONTEXT.md includes code_context from codebase analysis
  • DISCUSSION-LOG.md records assumptions and corrections as audit trail
  • STATE.md updated with session info
  • User knows next steps </success_criteria>